util.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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, insecure := getDiscoveryDomain(c)
  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. if insecure {
  84. return eps, err
  85. }
  86. // strip insecure connections
  87. ret := []string{}
  88. for _, ep := range eps {
  89. if strings.HasPrefix(ep, "http://") {
  90. fmt.Fprintf(os.Stderr, "ignoring discovered insecure endpoint %q\n", ep)
  91. continue
  92. }
  93. ret = append(ret, ep)
  94. }
  95. return ret, err
  96. }
  97. func getDiscoveryDomain(c *cli.Context) (domainstr string, insecure bool) {
  98. domainstr = c.GlobalString("discovery-srv")
  99. // Use an environment variable if nothing was supplied on the
  100. // command line
  101. if domainstr == "" {
  102. domainstr = os.Getenv("ETCDCTL_DISCOVERY_SRV")
  103. }
  104. insecure = c.GlobalBool("insecure-discovery") || (os.Getenv("ETCDCTL_INSECURE_DISCOVERY") != "")
  105. return domainstr, insecure
  106. }
  107. func getEndpoints(c *cli.Context) ([]string, error) {
  108. eps, err := getDomainDiscoveryFlagValue(c)
  109. if err != nil {
  110. return nil, err
  111. }
  112. // If domain discovery returns no endpoints, check peer flag
  113. if len(eps) == 0 {
  114. eps = getPeersFlagValue(c)
  115. }
  116. for i, ep := range eps {
  117. u, err := url.Parse(ep)
  118. if err != nil {
  119. return nil, err
  120. }
  121. if u.Scheme == "" {
  122. u.Scheme = "http"
  123. }
  124. eps[i] = u.String()
  125. }
  126. return eps, nil
  127. }
  128. func getTransport(c *cli.Context) (*http.Transport, error) {
  129. cafile := c.GlobalString("ca-file")
  130. certfile := c.GlobalString("cert-file")
  131. keyfile := c.GlobalString("key-file")
  132. // Use an environment variable if nothing was supplied on the
  133. // command line
  134. if cafile == "" {
  135. cafile = os.Getenv("ETCDCTL_CA_FILE")
  136. }
  137. if certfile == "" {
  138. certfile = os.Getenv("ETCDCTL_CERT_FILE")
  139. }
  140. if keyfile == "" {
  141. keyfile = os.Getenv("ETCDCTL_KEY_FILE")
  142. }
  143. discoveryDomain, insecure := getDiscoveryDomain(c)
  144. if insecure {
  145. discoveryDomain = ""
  146. }
  147. tls := transport.TLSInfo{
  148. CAFile: cafile,
  149. CertFile: certfile,
  150. KeyFile: keyfile,
  151. ServerName: discoveryDomain,
  152. }
  153. dialTimeout := defaultDialTimeout
  154. totalTimeout := c.GlobalDuration("total-timeout")
  155. if totalTimeout != 0 && totalTimeout < dialTimeout {
  156. dialTimeout = totalTimeout
  157. }
  158. return transport.NewTransport(tls, dialTimeout)
  159. }
  160. func getUsernamePasswordFromFlag(usernameFlag string) (username string, password string, err error) {
  161. return getUsernamePassword("Password: ", usernameFlag)
  162. }
  163. func getUsernamePassword(prompt, usernameFlag string) (username string, password string, err error) {
  164. colon := strings.Index(usernameFlag, ":")
  165. if colon == -1 {
  166. username = usernameFlag
  167. // Prompt for the password.
  168. password, err = speakeasy.Ask(prompt)
  169. if err != nil {
  170. return "", "", err
  171. }
  172. } else {
  173. username = usernameFlag[:colon]
  174. password = usernameFlag[colon+1:]
  175. }
  176. return username, password, nil
  177. }
  178. func mustNewKeyAPI(c *cli.Context) client.KeysAPI {
  179. return client.NewKeysAPI(mustNewClient(c))
  180. }
  181. func mustNewMembersAPI(c *cli.Context) client.MembersAPI {
  182. return client.NewMembersAPI(mustNewClient(c))
  183. }
  184. func mustNewClient(c *cli.Context) client.Client {
  185. hc, err := newClient(c)
  186. if err != nil {
  187. fmt.Fprintln(os.Stderr, err.Error())
  188. os.Exit(1)
  189. }
  190. debug := c.GlobalBool("debug")
  191. if debug {
  192. client.EnablecURLDebug()
  193. }
  194. if !c.GlobalBool("no-sync") {
  195. if debug {
  196. fmt.Fprintf(os.Stderr, "start to sync cluster using endpoints(%s)\n", strings.Join(hc.Endpoints(), ","))
  197. }
  198. ctx, cancel := contextWithTotalTimeout(c)
  199. err := hc.Sync(ctx)
  200. cancel()
  201. if err != nil {
  202. if err == client.ErrNoEndpoints {
  203. fmt.Fprintf(os.Stderr, "etcd cluster has no published client endpoints.\n")
  204. fmt.Fprintf(os.Stderr, "Try '--no-sync' if you want to access non-published client endpoints(%s).\n", strings.Join(hc.Endpoints(), ","))
  205. handleError(c, ExitServerError, err)
  206. }
  207. if isConnectionError(err) {
  208. handleError(c, ExitBadConnection, err)
  209. }
  210. }
  211. if debug {
  212. fmt.Fprintf(os.Stderr, "got endpoints(%s) after sync\n", strings.Join(hc.Endpoints(), ","))
  213. }
  214. }
  215. if debug {
  216. fmt.Fprintf(os.Stderr, "Cluster-Endpoints: %s\n", strings.Join(hc.Endpoints(), ", "))
  217. }
  218. return hc
  219. }
  220. func isConnectionError(err error) bool {
  221. switch t := err.(type) {
  222. case *client.ClusterError:
  223. for _, cerr := range t.Errors {
  224. if !isConnectionError(cerr) {
  225. return false
  226. }
  227. }
  228. return true
  229. case *net.OpError:
  230. if t.Op == "dial" || t.Op == "read" {
  231. return true
  232. }
  233. return isConnectionError(t.Err)
  234. case net.Error:
  235. if t.Timeout() {
  236. return true
  237. }
  238. case syscall.Errno:
  239. if t == syscall.ECONNREFUSED {
  240. return true
  241. }
  242. }
  243. return false
  244. }
  245. func mustNewClientNoSync(c *cli.Context) client.Client {
  246. hc, err := newClient(c)
  247. if err != nil {
  248. fmt.Fprintln(os.Stderr, err.Error())
  249. os.Exit(1)
  250. }
  251. if c.GlobalBool("debug") {
  252. fmt.Fprintf(os.Stderr, "Cluster-Endpoints: %s\n", strings.Join(hc.Endpoints(), ", "))
  253. client.EnablecURLDebug()
  254. }
  255. return hc
  256. }
  257. func newClient(c *cli.Context) (client.Client, error) {
  258. eps, err := getEndpoints(c)
  259. if err != nil {
  260. return nil, err
  261. }
  262. tr, err := getTransport(c)
  263. if err != nil {
  264. return nil, err
  265. }
  266. cfg := client.Config{
  267. Transport: tr,
  268. Endpoints: eps,
  269. HeaderTimeoutPerRequest: c.GlobalDuration("timeout"),
  270. }
  271. uFlag := c.GlobalString("username")
  272. if uFlag == "" {
  273. uFlag = os.Getenv("ETCDCTL_USERNAME")
  274. }
  275. if uFlag != "" {
  276. username, password, err := getUsernamePasswordFromFlag(uFlag)
  277. if err != nil {
  278. return nil, err
  279. }
  280. cfg.Username = username
  281. cfg.Password = password
  282. }
  283. return client.New(cfg)
  284. }
  285. func contextWithTotalTimeout(c *cli.Context) (context.Context, context.CancelFunc) {
  286. return context.WithTimeout(context.Background(), c.GlobalDuration("total-timeout"))
  287. }