config.go 13 KB

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