config.go 29 KB

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