config.go 30 KB

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