config.go 30 KB

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