util.go 7.0 KB

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