config.go 28 KB

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