config.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package etcdmain
  14. import (
  15. "errors"
  16. "flag"
  17. "fmt"
  18. "log"
  19. "net/url"
  20. "os"
  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/netutil"
  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. )
  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. )
  57. type config struct {
  58. *flag.FlagSet
  59. // member
  60. corsInfo *cors.CORSInfo
  61. dir string
  62. lpurls, lcurls []url.URL
  63. maxSnapFiles uint
  64. maxWalFiles uint
  65. name string
  66. snapCount uint64
  67. // clustering
  68. apurls, acurls []url.URL
  69. clusterState *flags.StringsFlag
  70. dnsCluster string
  71. dproxy string
  72. durl string
  73. fallback *flags.StringsFlag
  74. initialCluster string
  75. initialClusterToken string
  76. // proxy
  77. proxy *flags.StringsFlag
  78. // security
  79. clientTLSInfo, peerTLSInfo transport.TLSInfo
  80. // unsafe
  81. forceNewCluster bool
  82. printVersion bool
  83. ignored []string
  84. }
  85. func NewConfig() *config {
  86. cfg := &config{
  87. corsInfo: &cors.CORSInfo{},
  88. clusterState: flags.NewStringsFlag(
  89. clusterStateFlagNew,
  90. clusterStateFlagExisting,
  91. ),
  92. fallback: flags.NewStringsFlag(
  93. fallbackFlagExit,
  94. fallbackFlagProxy,
  95. ),
  96. ignored: ignored,
  97. proxy: flags.NewStringsFlag(
  98. proxyFlagOff,
  99. proxyFlagReadonly,
  100. proxyFlagOn,
  101. ),
  102. }
  103. cfg.FlagSet = flag.NewFlagSet("etcd", flag.ContinueOnError)
  104. fs := cfg.FlagSet
  105. fs.Usage = func() {
  106. fmt.Println(usageline)
  107. fmt.Println(flagsline)
  108. }
  109. // member
  110. fs.Var(cfg.corsInfo, "cors", "Comma-separated white list of origins for CORS (cross-origin resource sharing).")
  111. fs.StringVar(&cfg.dir, "data-dir", "", "Path to the data directory")
  112. fs.Var(flags.NewURLsValue("http://localhost:2380,http://localhost:7001"), "listen-peer-urls", "List of URLs to listen on for peer traffic")
  113. fs.Var(flags.NewURLsValue("http://localhost:2379,http://localhost:4001"), "listen-client-urls", "List of URLs to listen on for client traffic")
  114. fs.UintVar(&cfg.maxSnapFiles, "max-snapshots", defaultMaxSnapshots, "Maximum number of snapshot files to retain (0 is unlimited)")
  115. fs.UintVar(&cfg.maxWalFiles, "max-wals", defaultMaxWALs, "Maximum number of wal files to retain (0 is unlimited)")
  116. fs.StringVar(&cfg.name, "name", "default", "Unique human-readable name for this node")
  117. fs.Uint64Var(&cfg.snapCount, "snapshot-count", etcdserver.DefaultSnapCount, "Number of committed transactions to trigger a snapshot")
  118. // clustering
  119. 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")
  120. 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")
  121. fs.StringVar(&cfg.durl, "discovery", "", "Discovery service used to bootstrap the initial cluster")
  122. fs.Var(cfg.fallback, "discovery-fallback", fmt.Sprintf("Valid values include %s", strings.Join(cfg.fallback.Values, ", ")))
  123. if err := cfg.fallback.Set(fallbackFlagProxy); err != nil {
  124. // Should never happen.
  125. log.Panicf("unexpected error setting up discovery-fallback flag: %v", err)
  126. }
  127. fs.StringVar(&cfg.dproxy, "discovery-proxy", "", "HTTP proxy to use for traffic to discovery service")
  128. fs.StringVar(&cfg.dnsCluster, "discovery-srv", "", "DNS domain used to bootstrap initial cluster")
  129. fs.StringVar(&cfg.initialCluster, "initial-cluster", "default=http://localhost:2380,default=http://localhost:7001", "Initial cluster configuration for bootstrapping")
  130. fs.StringVar(&cfg.initialClusterToken, "initial-cluster-token", "etcd-cluster", "Initial cluster token for the etcd cluster during bootstrap")
  131. fs.Var(cfg.clusterState, "initial-cluster-state", "Initial cluster configuration for bootstrapping")
  132. if err := cfg.clusterState.Set(clusterStateFlagNew); err != nil {
  133. // Should never happen.
  134. log.Panicf("unexpected error setting up clusterStateFlag: %v", err)
  135. }
  136. // proxy
  137. fs.Var(cfg.proxy, "proxy", fmt.Sprintf("Valid values include %s", strings.Join(cfg.proxy.Values, ", ")))
  138. if err := cfg.proxy.Set(proxyFlagOff); err != nil {
  139. // Should never happen.
  140. log.Panicf("unexpected error setting up proxyFlag: %v", err)
  141. }
  142. // security
  143. fs.StringVar(&cfg.clientTLSInfo.CAFile, "ca-file", "", "Path to the client server TLS CA file.")
  144. fs.StringVar(&cfg.clientTLSInfo.CertFile, "cert-file", "", "Path to the client server TLS cert file.")
  145. fs.StringVar(&cfg.clientTLSInfo.KeyFile, "key-file", "", "Path to the client server TLS key file.")
  146. fs.StringVar(&cfg.peerTLSInfo.CAFile, "peer-ca-file", "", "Path to the peer server TLS CA file.")
  147. fs.StringVar(&cfg.peerTLSInfo.CertFile, "peer-cert-file", "", "Path to the peer server TLS cert file.")
  148. fs.StringVar(&cfg.peerTLSInfo.KeyFile, "peer-key-file", "", "Path to the peer server TLS key file.")
  149. // unsafe
  150. fs.BoolVar(&cfg.forceNewCluster, "force-new-cluster", false, "Force to create a new one member cluster")
  151. // version
  152. fs.BoolVar(&cfg.printVersion, "version", false, "Print the version and exit")
  153. // backwards-compatibility with v0.4.6
  154. fs.Var(&flags.IPAddressPort{}, "addr", "DEPRECATED: Use -advertise-client-urls instead.")
  155. fs.Var(&flags.IPAddressPort{}, "bind-addr", "DEPRECATED: Use -listen-client-urls instead.")
  156. fs.Var(&flags.IPAddressPort{}, "peer-addr", "DEPRECATED: Use -initial-advertise-peer-urls instead.")
  157. fs.Var(&flags.IPAddressPort{}, "peer-bind-addr", "DEPRECATED: Use -listen-peer-urls instead.")
  158. fs.Var(&flags.DeprecatedFlag{Name: "peers"}, "peers", "DEPRECATED: Use -initial-cluster instead")
  159. fs.Var(&flags.DeprecatedFlag{Name: "peers-file"}, "peers-file", "DEPRECATED: Use -initial-cluster instead")
  160. // ignored
  161. for _, f := range cfg.ignored {
  162. fs.Var(&flags.IgnoredFlag{Name: f}, f, "")
  163. }
  164. return cfg
  165. }
  166. func (cfg *config) Parse(arguments []string) error {
  167. perr := cfg.FlagSet.Parse(arguments)
  168. switch perr {
  169. case nil:
  170. case flag.ErrHelp:
  171. os.Exit(0)
  172. default:
  173. os.Exit(2)
  174. }
  175. if cfg.printVersion {
  176. fmt.Println("etcd version", version.Version)
  177. os.Exit(0)
  178. }
  179. err := flags.SetFlagsFromEnv(cfg.FlagSet)
  180. if err != nil {
  181. log.Fatalf("etcd: %v", err)
  182. }
  183. set := make(map[string]bool)
  184. cfg.FlagSet.Visit(func(f *flag.Flag) {
  185. set[f.Name] = true
  186. })
  187. nSet := 0
  188. for _, v := range []bool{set["discovery"], set["initial-cluster"], set["discovery-srv"]} {
  189. if v {
  190. nSet += 1
  191. }
  192. }
  193. if nSet > 1 {
  194. return ErrConflictBootstrapFlags
  195. }
  196. cfg.lpurls, err = flags.URLsFromFlags(cfg.FlagSet, "listen-peer-urls", "peer-bind-addr", cfg.peerTLSInfo)
  197. if err != nil {
  198. return err
  199. }
  200. cfg.apurls, err = flags.URLsFromFlags(cfg.FlagSet, "initial-advertise-peer-urls", "peer-addr", cfg.peerTLSInfo)
  201. if err != nil {
  202. return err
  203. }
  204. cfg.lcurls, err = flags.URLsFromFlags(cfg.FlagSet, "listen-client-urls", "bind-addr", cfg.clientTLSInfo)
  205. if err != nil {
  206. return err
  207. }
  208. cfg.acurls, err = flags.URLsFromFlags(cfg.FlagSet, "advertise-client-urls", "addr", cfg.clientTLSInfo)
  209. if err != nil {
  210. return err
  211. }
  212. if err := cfg.resolveUrls(); err != nil {
  213. return errors.New("cannot resolve DNS hostnames.")
  214. }
  215. return nil
  216. }
  217. func (cfg *config) resolveUrls() error {
  218. return netutil.ResolveTCPAddrs(cfg.lpurls, cfg.apurls, cfg.lcurls, cfg.acurls)
  219. }
  220. func (cfg config) isNewCluster() bool { return cfg.clusterState.String() == clusterStateFlagNew }
  221. func (cfg config) isProxy() bool { return cfg.proxy.String() != proxyFlagOff }
  222. func (cfg config) isReadonlyProxy() bool { return cfg.proxy.String() == proxyFlagReadonly }
  223. func (cfg config) shouldFallbackToProxy() bool { return cfg.fallback.String() == fallbackFlagProxy }