config.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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. // Every change should be reflected on help.go as well.
  15. package etcdmain
  16. import (
  17. "flag"
  18. "fmt"
  19. "io/ioutil"
  20. "net/url"
  21. "os"
  22. "runtime"
  23. "strings"
  24. "github.com/coreos/etcd/embed"
  25. "github.com/coreos/etcd/pkg/flags"
  26. "github.com/coreos/etcd/pkg/types"
  27. "github.com/coreos/etcd/version"
  28. "sigs.k8s.io/yaml"
  29. )
  30. var (
  31. proxyFlagOff = "off"
  32. proxyFlagReadonly = "readonly"
  33. proxyFlagOn = "on"
  34. fallbackFlagExit = "exit"
  35. fallbackFlagProxy = "proxy"
  36. ignored = []string{
  37. "cluster-active-size",
  38. "cluster-remove-delay",
  39. "cluster-sync-interval",
  40. "config",
  41. "force",
  42. "max-result-buffer",
  43. "max-retry-attempts",
  44. "peer-heartbeat-interval",
  45. "peer-election-timeout",
  46. "retry-interval",
  47. "snapshot",
  48. "v",
  49. "vv",
  50. // for coverage testing
  51. "test.coverprofile",
  52. "test.outputdir",
  53. }
  54. )
  55. type configProxy struct {
  56. ProxyFailureWaitMs uint `json:"proxy-failure-wait"`
  57. ProxyRefreshIntervalMs uint `json:"proxy-refresh-interval"`
  58. ProxyDialTimeoutMs uint `json:"proxy-dial-timeout"`
  59. ProxyWriteTimeoutMs uint `json:"proxy-write-timeout"`
  60. ProxyReadTimeoutMs uint `json:"proxy-read-timeout"`
  61. Fallback string
  62. Proxy string
  63. ProxyJSON string `json:"proxy"`
  64. FallbackJSON string `json:"discovery-fallback"`
  65. }
  66. // config holds the config for a command line invocation of etcd
  67. type config struct {
  68. ec embed.Config
  69. cp configProxy
  70. cf configFlags
  71. configFile string
  72. printVersion bool
  73. ignored []string
  74. }
  75. // configFlags has the set of flags used for command line parsing a Config
  76. type configFlags struct {
  77. flagSet *flag.FlagSet
  78. clusterState *flags.StringsFlag
  79. fallback *flags.StringsFlag
  80. proxy *flags.StringsFlag
  81. }
  82. func newConfig() *config {
  83. cfg := &config{
  84. ec: *embed.NewConfig(),
  85. cp: configProxy{
  86. Proxy: proxyFlagOff,
  87. ProxyFailureWaitMs: 5000,
  88. ProxyRefreshIntervalMs: 30000,
  89. ProxyDialTimeoutMs: 1000,
  90. ProxyWriteTimeoutMs: 5000,
  91. },
  92. ignored: ignored,
  93. }
  94. cfg.cf = configFlags{
  95. flagSet: flag.NewFlagSet("etcd", flag.ContinueOnError),
  96. clusterState: flags.NewStringsFlag(
  97. embed.ClusterStateFlagNew,
  98. embed.ClusterStateFlagExisting,
  99. ),
  100. fallback: flags.NewStringsFlag(
  101. fallbackFlagProxy,
  102. fallbackFlagExit,
  103. ),
  104. proxy: flags.NewStringsFlag(
  105. proxyFlagOff,
  106. proxyFlagReadonly,
  107. proxyFlagOn,
  108. ),
  109. }
  110. fs := cfg.cf.flagSet
  111. fs.Usage = func() {
  112. fmt.Fprintln(os.Stderr, usageline)
  113. }
  114. fs.StringVar(&cfg.configFile, "config-file", "", "Path to the server configuration file")
  115. // member
  116. fs.Var(cfg.ec.CorsInfo, "cors", "Comma-separated white list of origins for CORS (cross-origin resource sharing).")
  117. fs.StringVar(&cfg.ec.Dir, "data-dir", cfg.ec.Dir, "Path to the data directory.")
  118. fs.StringVar(&cfg.ec.WalDir, "wal-dir", cfg.ec.WalDir, "Path to the dedicated wal directory.")
  119. fs.Var(flags.NewURLsValue(embed.DefaultListenPeerURLs), "listen-peer-urls", "List of URLs to listen on for peer traffic.")
  120. fs.Var(flags.NewURLsValue(embed.DefaultListenClientURLs), "listen-client-urls", "List of URLs to listen on for client traffic.")
  121. fs.StringVar(&cfg.ec.ListenMetricsUrlsJSON, "listen-metrics-urls", "", "List of URLs to listen on for metrics.")
  122. fs.UintVar(&cfg.ec.MaxSnapFiles, "max-snapshots", cfg.ec.MaxSnapFiles, "Maximum number of snapshot files to retain (0 is unlimited).")
  123. fs.UintVar(&cfg.ec.MaxWalFiles, "max-wals", cfg.ec.MaxWalFiles, "Maximum number of wal files to retain (0 is unlimited).")
  124. fs.StringVar(&cfg.ec.Name, "name", cfg.ec.Name, "Human-readable name for this member.")
  125. fs.Uint64Var(&cfg.ec.SnapCount, "snapshot-count", cfg.ec.SnapCount, "Number of committed transactions to trigger a snapshot to disk.")
  126. fs.UintVar(&cfg.ec.TickMs, "heartbeat-interval", cfg.ec.TickMs, "Time (in milliseconds) of a heartbeat interval.")
  127. fs.UintVar(&cfg.ec.ElectionMs, "election-timeout", cfg.ec.ElectionMs, "Time (in milliseconds) for an election to timeout.")
  128. fs.BoolVar(&cfg.ec.InitialElectionTickAdvance, "initial-election-tick-advance", cfg.ec.InitialElectionTickAdvance, "Whether to fast-forward initial election ticks on boot for faster election.")
  129. fs.Int64Var(&cfg.ec.QuotaBackendBytes, "quota-backend-bytes", cfg.ec.QuotaBackendBytes, "Raise alarms when backend size exceeds the given quota. 0 means use the default quota.")
  130. fs.UintVar(&cfg.ec.MaxTxnOps, "max-txn-ops", cfg.ec.MaxTxnOps, "Maximum number of operations permitted in a transaction.")
  131. fs.UintVar(&cfg.ec.MaxRequestBytes, "max-request-bytes", cfg.ec.MaxRequestBytes, "Maximum client request size in bytes the server will accept.")
  132. fs.DurationVar(&cfg.ec.GRPCKeepAliveMinTime, "grpc-keepalive-min-time", cfg.ec.GRPCKeepAliveMinTime, "Minimum interval duration that a client should wait before pinging server.")
  133. fs.DurationVar(&cfg.ec.GRPCKeepAliveInterval, "grpc-keepalive-interval", cfg.ec.GRPCKeepAliveInterval, "Frequency duration of server-to-client ping to check if a connection is alive (0 to disable).")
  134. fs.DurationVar(&cfg.ec.GRPCKeepAliveTimeout, "grpc-keepalive-timeout", cfg.ec.GRPCKeepAliveTimeout, "Additional duration of wait before closing a non-responsive connection (0 to disable).")
  135. // clustering
  136. fs.Var(flags.NewURLsValue(embed.DefaultInitialAdvertisePeerURLs), "initial-advertise-peer-urls", "List of this member's peer URLs to advertise to the rest of the cluster.")
  137. fs.Var(flags.NewURLsValue(embed.DefaultAdvertiseClientURLs), "advertise-client-urls", "List of this member's client URLs to advertise to the public.")
  138. fs.StringVar(&cfg.ec.Durl, "discovery", cfg.ec.Durl, "Discovery URL used to bootstrap the cluster.")
  139. fs.Var(cfg.cf.fallback, "discovery-fallback", fmt.Sprintf("Valid values include %s", strings.Join(cfg.cf.fallback.Values, ", ")))
  140. fs.StringVar(&cfg.ec.Dproxy, "discovery-proxy", cfg.ec.Dproxy, "HTTP proxy to use for traffic to discovery service.")
  141. fs.StringVar(&cfg.ec.DNSCluster, "discovery-srv", cfg.ec.DNSCluster, "DNS domain used to bootstrap initial cluster.")
  142. fs.StringVar(&cfg.ec.InitialCluster, "initial-cluster", cfg.ec.InitialCluster, "Initial cluster configuration for bootstrapping.")
  143. fs.StringVar(&cfg.ec.InitialClusterToken, "initial-cluster-token", cfg.ec.InitialClusterToken, "Initial cluster token for the etcd cluster during bootstrap.")
  144. fs.Var(cfg.cf.clusterState, "initial-cluster-state", "Initial cluster state ('new' or 'existing').")
  145. fs.BoolVar(&cfg.ec.StrictReconfigCheck, "strict-reconfig-check", cfg.ec.StrictReconfigCheck, "Reject reconfiguration requests that would cause quorum loss.")
  146. fs.BoolVar(&cfg.ec.EnableV2, "enable-v2", cfg.ec.EnableV2, "Accept etcd V2 client requests.")
  147. fs.StringVar(&cfg.ec.ExperimentalEnableV2V3, "experimental-enable-v2v3", cfg.ec.ExperimentalEnableV2V3, "v3 prefix for serving emulated v2 state.")
  148. // proxy
  149. fs.Var(cfg.cf.proxy, "proxy", fmt.Sprintf("Valid values include %s", strings.Join(cfg.cf.proxy.Values, ", ")))
  150. fs.UintVar(&cfg.cp.ProxyFailureWaitMs, "proxy-failure-wait", cfg.cp.ProxyFailureWaitMs, "Time (in milliseconds) an endpoint will be held in a failed state.")
  151. fs.UintVar(&cfg.cp.ProxyRefreshIntervalMs, "proxy-refresh-interval", cfg.cp.ProxyRefreshIntervalMs, "Time (in milliseconds) of the endpoints refresh interval.")
  152. fs.UintVar(&cfg.cp.ProxyDialTimeoutMs, "proxy-dial-timeout", cfg.cp.ProxyDialTimeoutMs, "Time (in milliseconds) for a dial to timeout.")
  153. fs.UintVar(&cfg.cp.ProxyWriteTimeoutMs, "proxy-write-timeout", cfg.cp.ProxyWriteTimeoutMs, "Time (in milliseconds) for a write to timeout.")
  154. fs.UintVar(&cfg.cp.ProxyReadTimeoutMs, "proxy-read-timeout", cfg.cp.ProxyReadTimeoutMs, "Time (in milliseconds) for a read to timeout.")
  155. // security
  156. fs.StringVar(&cfg.ec.ClientTLSInfo.CAFile, "ca-file", "", "DEPRECATED: Path to the client server TLS CA file.")
  157. fs.StringVar(&cfg.ec.ClientTLSInfo.CertFile, "cert-file", "", "Path to the client server TLS cert file.")
  158. fs.StringVar(&cfg.ec.ClientTLSInfo.KeyFile, "key-file", "", "Path to the client server TLS key file.")
  159. fs.BoolVar(&cfg.ec.ClientTLSInfo.ClientCertAuth, "client-cert-auth", false, "Enable client cert authentication.")
  160. fs.StringVar(&cfg.ec.ClientTLSInfo.CRLFile, "client-crl-file", "", "Path to the client certificate revocation list file.")
  161. fs.StringVar(&cfg.ec.ClientTLSInfo.TrustedCAFile, "trusted-ca-file", "", "Path to the client server TLS trusted CA cert file.")
  162. fs.BoolVar(&cfg.ec.ClientAutoTLS, "auto-tls", false, "Client TLS using generated certificates")
  163. fs.StringVar(&cfg.ec.PeerTLSInfo.CAFile, "peer-ca-file", "", "DEPRECATED: Path to the peer server TLS CA file.")
  164. fs.StringVar(&cfg.ec.PeerTLSInfo.CertFile, "peer-cert-file", "", "Path to the peer server TLS cert file.")
  165. fs.StringVar(&cfg.ec.PeerTLSInfo.KeyFile, "peer-key-file", "", "Path to the peer server TLS key file.")
  166. fs.BoolVar(&cfg.ec.PeerTLSInfo.ClientCertAuth, "peer-client-cert-auth", false, "Enable peer client cert authentication.")
  167. fs.StringVar(&cfg.ec.PeerTLSInfo.TrustedCAFile, "peer-trusted-ca-file", "", "Path to the peer server TLS trusted CA file.")
  168. fs.BoolVar(&cfg.ec.PeerAutoTLS, "peer-auto-tls", false, "Peer TLS using generated certificates")
  169. fs.StringVar(&cfg.ec.PeerTLSInfo.CRLFile, "peer-crl-file", "", "Path to the peer certificate revocation list file.")
  170. fs.StringVar(&cfg.ec.PeerTLSInfo.AllowedCN, "peer-cert-allowed-cn", "", "Allowed CN for inter peer authentication.")
  171. fs.Var(flags.NewStringsValueV2(""), "cipher-suites", "Comma-separated list of supported TLS cipher suites between client/server and peers (empty will be auto-populated by Go).")
  172. // logging
  173. fs.BoolVar(&cfg.ec.Debug, "debug", false, "Enable debug-level logging for etcd.")
  174. fs.StringVar(&cfg.ec.LogPkgLevels, "log-package-levels", "", "Specify a particular log level for each etcd package (eg: 'etcdmain=CRITICAL,etcdserver=DEBUG').")
  175. fs.StringVar(&cfg.ec.LogOutput, "log-output", embed.DefaultLogOutput, "Specify 'stdout' or 'stderr' to skip journald logging even when running under systemd.")
  176. // unsafe
  177. fs.BoolVar(&cfg.ec.ForceNewCluster, "force-new-cluster", false, "Force to create a new one member cluster.")
  178. // version
  179. fs.BoolVar(&cfg.printVersion, "version", false, "Print the version and exit.")
  180. fs.StringVar(&cfg.ec.AutoCompactionRetention, "auto-compaction-retention", "0", "Auto compaction retention for mvcc key value store. 0 means disable auto compaction.")
  181. fs.StringVar(&cfg.ec.AutoCompactionMode, "auto-compaction-mode", "periodic", "interpret 'auto-compaction-retention' one of: periodic|revision. 'periodic' for duration based retention, defaulting to hours if no time unit is provided (e.g. '5m'). 'revision' for revision number based retention.")
  182. // pprof profiler via HTTP
  183. fs.BoolVar(&cfg.ec.EnablePprof, "enable-pprof", false, "Enable runtime profiling data via HTTP server. Address is at client URL + \"/debug/pprof/\"")
  184. // additional metrics
  185. fs.StringVar(&cfg.ec.Metrics, "metrics", cfg.ec.Metrics, "Set level of detail for exported metrics, specify 'extensive' to include histogram metrics")
  186. // auth
  187. fs.StringVar(&cfg.ec.AuthToken, "auth-token", cfg.ec.AuthToken, "Specify auth token specific options.")
  188. // experimental
  189. fs.BoolVar(&cfg.ec.ExperimentalInitialCorruptCheck, "experimental-initial-corrupt-check", cfg.ec.ExperimentalInitialCorruptCheck, "Enable to check data corruption before serving any client/peer traffic.")
  190. fs.DurationVar(&cfg.ec.ExperimentalCorruptCheckTime, "experimental-corrupt-check-time", cfg.ec.ExperimentalCorruptCheckTime, "Duration of time between cluster corruption check passes.")
  191. // ignored
  192. for _, f := range cfg.ignored {
  193. fs.Var(&flags.IgnoredFlag{Name: f}, f, "")
  194. }
  195. return cfg
  196. }
  197. func (cfg *config) parse(arguments []string) error {
  198. perr := cfg.cf.flagSet.Parse(arguments)
  199. switch perr {
  200. case nil:
  201. case flag.ErrHelp:
  202. fmt.Println(flagsline)
  203. os.Exit(0)
  204. default:
  205. os.Exit(2)
  206. }
  207. if len(cfg.cf.flagSet.Args()) != 0 {
  208. return fmt.Errorf("'%s' is not a valid flag", cfg.cf.flagSet.Arg(0))
  209. }
  210. if cfg.printVersion {
  211. fmt.Printf("etcd Version: %s\n", version.Version)
  212. fmt.Printf("Git SHA: %s\n", version.GitSHA)
  213. fmt.Printf("Go Version: %s\n", runtime.Version())
  214. fmt.Printf("Go OS/Arch: %s/%s\n", runtime.GOOS, runtime.GOARCH)
  215. os.Exit(0)
  216. }
  217. var err error
  218. if cfg.configFile != "" {
  219. plog.Infof("Loading server configuration from %q", cfg.configFile)
  220. err = cfg.configFromFile(cfg.configFile)
  221. } else {
  222. err = cfg.configFromCmdLine()
  223. }
  224. return err
  225. }
  226. func (cfg *config) configFromCmdLine() error {
  227. err := flags.SetFlagsFromEnv("ETCD", cfg.cf.flagSet)
  228. if err != nil {
  229. plog.Fatalf("%v", err)
  230. }
  231. cfg.ec.LPUrls = flags.URLsFromFlag(cfg.cf.flagSet, "listen-peer-urls")
  232. cfg.ec.APUrls = flags.URLsFromFlag(cfg.cf.flagSet, "initial-advertise-peer-urls")
  233. cfg.ec.LCUrls = flags.URLsFromFlag(cfg.cf.flagSet, "listen-client-urls")
  234. cfg.ec.ACUrls = flags.URLsFromFlag(cfg.cf.flagSet, "advertise-client-urls")
  235. if len(cfg.ec.ListenMetricsUrlsJSON) > 0 {
  236. u, err := types.NewURLs(strings.Split(cfg.ec.ListenMetricsUrlsJSON, ","))
  237. if err != nil {
  238. plog.Fatalf("unexpected error setting up listen-metrics-urls: %v", err)
  239. }
  240. cfg.ec.ListenMetricsUrls = []url.URL(u)
  241. }
  242. cfg.ec.CipherSuites = flags.StringsFromFlagV2(cfg.cf.flagSet, "cipher-suites")
  243. cfg.ec.ClusterState = cfg.cf.clusterState.String()
  244. cfg.cp.Fallback = cfg.cf.fallback.String()
  245. cfg.cp.Proxy = cfg.cf.proxy.String()
  246. // disable default advertise-client-urls if lcurls is set
  247. missingAC := flags.IsSet(cfg.cf.flagSet, "listen-client-urls") && !flags.IsSet(cfg.cf.flagSet, "advertise-client-urls")
  248. if !cfg.mayBeProxy() && missingAC {
  249. cfg.ec.ACUrls = nil
  250. }
  251. // disable default initial-cluster if discovery is set
  252. if (cfg.ec.Durl != "" || cfg.ec.DNSCluster != "") && !flags.IsSet(cfg.cf.flagSet, "initial-cluster") {
  253. cfg.ec.InitialCluster = ""
  254. }
  255. return cfg.validate()
  256. }
  257. func (cfg *config) configFromFile(path string) error {
  258. eCfg, err := embed.ConfigFromFile(path)
  259. if err != nil {
  260. return err
  261. }
  262. cfg.ec = *eCfg
  263. // load extra config information
  264. b, rerr := ioutil.ReadFile(path)
  265. if rerr != nil {
  266. return rerr
  267. }
  268. if yerr := yaml.Unmarshal(b, &cfg.cp); yerr != nil {
  269. return yerr
  270. }
  271. if cfg.cp.FallbackJSON != "" {
  272. if err := cfg.cf.fallback.Set(cfg.cp.FallbackJSON); err != nil {
  273. plog.Panicf("unexpected error setting up discovery-fallback flag: %v", err)
  274. }
  275. cfg.cp.Fallback = cfg.cf.fallback.String()
  276. }
  277. if cfg.cp.ProxyJSON != "" {
  278. if err := cfg.cf.proxy.Set(cfg.cp.ProxyJSON); err != nil {
  279. plog.Panicf("unexpected error setting up proxyFlag: %v", err)
  280. }
  281. cfg.cp.Proxy = cfg.cf.proxy.String()
  282. }
  283. return nil
  284. }
  285. func (cfg *config) mayBeProxy() bool {
  286. mayFallbackToProxy := cfg.ec.Durl != "" && cfg.cp.Fallback == fallbackFlagProxy
  287. return cfg.cp.Proxy != proxyFlagOff || mayFallbackToProxy
  288. }
  289. func (cfg *config) validate() error {
  290. err := cfg.ec.Validate()
  291. // TODO(yichengq): check this for joining through discovery service case
  292. if err == embed.ErrUnsetAdvertiseClientURLsFlag && cfg.mayBeProxy() {
  293. return nil
  294. }
  295. return err
  296. }
  297. func (cfg config) isProxy() bool { return cfg.cf.proxy.String() != proxyFlagOff }
  298. func (cfg config) isReadonlyProxy() bool { return cfg.cf.proxy.String() == proxyFlagReadonly }
  299. func (cfg config) shouldFallbackToProxy() bool { return cfg.cf.fallback.String() == fallbackFlagProxy }