util.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. "time"
  25. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/bgentry/speakeasy"
  26. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/codegangsta/cli"
  27. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  28. "github.com/coreos/etcd/client"
  29. "github.com/coreos/etcd/pkg/transport"
  30. )
  31. var (
  32. ErrNoAvailSrc = errors.New("no available argument and stdin")
  33. // the maximum amount of time a dial will wait for a connection to setup.
  34. // 30s is long enough for most of the network conditions.
  35. defaultDialTimeout = 30 * time.Second
  36. )
  37. // trimsplit slices s into all substrings separated by sep and returns a
  38. // slice of the substrings between the separator with all leading and trailing
  39. // white space removed, as defined by Unicode.
  40. func trimsplit(s, sep string) []string {
  41. raw := strings.Split(s, ",")
  42. trimmed := make([]string, 0)
  43. for _, r := range raw {
  44. trimmed = append(trimmed, strings.TrimSpace(r))
  45. }
  46. return trimmed
  47. }
  48. func argOrStdin(args []string, stdin io.Reader, i int) (string, error) {
  49. if i < len(args) {
  50. return args[i], nil
  51. }
  52. bytes, err := ioutil.ReadAll(stdin)
  53. if string(bytes) == "" || err != nil {
  54. return "", ErrNoAvailSrc
  55. }
  56. return string(bytes), nil
  57. }
  58. func getPeersFlagValue(c *cli.Context) []string {
  59. peerstr := c.GlobalString("endpoint")
  60. if peerstr == "" {
  61. peerstr = os.Getenv("ETCDCTL_ENDPOINT")
  62. }
  63. if peerstr == "" {
  64. peerstr = c.GlobalString("peers")
  65. }
  66. if peerstr == "" {
  67. peerstr = os.Getenv("ETCDCTL_PEERS")
  68. }
  69. // If we still don't have peers, use a default
  70. if peerstr == "" {
  71. peerstr = "http://127.0.0.1:4001,http://127.0.0.1:2379"
  72. }
  73. return strings.Split(peerstr, ",")
  74. }
  75. func getDomainDiscoveryFlagValue(c *cli.Context) ([]string, error) {
  76. domainstr := c.GlobalString("discovery-srv")
  77. // Use an environment variable if nothing was supplied on the
  78. // command line
  79. if domainstr == "" {
  80. domainstr = os.Getenv("ETCDCTL_DISCOVERY_SRV")
  81. }
  82. // If we still don't have domain discovery, return nothing
  83. if domainstr == "" {
  84. return []string{}, nil
  85. }
  86. discoverer := client.NewSRVDiscover()
  87. eps, err := discoverer.Discover(domainstr)
  88. if err != nil {
  89. return nil, err
  90. }
  91. return eps, err
  92. }
  93. func getEndpoints(c *cli.Context) ([]string, error) {
  94. eps, err := getDomainDiscoveryFlagValue(c)
  95. if err != nil {
  96. return nil, err
  97. }
  98. // If domain discovery returns no endpoints, check peer flag
  99. if len(eps) == 0 {
  100. eps = getPeersFlagValue(c)
  101. }
  102. for i, ep := range eps {
  103. u, err := url.Parse(ep)
  104. if err != nil {
  105. return nil, err
  106. }
  107. if u.Scheme == "" {
  108. u.Scheme = "http"
  109. }
  110. eps[i] = u.String()
  111. }
  112. return eps, nil
  113. }
  114. func getTransport(c *cli.Context) (*http.Transport, error) {
  115. cafile := c.GlobalString("ca-file")
  116. certfile := c.GlobalString("cert-file")
  117. keyfile := c.GlobalString("key-file")
  118. // Use an environment variable if nothing was supplied on the
  119. // command line
  120. if cafile == "" {
  121. cafile = os.Getenv("ETCDCTL_CA_FILE")
  122. }
  123. if certfile == "" {
  124. certfile = os.Getenv("ETCDCTL_CERT_FILE")
  125. }
  126. if keyfile == "" {
  127. keyfile = os.Getenv("ETCDCTL_KEY_FILE")
  128. }
  129. tls := transport.TLSInfo{
  130. CAFile: cafile,
  131. CertFile: certfile,
  132. KeyFile: keyfile,
  133. }
  134. return transport.NewTransport(tls, defaultDialTimeout)
  135. }
  136. func getUsernamePasswordFromFlag(usernameFlag string) (username string, password string, err error) {
  137. colon := strings.Index(usernameFlag, ":")
  138. if colon == -1 {
  139. username = usernameFlag
  140. // Prompt for the password.
  141. password, err = speakeasy.Ask("Password: ")
  142. if err != nil {
  143. return "", "", err
  144. }
  145. } else {
  146. username = usernameFlag[:colon]
  147. password = usernameFlag[colon+1:]
  148. }
  149. return username, password, nil
  150. }
  151. func mustNewKeyAPI(c *cli.Context) client.KeysAPI {
  152. return client.NewKeysAPI(mustNewClient(c))
  153. }
  154. func mustNewMembersAPI(c *cli.Context) client.MembersAPI {
  155. return client.NewMembersAPI(mustNewClient(c))
  156. }
  157. func mustNewClient(c *cli.Context) client.Client {
  158. hc, err := newClient(c)
  159. if err != nil {
  160. fmt.Fprintln(os.Stderr, err.Error())
  161. os.Exit(1)
  162. }
  163. debug := c.GlobalBool("debug")
  164. if debug {
  165. client.EnablecURLDebug()
  166. }
  167. if !c.GlobalBool("no-sync") {
  168. if debug {
  169. fmt.Fprintf(os.Stderr, "start to sync cluster using endpoints(%s)\n", strings.Join(hc.Endpoints(), ","))
  170. }
  171. ctx, cancel := context.WithTimeout(context.Background(), client.DefaultRequestTimeout)
  172. err := hc.Sync(ctx)
  173. cancel()
  174. if err != nil {
  175. if err == client.ErrNoEndpoints {
  176. fmt.Fprintf(os.Stderr, "etcd cluster has no published client endpoints.\n")
  177. fmt.Fprintf(os.Stderr, "Try '--no-sync' if you want to access non-published client endpoints(%s).\n", strings.Join(hc.Endpoints(), ","))
  178. }
  179. handleError(ExitServerError, err)
  180. }
  181. if debug {
  182. fmt.Fprintf(os.Stderr, "got endpoints(%s) after sync\n", strings.Join(hc.Endpoints(), ","))
  183. }
  184. }
  185. if debug {
  186. fmt.Fprintf(os.Stderr, "Cluster-Endpoints: %s\n", strings.Join(hc.Endpoints(), ", "))
  187. }
  188. return hc
  189. }
  190. func mustNewClientNoSync(c *cli.Context) client.Client {
  191. hc, err := newClient(c)
  192. if err != nil {
  193. fmt.Fprintln(os.Stderr, err.Error())
  194. os.Exit(1)
  195. }
  196. if c.GlobalBool("debug") {
  197. fmt.Fprintf(os.Stderr, "Cluster-Endpoints: %s\n", strings.Join(hc.Endpoints(), ", "))
  198. client.EnablecURLDebug()
  199. }
  200. return hc
  201. }
  202. func newClient(c *cli.Context) (client.Client, error) {
  203. eps, err := getEndpoints(c)
  204. if err != nil {
  205. return nil, err
  206. }
  207. tr, err := getTransport(c)
  208. if err != nil {
  209. return nil, err
  210. }
  211. cfg := client.Config{
  212. Transport: tr,
  213. Endpoints: eps,
  214. HeaderTimeoutPerRequest: c.GlobalDuration("timeout"),
  215. }
  216. uFlag := c.GlobalString("username")
  217. if uFlag != "" {
  218. username, password, err := getUsernamePasswordFromFlag(uFlag)
  219. if err != nil {
  220. return nil, err
  221. }
  222. cfg.Username = username
  223. cfg.Password = password
  224. }
  225. return client.New(cfg)
  226. }
  227. func contextWithTotalTimeout(c *cli.Context) (context.Context, context.CancelFunc) {
  228. return context.WithTimeout(context.Background(), c.GlobalDuration("total-timeout"))
  229. }