handle.go 4.8 KB

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