config.go 10 KB

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