handle.go 4.8 KB

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