config.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. // Copyright 2015 The etcd Authors
  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. "io/ioutil"
  20. "log"
  21. "net/url"
  22. "os"
  23. "runtime"
  24. "strings"
  25. "go.etcd.io/etcd/embed"
  26. "go.etcd.io/etcd/pkg/flags"
  27. "go.etcd.io/etcd/pkg/logutil"
  28. "go.etcd.io/etcd/pkg/types"
  29. "go.etcd.io/etcd/version"
  30. "go.uber.org/zap"
  31. "sigs.k8s.io/yaml"
  32. )
  33. var (
  34. proxyFlagOff = "off"
  35. proxyFlagReadonly = "readonly"
  36. proxyFlagOn = "on"
  37. fallbackFlagExit = "exit"
  38. fallbackFlagProxy = "proxy"
  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. // for coverage testing
  54. "test.coverprofile",
  55. "test.outputdir",
  56. }
  57. )
  58. type configProxy struct {
  59. ProxyFailureWaitMs uint `json:"proxy-failure-wait"`
  60. ProxyRefreshIntervalMs uint `json:"proxy-refresh-interval"`
  61. ProxyDialTimeoutMs uint `json:"proxy-dial-timeout"`
  62. ProxyWriteTimeoutMs uint `json:"proxy-write-timeout"`
  63. ProxyReadTimeoutMs uint `json:"proxy-read-timeout"`
  64. Fallback string
  65. Proxy string
  66. ProxyJSON string `json:"proxy"`
  67. FallbackJSON string `json:"discovery-fallback"`
  68. }
  69. // config holds the config for a command line invocation of etcd
  70. type config struct {
  71. ec embed.Config
  72. cp configProxy
  73. cf configFlags
  74. configFile string
  75. printVersion bool
  76. ignored []string
  77. }
  78. // configFlags has the set of flags used for command line parsing a Config
  79. type configFlags struct {
  80. flagSet *flag.FlagSet
  81. clusterState *flags.SelectiveStringValue
  82. fallback *flags.SelectiveStringValue
  83. proxy *flags.SelectiveStringValue
  84. }
  85. func newConfig() *config {
  86. cfg := &config{
  87. ec: *embed.NewConfig(),
  88. cp: configProxy{
  89. Proxy: proxyFlagOff,
  90. ProxyFailureWaitMs: 5000,
  91. ProxyRefreshIntervalMs: 30000,
  92. ProxyDialTimeoutMs: 1000,
  93. ProxyWriteTimeoutMs: 5000,
  94. },
  95. ignored: ignored,
  96. }
  97. cfg.cf = configFlags{
  98. flagSet: flag.NewFlagSet("etcd", flag.ContinueOnError),
  99. clusterState: flags.NewSelectiveStringValue(
  100. embed.ClusterStateFlagNew,
  101. embed.ClusterStateFlagExisting,
  102. ),
  103. fallback: flags.NewSelectiveStringValue(
  104. fallbackFlagProxy,
  105. fallbackFlagExit,
  106. ),
  107. proxy: flags.NewSelectiveStringValue(
  108. proxyFlagOff,
  109. proxyFlagReadonly,
  110. proxyFlagOn,
  111. ),
  112. }
  113. fs := cfg.cf.flagSet
  114. fs.Usage = func() {
  115. fmt.Fprintln(os.Stderr, usageline)
  116. }
  117. fs.StringVar(&cfg.configFile, "config-file", "", "Path to the server configuration file. Note that if a configuration file is provided, other command line flags and environment variables will be ignored.")
  118. // member
  119. fs.StringVar(&cfg.ec.Dir, "data-dir", cfg.ec.Dir, "Path to the data directory.")
  120. fs.StringVar(&cfg.ec.WalDir, "wal-dir", cfg.ec.WalDir, "Path to the dedicated wal directory.")
  121. fs.Var(
  122. flags.NewUniqueURLsWithExceptions(embed.DefaultListenPeerURLs, ""),
  123. "listen-peer-urls",
  124. "List of URLs to listen on for peer traffic.",
  125. )
  126. fs.Var(
  127. flags.NewUniqueURLsWithExceptions(embed.DefaultListenClientURLs, ""), "listen-client-urls",
  128. "List of URLs to listen on for client traffic.",
  129. )
  130. fs.Var(
  131. flags.NewUniqueURLsWithExceptions("", ""),
  132. "listen-metrics-urls",
  133. "List of URLs to listen on for the metrics and health endpoints.",
  134. )
  135. fs.UintVar(&cfg.ec.MaxSnapFiles, "max-snapshots", cfg.ec.MaxSnapFiles, "Maximum number of snapshot files to retain (0 is unlimited).")
  136. fs.UintVar(&cfg.ec.MaxWalFiles, "max-wals", cfg.ec.MaxWalFiles, "Maximum number of wal files to retain (0 is unlimited).")
  137. fs.StringVar(&cfg.ec.Name, "name", cfg.ec.Name, "Human-readable name for this member.")
  138. fs.Uint64Var(&cfg.ec.SnapshotCount, "snapshot-count", cfg.ec.SnapshotCount, "Number of committed transactions to trigger a snapshot to disk.")
  139. fs.UintVar(&cfg.ec.TickMs, "heartbeat-interval", cfg.ec.TickMs, "Time (in milliseconds) of a heartbeat interval.")
  140. fs.UintVar(&cfg.ec.ElectionMs, "election-timeout", cfg.ec.ElectionMs, "Time (in milliseconds) for an election to timeout.")
  141. fs.BoolVar(&cfg.ec.InitialElectionTickAdvance, "initial-election-tick-advance", cfg.ec.InitialElectionTickAdvance, "Whether to fast-forward initial election ticks on boot for faster election.")
  142. fs.Int64Var(&cfg.ec.QuotaBackendBytes, "quota-backend-bytes", cfg.ec.QuotaBackendBytes, "Raise alarms when backend size exceeds the given quota. 0 means use the default quota.")
  143. fs.DurationVar(&cfg.ec.BackendBatchInterval, "backend-batch-interval", cfg.ec.BackendBatchInterval, "BackendBatchInterval is the maximum time before commit the backend transaction.")
  144. fs.IntVar(&cfg.ec.BackendBatchLimit, "backend-batch-limit", cfg.ec.BackendBatchLimit, "BackendBatchLimit is the maximum operations before commit the backend transaction.")
  145. fs.UintVar(&cfg.ec.MaxTxnOps, "max-txn-ops", cfg.ec.MaxTxnOps, "Maximum number of operations permitted in a transaction.")
  146. fs.UintVar(&cfg.ec.MaxRequestBytes, "max-request-bytes", cfg.ec.MaxRequestBytes, "Maximum client request size in bytes the server will accept.")
  147. fs.DurationVar(&cfg.ec.GRPCKeepAliveMinTime, "grpc-keepalive-min-time", cfg.ec.GRPCKeepAliveMinTime, "Minimum interval duration that a client should wait before pinging server.")
  148. fs.DurationVar(&cfg.ec.GRPCKeepAliveInterval, "grpc-keepalive-interval", cfg.ec.GRPCKeepAliveInterval, "Frequency duration of server-to-client ping to check if a connection is alive (0 to disable).")
  149. fs.DurationVar(&cfg.ec.GRPCKeepAliveTimeout, "grpc-keepalive-timeout", cfg.ec.GRPCKeepAliveTimeout, "Additional duration of wait before closing a non-responsive connection (0 to disable).")
  150. // clustering
  151. fs.Var(
  152. flags.NewUniqueURLsWithExceptions(embed.DefaultInitialAdvertisePeerURLs, ""),
  153. "initial-advertise-peer-urls",
  154. "List of this member's peer URLs to advertise to the rest of the cluster.",
  155. )
  156. fs.Var(
  157. flags.NewUniqueURLsWithExceptions(embed.DefaultAdvertiseClientURLs, ""),
  158. "advertise-client-urls",
  159. "List of this member's client URLs to advertise to the public.",
  160. )
  161. fs.StringVar(&cfg.ec.Durl, "discovery", cfg.ec.Durl, "Discovery URL used to bootstrap the cluster.")
  162. fs.Var(cfg.cf.fallback, "discovery-fallback", fmt.Sprintf("Valid values include %q", cfg.cf.fallback.Valids()))
  163. fs.StringVar(&cfg.ec.Dproxy, "discovery-proxy", cfg.ec.Dproxy, "HTTP proxy to use for traffic to discovery service.")
  164. fs.StringVar(&cfg.ec.DNSCluster, "discovery-srv", cfg.ec.DNSCluster, "DNS domain used to bootstrap initial cluster.")
  165. fs.StringVar(&cfg.ec.DNSClusterServiceName, "discovery-srv-name", cfg.ec.DNSClusterServiceName, "Service name to query when using DNS discovery.")
  166. fs.StringVar(&cfg.ec.InitialCluster, "initial-cluster", cfg.ec.InitialCluster, "Initial cluster configuration for bootstrapping.")
  167. fs.StringVar(&cfg.ec.InitialClusterToken, "initial-cluster-token", cfg.ec.InitialClusterToken, "Initial cluster token for the etcd cluster during bootstrap.")
  168. fs.Var(cfg.cf.clusterState, "initial-cluster-state", "Initial cluster state ('new' or 'existing').")
  169. fs.BoolVar(&cfg.ec.StrictReconfigCheck, "strict-reconfig-check", cfg.ec.StrictReconfigCheck, "Reject reconfiguration requests that would cause quorum loss.")
  170. fs.BoolVar(&cfg.ec.EnableV2, "enable-v2", cfg.ec.EnableV2, "Accept etcd V2 client requests.")
  171. fs.BoolVar(&cfg.ec.PreVote, "pre-vote", cfg.ec.PreVote, "Enable to run an additional Raft election phase.")
  172. // proxy
  173. fs.Var(cfg.cf.proxy, "proxy", fmt.Sprintf("Valid values include %q", cfg.cf.proxy.Valids()))
  174. fs.UintVar(&cfg.cp.ProxyFailureWaitMs, "proxy-failure-wait", cfg.cp.ProxyFailureWaitMs, "Time (in milliseconds) an endpoint will be held in a failed state.")
  175. fs.UintVar(&cfg.cp.ProxyRefreshIntervalMs, "proxy-refresh-interval", cfg.cp.ProxyRefreshIntervalMs, "Time (in milliseconds) of the endpoints refresh interval.")
  176. fs.UintVar(&cfg.cp.ProxyDialTimeoutMs, "proxy-dial-timeout", cfg.cp.ProxyDialTimeoutMs, "Time (in milliseconds) for a dial to timeout.")
  177. fs.UintVar(&cfg.cp.ProxyWriteTimeoutMs, "proxy-write-timeout", cfg.cp.ProxyWriteTimeoutMs, "Time (in milliseconds) for a write to timeout.")
  178. fs.UintVar(&cfg.cp.ProxyReadTimeoutMs, "proxy-read-timeout", cfg.cp.ProxyReadTimeoutMs, "Time (in milliseconds) for a read to timeout.")
  179. // security
  180. fs.StringVar(&cfg.ec.ClientTLSInfo.CertFile, "cert-file", "", "Path to the client server TLS cert file.")
  181. fs.StringVar(&cfg.ec.ClientTLSInfo.KeyFile, "key-file", "", "Path to the client server TLS key file.")
  182. fs.BoolVar(&cfg.ec.ClientTLSInfo.ClientCertAuth, "client-cert-auth", false, "Enable client cert authentication.")
  183. fs.StringVar(&cfg.ec.ClientTLSInfo.CRLFile, "client-crl-file", "", "Path to the client certificate revocation list file.")
  184. fs.StringVar(&cfg.ec.ClientTLSInfo.AllowedHostname, "client-cert-allowed-hostname", "", "Allowed TLS hostname for client cert authentication.")
  185. fs.StringVar(&cfg.ec.ClientTLSInfo.TrustedCAFile, "trusted-ca-file", "", "Path to the client server TLS trusted CA cert file.")
  186. fs.BoolVar(&cfg.ec.ClientAutoTLS, "auto-tls", false, "Client TLS using generated certificates")
  187. fs.StringVar(&cfg.ec.PeerTLSInfo.CertFile, "peer-cert-file", "", "Path to the peer server TLS cert file.")
  188. fs.StringVar(&cfg.ec.PeerTLSInfo.KeyFile, "peer-key-file", "", "Path to the peer server TLS key file.")
  189. fs.BoolVar(&cfg.ec.PeerTLSInfo.ClientCertAuth, "peer-client-cert-auth", false, "Enable peer client cert authentication.")
  190. fs.StringVar(&cfg.ec.PeerTLSInfo.TrustedCAFile, "peer-trusted-ca-file", "", "Path to the peer server TLS trusted CA file.")
  191. fs.BoolVar(&cfg.ec.PeerAutoTLS, "peer-auto-tls", false, "Peer TLS using generated certificates")
  192. fs.StringVar(&cfg.ec.PeerTLSInfo.CRLFile, "peer-crl-file", "", "Path to the peer certificate revocation list file.")
  193. fs.StringVar(&cfg.ec.PeerTLSInfo.AllowedCN, "peer-cert-allowed-cn", "", "Allowed CN for inter peer authentication.")
  194. fs.StringVar(&cfg.ec.PeerTLSInfo.AllowedHostname, "peer-cert-allowed-hostname", "", "Allowed TLS hostname for inter peer authentication.")
  195. fs.Var(flags.NewStringsValue(""), "cipher-suites", "Comma-separated list of supported TLS cipher suites between client/server and peers (empty will be auto-populated by Go).")
  196. fs.BoolVar(&cfg.ec.PeerTLSInfo.SkipClientSANVerify, "experimental-peer-skip-client-san-verification", false, "Skip verification of SAN field in client certificate for peer connections.")
  197. fs.Var(
  198. flags.NewUniqueURLsWithExceptions("*", "*"),
  199. "cors",
  200. "Comma-separated white list of origins for CORS, or cross-origin resource sharing, (empty or * means allow all)",
  201. )
  202. fs.Var(flags.NewUniqueStringsValue("*"), "host-whitelist", "Comma-separated acceptable hostnames from HTTP client requests, if server is not secure (empty means allow all).")
  203. // logging
  204. fs.StringVar(&cfg.ec.Logger, "logger", "capnslog", "Specify 'zap' for structured logging or 'capnslog'. WARN: 'capnslog' is being deprecated in v3.5.")
  205. fs.Var(flags.NewUniqueStringsValue(embed.DefaultLogOutput), "log-output", "[TO BE DEPRECATED IN v3.5] use '--log-outputs'.")
  206. fs.Var(flags.NewUniqueStringsValue(embed.DefaultLogOutput), "log-outputs", "Specify 'stdout' or 'stderr' to skip journald logging even when running under systemd, or list of comma separated output targets.")
  207. fs.BoolVar(&cfg.ec.Debug, "debug", false, "[TO BE DEPRECATED IN v3.5] Enable debug-level logging for etcd. Use '--log-level=debug' instead.")
  208. fs.StringVar(&cfg.ec.LogLevel, "log-level", logutil.DefaultLogLevel, "Configures log level. Only supports debug, info, warn, error, panic, or fatal. Default 'info'.")
  209. fs.StringVar(&cfg.ec.LogPkgLevels, "log-package-levels", "", "[TO BE DEPRECATED IN v3.5] Specify a particular log level for each etcd package (eg: 'etcdmain=CRITICAL,etcdserver=DEBUG').")
  210. // version
  211. fs.BoolVar(&cfg.printVersion, "version", false, "Print the version and exit.")
  212. fs.StringVar(&cfg.ec.AutoCompactionRetention, "auto-compaction-retention", "0", "Auto compaction retention for mvcc key value store. 0 means disable auto compaction.")
  213. fs.StringVar(&cfg.ec.AutoCompactionMode, "auto-compaction-mode", "periodic", "interpret 'auto-compaction-retention' one of: periodic|revision. 'periodic' for duration based retention, defaulting to hours if no time unit is provided (e.g. '5m'). 'revision' for revision number based retention.")
  214. // pprof profiler via HTTP
  215. fs.BoolVar(&cfg.ec.EnablePprof, "enable-pprof", false, "Enable runtime profiling data via HTTP server. Address is at client URL + \"/debug/pprof/\"")
  216. // additional metrics
  217. fs.StringVar(&cfg.ec.Metrics, "metrics", cfg.ec.Metrics, "Set level of detail for exported metrics, specify 'extensive' to include server side grpc histogram metrics")
  218. // auth
  219. fs.StringVar(&cfg.ec.AuthToken, "auth-token", cfg.ec.AuthToken, "Specify auth token specific options.")
  220. fs.UintVar(&cfg.ec.BcryptCost, "bcrypt-cost", cfg.ec.BcryptCost, "Specify bcrypt algorithm cost factor for auth password hashing.")
  221. // gateway
  222. fs.BoolVar(&cfg.ec.EnableGRPCGateway, "enable-grpc-gateway", true, "Enable GRPC gateway.")
  223. // experimental
  224. fs.BoolVar(&cfg.ec.ExperimentalInitialCorruptCheck, "experimental-initial-corrupt-check", cfg.ec.ExperimentalInitialCorruptCheck, "Enable to check data corruption before serving any client/peer traffic.")
  225. fs.DurationVar(&cfg.ec.ExperimentalCorruptCheckTime, "experimental-corrupt-check-time", cfg.ec.ExperimentalCorruptCheckTime, "Duration of time between cluster corruption check passes.")
  226. fs.StringVar(&cfg.ec.ExperimentalEnableV2V3, "experimental-enable-v2v3", cfg.ec.ExperimentalEnableV2V3, "v3 prefix for serving emulated v2 state.")
  227. fs.StringVar(&cfg.ec.ExperimentalBackendFreelistType, "experimental-backend-bbolt-freelist-type", cfg.ec.ExperimentalBackendFreelistType, "ExperimentalBackendFreelistType specifies the type of freelist that boltdb backend uses(array and map are supported types)")
  228. fs.BoolVar(&cfg.ec.ExperimentalEnableLeaseCheckpoint, "experimental-enable-lease-checkpoint", false, "Enable to persist lease remaining TTL to prevent indefinite auto-renewal of long lived leases.")
  229. fs.IntVar(&cfg.ec.ExperimentalCompactionBatchLimit, "experimental-compaction-batch-limit", cfg.ec.ExperimentalCompactionBatchLimit, "Sets the maximum revisions deleted in each compaction batch.")
  230. // unsafe
  231. fs.BoolVar(&cfg.ec.ForceNewCluster, "force-new-cluster", false, "Force to create a new one member cluster.")
  232. // ignored
  233. for _, f := range cfg.ignored {
  234. fs.Var(&flags.IgnoredFlag{Name: f}, f, "")
  235. }
  236. return cfg
  237. }
  238. func (cfg *config) parse(arguments []string) error {
  239. perr := cfg.cf.flagSet.Parse(arguments)
  240. switch perr {
  241. case nil:
  242. case flag.ErrHelp:
  243. fmt.Println(flagsline)
  244. os.Exit(0)
  245. default:
  246. os.Exit(2)
  247. }
  248. if len(cfg.cf.flagSet.Args()) != 0 {
  249. return fmt.Errorf("'%s' is not a valid flag", cfg.cf.flagSet.Arg(0))
  250. }
  251. if cfg.printVersion {
  252. fmt.Printf("etcd Version: %s\n", version.Version)
  253. fmt.Printf("Git SHA: %s\n", version.GitSHA)
  254. fmt.Printf("Go Version: %s\n", runtime.Version())
  255. fmt.Printf("Go OS/Arch: %s/%s\n", runtime.GOOS, runtime.GOARCH)
  256. os.Exit(0)
  257. }
  258. var err error
  259. // This env variable must be parsed separately
  260. // because we need to determine whether to use or
  261. // ignore the env variables based on if the config file is set.
  262. if cfg.configFile == "" {
  263. cfg.configFile = os.Getenv(flags.FlagToEnv("ETCD", "config-file"))
  264. }
  265. if cfg.configFile != "" {
  266. err = cfg.configFromFile(cfg.configFile)
  267. if lg := cfg.ec.GetLogger(); lg != nil {
  268. lg.Info(
  269. "loaded server configuration, other configuration command line flags and environment variables will be ignored if provided",
  270. zap.String("path", cfg.configFile),
  271. )
  272. } else {
  273. plog.Infof("Loading server configuration from %q. Other configuration command line flags and environment variables will be ignored if provided.", cfg.configFile)
  274. }
  275. } else {
  276. err = cfg.configFromCmdLine()
  277. }
  278. // now logger is set up
  279. return err
  280. }
  281. func (cfg *config) configFromCmdLine() error {
  282. verKey := "ETCD_VERSION"
  283. if verVal := os.Getenv(verKey); verVal != "" {
  284. // unset to avoid any possible side-effect.
  285. os.Unsetenv(verKey)
  286. plog.Warningf("cannot set special environment variable %s=%s", verKey, verVal)
  287. }
  288. err := flags.SetFlagsFromEnv("ETCD", cfg.cf.flagSet)
  289. if err != nil {
  290. return err
  291. }
  292. cfg.ec.LPUrls = flags.UniqueURLsFromFlag(cfg.cf.flagSet, "listen-peer-urls")
  293. cfg.ec.APUrls = flags.UniqueURLsFromFlag(cfg.cf.flagSet, "initial-advertise-peer-urls")
  294. cfg.ec.LCUrls = flags.UniqueURLsFromFlag(cfg.cf.flagSet, "listen-client-urls")
  295. cfg.ec.ACUrls = flags.UniqueURLsFromFlag(cfg.cf.flagSet, "advertise-client-urls")
  296. cfg.ec.ListenMetricsUrls = flags.UniqueURLsFromFlag(cfg.cf.flagSet, "listen-metrics-urls")
  297. cfg.ec.CORS = flags.UniqueURLsMapFromFlag(cfg.cf.flagSet, "cors")
  298. cfg.ec.HostWhitelist = flags.UniqueStringsMapFromFlag(cfg.cf.flagSet, "host-whitelist")
  299. cfg.ec.CipherSuites = flags.StringsFromFlag(cfg.cf.flagSet, "cipher-suites")
  300. // TODO: remove this in v3.5
  301. cfg.ec.DeprecatedLogOutput = flags.UniqueStringsFromFlag(cfg.cf.flagSet, "log-output")
  302. cfg.ec.LogOutputs = flags.UniqueStringsFromFlag(cfg.cf.flagSet, "log-outputs")
  303. cfg.ec.ClusterState = cfg.cf.clusterState.String()
  304. cfg.cp.Fallback = cfg.cf.fallback.String()
  305. cfg.cp.Proxy = cfg.cf.proxy.String()
  306. // disable default advertise-client-urls if lcurls is set
  307. missingAC := flags.IsSet(cfg.cf.flagSet, "listen-client-urls") && !flags.IsSet(cfg.cf.flagSet, "advertise-client-urls")
  308. if !cfg.mayBeProxy() && missingAC {
  309. cfg.ec.ACUrls = nil
  310. }
  311. // disable default initial-cluster if discovery is set
  312. if (cfg.ec.Durl != "" || cfg.ec.DNSCluster != "" || cfg.ec.DNSClusterServiceName != "") && !flags.IsSet(cfg.cf.flagSet, "initial-cluster") {
  313. cfg.ec.InitialCluster = ""
  314. }
  315. return cfg.validate()
  316. }
  317. func (cfg *config) configFromFile(path string) error {
  318. eCfg, err := embed.ConfigFromFile(path)
  319. if err != nil {
  320. return err
  321. }
  322. cfg.ec = *eCfg
  323. // load extra config information
  324. b, rerr := ioutil.ReadFile(path)
  325. if rerr != nil {
  326. return rerr
  327. }
  328. if yerr := yaml.Unmarshal(b, &cfg.cp); yerr != nil {
  329. return yerr
  330. }
  331. if cfg.ec.ListenMetricsUrlsJSON != "" {
  332. us, err := types.NewURLs(strings.Split(cfg.ec.ListenMetricsUrlsJSON, ","))
  333. if err != nil {
  334. log.Fatalf("unexpected error setting up listen-metrics-urls: %v", err)
  335. }
  336. cfg.ec.ListenMetricsUrls = []url.URL(us)
  337. }
  338. if cfg.cp.FallbackJSON != "" {
  339. if err := cfg.cf.fallback.Set(cfg.cp.FallbackJSON); err != nil {
  340. log.Fatalf("unexpected error setting up discovery-fallback flag: %v", err)
  341. }
  342. cfg.cp.Fallback = cfg.cf.fallback.String()
  343. }
  344. if cfg.cp.ProxyJSON != "" {
  345. if err := cfg.cf.proxy.Set(cfg.cp.ProxyJSON); err != nil {
  346. log.Fatalf("unexpected error setting up proxyFlag: %v", err)
  347. }
  348. cfg.cp.Proxy = cfg.cf.proxy.String()
  349. }
  350. return nil
  351. }
  352. func (cfg *config) mayBeProxy() bool {
  353. mayFallbackToProxy := cfg.ec.Durl != "" && cfg.cp.Fallback == fallbackFlagProxy
  354. return cfg.cp.Proxy != proxyFlagOff || mayFallbackToProxy
  355. }
  356. func (cfg *config) validate() error {
  357. err := cfg.ec.Validate()
  358. // TODO(yichengq): check this for joining through discovery service case
  359. if err == embed.ErrUnsetAdvertiseClientURLsFlag && cfg.mayBeProxy() {
  360. return nil
  361. }
  362. return err
  363. }
  364. func (cfg config) isProxy() bool { return cfg.cf.proxy.String() != proxyFlagOff }
  365. func (cfg config) isReadonlyProxy() bool { return cfg.cf.proxy.String() == proxyFlagReadonly }
  366. func (cfg config) shouldFallbackToProxy() bool { return cfg.cf.fallback.String() == fallbackFlagProxy }