config.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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. )
  38. var (
  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. }
  54. ErrConflictBootstrapFlags = fmt.Errorf("multiple discovery or bootstrap flags are set" +
  55. "Choose one of \"initial-cluster\", \"discovery\" or \"discovery-srv\"")
  56. errUnsetAdvertiseClientURLsFlag = fmt.Errorf("-advertise-client-urls is required when -listen-client-urls is set explicitly")
  57. )
  58. type config struct {
  59. *flag.FlagSet
  60. // member
  61. corsInfo *cors.CORSInfo
  62. dir string
  63. lpurls, lcurls []url.URL
  64. maxSnapFiles uint
  65. maxWalFiles uint
  66. name string
  67. snapCount uint64
  68. // TODO: decouple tickMs and heartbeat tick (current heartbeat tick = 1).
  69. // make ticks a cluster wide configuration.
  70. TickMs uint
  71. ElectionMs uint
  72. // clustering
  73. apurls, acurls []url.URL
  74. clusterState *flags.StringsFlag
  75. dnsCluster string
  76. dproxy string
  77. durl string
  78. fallback *flags.StringsFlag
  79. initialCluster string
  80. initialClusterToken string
  81. // proxy
  82. proxy *flags.StringsFlag
  83. // security
  84. clientTLSInfo, peerTLSInfo transport.TLSInfo
  85. // logging
  86. debug bool
  87. logPkgLevels string
  88. // unsafe
  89. forceNewCluster bool
  90. printVersion bool
  91. ignored []string
  92. }
  93. func NewConfig() *config {
  94. cfg := &config{
  95. corsInfo: &cors.CORSInfo{},
  96. clusterState: flags.NewStringsFlag(
  97. clusterStateFlagNew,
  98. clusterStateFlagExisting,
  99. ),
  100. fallback: flags.NewStringsFlag(
  101. fallbackFlagExit,
  102. fallbackFlagProxy,
  103. ),
  104. ignored: ignored,
  105. proxy: flags.NewStringsFlag(
  106. proxyFlagOff,
  107. proxyFlagReadonly,
  108. proxyFlagOn,
  109. ),
  110. }
  111. cfg.FlagSet = flag.NewFlagSet("etcd", flag.ContinueOnError)
  112. fs := cfg.FlagSet
  113. fs.Usage = func() {
  114. fmt.Println(usageline)
  115. fmt.Println(flagsline)
  116. }
  117. // member
  118. fs.Var(cfg.corsInfo, "cors", "Comma-separated white list of origins for CORS (cross-origin resource sharing).")
  119. fs.StringVar(&cfg.dir, "data-dir", "", "Path to the data directory")
  120. fs.Var(flags.NewURLsValue("http://localhost:2380,http://localhost:7001"), "listen-peer-urls", "List of URLs to listen on for peer traffic")
  121. fs.Var(flags.NewURLsValue("http://localhost:2379,http://localhost:4001"), "listen-client-urls", "List of URLs to listen on for client traffic")
  122. fs.UintVar(&cfg.maxSnapFiles, "max-snapshots", defaultMaxSnapshots, "Maximum number of snapshot files to retain (0 is unlimited)")
  123. fs.UintVar(&cfg.maxWalFiles, "max-wals", defaultMaxWALs, "Maximum number of wal files to retain (0 is unlimited)")
  124. fs.StringVar(&cfg.name, "name", defaultName, "Unique human-readable name for this node")
  125. fs.Uint64Var(&cfg.snapCount, "snapshot-count", etcdserver.DefaultSnapCount, "Number of committed transactions to trigger a snapshot")
  126. fs.UintVar(&cfg.TickMs, "heartbeat-interval", 100, "Time (in milliseconds) of a heartbeat interval.")
  127. fs.UintVar(&cfg.ElectionMs, "election-timeout", 1000, "Time (in milliseconds) for an election to timeout.")
  128. // clustering
  129. 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")
  130. 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")
  131. fs.StringVar(&cfg.durl, "discovery", "", "Discovery service used to bootstrap the initial cluster")
  132. fs.Var(cfg.fallback, "discovery-fallback", fmt.Sprintf("Valid values include %s", strings.Join(cfg.fallback.Values, ", ")))
  133. if err := cfg.fallback.Set(fallbackFlagProxy); err != nil {
  134. // Should never happen.
  135. log.Panicf("unexpected error setting up discovery-fallback flag: %v", err)
  136. }
  137. fs.StringVar(&cfg.dproxy, "discovery-proxy", "", "HTTP proxy to use for traffic to discovery service")
  138. fs.StringVar(&cfg.dnsCluster, "discovery-srv", "", "DNS domain used to bootstrap initial cluster")
  139. fs.StringVar(&cfg.initialCluster, "initial-cluster", initialClusterFromName(defaultName), "Initial cluster configuration for bootstrapping")
  140. fs.StringVar(&cfg.initialClusterToken, "initial-cluster-token", "etcd-cluster", "Initial cluster token for the etcd cluster during bootstrap")
  141. fs.Var(cfg.clusterState, "initial-cluster-state", "Initial cluster configuration for bootstrapping")
  142. if err := cfg.clusterState.Set(clusterStateFlagNew); err != nil {
  143. // Should never happen.
  144. log.Panicf("unexpected error setting up clusterStateFlag: %v", err)
  145. }
  146. // proxy
  147. fs.Var(cfg.proxy, "proxy", fmt.Sprintf("Valid values include %s", strings.Join(cfg.proxy.Values, ", ")))
  148. if err := cfg.proxy.Set(proxyFlagOff); err != nil {
  149. // Should never happen.
  150. log.Panicf("unexpected error setting up proxyFlag: %v", err)
  151. }
  152. // security
  153. fs.StringVar(&cfg.clientTLSInfo.CAFile, "ca-file", "", "DEPRECATED: Path to the client server TLS CA file.")
  154. fs.StringVar(&cfg.clientTLSInfo.CertFile, "cert-file", "", "Path to the client server TLS cert file.")
  155. fs.StringVar(&cfg.clientTLSInfo.KeyFile, "key-file", "", "Path to the client server TLS key file.")
  156. fs.BoolVar(&cfg.clientTLSInfo.ClientCertAuth, "client-cert-auth", false, "Enable client cert authentication.")
  157. fs.StringVar(&cfg.clientTLSInfo.TrustedCAFile, "trusted-ca-file", "", "Path to the client server TLS trusted CA key file.")
  158. fs.StringVar(&cfg.peerTLSInfo.CAFile, "peer-ca-file", "", "DEPRECATED: Path to the peer server TLS CA file.")
  159. fs.StringVar(&cfg.peerTLSInfo.CertFile, "peer-cert-file", "", "Path to the peer server TLS cert file.")
  160. fs.StringVar(&cfg.peerTLSInfo.KeyFile, "peer-key-file", "", "Path to the peer server TLS key file.")
  161. fs.BoolVar(&cfg.peerTLSInfo.ClientCertAuth, "peer-client-cert-auth", false, "Enable peer client cert authentication.")
  162. fs.StringVar(&cfg.peerTLSInfo.TrustedCAFile, "peer-trusted-ca-file", "", "Path to the peer server TLS trusted CA file.")
  163. // logging
  164. fs.BoolVar(&cfg.debug, "debug", false, "Enable debug output to the logs.")
  165. fs.StringVar(&cfg.logPkgLevels, "log-package-levels", "", "Specify a particular log level for each etcd package.")
  166. // unsafe
  167. fs.BoolVar(&cfg.forceNewCluster, "force-new-cluster", false, "Force to create a new one member cluster")
  168. // version
  169. fs.BoolVar(&cfg.printVersion, "version", false, "Print the version and exit")
  170. // backwards-compatibility with v0.4.6
  171. fs.Var(&flags.IPAddressPort{}, "addr", "DEPRECATED: Use -advertise-client-urls instead.")
  172. fs.Var(&flags.IPAddressPort{}, "bind-addr", "DEPRECATED: Use -listen-client-urls instead.")
  173. fs.Var(&flags.IPAddressPort{}, "peer-addr", "DEPRECATED: Use -initial-advertise-peer-urls instead.")
  174. fs.Var(&flags.IPAddressPort{}, "peer-bind-addr", "DEPRECATED: Use -listen-peer-urls instead.")
  175. fs.Var(&flags.DeprecatedFlag{Name: "peers"}, "peers", "DEPRECATED: Use -initial-cluster instead")
  176. fs.Var(&flags.DeprecatedFlag{Name: "peers-file"}, "peers-file", "DEPRECATED: Use -initial-cluster instead")
  177. // ignored
  178. for _, f := range cfg.ignored {
  179. fs.Var(&flags.IgnoredFlag{Name: f}, f, "")
  180. }
  181. return cfg
  182. }
  183. func (cfg *config) Parse(arguments []string) error {
  184. perr := cfg.FlagSet.Parse(arguments)
  185. switch perr {
  186. case nil:
  187. case flag.ErrHelp:
  188. os.Exit(0)
  189. default:
  190. os.Exit(2)
  191. }
  192. if len(cfg.FlagSet.Args()) != 0 {
  193. return fmt.Errorf("'%s' is not a valid flag", cfg.FlagSet.Arg(0))
  194. }
  195. if cfg.printVersion {
  196. fmt.Printf("etcd Version: %s\n", version.Version)
  197. fmt.Printf("Git SHA: %s\n", version.GitSHA)
  198. fmt.Printf("Go Version: %s\n", runtime.Version())
  199. fmt.Printf("Go OS/Arch: %s/%s\n", runtime.GOOS, runtime.GOARCH)
  200. os.Exit(0)
  201. }
  202. err := flags.SetFlagsFromEnv(cfg.FlagSet)
  203. if err != nil {
  204. log.Fatalf("%v", err)
  205. }
  206. set := make(map[string]bool)
  207. cfg.FlagSet.Visit(func(f *flag.Flag) {
  208. set[f.Name] = true
  209. })
  210. nSet := 0
  211. for _, v := range []bool{set["discovery"], set["initial-cluster"], set["discovery-srv"]} {
  212. if v {
  213. nSet += 1
  214. }
  215. }
  216. if nSet > 1 {
  217. return ErrConflictBootstrapFlags
  218. }
  219. flags.SetBindAddrFromAddr(cfg.FlagSet, "peer-bind-addr", "peer-addr")
  220. flags.SetBindAddrFromAddr(cfg.FlagSet, "bind-addr", "addr")
  221. cfg.lpurls, err = flags.URLsFromFlags(cfg.FlagSet, "listen-peer-urls", "peer-bind-addr", cfg.peerTLSInfo)
  222. if err != nil {
  223. return err
  224. }
  225. cfg.apurls, err = flags.URLsFromFlags(cfg.FlagSet, "initial-advertise-peer-urls", "peer-addr", cfg.peerTLSInfo)
  226. if err != nil {
  227. return err
  228. }
  229. cfg.lcurls, err = flags.URLsFromFlags(cfg.FlagSet, "listen-client-urls", "bind-addr", cfg.clientTLSInfo)
  230. if err != nil {
  231. return err
  232. }
  233. cfg.acurls, err = flags.URLsFromFlags(cfg.FlagSet, "advertise-client-urls", "addr", cfg.clientTLSInfo)
  234. if err != nil {
  235. return err
  236. }
  237. // when etcd runs in member mode user needs to set -advertise-client-urls if -listen-client-urls is set.
  238. if cfg.proxy.String() != proxyFlagOn {
  239. if flags.IsSet(cfg.FlagSet, "listen-client-urls") && !flags.IsSet(cfg.FlagSet, "advertise-client-urls") {
  240. return errUnsetAdvertiseClientURLsFlag
  241. }
  242. }
  243. if 5*cfg.TickMs > cfg.ElectionMs {
  244. return fmt.Errorf("-election-timeout[%vms] should be at least as 5 times as -heartbeat-interval[%vms]", cfg.ElectionMs, cfg.TickMs)
  245. }
  246. return nil
  247. }
  248. func initialClusterFromName(name string) string {
  249. n := name
  250. if name == "" {
  251. n = defaultName
  252. }
  253. return fmt.Sprintf("%s=http://localhost:2380,%s=http://localhost:7001", n, n)
  254. }
  255. func (cfg config) isNewCluster() bool { return cfg.clusterState.String() == clusterStateFlagNew }
  256. func (cfg config) isProxy() bool { return cfg.proxy.String() != proxyFlagOff }
  257. func (cfg config) isReadonlyProxy() bool { return cfg.proxy.String() == proxyFlagReadonly }
  258. func (cfg config) shouldFallbackToProxy() bool { return cfg.fallback.String() == fallbackFlagProxy }
  259. func (cfg config) electionTicks() int { return int(cfg.ElectionMs / cfg.TickMs) }