util.go 6.2 KB

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