util.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package command
  15. import (
  16. "errors"
  17. "fmt"
  18. "io"
  19. "io/ioutil"
  20. "net/http"
  21. "net/url"
  22. "os"
  23. "strings"
  24. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/bgentry/speakeasy"
  25. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/codegangsta/cli"
  26. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  27. "github.com/coreos/etcd/client"
  28. "github.com/coreos/etcd/pkg/transport"
  29. )
  30. var (
  31. ErrNoAvailSrc = errors.New("no available argument and stdin")
  32. )
  33. // trimsplit slices s into all substrings separated by sep and returns a
  34. // slice of the substrings between the separator with all leading and trailing
  35. // white space removed, as defined by Unicode.
  36. func trimsplit(s, sep string) []string {
  37. raw := strings.Split(s, ",")
  38. trimmed := make([]string, 0)
  39. for _, r := range raw {
  40. trimmed = append(trimmed, strings.TrimSpace(r))
  41. }
  42. return trimmed
  43. }
  44. func argOrStdin(args []string, stdin io.Reader, i int) (string, error) {
  45. if i < len(args) {
  46. return args[i], nil
  47. }
  48. bytes, err := ioutil.ReadAll(stdin)
  49. if string(bytes) == "" || err != nil {
  50. return "", ErrNoAvailSrc
  51. }
  52. return string(bytes), nil
  53. }
  54. func getPeersFlagValue(c *cli.Context) []string {
  55. peerstr := c.GlobalString("peers")
  56. // Use an environment variable if nothing was supplied on the
  57. // command line
  58. if peerstr == "" {
  59. peerstr = os.Getenv("ETCDCTL_PEERS")
  60. }
  61. // If we still don't have peers, use a default
  62. if peerstr == "" {
  63. peerstr = "127.0.0.1:4001,127.0.0.1:2379"
  64. }
  65. return strings.Split(peerstr, ",")
  66. }
  67. func getEndpoints(c *cli.Context) ([]string, error) {
  68. eps := getPeersFlagValue(c)
  69. for i, ep := range eps {
  70. u, err := url.Parse(ep)
  71. if err != nil {
  72. return nil, err
  73. }
  74. if u.Scheme == "" {
  75. u.Scheme = "http"
  76. }
  77. eps[i] = u.String()
  78. }
  79. return eps, nil
  80. }
  81. func getTransport(c *cli.Context) (*http.Transport, error) {
  82. cafile := c.GlobalString("ca-file")
  83. certfile := c.GlobalString("cert-file")
  84. keyfile := c.GlobalString("key-file")
  85. // Use an environment variable if nothing was supplied on the
  86. // command line
  87. if cafile == "" {
  88. cafile = os.Getenv("ETCDCTL_CA_FILE")
  89. }
  90. if certfile == "" {
  91. certfile = os.Getenv("ETCDCTL_CERT_FILE")
  92. }
  93. if keyfile == "" {
  94. keyfile = os.Getenv("ETCDCTL_KEY_FILE")
  95. }
  96. tls := transport.TLSInfo{
  97. CAFile: cafile,
  98. CertFile: certfile,
  99. KeyFile: keyfile,
  100. }
  101. return transport.NewTransport(tls)
  102. }
  103. func getUsernamePasswordFromFlag(usernameFlag string) (username string, password string, err error) {
  104. colon := strings.Index(usernameFlag, ":")
  105. if colon == -1 {
  106. username = usernameFlag
  107. // Prompt for the password.
  108. password, err = speakeasy.Ask("Password: ")
  109. if err != nil {
  110. return "", "", err
  111. }
  112. } else {
  113. username = usernameFlag[:colon]
  114. password = usernameFlag[colon+1:]
  115. }
  116. return username, password, nil
  117. }
  118. func mustNewKeyAPI(c *cli.Context) client.KeysAPI {
  119. return client.NewKeysAPI(mustNewClient(c))
  120. }
  121. func mustNewMembersAPI(c *cli.Context) client.MembersAPI {
  122. return client.NewMembersAPI(mustNewClient(c))
  123. }
  124. func mustNewClient(c *cli.Context) client.Client {
  125. eps, err := getEndpoints(c)
  126. if err != nil {
  127. fmt.Fprintln(os.Stderr, err.Error())
  128. os.Exit(1)
  129. }
  130. tr, err := getTransport(c)
  131. if err != nil {
  132. fmt.Fprintln(os.Stderr, err.Error())
  133. os.Exit(1)
  134. }
  135. cfg := client.Config{
  136. Transport: tr,
  137. Endpoints: eps,
  138. }
  139. uFlag := c.GlobalString("username")
  140. if uFlag != "" {
  141. username, password, err := getUsernamePasswordFromFlag(uFlag)
  142. if err != nil {
  143. fmt.Fprintln(os.Stderr, err.Error())
  144. os.Exit(1)
  145. }
  146. cfg.Username = username
  147. cfg.Password = password
  148. }
  149. hc, err := client.New(cfg)
  150. if err != nil {
  151. fmt.Fprintln(os.Stderr, err.Error())
  152. os.Exit(1)
  153. }
  154. if !c.GlobalBool("no-sync") {
  155. ctx, cancel := context.WithTimeout(context.Background(), client.DefaultRequestTimeout)
  156. err := hc.Sync(ctx)
  157. cancel()
  158. if err != nil {
  159. fmt.Fprintln(os.Stderr, err.Error())
  160. os.Exit(1)
  161. }
  162. }
  163. if c.GlobalBool("debug") {
  164. fmt.Fprintf(os.Stderr, "Cluster-Endpoints: %s\n", strings.Join(hc.Endpoints(), ", "))
  165. client.EnablecURLDebug()
  166. }
  167. return hc
  168. }