util.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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/codegangsta/cli"
  29. "github.com/coreos/etcd/client"
  30. "github.com/coreos/etcd/pkg/transport"
  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. // fail-back to try sync cluster with peer API. this is for making etcdctl work with etcd 0.4.x.
  189. // TODO: remove this when we deprecate the support for etcd 0.4.
  190. eps, serr := syncWithPeerAPI(c, ctx, hc.Endpoints())
  191. if serr != nil {
  192. if isConnectionError(serr) {
  193. handleError(ExitBadConnection, serr)
  194. } else {
  195. handleError(ExitServerError, serr)
  196. }
  197. }
  198. err = hc.SetEndpoints(eps)
  199. if err != nil {
  200. handleError(ExitServerError, err)
  201. }
  202. }
  203. if debug {
  204. fmt.Fprintf(os.Stderr, "got endpoints(%s) after sync\n", strings.Join(hc.Endpoints(), ","))
  205. }
  206. }
  207. if debug {
  208. fmt.Fprintf(os.Stderr, "Cluster-Endpoints: %s\n", strings.Join(hc.Endpoints(), ", "))
  209. }
  210. return hc
  211. }
  212. func isConnectionError(err error) bool {
  213. switch t := err.(type) {
  214. case *client.ClusterError:
  215. for _, cerr := range t.Errors {
  216. if !isConnectionError(cerr) {
  217. return false
  218. }
  219. }
  220. return true
  221. case *net.OpError:
  222. if t.Op == "dial" || t.Op == "read" {
  223. return true
  224. }
  225. return isConnectionError(t.Err)
  226. case net.Error:
  227. if t.Timeout() {
  228. return true
  229. }
  230. case syscall.Errno:
  231. if t == syscall.ECONNREFUSED {
  232. return true
  233. }
  234. }
  235. return false
  236. }
  237. func mustNewClientNoSync(c *cli.Context) client.Client {
  238. hc, err := newClient(c)
  239. if err != nil {
  240. fmt.Fprintln(os.Stderr, err.Error())
  241. os.Exit(1)
  242. }
  243. if c.GlobalBool("debug") {
  244. fmt.Fprintf(os.Stderr, "Cluster-Endpoints: %s\n", strings.Join(hc.Endpoints(), ", "))
  245. client.EnablecURLDebug()
  246. }
  247. return hc
  248. }
  249. func newClient(c *cli.Context) (client.Client, error) {
  250. eps, err := getEndpoints(c)
  251. if err != nil {
  252. return nil, err
  253. }
  254. tr, err := getTransport(c)
  255. if err != nil {
  256. return nil, err
  257. }
  258. cfg := client.Config{
  259. Transport: tr,
  260. Endpoints: eps,
  261. HeaderTimeoutPerRequest: c.GlobalDuration("timeout"),
  262. }
  263. uFlag := c.GlobalString("username")
  264. if uFlag == "" {
  265. uFlag = os.Getenv("ETCDCTL_USERNAME")
  266. }
  267. if uFlag != "" {
  268. username, password, err := getUsernamePasswordFromFlag(uFlag)
  269. if err != nil {
  270. return nil, err
  271. }
  272. cfg.Username = username
  273. cfg.Password = password
  274. }
  275. return client.New(cfg)
  276. }
  277. func contextWithTotalTimeout(c *cli.Context) (context.Context, context.CancelFunc) {
  278. return context.WithTimeout(context.Background(), c.GlobalDuration("total-timeout"))
  279. }
  280. // syncWithPeerAPI syncs cluster with peer API defined at
  281. // https://github.com/coreos/etcd/blob/v0.4.9/server/server.go#L311.
  282. // This exists for backward compatibility with etcd 0.4.x.
  283. func syncWithPeerAPI(c *cli.Context, ctx context.Context, knownPeers []string) ([]string, error) {
  284. tr, err := getTransport(c)
  285. if err != nil {
  286. return nil, err
  287. }
  288. var (
  289. body []byte
  290. resp *http.Response
  291. )
  292. for _, p := range knownPeers {
  293. var req *http.Request
  294. req, err = http.NewRequest("GET", p+"/v2/peers", nil)
  295. if err != nil {
  296. continue
  297. }
  298. resp, err = tr.RoundTrip(req)
  299. if err != nil {
  300. continue
  301. }
  302. if resp.StatusCode != http.StatusOK {
  303. resp.Body.Close()
  304. continue
  305. }
  306. body, err = ioutil.ReadAll(resp.Body)
  307. resp.Body.Close()
  308. if err == nil {
  309. break
  310. }
  311. }
  312. if err != nil {
  313. return nil, err
  314. }
  315. // Parse the peers API format: https://github.com/coreos/etcd/blob/v0.4.9/server/server.go#L311
  316. return strings.Split(string(body), ", "), nil
  317. }