config.go 17 KB

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