config.go 14 KB

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