config.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. // Every change should be reflected on help.go as well.
  15. package etcdmain
  16. import (
  17. "flag"
  18. "fmt"
  19. "net/url"
  20. "os"
  21. "runtime"
  22. "strings"
  23. "github.com/coreos/etcd/etcdserver"
  24. "github.com/coreos/etcd/pkg/cors"
  25. "github.com/coreos/etcd/pkg/flags"
  26. "github.com/coreos/etcd/pkg/transport"
  27. "github.com/coreos/etcd/version"
  28. )
  29. const (
  30. proxyFlagOff = "off"
  31. proxyFlagReadonly = "readonly"
  32. proxyFlagOn = "on"
  33. fallbackFlagExit = "exit"
  34. fallbackFlagProxy = "proxy"
  35. clusterStateFlagNew = "new"
  36. clusterStateFlagExisting = "existing"
  37. defaultName = "default"
  38. defaultInitialAdvertisePeerURLs = "http://localhost:2380,http://localhost:7001"
  39. // maxElectionMs specifies the maximum value of election timeout.
  40. // More details are listed in ../Documentation/tuning.md#time-parameters.
  41. maxElectionMs = 50000
  42. )
  43. var (
  44. ignored = []string{
  45. "cluster-active-size",
  46. "cluster-remove-delay",
  47. "cluster-sync-interval",
  48. "config",
  49. "force",
  50. "max-result-buffer",
  51. "max-retry-attempts",
  52. "peer-heartbeat-interval",
  53. "peer-election-timeout",
  54. "retry-interval",
  55. "snapshot",
  56. "v",
  57. "vv",
  58. }
  59. ErrConflictBootstrapFlags = fmt.Errorf("multiple discovery or bootstrap flags are set. " +
  60. "Choose one of \"initial-cluster\", \"discovery\" or \"discovery-srv\"")
  61. errUnsetAdvertiseClientURLsFlag = fmt.Errorf("-advertise-client-urls is required when --listen-client-urls is set explicitly")
  62. )
  63. type config struct {
  64. *flag.FlagSet
  65. // member
  66. corsInfo *cors.CORSInfo
  67. dir string
  68. walDir string
  69. lpurls, lcurls []url.URL
  70. maxSnapFiles uint
  71. maxWalFiles uint
  72. name string
  73. snapCount uint64
  74. // TickMs is the number of milliseconds between heartbeat ticks.
  75. // TODO: decouple tickMs and heartbeat tick (current heartbeat tick = 1).
  76. // make ticks a cluster wide configuration.
  77. TickMs uint
  78. ElectionMs uint
  79. quotaBackendBytes int64
  80. // clustering
  81. apurls, acurls []url.URL
  82. clusterState *flags.StringsFlag
  83. dnsCluster string
  84. dproxy string
  85. durl string
  86. fallback *flags.StringsFlag
  87. initialCluster string
  88. initialClusterToken string
  89. strictReconfigCheck bool
  90. // proxy
  91. proxy *flags.StringsFlag
  92. proxyFailureWaitMs uint
  93. proxyRefreshIntervalMs uint
  94. proxyDialTimeoutMs uint
  95. proxyWriteTimeoutMs uint
  96. proxyReadTimeoutMs uint
  97. // security
  98. clientTLSInfo, peerTLSInfo transport.TLSInfo
  99. clientAutoTLS, peerAutoTLS bool
  100. // logging
  101. debug bool
  102. logPkgLevels string
  103. // unsafe
  104. forceNewCluster bool
  105. printVersion bool
  106. autoCompactionRetention int
  107. enablePprof bool
  108. ignored []string
  109. }
  110. func NewConfig() *config {
  111. cfg := &config{
  112. corsInfo: &cors.CORSInfo{},
  113. clusterState: flags.NewStringsFlag(
  114. clusterStateFlagNew,
  115. clusterStateFlagExisting,
  116. ),
  117. fallback: flags.NewStringsFlag(
  118. fallbackFlagExit,
  119. fallbackFlagProxy,
  120. ),
  121. ignored: ignored,
  122. proxy: flags.NewStringsFlag(
  123. proxyFlagOff,
  124. proxyFlagReadonly,
  125. proxyFlagOn,
  126. ),
  127. }
  128. cfg.FlagSet = flag.NewFlagSet("etcd", flag.ContinueOnError)
  129. fs := cfg.FlagSet
  130. fs.Usage = func() {
  131. fmt.Println(usageline)
  132. }
  133. // member
  134. fs.Var(cfg.corsInfo, "cors", "Comma-separated white list of origins for CORS (cross-origin resource sharing).")
  135. fs.StringVar(&cfg.dir, "data-dir", "", "Path to the data directory.")
  136. fs.StringVar(&cfg.walDir, "wal-dir", "", "Path to the dedicated wal directory.")
  137. fs.Var(flags.NewURLsValue("http://localhost:2380,http://localhost:7001"), "listen-peer-urls", "List of URLs to listen on for peer traffic.")
  138. fs.Var(flags.NewURLsValue("http://localhost:2379,http://localhost:4001"), "listen-client-urls", "List of URLs to listen on for client traffic.")
  139. fs.UintVar(&cfg.maxSnapFiles, "max-snapshots", defaultMaxSnapshots, "Maximum number of snapshot files to retain (0 is unlimited).")
  140. fs.UintVar(&cfg.maxWalFiles, "max-wals", defaultMaxWALs, "Maximum number of wal files to retain (0 is unlimited).")
  141. fs.StringVar(&cfg.name, "name", defaultName, "Human-readable name for this member.")
  142. fs.Uint64Var(&cfg.snapCount, "snapshot-count", etcdserver.DefaultSnapCount, "Number of committed transactions to trigger a snapshot to disk.")
  143. fs.UintVar(&cfg.TickMs, "heartbeat-interval", 100, "Time (in milliseconds) of a heartbeat interval.")
  144. fs.UintVar(&cfg.ElectionMs, "election-timeout", 1000, "Time (in milliseconds) for an election to timeout.")
  145. fs.Int64Var(&cfg.quotaBackendBytes, "quota-backend-bytes", 0, "Raise alarms when backend size exceeds the given quota. 0 means use the default quota.")
  146. // clustering
  147. fs.Var(flags.NewURLsValue(defaultInitialAdvertisePeerURLs), "initial-advertise-peer-urls", "List of this member's peer URLs to advertise to the rest of the cluster.")
  148. fs.Var(flags.NewURLsValue("http://localhost:2379,http://localhost:4001"), "advertise-client-urls", "List of this member's client URLs to advertise to the public.")
  149. fs.StringVar(&cfg.durl, "discovery", "", "Discovery URL used to bootstrap the cluster.")
  150. fs.Var(cfg.fallback, "discovery-fallback", fmt.Sprintf("Valid values include %s", strings.Join(cfg.fallback.Values, ", ")))
  151. if err := cfg.fallback.Set(fallbackFlagProxy); err != nil {
  152. // Should never happen.
  153. plog.Panicf("unexpected error setting up discovery-fallback flag: %v", err)
  154. }
  155. fs.StringVar(&cfg.dproxy, "discovery-proxy", "", "HTTP proxy to use for traffic to discovery service.")
  156. fs.StringVar(&cfg.dnsCluster, "discovery-srv", "", "DNS domain used to bootstrap initial cluster.")
  157. fs.StringVar(&cfg.initialCluster, "initial-cluster", initialClusterFromName(defaultName), "Initial cluster configuration for bootstrapping.")
  158. fs.StringVar(&cfg.initialClusterToken, "initial-cluster-token", "etcd-cluster", "Initial cluster token for the etcd cluster during bootstrap.")
  159. fs.Var(cfg.clusterState, "initial-cluster-state", "Initial cluster state ('new' or 'existing').")
  160. if err := cfg.clusterState.Set(clusterStateFlagNew); err != nil {
  161. // Should never happen.
  162. plog.Panicf("unexpected error setting up clusterStateFlag: %v", err)
  163. }
  164. fs.BoolVar(&cfg.strictReconfigCheck, "strict-reconfig-check", false, "Reject reconfiguration requests that would cause quorum loss.")
  165. // proxy
  166. fs.Var(cfg.proxy, "proxy", fmt.Sprintf("Valid values include %s", strings.Join(cfg.proxy.Values, ", ")))
  167. if err := cfg.proxy.Set(proxyFlagOff); err != nil {
  168. // Should never happen.
  169. plog.Panicf("unexpected error setting up proxyFlag: %v", err)
  170. }
  171. fs.UintVar(&cfg.proxyFailureWaitMs, "proxy-failure-wait", 5000, "Time (in milliseconds) an endpoint will be held in a failed state.")
  172. fs.UintVar(&cfg.proxyRefreshIntervalMs, "proxy-refresh-interval", 30000, "Time (in milliseconds) of the endpoints refresh interval.")
  173. fs.UintVar(&cfg.proxyDialTimeoutMs, "proxy-dial-timeout", 1000, "Time (in milliseconds) for a dial to timeout.")
  174. fs.UintVar(&cfg.proxyWriteTimeoutMs, "proxy-write-timeout", 5000, "Time (in milliseconds) for a write to timeout.")
  175. fs.UintVar(&cfg.proxyReadTimeoutMs, "proxy-read-timeout", 0, "Time (in milliseconds) for a read to timeout.")
  176. // security
  177. fs.StringVar(&cfg.clientTLSInfo.CAFile, "ca-file", "", "DEPRECATED: Path to the client server TLS CA file.")
  178. fs.StringVar(&cfg.clientTLSInfo.CertFile, "cert-file", "", "Path to the client server TLS cert file.")
  179. fs.StringVar(&cfg.clientTLSInfo.KeyFile, "key-file", "", "Path to the client server TLS key file.")
  180. fs.BoolVar(&cfg.clientTLSInfo.ClientCertAuth, "client-cert-auth", false, "Enable client cert authentication.")
  181. fs.StringVar(&cfg.clientTLSInfo.TrustedCAFile, "trusted-ca-file", "", "Path to the client server TLS trusted CA key file.")
  182. fs.BoolVar(&cfg.clientAutoTLS, "auto-tls", false, "Client TLS using generated certificates")
  183. fs.StringVar(&cfg.peerTLSInfo.CAFile, "peer-ca-file", "", "DEPRECATED: Path to the peer server TLS CA file.")
  184. fs.StringVar(&cfg.peerTLSInfo.CertFile, "peer-cert-file", "", "Path to the peer server TLS cert file.")
  185. fs.StringVar(&cfg.peerTLSInfo.KeyFile, "peer-key-file", "", "Path to the peer server TLS key file.")
  186. fs.BoolVar(&cfg.peerTLSInfo.ClientCertAuth, "peer-client-cert-auth", false, "Enable peer client cert authentication.")
  187. fs.StringVar(&cfg.peerTLSInfo.TrustedCAFile, "peer-trusted-ca-file", "", "Path to the peer server TLS trusted CA file.")
  188. fs.BoolVar(&cfg.peerAutoTLS, "peer-auto-tls", false, "Peer TLS using generated certificates")
  189. // logging
  190. fs.BoolVar(&cfg.debug, "debug", false, "Enable debug-level logging for etcd.")
  191. fs.StringVar(&cfg.logPkgLevels, "log-package-levels", "", "Specify a particular log level for each etcd package (eg: 'etcdmain=CRITICAL,etcdserver=DEBUG').")
  192. // unsafe
  193. fs.BoolVar(&cfg.forceNewCluster, "force-new-cluster", false, "Force to create a new one member cluster.")
  194. // version
  195. fs.BoolVar(&cfg.printVersion, "version", false, "Print the version and exit.")
  196. // demo flag
  197. fs.IntVar(&cfg.autoCompactionRetention, "experimental-auto-compaction-retention", 0, "Auto compaction retention in hour. 0 means disable auto compaction.")
  198. // backwards-compatibility with v0.4.6
  199. fs.Var(&flags.IPAddressPort{}, "addr", "DEPRECATED: Use --advertise-client-urls instead.")
  200. fs.Var(&flags.IPAddressPort{}, "bind-addr", "DEPRECATED: Use --listen-client-urls instead.")
  201. fs.Var(&flags.IPAddressPort{}, "peer-addr", "DEPRECATED: Use --initial-advertise-peer-urls instead.")
  202. fs.Var(&flags.IPAddressPort{}, "peer-bind-addr", "DEPRECATED: Use --listen-peer-urls instead.")
  203. fs.Var(&flags.DeprecatedFlag{Name: "peers"}, "peers", "DEPRECATED: Use --initial-cluster instead.")
  204. fs.Var(&flags.DeprecatedFlag{Name: "peers-file"}, "peers-file", "DEPRECATED: Use --initial-cluster instead.")
  205. // pprof profiler via HTTP
  206. fs.BoolVar(&cfg.enablePprof, "enable-pprof", false, "Enable runtime profiling data via HTTP server. Address is at client URL + \"/debug/pprof\"")
  207. // ignored
  208. for _, f := range cfg.ignored {
  209. fs.Var(&flags.IgnoredFlag{Name: f}, f, "")
  210. }
  211. return cfg
  212. }
  213. func (cfg *config) Parse(arguments []string) error {
  214. perr := cfg.FlagSet.Parse(arguments)
  215. switch perr {
  216. case nil:
  217. case flag.ErrHelp:
  218. fmt.Println(flagsline)
  219. os.Exit(0)
  220. default:
  221. os.Exit(2)
  222. }
  223. if len(cfg.FlagSet.Args()) != 0 {
  224. return fmt.Errorf("'%s' is not a valid flag", cfg.FlagSet.Arg(0))
  225. }
  226. if cfg.printVersion {
  227. fmt.Printf("etcd Version: %s\n", version.Version)
  228. fmt.Printf("Git SHA: %s\n", version.GitSHA)
  229. fmt.Printf("Go Version: %s\n", runtime.Version())
  230. fmt.Printf("Go OS/Arch: %s/%s\n", runtime.GOOS, runtime.GOARCH)
  231. os.Exit(0)
  232. }
  233. err := flags.SetFlagsFromEnv("ETCD", cfg.FlagSet)
  234. if err != nil {
  235. plog.Fatalf("%v", err)
  236. }
  237. set := make(map[string]bool)
  238. cfg.FlagSet.Visit(func(f *flag.Flag) {
  239. set[f.Name] = true
  240. })
  241. nSet := 0
  242. for _, v := range []bool{set["discovery"], set["initial-cluster"], set["discovery-srv"]} {
  243. if v {
  244. nSet += 1
  245. }
  246. }
  247. if nSet > 1 {
  248. return ErrConflictBootstrapFlags
  249. }
  250. flags.SetBindAddrFromAddr(cfg.FlagSet, "peer-bind-addr", "peer-addr")
  251. flags.SetBindAddrFromAddr(cfg.FlagSet, "bind-addr", "addr")
  252. cfg.lpurls, err = flags.URLsFromFlags(cfg.FlagSet, "listen-peer-urls", "peer-bind-addr", cfg.peerTLSInfo)
  253. if err != nil {
  254. return err
  255. }
  256. cfg.apurls, err = flags.URLsFromFlags(cfg.FlagSet, "initial-advertise-peer-urls", "peer-addr", cfg.peerTLSInfo)
  257. if err != nil {
  258. return err
  259. }
  260. cfg.lcurls, err = flags.URLsFromFlags(cfg.FlagSet, "listen-client-urls", "bind-addr", cfg.clientTLSInfo)
  261. if err != nil {
  262. return err
  263. }
  264. cfg.acurls, err = flags.URLsFromFlags(cfg.FlagSet, "advertise-client-urls", "addr", cfg.clientTLSInfo)
  265. if err != nil {
  266. return err
  267. }
  268. // when etcd runs in member mode user needs to set --advertise-client-urls if --listen-client-urls is set.
  269. // TODO(yichengq): check this for joining through discovery service case
  270. mayFallbackToProxy := flags.IsSet(cfg.FlagSet, "discovery") && cfg.fallback.String() == fallbackFlagProxy
  271. mayBeProxy := cfg.proxy.String() != proxyFlagOff || mayFallbackToProxy
  272. if !mayBeProxy {
  273. if flags.IsSet(cfg.FlagSet, "listen-client-urls") && !flags.IsSet(cfg.FlagSet, "advertise-client-urls") {
  274. return errUnsetAdvertiseClientURLsFlag
  275. }
  276. }
  277. if 5*cfg.TickMs > cfg.ElectionMs {
  278. return fmt.Errorf("--election-timeout[%vms] should be at least as 5 times as --heartbeat-interval[%vms]", cfg.ElectionMs, cfg.TickMs)
  279. }
  280. if cfg.ElectionMs > maxElectionMs {
  281. return fmt.Errorf("--election-timeout[%vms] is too long, and should be set less than %vms", cfg.ElectionMs, maxElectionMs)
  282. }
  283. return nil
  284. }
  285. func initialClusterFromName(name string) string {
  286. n := name
  287. if name == "" {
  288. n = defaultName
  289. }
  290. return fmt.Sprintf("%s=http://localhost:2380,%s=http://localhost:7001", n, n)
  291. }
  292. func (cfg config) isNewCluster() bool { return cfg.clusterState.String() == clusterStateFlagNew }
  293. func (cfg config) isProxy() bool { return cfg.proxy.String() != proxyFlagOff }
  294. func (cfg config) isReadonlyProxy() bool { return cfg.proxy.String() == proxyFlagReadonly }
  295. func (cfg config) shouldFallbackToProxy() bool { return cfg.fallback.String() == fallbackFlagProxy }
  296. func (cfg config) electionTicks() int { return int(cfg.ElectionMs / cfg.TickMs) }