handle.go 4.4 KB

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