global.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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. "crypto/tls"
  17. "errors"
  18. "fmt"
  19. "io"
  20. "io/ioutil"
  21. "os"
  22. "strings"
  23. "time"
  24. "github.com/bgentry/speakeasy"
  25. "github.com/coreos/etcd/clientv3"
  26. "github.com/coreos/etcd/pkg/flags"
  27. "github.com/coreos/etcd/pkg/srv"
  28. "github.com/coreos/etcd/pkg/transport"
  29. "github.com/spf13/cobra"
  30. "github.com/spf13/pflag"
  31. "google.golang.org/grpc/grpclog"
  32. )
  33. // GlobalFlags are flags that defined globally
  34. // and are inherited to all sub-commands.
  35. type GlobalFlags struct {
  36. Insecure bool
  37. InsecureSkipVerify bool
  38. InsecureDiscovery bool
  39. Endpoints []string
  40. DialTimeout time.Duration
  41. CommandTimeOut time.Duration
  42. KeepAliveTime time.Duration
  43. KeepAliveTimeout time.Duration
  44. TLS transport.TLSInfo
  45. OutputFormat string
  46. IsHex bool
  47. User string
  48. Debug bool
  49. }
  50. type secureCfg struct {
  51. cert string
  52. key string
  53. cacert string
  54. serverName string
  55. insecureTransport bool
  56. insecureSkipVerify bool
  57. }
  58. type authCfg struct {
  59. username string
  60. password string
  61. }
  62. type discoveryCfg struct {
  63. domain string
  64. insecure bool
  65. }
  66. var display printer = &simplePrinter{}
  67. func initDisplayFromCmd(cmd *cobra.Command) {
  68. isHex, err := cmd.Flags().GetBool("hex")
  69. if err != nil {
  70. ExitWithError(ExitError, err)
  71. }
  72. outputType, err := cmd.Flags().GetString("write-out")
  73. if err != nil {
  74. ExitWithError(ExitError, err)
  75. }
  76. if display = NewPrinter(outputType, isHex); display == nil {
  77. ExitWithError(ExitBadFeature, errors.New("unsupported output format"))
  78. }
  79. }
  80. type clientConfig struct {
  81. endpoints []string
  82. dialTimeout time.Duration
  83. keepAliveTime time.Duration
  84. keepAliveTimeout time.Duration
  85. scfg *secureCfg
  86. acfg *authCfg
  87. }
  88. type discardValue struct{}
  89. func (*discardValue) String() string { return "" }
  90. func (*discardValue) Set(string) error { return nil }
  91. func (*discardValue) Type() string { return "" }
  92. func clientConfigFromCmd(cmd *cobra.Command) *clientConfig {
  93. fs := cmd.InheritedFlags()
  94. if strings.HasPrefix(cmd.Use, "watch") {
  95. // silence "pkg/flags: unrecognized environment variable ETCDCTL_WATCH_KEY=foo" warnings
  96. // silence "pkg/flags: unrecognized environment variable ETCDCTL_WATCH_RANGE_END=bar" warnings
  97. fs.AddFlag(&pflag.Flag{Name: "watch-key", Value: &discardValue{}})
  98. fs.AddFlag(&pflag.Flag{Name: "watch-range-end", Value: &discardValue{}})
  99. }
  100. flags.SetPflagsFromEnv("ETCDCTL", fs)
  101. debug, err := cmd.Flags().GetBool("debug")
  102. if err != nil {
  103. ExitWithError(ExitError, err)
  104. }
  105. if debug {
  106. clientv3.SetLogger(grpclog.NewLoggerV2WithVerbosity(os.Stderr, os.Stderr, os.Stderr, 4))
  107. fs.VisitAll(func(f *pflag.Flag) {
  108. fmt.Fprintf(os.Stderr, "%s=%v\n", flags.FlagToEnv("ETCDCTL", f.Name), f.Value)
  109. })
  110. } else {
  111. clientv3.SetLogger(grpclog.NewLoggerV2(ioutil.Discard, ioutil.Discard, ioutil.Discard))
  112. }
  113. cfg := &clientConfig{}
  114. cfg.endpoints, err = endpointsFromCmd(cmd)
  115. if err != nil {
  116. ExitWithError(ExitError, err)
  117. }
  118. cfg.dialTimeout = dialTimeoutFromCmd(cmd)
  119. cfg.keepAliveTime = keepAliveTimeFromCmd(cmd)
  120. cfg.keepAliveTimeout = keepAliveTimeoutFromCmd(cmd)
  121. cfg.scfg = secureCfgFromCmd(cmd)
  122. cfg.acfg = authCfgFromCmd(cmd)
  123. initDisplayFromCmd(cmd)
  124. return cfg
  125. }
  126. func mustClientFromCmd(cmd *cobra.Command) *clientv3.Client {
  127. cfg := clientConfigFromCmd(cmd)
  128. return cfg.mustClient()
  129. }
  130. func (cc *clientConfig) mustClient() *clientv3.Client {
  131. cfg, err := newClientCfg(cc.endpoints, cc.dialTimeout, cc.keepAliveTime, cc.keepAliveTimeout, cc.scfg, cc.acfg)
  132. if err != nil {
  133. ExitWithError(ExitBadArgs, err)
  134. }
  135. client, err := clientv3.New(*cfg)
  136. if err != nil {
  137. ExitWithError(ExitBadConnection, err)
  138. }
  139. return client
  140. }
  141. func newClientCfg(endpoints []string, dialTimeout, keepAliveTime, keepAliveTimeout time.Duration, scfg *secureCfg, acfg *authCfg) (*clientv3.Config, error) {
  142. // set tls if any one tls option set
  143. var cfgtls *transport.TLSInfo
  144. tlsinfo := transport.TLSInfo{}
  145. if scfg.cert != "" {
  146. tlsinfo.CertFile = scfg.cert
  147. cfgtls = &tlsinfo
  148. }
  149. if scfg.key != "" {
  150. tlsinfo.KeyFile = scfg.key
  151. cfgtls = &tlsinfo
  152. }
  153. if scfg.cacert != "" {
  154. tlsinfo.CAFile = scfg.cacert
  155. cfgtls = &tlsinfo
  156. }
  157. if scfg.serverName != "" {
  158. tlsinfo.ServerName = scfg.serverName
  159. cfgtls = &tlsinfo
  160. }
  161. cfg := &clientv3.Config{
  162. Endpoints: endpoints,
  163. DialTimeout: dialTimeout,
  164. DialKeepAliveTime: keepAliveTime,
  165. DialKeepAliveTimeout: keepAliveTimeout,
  166. }
  167. if cfgtls != nil {
  168. clientTLS, err := cfgtls.ClientConfig()
  169. if err != nil {
  170. return nil, err
  171. }
  172. cfg.TLS = clientTLS
  173. }
  174. // if key/cert is not given but user wants secure connection, we
  175. // should still setup an empty tls configuration for gRPC to setup
  176. // secure connection.
  177. if cfg.TLS == nil && !scfg.insecureTransport {
  178. cfg.TLS = &tls.Config{}
  179. }
  180. // If the user wants to skip TLS verification then we should set
  181. // the InsecureSkipVerify flag in tls configuration.
  182. if scfg.insecureSkipVerify && cfg.TLS != nil {
  183. cfg.TLS.InsecureSkipVerify = true
  184. }
  185. if acfg != nil {
  186. cfg.Username = acfg.username
  187. cfg.Password = acfg.password
  188. }
  189. return cfg, nil
  190. }
  191. func argOrStdin(args []string, stdin io.Reader, i int) (string, error) {
  192. if i < len(args) {
  193. return args[i], nil
  194. }
  195. bytes, err := ioutil.ReadAll(stdin)
  196. if string(bytes) == "" || err != nil {
  197. return "", errors.New("no available argument and stdin")
  198. }
  199. return string(bytes), nil
  200. }
  201. func dialTimeoutFromCmd(cmd *cobra.Command) time.Duration {
  202. dialTimeout, err := cmd.Flags().GetDuration("dial-timeout")
  203. if err != nil {
  204. ExitWithError(ExitError, err)
  205. }
  206. return dialTimeout
  207. }
  208. func keepAliveTimeFromCmd(cmd *cobra.Command) time.Duration {
  209. keepAliveTime, err := cmd.Flags().GetDuration("keepalive-time")
  210. if err != nil {
  211. ExitWithError(ExitError, err)
  212. }
  213. return keepAliveTime
  214. }
  215. func keepAliveTimeoutFromCmd(cmd *cobra.Command) time.Duration {
  216. keepAliveTimeout, err := cmd.Flags().GetDuration("keepalive-timeout")
  217. if err != nil {
  218. ExitWithError(ExitError, err)
  219. }
  220. return keepAliveTimeout
  221. }
  222. func secureCfgFromCmd(cmd *cobra.Command) *secureCfg {
  223. cert, key, cacert := keyAndCertFromCmd(cmd)
  224. insecureTr := insecureTransportFromCmd(cmd)
  225. skipVerify := insecureSkipVerifyFromCmd(cmd)
  226. discoveryCfg := discoveryCfgFromCmd(cmd)
  227. if discoveryCfg.insecure {
  228. discoveryCfg.domain = ""
  229. }
  230. return &secureCfg{
  231. cert: cert,
  232. key: key,
  233. cacert: cacert,
  234. serverName: discoveryCfg.domain,
  235. insecureTransport: insecureTr,
  236. insecureSkipVerify: skipVerify,
  237. }
  238. }
  239. func insecureTransportFromCmd(cmd *cobra.Command) bool {
  240. insecureTr, err := cmd.Flags().GetBool("insecure-transport")
  241. if err != nil {
  242. ExitWithError(ExitError, err)
  243. }
  244. return insecureTr
  245. }
  246. func insecureSkipVerifyFromCmd(cmd *cobra.Command) bool {
  247. skipVerify, err := cmd.Flags().GetBool("insecure-skip-tls-verify")
  248. if err != nil {
  249. ExitWithError(ExitError, err)
  250. }
  251. return skipVerify
  252. }
  253. func keyAndCertFromCmd(cmd *cobra.Command) (cert, key, cacert string) {
  254. var err error
  255. if cert, err = cmd.Flags().GetString("cert"); err != nil {
  256. ExitWithError(ExitBadArgs, err)
  257. } else if cert == "" && cmd.Flags().Changed("cert") {
  258. ExitWithError(ExitBadArgs, errors.New("empty string is passed to --cert option"))
  259. }
  260. if key, err = cmd.Flags().GetString("key"); err != nil {
  261. ExitWithError(ExitBadArgs, err)
  262. } else if key == "" && cmd.Flags().Changed("key") {
  263. ExitWithError(ExitBadArgs, errors.New("empty string is passed to --key option"))
  264. }
  265. if cacert, err = cmd.Flags().GetString("cacert"); err != nil {
  266. ExitWithError(ExitBadArgs, err)
  267. } else if cacert == "" && cmd.Flags().Changed("cacert") {
  268. ExitWithError(ExitBadArgs, errors.New("empty string is passed to --cacert option"))
  269. }
  270. return cert, key, cacert
  271. }
  272. func authCfgFromCmd(cmd *cobra.Command) *authCfg {
  273. userFlag, err := cmd.Flags().GetString("user")
  274. if err != nil {
  275. ExitWithError(ExitBadArgs, err)
  276. }
  277. if userFlag == "" {
  278. return nil
  279. }
  280. var cfg authCfg
  281. splitted := strings.SplitN(userFlag, ":", 2)
  282. if len(splitted) < 2 {
  283. cfg.username = userFlag
  284. cfg.password, err = speakeasy.Ask("Password: ")
  285. if err != nil {
  286. ExitWithError(ExitError, err)
  287. }
  288. } else {
  289. cfg.username = splitted[0]
  290. cfg.password = splitted[1]
  291. }
  292. return &cfg
  293. }
  294. func insecureDiscoveryFromCmd(cmd *cobra.Command) bool {
  295. discovery, err := cmd.Flags().GetBool("insecure-discovery")
  296. if err != nil {
  297. ExitWithError(ExitError, err)
  298. }
  299. return discovery
  300. }
  301. func discoverySrvFromCmd(cmd *cobra.Command) string {
  302. domainStr, err := cmd.Flags().GetString("discovery-srv")
  303. if err != nil {
  304. ExitWithError(ExitBadArgs, err)
  305. }
  306. return domainStr
  307. }
  308. func discoveryCfgFromCmd(cmd *cobra.Command) *discoveryCfg {
  309. return &discoveryCfg{
  310. domain: discoverySrvFromCmd(cmd),
  311. insecure: insecureDiscoveryFromCmd(cmd),
  312. }
  313. }
  314. func endpointsFromCmd(cmd *cobra.Command) ([]string, error) {
  315. eps, err := endpointsFromFlagValue(cmd)
  316. if err != nil {
  317. return nil, err
  318. }
  319. // If domain discovery returns no endpoints, check endpoints flag
  320. if len(eps) == 0 {
  321. eps, err = cmd.Flags().GetStringSlice("endpoints")
  322. }
  323. return eps, err
  324. }
  325. func endpointsFromFlagValue(cmd *cobra.Command) ([]string, error) {
  326. discoveryCfg := discoveryCfgFromCmd(cmd)
  327. // If we still don't have domain discovery, return nothing
  328. if discoveryCfg.domain == "" {
  329. return []string{}, nil
  330. }
  331. srvs, err := srv.GetClient("etcd-client", discoveryCfg.domain)
  332. if err != nil {
  333. return nil, err
  334. }
  335. eps := srvs.Endpoints
  336. if discoveryCfg.insecure {
  337. return eps, err
  338. }
  339. // strip insecure connections
  340. ret := []string{}
  341. for _, ep := range eps {
  342. if strings.HasPrefix(ep, "http://") {
  343. fmt.Fprintf(os.Stderr, "ignoring discovered insecure endpoint %q\n", ep)
  344. continue
  345. }
  346. ret = append(ret, ep)
  347. }
  348. return ret, err
  349. }