config.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  1. // Copyright 2016 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. package embed
  15. import (
  16. "crypto/tls"
  17. "fmt"
  18. "io/ioutil"
  19. "net"
  20. "net/http"
  21. "net/url"
  22. "os"
  23. "path/filepath"
  24. "strings"
  25. "sync"
  26. "time"
  27. "go.etcd.io/etcd/v3/etcdserver"
  28. "go.etcd.io/etcd/v3/etcdserver/api/v3compactor"
  29. "go.etcd.io/etcd/v3/pkg/flags"
  30. "go.etcd.io/etcd/v3/pkg/netutil"
  31. "go.etcd.io/etcd/v3/pkg/srv"
  32. "go.etcd.io/etcd/v3/pkg/tlsutil"
  33. "go.etcd.io/etcd/v3/pkg/transport"
  34. "go.etcd.io/etcd/v3/pkg/types"
  35. bolt "go.etcd.io/bbolt"
  36. "go.uber.org/zap"
  37. "go.uber.org/zap/zapcore"
  38. "golang.org/x/crypto/bcrypt"
  39. "google.golang.org/grpc"
  40. "sigs.k8s.io/yaml"
  41. )
  42. const (
  43. ClusterStateFlagNew = "new"
  44. ClusterStateFlagExisting = "existing"
  45. DefaultName = "default"
  46. DefaultMaxSnapshots = 5
  47. DefaultMaxWALs = 5
  48. DefaultMaxTxnOps = uint(128)
  49. DefaultMaxRequestBytes = 1.5 * 1024 * 1024
  50. DefaultGRPCKeepAliveMinTime = 5 * time.Second
  51. DefaultGRPCKeepAliveInterval = 2 * time.Hour
  52. DefaultGRPCKeepAliveTimeout = 20 * time.Second
  53. DefaultListenPeerURLs = "http://localhost:2380"
  54. DefaultListenClientURLs = "http://localhost:2379"
  55. DefaultLogOutput = "default"
  56. JournalLogOutput = "systemd/journal"
  57. StdErrLogOutput = "stderr"
  58. StdOutLogOutput = "stdout"
  59. // DefaultStrictReconfigCheck is the default value for "--strict-reconfig-check" flag.
  60. // It's enabled by default.
  61. DefaultStrictReconfigCheck = true
  62. // DefaultEnableV2 is the default value for "--enable-v2" flag.
  63. // v2 is enabled by default.
  64. // TODO: disable v2 when deprecated.
  65. DefaultEnableV2 = true
  66. // maxElectionMs specifies the maximum value of election timeout.
  67. // More details are listed in ../Documentation/tuning.md#time-parameters.
  68. maxElectionMs = 50000
  69. // backend freelist map type
  70. freelistMapType = "map"
  71. )
  72. var (
  73. ErrConflictBootstrapFlags = fmt.Errorf("multiple discovery or bootstrap flags are set. " +
  74. "Choose one of \"initial-cluster\", \"discovery\" or \"discovery-srv\"")
  75. ErrUnsetAdvertiseClientURLsFlag = fmt.Errorf("--advertise-client-urls is required when --listen-client-urls is set explicitly")
  76. DefaultInitialAdvertisePeerURLs = "http://localhost:2380"
  77. DefaultAdvertiseClientURLs = "http://localhost:2379"
  78. defaultHostname string
  79. defaultHostStatus error
  80. )
  81. var (
  82. // CompactorModePeriodic is periodic compaction mode
  83. // for "Config.AutoCompactionMode" field.
  84. // If "AutoCompactionMode" is CompactorModePeriodic and
  85. // "AutoCompactionRetention" is "1h", it automatically compacts
  86. // compacts storage every hour.
  87. CompactorModePeriodic = v3compactor.ModePeriodic
  88. // CompactorModeRevision is revision-based compaction mode
  89. // for "Config.AutoCompactionMode" field.
  90. // If "AutoCompactionMode" is CompactorModeRevision and
  91. // "AutoCompactionRetention" is "1000", it compacts log on
  92. // revision 5000 when the current revision is 6000.
  93. // This runs every 5-minute if enough of logs have proceeded.
  94. CompactorModeRevision = v3compactor.ModeRevision
  95. )
  96. func init() {
  97. defaultHostname, defaultHostStatus = netutil.GetDefaultHost()
  98. }
  99. // Config holds the arguments for configuring an etcd server.
  100. type Config struct {
  101. Name string `json:"name"`
  102. Dir string `json:"data-dir"`
  103. WalDir string `json:"wal-dir"`
  104. SnapshotCount uint64 `json:"snapshot-count"`
  105. // SnapshotCatchUpEntries is the number of entries for a slow follower
  106. // to catch-up after compacting the raft storage entries.
  107. // We expect the follower has a millisecond level latency with the leader.
  108. // The max throughput is around 10K. Keep a 5K entries is enough for helping
  109. // follower to catch up.
  110. // WARNING: only change this for tests.
  111. // Always use "DefaultSnapshotCatchUpEntries"
  112. SnapshotCatchUpEntries uint64
  113. MaxSnapFiles uint `json:"max-snapshots"`
  114. MaxWalFiles uint `json:"max-wals"`
  115. // TickMs is the number of milliseconds between heartbeat ticks.
  116. // TODO: decouple tickMs and heartbeat tick (current heartbeat tick = 1).
  117. // make ticks a cluster wide configuration.
  118. TickMs uint `json:"heartbeat-interval"`
  119. ElectionMs uint `json:"election-timeout"`
  120. // InitialElectionTickAdvance is true, then local member fast-forwards
  121. // election ticks to speed up "initial" leader election trigger. This
  122. // benefits the case of larger election ticks. For instance, cross
  123. // datacenter deployment may require longer election timeout of 10-second.
  124. // If true, local node does not need wait up to 10-second. Instead,
  125. // forwards its election ticks to 8-second, and have only 2-second left
  126. // before leader election.
  127. //
  128. // Major assumptions are that:
  129. // - cluster has no active leader thus advancing ticks enables faster
  130. // leader election, or
  131. // - cluster already has an established leader, and rejoining follower
  132. // is likely to receive heartbeats from the leader after tick advance
  133. // and before election timeout.
  134. //
  135. // However, when network from leader to rejoining follower is congested,
  136. // and the follower does not receive leader heartbeat within left election
  137. // ticks, disruptive election has to happen thus affecting cluster
  138. // availabilities.
  139. //
  140. // Disabling this would slow down initial bootstrap process for cross
  141. // datacenter deployments. Make your own tradeoffs by configuring
  142. // --initial-election-tick-advance at the cost of slow initial bootstrap.
  143. //
  144. // If single-node, it advances ticks regardless.
  145. //
  146. // See https://github.com/etcd-io/etcd/issues/9333 for more detail.
  147. InitialElectionTickAdvance bool `json:"initial-election-tick-advance"`
  148. // BackendBatchInterval is the maximum time before commit the backend transaction.
  149. BackendBatchInterval time.Duration `json:"backend-batch-interval"`
  150. // BackendBatchLimit is the maximum operations before commit the backend transaction.
  151. BackendBatchLimit int `json:"backend-batch-limit"`
  152. QuotaBackendBytes int64 `json:"quota-backend-bytes"`
  153. MaxTxnOps uint `json:"max-txn-ops"`
  154. MaxRequestBytes uint `json:"max-request-bytes"`
  155. LPUrls, LCUrls []url.URL
  156. APUrls, ACUrls []url.URL
  157. ClientTLSInfo transport.TLSInfo
  158. ClientAutoTLS bool
  159. PeerTLSInfo transport.TLSInfo
  160. PeerAutoTLS bool
  161. // CipherSuites is a list of supported TLS cipher suites between
  162. // client/server and peers. If empty, Go auto-populates the list.
  163. // Note that cipher suites are prioritized in the given order.
  164. CipherSuites []string `json:"cipher-suites"`
  165. ClusterState string `json:"initial-cluster-state"`
  166. DNSCluster string `json:"discovery-srv"`
  167. DNSClusterServiceName string `json:"discovery-srv-name"`
  168. Dproxy string `json:"discovery-proxy"`
  169. Durl string `json:"discovery"`
  170. InitialCluster string `json:"initial-cluster"`
  171. InitialClusterToken string `json:"initial-cluster-token"`
  172. StrictReconfigCheck bool `json:"strict-reconfig-check"`
  173. EnableV2 bool `json:"enable-v2"`
  174. // AutoCompactionMode is either 'periodic' or 'revision'.
  175. AutoCompactionMode string `json:"auto-compaction-mode"`
  176. // AutoCompactionRetention is either duration string with time unit
  177. // (e.g. '5m' for 5-minute), or revision unit (e.g. '5000').
  178. // If no time unit is provided and compaction mode is 'periodic',
  179. // the unit defaults to hour. For example, '5' translates into 5-hour.
  180. AutoCompactionRetention string `json:"auto-compaction-retention"`
  181. // GRPCKeepAliveMinTime is the minimum interval that a client should
  182. // wait before pinging server. When client pings "too fast", server
  183. // sends goaway and closes the connection (errors: too_many_pings,
  184. // http2.ErrCodeEnhanceYourCalm). When too slow, nothing happens.
  185. // Server expects client pings only when there is any active streams
  186. // (PermitWithoutStream is set false).
  187. GRPCKeepAliveMinTime time.Duration `json:"grpc-keepalive-min-time"`
  188. // GRPCKeepAliveInterval is the frequency of server-to-client ping
  189. // to check if a connection is alive. Close a non-responsive connection
  190. // after an additional duration of Timeout. 0 to disable.
  191. GRPCKeepAliveInterval time.Duration `json:"grpc-keepalive-interval"`
  192. // GRPCKeepAliveTimeout is the additional duration of wait
  193. // before closing a non-responsive connection. 0 to disable.
  194. GRPCKeepAliveTimeout time.Duration `json:"grpc-keepalive-timeout"`
  195. // PreVote is true to enable Raft Pre-Vote.
  196. // If enabled, Raft runs an additional election phase
  197. // to check whether it would get enough votes to win
  198. // an election, thus minimizing disruptions.
  199. // TODO: enable by default in 3.5.
  200. PreVote bool `json:"pre-vote"`
  201. CORS map[string]struct{}
  202. // HostWhitelist lists acceptable hostnames from HTTP client requests.
  203. // Client origin policy protects against "DNS Rebinding" attacks
  204. // to insecure etcd servers. That is, any website can simply create
  205. // an authorized DNS name, and direct DNS to "localhost" (or any
  206. // other address). Then, all HTTP endpoints of etcd server listening
  207. // on "localhost" becomes accessible, thus vulnerable to DNS rebinding
  208. // attacks. See "CVE-2018-5702" for more detail.
  209. //
  210. // 1. If client connection is secure via HTTPS, allow any hostnames.
  211. // 2. If client connection is not secure and "HostWhitelist" is not empty,
  212. // only allow HTTP requests whose Host field is listed in whitelist.
  213. //
  214. // Note that the client origin policy is enforced whether authentication
  215. // is enabled or not, for tighter controls.
  216. //
  217. // By default, "HostWhitelist" is "*", which allows any hostnames.
  218. // Note that when specifying hostnames, loopback addresses are not added
  219. // automatically. To allow loopback interfaces, leave it empty or set it "*",
  220. // or add them to whitelist manually (e.g. "localhost", "127.0.0.1", etc.).
  221. //
  222. // CVE-2018-5702 reference:
  223. // - https://bugs.chromium.org/p/project-zero/issues/detail?id=1447#c2
  224. // - https://github.com/transmission/transmission/pull/468
  225. // - https://github.com/etcd-io/etcd/issues/9353
  226. HostWhitelist map[string]struct{}
  227. // UserHandlers is for registering users handlers and only used for
  228. // embedding etcd into other applications.
  229. // The map key is the route path for the handler, and
  230. // you must ensure it can't be conflicted with etcd's.
  231. UserHandlers map[string]http.Handler `json:"-"`
  232. // ServiceRegister is for registering users' gRPC services. A simple usage example:
  233. // cfg := embed.NewConfig()
  234. // cfg.ServerRegister = func(s *grpc.Server) {
  235. // pb.RegisterFooServer(s, &fooServer{})
  236. // pb.RegisterBarServer(s, &barServer{})
  237. // }
  238. // embed.StartEtcd(cfg)
  239. ServiceRegister func(*grpc.Server) `json:"-"`
  240. AuthToken string `json:"auth-token"`
  241. BcryptCost uint `json:"bcrypt-cost"`
  242. ExperimentalInitialCorruptCheck bool `json:"experimental-initial-corrupt-check"`
  243. ExperimentalCorruptCheckTime time.Duration `json:"experimental-corrupt-check-time"`
  244. ExperimentalEnableV2V3 string `json:"experimental-enable-v2v3"`
  245. // ExperimentalBackendFreelistType specifies the type of freelist that boltdb backend uses (array and map are supported types).
  246. ExperimentalBackendFreelistType string `json:"experimental-backend-bbolt-freelist-type"`
  247. // ForceNewCluster starts a new cluster even if previously started; unsafe.
  248. ForceNewCluster bool `json:"force-new-cluster"`
  249. EnablePprof bool `json:"enable-pprof"`
  250. Metrics string `json:"metrics"`
  251. ListenMetricsUrls []url.URL
  252. ListenMetricsUrlsJSON string `json:"listen-metrics-urls"`
  253. // Logger is logger options: "zap", "capnslog".
  254. // WARN: "capnslog" is being deprecated in v3.5.
  255. Logger string `json:"logger"`
  256. // DeprecatedLogOutput is to be deprecated in v3.5.
  257. // Just here for safe migration in v3.4.
  258. DeprecatedLogOutput []string `json:"log-output"`
  259. // LogOutputs is either:
  260. // - "default" as os.Stderr,
  261. // - "stderr" as os.Stderr,
  262. // - "stdout" as os.Stdout,
  263. // - file path to append server logs to.
  264. // It can be multiple when "Logger" is zap.
  265. LogOutputs []string `json:"log-outputs"`
  266. // Debug is true, to enable debug level logging.
  267. Debug bool `json:"debug"`
  268. // ZapLoggerBuilder is used to build the zap logger.
  269. ZapLoggerBuilder func(*Config) error
  270. // logger logs server-side operations. The default is nil,
  271. // and "setupLogging" must be called before starting server.
  272. // Do not set logger directly.
  273. loggerMu *sync.RWMutex
  274. logger *zap.Logger
  275. // loggerConfig is server logger configuration for Raft logger.
  276. // Must be either: "loggerConfig != nil" or "loggerCore != nil && loggerWriteSyncer != nil".
  277. loggerConfig *zap.Config
  278. // loggerCore is "zapcore.Core" for raft logger.
  279. // Must be either: "loggerConfig != nil" or "loggerCore != nil && loggerWriteSyncer != nil".
  280. loggerCore zapcore.Core
  281. loggerWriteSyncer zapcore.WriteSyncer
  282. // EnableGRPCGateway is false to disable grpc gateway.
  283. EnableGRPCGateway bool `json:"enable-grpc-gateway"`
  284. // TO BE DEPRECATED
  285. // LogPkgLevels is being deprecated in v3.5.
  286. // Only valid if "logger" option is "capnslog".
  287. // WARN: DO NOT USE THIS!
  288. LogPkgLevels string `json:"log-package-levels"`
  289. }
  290. // configYAML holds the config suitable for yaml parsing
  291. type configYAML struct {
  292. Config
  293. configJSON
  294. }
  295. // configJSON has file options that are translated into Config options
  296. type configJSON struct {
  297. LPUrlsJSON string `json:"listen-peer-urls"`
  298. LCUrlsJSON string `json:"listen-client-urls"`
  299. APUrlsJSON string `json:"initial-advertise-peer-urls"`
  300. ACUrlsJSON string `json:"advertise-client-urls"`
  301. CORSJSON string `json:"cors"`
  302. HostWhitelistJSON string `json:"host-whitelist"`
  303. ClientSecurityJSON securityConfig `json:"client-transport-security"`
  304. PeerSecurityJSON securityConfig `json:"peer-transport-security"`
  305. }
  306. type securityConfig struct {
  307. CertFile string `json:"cert-file"`
  308. KeyFile string `json:"key-file"`
  309. CertAuth bool `json:"client-cert-auth"`
  310. TrustedCAFile string `json:"trusted-ca-file"`
  311. AutoTLS bool `json:"auto-tls"`
  312. }
  313. // NewConfig creates a new Config populated with default values.
  314. func NewConfig() *Config {
  315. lpurl, _ := url.Parse(DefaultListenPeerURLs)
  316. apurl, _ := url.Parse(DefaultInitialAdvertisePeerURLs)
  317. lcurl, _ := url.Parse(DefaultListenClientURLs)
  318. acurl, _ := url.Parse(DefaultAdvertiseClientURLs)
  319. cfg := &Config{
  320. MaxSnapFiles: DefaultMaxSnapshots,
  321. MaxWalFiles: DefaultMaxWALs,
  322. Name: DefaultName,
  323. SnapshotCount: etcdserver.DefaultSnapshotCount,
  324. SnapshotCatchUpEntries: etcdserver.DefaultSnapshotCatchUpEntries,
  325. MaxTxnOps: DefaultMaxTxnOps,
  326. MaxRequestBytes: DefaultMaxRequestBytes,
  327. GRPCKeepAliveMinTime: DefaultGRPCKeepAliveMinTime,
  328. GRPCKeepAliveInterval: DefaultGRPCKeepAliveInterval,
  329. GRPCKeepAliveTimeout: DefaultGRPCKeepAliveTimeout,
  330. TickMs: 100,
  331. ElectionMs: 1000,
  332. InitialElectionTickAdvance: true,
  333. LPUrls: []url.URL{*lpurl},
  334. LCUrls: []url.URL{*lcurl},
  335. APUrls: []url.URL{*apurl},
  336. ACUrls: []url.URL{*acurl},
  337. ClusterState: ClusterStateFlagNew,
  338. InitialClusterToken: "etcd-cluster",
  339. StrictReconfigCheck: DefaultStrictReconfigCheck,
  340. Metrics: "basic",
  341. EnableV2: DefaultEnableV2,
  342. CORS: map[string]struct{}{"*": {}},
  343. HostWhitelist: map[string]struct{}{"*": {}},
  344. AuthToken: "simple",
  345. BcryptCost: uint(bcrypt.DefaultCost),
  346. PreVote: false, // TODO: enable by default in v3.5
  347. loggerMu: new(sync.RWMutex),
  348. logger: nil,
  349. Logger: "capnslog",
  350. DeprecatedLogOutput: []string{DefaultLogOutput},
  351. LogOutputs: []string{DefaultLogOutput},
  352. Debug: false,
  353. LogPkgLevels: "",
  354. }
  355. cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
  356. return cfg
  357. }
  358. func logTLSHandshakeFailure(conn *tls.Conn, err error) {
  359. state := conn.ConnectionState()
  360. remoteAddr := conn.RemoteAddr().String()
  361. serverName := state.ServerName
  362. if len(state.PeerCertificates) > 0 {
  363. cert := state.PeerCertificates[0]
  364. ips, dns := cert.IPAddresses, cert.DNSNames
  365. plog.Infof("rejected connection from %q (error %q, ServerName %q, IPAddresses %q, DNSNames %q)", remoteAddr, err.Error(), serverName, ips, dns)
  366. } else {
  367. plog.Infof("rejected connection from %q (error %q, ServerName %q)", remoteAddr, err.Error(), serverName)
  368. }
  369. }
  370. func ConfigFromFile(path string) (*Config, error) {
  371. cfg := &configYAML{Config: *NewConfig()}
  372. if err := cfg.configFromFile(path); err != nil {
  373. return nil, err
  374. }
  375. return &cfg.Config, nil
  376. }
  377. func (cfg *configYAML) configFromFile(path string) error {
  378. b, err := ioutil.ReadFile(path)
  379. if err != nil {
  380. return err
  381. }
  382. defaultInitialCluster := cfg.InitialCluster
  383. err = yaml.Unmarshal(b, cfg)
  384. if err != nil {
  385. return err
  386. }
  387. if cfg.LPUrlsJSON != "" {
  388. u, err := types.NewURLs(strings.Split(cfg.LPUrlsJSON, ","))
  389. if err != nil {
  390. fmt.Fprintf(os.Stderr, "unexpected error setting up listen-peer-urls: %v\n", err)
  391. os.Exit(1)
  392. }
  393. cfg.LPUrls = []url.URL(u)
  394. }
  395. if cfg.LCUrlsJSON != "" {
  396. u, err := types.NewURLs(strings.Split(cfg.LCUrlsJSON, ","))
  397. if err != nil {
  398. fmt.Fprintf(os.Stderr, "unexpected error setting up listen-client-urls: %v\n", err)
  399. os.Exit(1)
  400. }
  401. cfg.LCUrls = []url.URL(u)
  402. }
  403. if cfg.APUrlsJSON != "" {
  404. u, err := types.NewURLs(strings.Split(cfg.APUrlsJSON, ","))
  405. if err != nil {
  406. fmt.Fprintf(os.Stderr, "unexpected error setting up initial-advertise-peer-urls: %v\n", err)
  407. os.Exit(1)
  408. }
  409. cfg.APUrls = []url.URL(u)
  410. }
  411. if cfg.ACUrlsJSON != "" {
  412. u, err := types.NewURLs(strings.Split(cfg.ACUrlsJSON, ","))
  413. if err != nil {
  414. fmt.Fprintf(os.Stderr, "unexpected error setting up advertise-peer-urls: %v\n", err)
  415. os.Exit(1)
  416. }
  417. cfg.ACUrls = []url.URL(u)
  418. }
  419. if cfg.ListenMetricsUrlsJSON != "" {
  420. u, err := types.NewURLs(strings.Split(cfg.ListenMetricsUrlsJSON, ","))
  421. if err != nil {
  422. fmt.Fprintf(os.Stderr, "unexpected error setting up listen-metrics-urls: %v\n", err)
  423. os.Exit(1)
  424. }
  425. cfg.ListenMetricsUrls = []url.URL(u)
  426. }
  427. if cfg.CORSJSON != "" {
  428. uv := flags.NewUniqueURLsWithExceptions(cfg.CORSJSON, "*")
  429. cfg.CORS = uv.Values
  430. }
  431. if cfg.HostWhitelistJSON != "" {
  432. uv := flags.NewUniqueStringsValue(cfg.HostWhitelistJSON)
  433. cfg.HostWhitelist = uv.Values
  434. }
  435. // If a discovery flag is set, clear default initial cluster set by InitialClusterFromName
  436. if (cfg.Durl != "" || cfg.DNSCluster != "") && cfg.InitialCluster == defaultInitialCluster {
  437. cfg.InitialCluster = ""
  438. }
  439. if cfg.ClusterState == "" {
  440. cfg.ClusterState = ClusterStateFlagNew
  441. }
  442. copySecurityDetails := func(tls *transport.TLSInfo, ysc *securityConfig) {
  443. tls.CertFile = ysc.CertFile
  444. tls.KeyFile = ysc.KeyFile
  445. tls.ClientCertAuth = ysc.CertAuth
  446. tls.TrustedCAFile = ysc.TrustedCAFile
  447. }
  448. copySecurityDetails(&cfg.ClientTLSInfo, &cfg.ClientSecurityJSON)
  449. copySecurityDetails(&cfg.PeerTLSInfo, &cfg.PeerSecurityJSON)
  450. cfg.ClientAutoTLS = cfg.ClientSecurityJSON.AutoTLS
  451. cfg.PeerAutoTLS = cfg.PeerSecurityJSON.AutoTLS
  452. return cfg.Validate()
  453. }
  454. func updateCipherSuites(tls *transport.TLSInfo, ss []string) error {
  455. if len(tls.CipherSuites) > 0 && len(ss) > 0 {
  456. return fmt.Errorf("TLSInfo.CipherSuites is already specified (given %v)", ss)
  457. }
  458. if len(ss) > 0 {
  459. cs := make([]uint16, len(ss))
  460. for i, s := range ss {
  461. var ok bool
  462. cs[i], ok = tlsutil.GetCipherSuite(s)
  463. if !ok {
  464. return fmt.Errorf("unexpected TLS cipher suite %q", s)
  465. }
  466. }
  467. tls.CipherSuites = cs
  468. }
  469. return nil
  470. }
  471. // Validate ensures that '*embed.Config' fields are properly configured.
  472. func (cfg *Config) Validate() error {
  473. if err := cfg.setupLogging(); err != nil {
  474. return err
  475. }
  476. if err := checkBindURLs(cfg.LPUrls); err != nil {
  477. return err
  478. }
  479. if err := checkBindURLs(cfg.LCUrls); err != nil {
  480. return err
  481. }
  482. if err := checkBindURLs(cfg.ListenMetricsUrls); err != nil {
  483. return err
  484. }
  485. if err := checkHostURLs(cfg.APUrls); err != nil {
  486. addrs := cfg.getAPURLs()
  487. return fmt.Errorf(`--initial-advertise-peer-urls %q must be "host:port" (%v)`, strings.Join(addrs, ","), err)
  488. }
  489. if err := checkHostURLs(cfg.ACUrls); err != nil {
  490. addrs := cfg.getACURLs()
  491. return fmt.Errorf(`--advertise-client-urls %q must be "host:port" (%v)`, strings.Join(addrs, ","), err)
  492. }
  493. // Check if conflicting flags are passed.
  494. nSet := 0
  495. for _, v := range []bool{cfg.Durl != "", cfg.InitialCluster != "", cfg.DNSCluster != ""} {
  496. if v {
  497. nSet++
  498. }
  499. }
  500. if cfg.ClusterState != ClusterStateFlagNew && cfg.ClusterState != ClusterStateFlagExisting {
  501. return fmt.Errorf("unexpected clusterState %q", cfg.ClusterState)
  502. }
  503. if nSet > 1 {
  504. return ErrConflictBootstrapFlags
  505. }
  506. if cfg.TickMs <= 0 {
  507. return fmt.Errorf("--heartbeat-interval must be >0 (set to %dms)", cfg.TickMs)
  508. }
  509. if cfg.ElectionMs <= 0 {
  510. return fmt.Errorf("--election-timeout must be >0 (set to %dms)", cfg.ElectionMs)
  511. }
  512. if 5*cfg.TickMs > cfg.ElectionMs {
  513. return fmt.Errorf("--election-timeout[%vms] should be at least as 5 times as --heartbeat-interval[%vms]", cfg.ElectionMs, cfg.TickMs)
  514. }
  515. if cfg.ElectionMs > maxElectionMs {
  516. return fmt.Errorf("--election-timeout[%vms] is too long, and should be set less than %vms", cfg.ElectionMs, maxElectionMs)
  517. }
  518. // check this last since proxying in etcdmain may make this OK
  519. if cfg.LCUrls != nil && cfg.ACUrls == nil {
  520. return ErrUnsetAdvertiseClientURLsFlag
  521. }
  522. switch cfg.AutoCompactionMode {
  523. case "":
  524. case CompactorModeRevision, CompactorModePeriodic:
  525. default:
  526. return fmt.Errorf("unknown auto-compaction-mode %q", cfg.AutoCompactionMode)
  527. }
  528. return nil
  529. }
  530. // PeerURLsMapAndToken sets up an initial peer URLsMap and cluster token for bootstrap or discovery.
  531. func (cfg *Config) PeerURLsMapAndToken(which string) (urlsmap types.URLsMap, token string, err error) {
  532. token = cfg.InitialClusterToken
  533. switch {
  534. case cfg.Durl != "":
  535. urlsmap = types.URLsMap{}
  536. // If using discovery, generate a temporary cluster based on
  537. // self's advertised peer URLs
  538. urlsmap[cfg.Name] = cfg.APUrls
  539. token = cfg.Durl
  540. case cfg.DNSCluster != "":
  541. clusterStrs, cerr := cfg.GetDNSClusterNames()
  542. lg := cfg.logger
  543. if cerr != nil {
  544. if lg != nil {
  545. lg.Warn("failed to resolve during SRV discovery", zap.Error(cerr))
  546. } else {
  547. plog.Errorf("couldn't resolve during SRV discovery (%v)", cerr)
  548. }
  549. return nil, "", cerr
  550. }
  551. for _, s := range clusterStrs {
  552. if lg != nil {
  553. lg.Info("got bootstrap from DNS for etcd-server", zap.String("node", s))
  554. } else {
  555. plog.Noticef("got bootstrap from DNS for etcd-server at %s", s)
  556. }
  557. }
  558. clusterStr := strings.Join(clusterStrs, ",")
  559. if strings.Contains(clusterStr, "https://") && cfg.PeerTLSInfo.TrustedCAFile == "" {
  560. cfg.PeerTLSInfo.ServerName = cfg.DNSCluster
  561. }
  562. urlsmap, err = types.NewURLsMap(clusterStr)
  563. // only etcd member must belong to the discovered cluster.
  564. // proxy does not need to belong to the discovered cluster.
  565. if which == "etcd" {
  566. if _, ok := urlsmap[cfg.Name]; !ok {
  567. return nil, "", fmt.Errorf("cannot find local etcd member %q in SRV records", cfg.Name)
  568. }
  569. }
  570. default:
  571. // We're statically configured, and cluster has appropriately been set.
  572. urlsmap, err = types.NewURLsMap(cfg.InitialCluster)
  573. }
  574. return urlsmap, token, err
  575. }
  576. // GetDNSClusterNames uses DNS SRV records to get a list of initial nodes for cluster bootstrapping.
  577. func (cfg *Config) GetDNSClusterNames() ([]string, error) {
  578. var (
  579. clusterStrs []string
  580. cerr error
  581. serviceNameSuffix string
  582. )
  583. if cfg.DNSClusterServiceName != "" {
  584. serviceNameSuffix = "-" + cfg.DNSClusterServiceName
  585. }
  586. lg := cfg.GetLogger()
  587. // Use both etcd-server-ssl and etcd-server for discovery.
  588. // Combine the results if both are available.
  589. clusterStrs, cerr = srv.GetCluster("https", "etcd-server-ssl"+serviceNameSuffix, cfg.Name, cfg.DNSCluster, cfg.APUrls)
  590. if cerr != nil {
  591. clusterStrs = make([]string, 0)
  592. }
  593. if lg != nil {
  594. lg.Info(
  595. "get cluster for etcd-server-ssl SRV",
  596. zap.String("service-scheme", "https"),
  597. zap.String("service-name", "etcd-server-ssl"+serviceNameSuffix),
  598. zap.String("server-name", cfg.Name),
  599. zap.String("discovery-srv", cfg.DNSCluster),
  600. zap.Strings("advertise-peer-urls", cfg.getAPURLs()),
  601. zap.Strings("found-cluster", clusterStrs),
  602. zap.Error(cerr),
  603. )
  604. }
  605. defaultHTTPClusterStrs, httpCerr := srv.GetCluster("http", "etcd-server"+serviceNameSuffix, cfg.Name, cfg.DNSCluster, cfg.APUrls)
  606. if httpCerr != nil {
  607. clusterStrs = append(clusterStrs, defaultHTTPClusterStrs...)
  608. }
  609. if lg != nil {
  610. lg.Info(
  611. "get cluster for etcd-server SRV",
  612. zap.String("service-scheme", "http"),
  613. zap.String("service-name", "etcd-server"+serviceNameSuffix),
  614. zap.String("server-name", cfg.Name),
  615. zap.String("discovery-srv", cfg.DNSCluster),
  616. zap.Strings("advertise-peer-urls", cfg.getAPURLs()),
  617. zap.Strings("found-cluster", clusterStrs),
  618. zap.Error(httpCerr),
  619. )
  620. }
  621. return clusterStrs, cerr
  622. }
  623. func (cfg Config) InitialClusterFromName(name string) (ret string) {
  624. if len(cfg.APUrls) == 0 {
  625. return ""
  626. }
  627. n := name
  628. if name == "" {
  629. n = DefaultName
  630. }
  631. for i := range cfg.APUrls {
  632. ret = ret + "," + n + "=" + cfg.APUrls[i].String()
  633. }
  634. return ret[1:]
  635. }
  636. func (cfg Config) IsNewCluster() bool { return cfg.ClusterState == ClusterStateFlagNew }
  637. func (cfg Config) ElectionTicks() int { return int(cfg.ElectionMs / cfg.TickMs) }
  638. func (cfg Config) defaultPeerHost() bool {
  639. return len(cfg.APUrls) == 1 && cfg.APUrls[0].String() == DefaultInitialAdvertisePeerURLs
  640. }
  641. func (cfg Config) defaultClientHost() bool {
  642. return len(cfg.ACUrls) == 1 && cfg.ACUrls[0].String() == DefaultAdvertiseClientURLs
  643. }
  644. func (cfg *Config) ClientSelfCert() (err error) {
  645. if !cfg.ClientAutoTLS {
  646. return nil
  647. }
  648. if !cfg.ClientTLSInfo.Empty() {
  649. if cfg.logger != nil {
  650. cfg.logger.Warn("ignoring client auto TLS since certs given")
  651. } else {
  652. plog.Warningf("ignoring client auto TLS since certs given")
  653. }
  654. return nil
  655. }
  656. chosts := make([]string, len(cfg.LCUrls))
  657. for i, u := range cfg.LCUrls {
  658. chosts[i] = u.Host
  659. }
  660. cfg.ClientTLSInfo, err = transport.SelfCert(cfg.logger, filepath.Join(cfg.Dir, "fixtures", "client"), chosts)
  661. if err != nil {
  662. return err
  663. }
  664. return updateCipherSuites(&cfg.ClientTLSInfo, cfg.CipherSuites)
  665. }
  666. func (cfg *Config) PeerSelfCert() (err error) {
  667. if !cfg.PeerAutoTLS {
  668. return nil
  669. }
  670. if !cfg.PeerTLSInfo.Empty() {
  671. if cfg.logger != nil {
  672. cfg.logger.Warn("ignoring peer auto TLS since certs given")
  673. } else {
  674. plog.Warningf("ignoring peer auto TLS since certs given")
  675. }
  676. return nil
  677. }
  678. phosts := make([]string, len(cfg.LPUrls))
  679. for i, u := range cfg.LPUrls {
  680. phosts[i] = u.Host
  681. }
  682. cfg.PeerTLSInfo, err = transport.SelfCert(cfg.logger, filepath.Join(cfg.Dir, "fixtures", "peer"), phosts)
  683. if err != nil {
  684. return err
  685. }
  686. return updateCipherSuites(&cfg.PeerTLSInfo, cfg.CipherSuites)
  687. }
  688. // UpdateDefaultClusterFromName updates cluster advertise URLs with, if available, default host,
  689. // if advertise URLs are default values(localhost:2379,2380) AND if listen URL is 0.0.0.0.
  690. // e.g. advertise peer URL localhost:2380 or listen peer URL 0.0.0.0:2380
  691. // then the advertise peer host would be updated with machine's default host,
  692. // while keeping the listen URL's port.
  693. // User can work around this by explicitly setting URL with 127.0.0.1.
  694. // It returns the default hostname, if used, and the error, if any, from getting the machine's default host.
  695. // TODO: check whether fields are set instead of whether fields have default value
  696. func (cfg *Config) UpdateDefaultClusterFromName(defaultInitialCluster string) (string, error) {
  697. if defaultHostname == "" || defaultHostStatus != nil {
  698. // update 'initial-cluster' when only the name is specified (e.g. 'etcd --name=abc')
  699. if cfg.Name != DefaultName && cfg.InitialCluster == defaultInitialCluster {
  700. cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
  701. }
  702. return "", defaultHostStatus
  703. }
  704. used := false
  705. pip, pport := cfg.LPUrls[0].Hostname(), cfg.LPUrls[0].Port()
  706. if cfg.defaultPeerHost() && pip == "0.0.0.0" {
  707. cfg.APUrls[0] = url.URL{Scheme: cfg.APUrls[0].Scheme, Host: fmt.Sprintf("%s:%s", defaultHostname, pport)}
  708. used = true
  709. }
  710. // update 'initial-cluster' when only the name is specified (e.g. 'etcd --name=abc')
  711. if cfg.Name != DefaultName && cfg.InitialCluster == defaultInitialCluster {
  712. cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
  713. }
  714. cip, cport := cfg.LCUrls[0].Hostname(), cfg.LCUrls[0].Port()
  715. if cfg.defaultClientHost() && cip == "0.0.0.0" {
  716. cfg.ACUrls[0] = url.URL{Scheme: cfg.ACUrls[0].Scheme, Host: fmt.Sprintf("%s:%s", defaultHostname, cport)}
  717. used = true
  718. }
  719. dhost := defaultHostname
  720. if !used {
  721. dhost = ""
  722. }
  723. return dhost, defaultHostStatus
  724. }
  725. // checkBindURLs returns an error if any URL uses a domain name.
  726. func checkBindURLs(urls []url.URL) error {
  727. for _, url := range urls {
  728. if url.Scheme == "unix" || url.Scheme == "unixs" {
  729. continue
  730. }
  731. host, _, err := net.SplitHostPort(url.Host)
  732. if err != nil {
  733. return err
  734. }
  735. if host == "localhost" {
  736. // special case for local address
  737. // TODO: support /etc/hosts ?
  738. continue
  739. }
  740. if net.ParseIP(host) == nil {
  741. return fmt.Errorf("expected IP in URL for binding (%s)", url.String())
  742. }
  743. }
  744. return nil
  745. }
  746. func checkHostURLs(urls []url.URL) error {
  747. for _, url := range urls {
  748. host, _, err := net.SplitHostPort(url.Host)
  749. if err != nil {
  750. return err
  751. }
  752. if host == "" {
  753. return fmt.Errorf("unexpected empty host (%s)", url.String())
  754. }
  755. }
  756. return nil
  757. }
  758. func (cfg *Config) getAPURLs() (ss []string) {
  759. ss = make([]string, len(cfg.APUrls))
  760. for i := range cfg.APUrls {
  761. ss[i] = cfg.APUrls[i].String()
  762. }
  763. return ss
  764. }
  765. func (cfg *Config) getLPURLs() (ss []string) {
  766. ss = make([]string, len(cfg.LPUrls))
  767. for i := range cfg.LPUrls {
  768. ss[i] = cfg.LPUrls[i].String()
  769. }
  770. return ss
  771. }
  772. func (cfg *Config) getACURLs() (ss []string) {
  773. ss = make([]string, len(cfg.ACUrls))
  774. for i := range cfg.ACUrls {
  775. ss[i] = cfg.ACUrls[i].String()
  776. }
  777. return ss
  778. }
  779. func (cfg *Config) getLCURLs() (ss []string) {
  780. ss = make([]string, len(cfg.LCUrls))
  781. for i := range cfg.LCUrls {
  782. ss[i] = cfg.LCUrls[i].String()
  783. }
  784. return ss
  785. }
  786. func (cfg *Config) getMetricsURLs() (ss []string) {
  787. ss = make([]string, len(cfg.ListenMetricsUrls))
  788. for i := range cfg.ListenMetricsUrls {
  789. ss[i] = cfg.ListenMetricsUrls[i].String()
  790. }
  791. return ss
  792. }
  793. func parseBackendFreelistType(freelistType string) bolt.FreelistType {
  794. if freelistType == freelistMapType {
  795. return bolt.FreelistMapType
  796. }
  797. return bolt.FreelistArrayType
  798. }