util.go 7.8 KB

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