handle.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package command
  14. import (
  15. "encoding/json"
  16. "errors"
  17. "fmt"
  18. "net/url"
  19. "os"
  20. "strings"
  21. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/codegangsta/cli"
  22. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd"
  23. )
  24. type handlerFunc func(*cli.Context, *etcd.Client) (*etcd.Response, error)
  25. type printFunc func(*etcd.Response, string)
  26. type contextualPrintFunc func(*cli.Context, *etcd.Response, string)
  27. // dumpCURL blindly dumps all curl output to os.Stderr
  28. func dumpCURL(client *etcd.Client) {
  29. client.OpenCURL()
  30. for {
  31. fmt.Fprintf(os.Stderr, "Curl-Example: %s\n", client.RecvCURL())
  32. }
  33. }
  34. // createHttpPath attaches http scheme to the given address if needed
  35. func createHttpPath(addr string) (string, error) {
  36. u, err := url.Parse(addr)
  37. if err != nil {
  38. return "", err
  39. }
  40. if u.Scheme == "" {
  41. u.Scheme = "http"
  42. }
  43. return u.String(), nil
  44. }
  45. func getPeersFlagValue(c *cli.Context) []string {
  46. peerstr := c.GlobalString("peers")
  47. // Use an environment variable if nothing was supplied on the
  48. // command line
  49. if peerstr == "" {
  50. peerstr = os.Getenv("ETCDCTL_PEERS")
  51. }
  52. // If we still don't have peers, use a default
  53. if peerstr == "" {
  54. peerstr = "127.0.0.1:4001"
  55. }
  56. return strings.Split(peerstr, ",")
  57. }
  58. // rawhandle wraps the command function handlers and sets up the
  59. // environment but performs no output formatting.
  60. func rawhandle(c *cli.Context, fn handlerFunc) (*etcd.Response, error) {
  61. sync := !c.GlobalBool("no-sync")
  62. peers := getPeersFlagValue(c)
  63. // If no sync, create http path for each peer address
  64. if !sync {
  65. revisedPeers := make([]string, 0)
  66. for _, peer := range peers {
  67. if revisedPeer, err := createHttpPath(peer); err != nil {
  68. fmt.Fprintf(os.Stderr, "Unsupported url %v: %v\n", peer, err)
  69. } else {
  70. revisedPeers = append(revisedPeers, revisedPeer)
  71. }
  72. }
  73. peers = revisedPeers
  74. }
  75. client := etcd.NewClient(peers)
  76. if c.GlobalBool("debug") {
  77. go dumpCURL(client)
  78. }
  79. // Sync cluster.
  80. if sync {
  81. if ok := client.SyncCluster(); !ok {
  82. handleError(FailedToConnectToHost, errors.New("Cannot sync with the cluster using peers "+strings.Join(peers, ", ")))
  83. }
  84. }
  85. if c.GlobalBool("debug") {
  86. fmt.Fprintf(os.Stderr, "Cluster-Peers: %s\n",
  87. strings.Join(client.GetCluster(), " "))
  88. }
  89. // Execute handler function.
  90. return fn(c, client)
  91. }
  92. // handlePrint wraps the command function handlers to parse global flags
  93. // into a client and to properly format the response objects.
  94. func handlePrint(c *cli.Context, fn handlerFunc, pFn printFunc) {
  95. resp, err := rawhandle(c, fn)
  96. // Print error and exit, if necessary.
  97. if err != nil {
  98. handleError(ErrorFromEtcd, err)
  99. }
  100. if resp != nil && pFn != nil {
  101. pFn(resp, c.GlobalString("output"))
  102. }
  103. }
  104. // Just like handlePrint but also passed the context of the command
  105. func handleContextualPrint(c *cli.Context, fn handlerFunc, pFn contextualPrintFunc) {
  106. resp, err := rawhandle(c, fn)
  107. if err != nil {
  108. handleError(ErrorFromEtcd, err)
  109. }
  110. if resp != nil && pFn != nil {
  111. pFn(c, resp, c.GlobalString("output"))
  112. }
  113. }
  114. // handleDir handles a request that wants to do operations on a single dir.
  115. // Dir cannot be printed out, so we set NIL print function here.
  116. func handleDir(c *cli.Context, fn handlerFunc) {
  117. handlePrint(c, fn, nil)
  118. }
  119. // handleKey handles a request that wants to do operations on a single key.
  120. func handleKey(c *cli.Context, fn handlerFunc) {
  121. handlePrint(c, fn, printKey)
  122. }
  123. func handleAll(c *cli.Context, fn handlerFunc) {
  124. handlePrint(c, fn, printAll)
  125. }
  126. // printKey writes the etcd response to STDOUT in the given format.
  127. func printKey(resp *etcd.Response, format string) {
  128. // printKey is only for keys, error on directories
  129. if resp.Node.Dir == true {
  130. fmt.Fprintln(os.Stderr, fmt.Sprintf("Cannot print key [%s: Is a directory]", resp.Node.Key))
  131. os.Exit(1)
  132. }
  133. printKeyOnly(resp, format)
  134. }
  135. // printAll prints the etcd response in the given format in its best efforts.
  136. func printAll(resp *etcd.Response, format string) {
  137. if resp.Node.Dir == true {
  138. return
  139. }
  140. printKeyOnly(resp, format)
  141. }
  142. // printKeyOnly only supports to print key correctly.
  143. func printKeyOnly(resp *etcd.Response, format string) {
  144. // Format the result.
  145. switch format {
  146. case "simple":
  147. fmt.Println(resp.Node.Value)
  148. case "extended":
  149. // Extended prints in a rfc2822 style format
  150. fmt.Println("Key:", resp.Node.Key)
  151. fmt.Println("Created-Index:", resp.Node.CreatedIndex)
  152. fmt.Println("Modified-Index:", resp.Node.ModifiedIndex)
  153. if resp.PrevNode != nil {
  154. fmt.Println("PrevNode.Value:", resp.PrevNode.Value)
  155. }
  156. fmt.Println("TTL:", resp.Node.TTL)
  157. fmt.Println("Etcd-Index:", resp.EtcdIndex)
  158. fmt.Println("Raft-Index:", resp.RaftIndex)
  159. fmt.Println("Raft-Term:", resp.RaftTerm)
  160. fmt.Println("")
  161. fmt.Println(resp.Node.Value)
  162. case "json":
  163. b, err := json.Marshal(resp)
  164. if err != nil {
  165. panic(err)
  166. }
  167. fmt.Println(string(b))
  168. default:
  169. fmt.Fprintln(os.Stderr, "Unsupported output format:", format)
  170. }
  171. }