config.go 28 KB

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