config.go 28 KB

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