util.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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 = "http://127.0.0.1:4001,http://127.0.0.1:2379"
  64. }
  65. return strings.Split(peerstr, ",")
  66. }
  67. func getDomainDiscoveryFlagValue(c *cli.Context) ([]string, error) {
  68. domainstr := c.GlobalString("discovery-srv")
  69. // Use an environment variable if nothing was supplied on the
  70. // command line
  71. if domainstr == "" {
  72. domainstr = os.Getenv("ETCDCTL_DISCOVERY_SRV")
  73. }
  74. // If we still don't have domain discovery, return nothing
  75. if domainstr == "" {
  76. return []string{}, nil
  77. }
  78. discoverer := client.NewSRVDiscover()
  79. eps, err := discoverer.Discover(domainstr)
  80. if err != nil {
  81. return nil, err
  82. }
  83. return eps, err
  84. }
  85. func getEndpoints(c *cli.Context) ([]string, error) {
  86. eps, err := getDomainDiscoveryFlagValue(c)
  87. if err != nil {
  88. return nil, err
  89. }
  90. // If domain discovery returns no endpoints, check peer flag
  91. if len(eps) == 0 {
  92. eps = getPeersFlagValue(c)
  93. }
  94. for i, ep := range eps {
  95. u, err := url.Parse(ep)
  96. if err != nil {
  97. return nil, err
  98. }
  99. if u.Scheme == "" {
  100. u.Scheme = "http"
  101. }
  102. eps[i] = u.String()
  103. }
  104. return eps, nil
  105. }
  106. func getTransport(c *cli.Context) (*http.Transport, error) {
  107. cafile := c.GlobalString("ca-file")
  108. certfile := c.GlobalString("cert-file")
  109. keyfile := c.GlobalString("key-file")
  110. // Use an environment variable if nothing was supplied on the
  111. // command line
  112. if cafile == "" {
  113. cafile = os.Getenv("ETCDCTL_CA_FILE")
  114. }
  115. if certfile == "" {
  116. certfile = os.Getenv("ETCDCTL_CERT_FILE")
  117. }
  118. if keyfile == "" {
  119. keyfile = os.Getenv("ETCDCTL_KEY_FILE")
  120. }
  121. tls := transport.TLSInfo{
  122. CAFile: cafile,
  123. CertFile: certfile,
  124. KeyFile: keyfile,
  125. }
  126. return transport.NewTransport(tls)
  127. }
  128. func getUsernamePasswordFromFlag(usernameFlag string) (username string, password string, err error) {
  129. colon := strings.Index(usernameFlag, ":")
  130. if colon == -1 {
  131. username = usernameFlag
  132. // Prompt for the password.
  133. password, err = speakeasy.Ask("Password: ")
  134. if err != nil {
  135. return "", "", err
  136. }
  137. } else {
  138. username = usernameFlag[:colon]
  139. password = usernameFlag[colon+1:]
  140. }
  141. return username, password, nil
  142. }
  143. func mustNewKeyAPI(c *cli.Context) client.KeysAPI {
  144. return client.NewKeysAPI(mustNewClient(c))
  145. }
  146. func mustNewMembersAPI(c *cli.Context) client.MembersAPI {
  147. return client.NewMembersAPI(mustNewClient(c))
  148. }
  149. func mustNewClient(c *cli.Context) client.Client {
  150. eps, err := getEndpoints(c)
  151. if err != nil {
  152. fmt.Fprintln(os.Stderr, err.Error())
  153. os.Exit(1)
  154. }
  155. tr, err := getTransport(c)
  156. if err != nil {
  157. fmt.Fprintln(os.Stderr, err.Error())
  158. os.Exit(1)
  159. }
  160. cfg := client.Config{
  161. Transport: tr,
  162. Endpoints: eps,
  163. HeaderTimeoutPerRequest: c.GlobalDuration("timeout"),
  164. }
  165. uFlag := c.GlobalString("username")
  166. if uFlag != "" {
  167. username, password, err := getUsernamePasswordFromFlag(uFlag)
  168. if err != nil {
  169. fmt.Fprintln(os.Stderr, err.Error())
  170. os.Exit(1)
  171. }
  172. cfg.Username = username
  173. cfg.Password = password
  174. }
  175. hc, err := client.New(cfg)
  176. if err != nil {
  177. fmt.Fprintln(os.Stderr, err.Error())
  178. os.Exit(1)
  179. }
  180. if !c.GlobalBool("no-sync") {
  181. ctx, cancel := context.WithTimeout(context.Background(), client.DefaultRequestTimeout)
  182. err := hc.Sync(ctx)
  183. cancel()
  184. if err != nil {
  185. handleError(ExitServerError, err)
  186. os.Exit(1)
  187. }
  188. }
  189. if c.GlobalBool("debug") {
  190. fmt.Fprintf(os.Stderr, "Cluster-Endpoints: %s\n", strings.Join(hc.Endpoints(), ", "))
  191. client.EnablecURLDebug()
  192. }
  193. return hc
  194. }