util.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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"
  21. "net/http"
  22. "net/url"
  23. "os"
  24. "strings"
  25. "syscall"
  26. "time"
  27. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/bgentry/speakeasy"
  28. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/codegangsta/cli"
  29. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  30. "github.com/coreos/etcd/client"
  31. "github.com/coreos/etcd/pkg/transport"
  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. // trimsplit slices s into all substrings separated by sep and returns a
  40. // slice of the substrings between the separator with all leading and trailing
  41. // white space removed, as defined by Unicode.
  42. func trimsplit(s, sep string) []string {
  43. raw := strings.Split(s, ",")
  44. trimmed := make([]string, 0)
  45. for _, r := range raw {
  46. trimmed = append(trimmed, strings.TrimSpace(r))
  47. }
  48. return trimmed
  49. }
  50. func argOrStdin(args []string, stdin io.Reader, i int) (string, error) {
  51. if i < len(args) {
  52. return args[i], nil
  53. }
  54. bytes, err := ioutil.ReadAll(stdin)
  55. if string(bytes) == "" || err != nil {
  56. return "", ErrNoAvailSrc
  57. }
  58. return string(bytes), nil
  59. }
  60. func getPeersFlagValue(c *cli.Context) []string {
  61. peerstr := c.GlobalString("endpoint")
  62. if peerstr == "" {
  63. peerstr = os.Getenv("ETCDCTL_ENDPOINT")
  64. }
  65. if peerstr == "" {
  66. peerstr = c.GlobalString("peers")
  67. }
  68. if peerstr == "" {
  69. peerstr = os.Getenv("ETCDCTL_PEERS")
  70. }
  71. // If we still don't have peers, use a default
  72. if peerstr == "" {
  73. peerstr = "http://127.0.0.1:2379,http://127.0.0.1:4001"
  74. }
  75. return strings.Split(peerstr, ",")
  76. }
  77. func getDomainDiscoveryFlagValue(c *cli.Context) ([]string, error) {
  78. domainstr := c.GlobalString("discovery-srv")
  79. // Use an environment variable if nothing was supplied on the
  80. // command line
  81. if domainstr == "" {
  82. domainstr = os.Getenv("ETCDCTL_DISCOVERY_SRV")
  83. }
  84. // If we still don't have domain discovery, return nothing
  85. if domainstr == "" {
  86. return []string{}, nil
  87. }
  88. discoverer := client.NewSRVDiscover()
  89. eps, err := discoverer.Discover(domainstr)
  90. if err != nil {
  91. return nil, err
  92. }
  93. return eps, err
  94. }
  95. func getEndpoints(c *cli.Context) ([]string, error) {
  96. eps, err := getDomainDiscoveryFlagValue(c)
  97. if err != nil {
  98. return nil, err
  99. }
  100. // If domain discovery returns no endpoints, check peer flag
  101. if len(eps) == 0 {
  102. eps = getPeersFlagValue(c)
  103. }
  104. for i, ep := range eps {
  105. u, err := url.Parse(ep)
  106. if err != nil {
  107. return nil, err
  108. }
  109. if u.Scheme == "" {
  110. u.Scheme = "http"
  111. }
  112. eps[i] = u.String()
  113. }
  114. return eps, nil
  115. }
  116. func getTransport(c *cli.Context) (*http.Transport, error) {
  117. cafile := c.GlobalString("ca-file")
  118. certfile := c.GlobalString("cert-file")
  119. keyfile := c.GlobalString("key-file")
  120. // Use an environment variable if nothing was supplied on the
  121. // command line
  122. if cafile == "" {
  123. cafile = os.Getenv("ETCDCTL_CA_FILE")
  124. }
  125. if certfile == "" {
  126. certfile = os.Getenv("ETCDCTL_CERT_FILE")
  127. }
  128. if keyfile == "" {
  129. keyfile = os.Getenv("ETCDCTL_KEY_FILE")
  130. }
  131. tls := transport.TLSInfo{
  132. CAFile: cafile,
  133. CertFile: certfile,
  134. KeyFile: keyfile,
  135. }
  136. return transport.NewTransport(tls, defaultDialTimeout)
  137. }
  138. func getUsernamePasswordFromFlag(usernameFlag string) (username string, password string, err error) {
  139. colon := strings.Index(usernameFlag, ":")
  140. if colon == -1 {
  141. username = usernameFlag
  142. // Prompt for the password.
  143. password, err = speakeasy.Ask("Password: ")
  144. if err != nil {
  145. return "", "", err
  146. }
  147. } else {
  148. username = usernameFlag[:colon]
  149. password = usernameFlag[colon+1:]
  150. }
  151. return username, password, nil
  152. }
  153. func mustNewKeyAPI(c *cli.Context) client.KeysAPI {
  154. return client.NewKeysAPI(mustNewClient(c))
  155. }
  156. func mustNewMembersAPI(c *cli.Context) client.MembersAPI {
  157. return client.NewMembersAPI(mustNewClient(c))
  158. }
  159. func mustNewClient(c *cli.Context) client.Client {
  160. hc, err := newClient(c)
  161. if err != nil {
  162. fmt.Fprintln(os.Stderr, err.Error())
  163. os.Exit(1)
  164. }
  165. debug := c.GlobalBool("debug")
  166. if debug {
  167. client.EnablecURLDebug()
  168. }
  169. if !c.GlobalBool("no-sync") {
  170. if debug {
  171. fmt.Fprintf(os.Stderr, "start to sync cluster using endpoints(%s)\n", strings.Join(hc.Endpoints(), ","))
  172. }
  173. ctx, cancel := context.WithTimeout(context.Background(), client.DefaultRequestTimeout)
  174. err := hc.Sync(ctx)
  175. cancel()
  176. if err != nil {
  177. if err == client.ErrNoEndpoints {
  178. fmt.Fprintf(os.Stderr, "etcd cluster has no published client endpoints.\n")
  179. fmt.Fprintf(os.Stderr, "Try '--no-sync' if you want to access non-published client endpoints(%s).\n", strings.Join(hc.Endpoints(), ","))
  180. handleError(ExitServerError, err)
  181. }
  182. if isConnectionError(err) {
  183. handleError(ExitBadConnection, err)
  184. }
  185. // fail-back to try sync cluster with peer API. this is for making etcdctl work with etcd 0.4.x.
  186. // TODO: remove this when we deprecate the support for etcd 0.4.
  187. eps, serr := syncWithPeerAPI(c, ctx, hc.Endpoints())
  188. if serr != nil {
  189. if isConnectionError(serr) {
  190. handleError(ExitBadConnection, serr)
  191. } else {
  192. handleError(ExitServerError, serr)
  193. }
  194. }
  195. err = hc.SetEndpoints(eps)
  196. if err != nil {
  197. handleError(ExitServerError, err)
  198. }
  199. }
  200. if debug {
  201. fmt.Fprintf(os.Stderr, "got endpoints(%s) after sync\n", strings.Join(hc.Endpoints(), ","))
  202. }
  203. }
  204. if debug {
  205. fmt.Fprintf(os.Stderr, "Cluster-Endpoints: %s\n", strings.Join(hc.Endpoints(), ", "))
  206. }
  207. return hc
  208. }
  209. func isConnectionError(err error) bool {
  210. switch t := err.(type) {
  211. case *client.ClusterError:
  212. for _, cerr := range t.Errors {
  213. if !isConnectionError(cerr) {
  214. return false
  215. }
  216. }
  217. return true
  218. case *net.OpError:
  219. if t.Op == "dial" || t.Op == "read" {
  220. return true
  221. }
  222. return isConnectionError(t.Err)
  223. case net.Error:
  224. if t.Timeout() {
  225. return true
  226. }
  227. case syscall.Errno:
  228. if t == syscall.ECONNREFUSED {
  229. return true
  230. }
  231. }
  232. return false
  233. }
  234. func mustNewClientNoSync(c *cli.Context) client.Client {
  235. hc, err := newClient(c)
  236. if err != nil {
  237. fmt.Fprintln(os.Stderr, err.Error())
  238. os.Exit(1)
  239. }
  240. if c.GlobalBool("debug") {
  241. fmt.Fprintf(os.Stderr, "Cluster-Endpoints: %s\n", strings.Join(hc.Endpoints(), ", "))
  242. client.EnablecURLDebug()
  243. }
  244. return hc
  245. }
  246. func newClient(c *cli.Context) (client.Client, error) {
  247. eps, err := getEndpoints(c)
  248. if err != nil {
  249. return nil, err
  250. }
  251. tr, err := getTransport(c)
  252. if err != nil {
  253. return nil, err
  254. }
  255. cfg := client.Config{
  256. Transport: tr,
  257. Endpoints: eps,
  258. HeaderTimeoutPerRequest: c.GlobalDuration("timeout"),
  259. }
  260. uFlag := c.GlobalString("username")
  261. if uFlag != "" {
  262. username, password, err := getUsernamePasswordFromFlag(uFlag)
  263. if err != nil {
  264. return nil, err
  265. }
  266. cfg.Username = username
  267. cfg.Password = password
  268. }
  269. return client.New(cfg)
  270. }
  271. func contextWithTotalTimeout(c *cli.Context) (context.Context, context.CancelFunc) {
  272. return context.WithTimeout(context.Background(), c.GlobalDuration("total-timeout"))
  273. }
  274. // syncWithPeerAPI syncs cluster with peer API defined at
  275. // https://github.com/coreos/etcd/blob/v0.4.9/server/server.go#L311.
  276. // This exists for backward compatibility with etcd 0.4.x.
  277. func syncWithPeerAPI(c *cli.Context, ctx context.Context, knownPeers []string) ([]string, error) {
  278. tr, err := getTransport(c)
  279. if err != nil {
  280. return nil, err
  281. }
  282. var (
  283. body []byte
  284. resp *http.Response
  285. )
  286. for _, p := range knownPeers {
  287. var req *http.Request
  288. req, err = http.NewRequest("GET", p+"/v2/peers", nil)
  289. if err != nil {
  290. continue
  291. }
  292. resp, err = tr.RoundTrip(req)
  293. if err != nil {
  294. continue
  295. }
  296. if resp.StatusCode != http.StatusOK {
  297. resp.Body.Close()
  298. continue
  299. }
  300. body, err = ioutil.ReadAll(resp.Body)
  301. resp.Body.Close()
  302. if err == nil {
  303. break
  304. }
  305. }
  306. if err != nil {
  307. return nil, err
  308. }
  309. // Parse the peers API format: https://github.com/coreos/etcd/blob/v0.4.9/server/server.go#L311
  310. return strings.Split(string(body), ", "), nil
  311. }