config.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  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 "discard": // only for testing
  382. lcfg.OutputPaths = []string{}
  383. lcfg.ErrorOutputPaths = []string{}
  384. ignoreLog = true
  385. default:
  386. lcfg.OutputPaths = []string{cfg.LogOutput}
  387. lcfg.ErrorOutputPaths = []string{cfg.LogOutput}
  388. }
  389. if cfg.Debug {
  390. lcfg.Level = zap.NewAtomicLevelAt(zap.DebugLevel)
  391. grpc.EnableTracing = true
  392. }
  393. var err error
  394. if !ignoreLog {
  395. cfg.logger, err = lcfg.Build()
  396. } else {
  397. cfg.logger = zap.NewNop()
  398. }
  399. if err != nil {
  400. return err
  401. }
  402. cfg.loggerConfig = lcfg
  403. grpcLogOnce.Do(func() {
  404. // debug true, enable info, warning, error
  405. // debug false, only discard info
  406. var gl grpclog.LoggerV2
  407. gl, err = logutil.NewGRPCLoggerV2(lcfg)
  408. if err == nil {
  409. grpclog.SetLoggerV2(gl)
  410. }
  411. })
  412. if err != nil {
  413. return err
  414. }
  415. logTLSHandshakeFailure := func(conn *tls.Conn, err error) {
  416. state := conn.ConnectionState()
  417. remoteAddr := conn.RemoteAddr().String()
  418. serverName := state.ServerName
  419. if len(state.PeerCertificates) > 0 {
  420. cert := state.PeerCertificates[0]
  421. ips := make([]string, 0, len(cert.IPAddresses))
  422. for i := range cert.IPAddresses {
  423. ips[i] = cert.IPAddresses[i].String()
  424. }
  425. cfg.logger.Warn(
  426. "rejected connection",
  427. zap.String("remote-addr", remoteAddr),
  428. zap.String("server-name", serverName),
  429. zap.Strings("ip-addresses", ips),
  430. zap.Strings("dns-names", cert.DNSNames),
  431. zap.Error(err),
  432. )
  433. } else {
  434. cfg.logger.Warn(
  435. "rejected connection",
  436. zap.String("remote-addr", remoteAddr),
  437. zap.String("server-name", serverName),
  438. zap.Error(err),
  439. )
  440. }
  441. }
  442. cfg.ClientTLSInfo.HandshakeFailure = logTLSHandshakeFailure
  443. cfg.PeerTLSInfo.HandshakeFailure = logTLSHandshakeFailure
  444. default:
  445. return fmt.Errorf("unknown logger option %q", cfg.Logger)
  446. }
  447. return nil
  448. }
  449. func ConfigFromFile(path string) (*Config, error) {
  450. cfg := &configYAML{Config: *NewConfig()}
  451. if err := cfg.configFromFile(path); err != nil {
  452. return nil, err
  453. }
  454. return &cfg.Config, nil
  455. }
  456. func (cfg *configYAML) configFromFile(path string) error {
  457. b, err := ioutil.ReadFile(path)
  458. if err != nil {
  459. return err
  460. }
  461. defaultInitialCluster := cfg.InitialCluster
  462. err = yaml.Unmarshal(b, cfg)
  463. if err != nil {
  464. return err
  465. }
  466. if cfg.LPUrlsJSON != "" {
  467. u, err := types.NewURLs(strings.Split(cfg.LPUrlsJSON, ","))
  468. if err != nil {
  469. fmt.Fprintf(os.Stderr, "unexpected error setting up listen-peer-urls: %v\n", err)
  470. os.Exit(1)
  471. }
  472. cfg.LPUrls = []url.URL(u)
  473. }
  474. if cfg.LCUrlsJSON != "" {
  475. u, err := types.NewURLs(strings.Split(cfg.LCUrlsJSON, ","))
  476. if err != nil {
  477. fmt.Fprintf(os.Stderr, "unexpected error setting up listen-client-urls: %v\n", err)
  478. os.Exit(1)
  479. }
  480. cfg.LCUrls = []url.URL(u)
  481. }
  482. if cfg.APUrlsJSON != "" {
  483. u, err := types.NewURLs(strings.Split(cfg.APUrlsJSON, ","))
  484. if err != nil {
  485. fmt.Fprintf(os.Stderr, "unexpected error setting up initial-advertise-peer-urls: %v\n", err)
  486. os.Exit(1)
  487. }
  488. cfg.APUrls = []url.URL(u)
  489. }
  490. if cfg.ACUrlsJSON != "" {
  491. u, err := types.NewURLs(strings.Split(cfg.ACUrlsJSON, ","))
  492. if err != nil {
  493. fmt.Fprintf(os.Stderr, "unexpected error setting up advertise-peer-urls: %v\n", err)
  494. os.Exit(1)
  495. }
  496. cfg.ACUrls = []url.URL(u)
  497. }
  498. if cfg.ListenMetricsUrlsJSON != "" {
  499. u, err := types.NewURLs(strings.Split(cfg.ListenMetricsUrlsJSON, ","))
  500. if err != nil {
  501. fmt.Fprintf(os.Stderr, "unexpected error setting up listen-metrics-urls: %v\n", err)
  502. os.Exit(1)
  503. }
  504. cfg.ListenMetricsUrls = []url.URL(u)
  505. }
  506. if cfg.CORSJSON != "" {
  507. uv := flags.NewUniqueURLsWithExceptions(cfg.CORSJSON, "*")
  508. cfg.CORS = uv.Values
  509. }
  510. if cfg.HostWhitelistJSON != "" {
  511. uv := flags.NewUniqueStringsValue(cfg.HostWhitelistJSON)
  512. cfg.HostWhitelist = uv.Values
  513. }
  514. // If a discovery flag is set, clear default initial cluster set by InitialClusterFromName
  515. if (cfg.Durl != "" || cfg.DNSCluster != "") && cfg.InitialCluster == defaultInitialCluster {
  516. cfg.InitialCluster = ""
  517. }
  518. if cfg.ClusterState == "" {
  519. cfg.ClusterState = ClusterStateFlagNew
  520. }
  521. copySecurityDetails := func(tls *transport.TLSInfo, ysc *securityConfig) {
  522. tls.CertFile = ysc.CertFile
  523. tls.KeyFile = ysc.KeyFile
  524. tls.ClientCertAuth = ysc.CertAuth
  525. tls.TrustedCAFile = ysc.TrustedCAFile
  526. }
  527. copySecurityDetails(&cfg.ClientTLSInfo, &cfg.ClientSecurityJSON)
  528. copySecurityDetails(&cfg.PeerTLSInfo, &cfg.PeerSecurityJSON)
  529. cfg.ClientAutoTLS = cfg.ClientSecurityJSON.AutoTLS
  530. cfg.PeerAutoTLS = cfg.PeerSecurityJSON.AutoTLS
  531. return cfg.Validate()
  532. }
  533. // Validate ensures that '*embed.Config' fields are properly configured.
  534. func (cfg *Config) Validate() error {
  535. if err := cfg.setupLogging(); err != nil {
  536. return err
  537. }
  538. if err := checkBindURLs(cfg.LPUrls); err != nil {
  539. return err
  540. }
  541. if err := checkBindURLs(cfg.LCUrls); err != nil {
  542. return err
  543. }
  544. if err := checkBindURLs(cfg.ListenMetricsUrls); err != nil {
  545. return err
  546. }
  547. if err := checkHostURLs(cfg.APUrls); err != nil {
  548. addrs := make([]string, len(cfg.APUrls))
  549. for i := range cfg.APUrls {
  550. addrs[i] = cfg.APUrls[i].String()
  551. }
  552. return fmt.Errorf(`--initial-advertise-peer-urls %q must be "host:port" (%v)`, strings.Join(addrs, ","), err)
  553. }
  554. if err := checkHostURLs(cfg.ACUrls); err != nil {
  555. addrs := make([]string, len(cfg.ACUrls))
  556. for i := range cfg.ACUrls {
  557. addrs[i] = cfg.ACUrls[i].String()
  558. }
  559. return fmt.Errorf(`--advertise-client-urls %q must be "host:port" (%v)`, strings.Join(addrs, ","), err)
  560. }
  561. // Check if conflicting flags are passed.
  562. nSet := 0
  563. for _, v := range []bool{cfg.Durl != "", cfg.InitialCluster != "", cfg.DNSCluster != ""} {
  564. if v {
  565. nSet++
  566. }
  567. }
  568. if cfg.ClusterState != ClusterStateFlagNew && cfg.ClusterState != ClusterStateFlagExisting {
  569. return fmt.Errorf("unexpected clusterState %q", cfg.ClusterState)
  570. }
  571. if nSet > 1 {
  572. return ErrConflictBootstrapFlags
  573. }
  574. if cfg.TickMs <= 0 {
  575. return fmt.Errorf("--heartbeat-interval must be >0 (set to %dms)", cfg.TickMs)
  576. }
  577. if cfg.ElectionMs <= 0 {
  578. return fmt.Errorf("--election-timeout must be >0 (set to %dms)", cfg.ElectionMs)
  579. }
  580. if 5*cfg.TickMs > cfg.ElectionMs {
  581. return fmt.Errorf("--election-timeout[%vms] should be at least as 5 times as --heartbeat-interval[%vms]", cfg.ElectionMs, cfg.TickMs)
  582. }
  583. if cfg.ElectionMs > maxElectionMs {
  584. return fmt.Errorf("--election-timeout[%vms] is too long, and should be set less than %vms", cfg.ElectionMs, maxElectionMs)
  585. }
  586. // check this last since proxying in etcdmain may make this OK
  587. if cfg.LCUrls != nil && cfg.ACUrls == nil {
  588. return ErrUnsetAdvertiseClientURLsFlag
  589. }
  590. switch cfg.AutoCompactionMode {
  591. case "":
  592. case CompactorModeRevision, CompactorModePeriodic:
  593. default:
  594. return fmt.Errorf("unknown auto-compaction-mode %q", cfg.AutoCompactionMode)
  595. }
  596. return nil
  597. }
  598. // PeerURLsMapAndToken sets up an initial peer URLsMap and cluster token for bootstrap or discovery.
  599. func (cfg *Config) PeerURLsMapAndToken(which string) (urlsmap types.URLsMap, token string, err error) {
  600. token = cfg.InitialClusterToken
  601. switch {
  602. case cfg.Durl != "":
  603. urlsmap = types.URLsMap{}
  604. // If using discovery, generate a temporary cluster based on
  605. // self's advertised peer URLs
  606. urlsmap[cfg.Name] = cfg.APUrls
  607. token = cfg.Durl
  608. case cfg.DNSCluster != "":
  609. clusterStrs, cerr := cfg.GetDNSClusterNames()
  610. lg := cfg.logger
  611. if cerr != nil {
  612. if lg != nil {
  613. lg.Error("failed to resolve during SRV discovery", zap.Error(cerr))
  614. } else {
  615. plog.Errorf("couldn't resolve during SRV discovery (%v)", cerr)
  616. }
  617. return nil, "", cerr
  618. }
  619. for _, s := range clusterStrs {
  620. if lg != nil {
  621. lg.Info("got bootstrap from DNS for etcd-server", zap.String("node", s))
  622. } else {
  623. plog.Noticef("got bootstrap from DNS for etcd-server at %s", s)
  624. }
  625. }
  626. clusterStr := strings.Join(clusterStrs, ",")
  627. if strings.Contains(clusterStr, "https://") && cfg.PeerTLSInfo.TrustedCAFile == "" {
  628. cfg.PeerTLSInfo.ServerName = cfg.DNSCluster
  629. }
  630. urlsmap, err = types.NewURLsMap(clusterStr)
  631. // only etcd member must belong to the discovered cluster.
  632. // proxy does not need to belong to the discovered cluster.
  633. if which == "etcd" {
  634. if _, ok := urlsmap[cfg.Name]; !ok {
  635. return nil, "", fmt.Errorf("cannot find local etcd member %q in SRV records", cfg.Name)
  636. }
  637. }
  638. default:
  639. // We're statically configured, and cluster has appropriately been set.
  640. urlsmap, err = types.NewURLsMap(cfg.InitialCluster)
  641. }
  642. return urlsmap, token, err
  643. }
  644. // GetDNSClusterNames uses DNS SRV records to get a list of initial nodes for cluster bootstrapping.
  645. func (cfg *Config) GetDNSClusterNames() ([]string, error) {
  646. var (
  647. clusterStrs []string
  648. cerr error
  649. serviceNameSuffix string
  650. )
  651. if cfg.DNSClusterServiceName != "" {
  652. serviceNameSuffix = "-" + cfg.DNSClusterServiceName
  653. }
  654. // Use both etcd-server-ssl and etcd-server for discovery. Combine the results if both are available.
  655. clusterStrs, cerr = srv.GetCluster("https", "etcd-server-ssl"+serviceNameSuffix, cfg.Name, cfg.DNSCluster, cfg.APUrls)
  656. defaultHTTPClusterStrs, httpCerr := srv.GetCluster("http", "etcd-server"+serviceNameSuffix, cfg.Name, cfg.DNSCluster, cfg.APUrls)
  657. if cerr != nil {
  658. clusterStrs = make([]string, 0)
  659. }
  660. if httpCerr != nil {
  661. clusterStrs = append(clusterStrs, defaultHTTPClusterStrs...)
  662. }
  663. return clusterStrs, cerr
  664. }
  665. func (cfg Config) InitialClusterFromName(name string) (ret string) {
  666. if len(cfg.APUrls) == 0 {
  667. return ""
  668. }
  669. n := name
  670. if name == "" {
  671. n = DefaultName
  672. }
  673. for i := range cfg.APUrls {
  674. ret = ret + "," + n + "=" + cfg.APUrls[i].String()
  675. }
  676. return ret[1:]
  677. }
  678. func (cfg Config) IsNewCluster() bool { return cfg.ClusterState == ClusterStateFlagNew }
  679. func (cfg Config) ElectionTicks() int { return int(cfg.ElectionMs / cfg.TickMs) }
  680. func (cfg Config) defaultPeerHost() bool {
  681. return len(cfg.APUrls) == 1 && cfg.APUrls[0].String() == DefaultInitialAdvertisePeerURLs
  682. }
  683. func (cfg Config) defaultClientHost() bool {
  684. return len(cfg.ACUrls) == 1 && cfg.ACUrls[0].String() == DefaultAdvertiseClientURLs
  685. }
  686. func (cfg *Config) ClientSelfCert() (err error) {
  687. if cfg.ClientAutoTLS && cfg.ClientTLSInfo.Empty() {
  688. chosts := make([]string, len(cfg.LCUrls))
  689. for i, u := range cfg.LCUrls {
  690. chosts[i] = u.Host
  691. }
  692. cfg.ClientTLSInfo, err = transport.SelfCert(cfg.logger, filepath.Join(cfg.Dir, "fixtures", "client"), chosts)
  693. return err
  694. } else if cfg.ClientAutoTLS {
  695. if cfg.logger != nil {
  696. cfg.logger.Warn("ignoring client auto TLS since certs given")
  697. } else {
  698. plog.Warningf("ignoring client auto TLS since certs given")
  699. }
  700. }
  701. return nil
  702. }
  703. func (cfg *Config) PeerSelfCert() (err error) {
  704. if cfg.PeerAutoTLS && cfg.PeerTLSInfo.Empty() {
  705. phosts := make([]string, len(cfg.LPUrls))
  706. for i, u := range cfg.LPUrls {
  707. phosts[i] = u.Host
  708. }
  709. cfg.PeerTLSInfo, err = transport.SelfCert(cfg.logger, filepath.Join(cfg.Dir, "fixtures", "peer"), phosts)
  710. return err
  711. } else if cfg.PeerAutoTLS {
  712. if cfg.logger != nil {
  713. cfg.logger.Warn("ignoring peer auto TLS since certs given")
  714. } else {
  715. plog.Warningf("ignoring peer auto TLS since certs given")
  716. }
  717. }
  718. return nil
  719. }
  720. // UpdateDefaultClusterFromName updates cluster advertise URLs with, if available, default host,
  721. // if advertise URLs are default values(localhost:2379,2380) AND if listen URL is 0.0.0.0.
  722. // e.g. advertise peer URL localhost:2380 or listen peer URL 0.0.0.0:2380
  723. // then the advertise peer host would be updated with machine's default host,
  724. // while keeping the listen URL's port.
  725. // User can work around this by explicitly setting URL with 127.0.0.1.
  726. // It returns the default hostname, if used, and the error, if any, from getting the machine's default host.
  727. // TODO: check whether fields are set instead of whether fields have default value
  728. func (cfg *Config) UpdateDefaultClusterFromName(defaultInitialCluster string) (string, error) {
  729. if defaultHostname == "" || defaultHostStatus != nil {
  730. // update 'initial-cluster' when only the name is specified (e.g. 'etcd --name=abc')
  731. if cfg.Name != DefaultName && cfg.InitialCluster == defaultInitialCluster {
  732. cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
  733. }
  734. return "", defaultHostStatus
  735. }
  736. used := false
  737. pip, pport := cfg.LPUrls[0].Hostname(), cfg.LPUrls[0].Port()
  738. if cfg.defaultPeerHost() && pip == "0.0.0.0" {
  739. cfg.APUrls[0] = url.URL{Scheme: cfg.APUrls[0].Scheme, Host: fmt.Sprintf("%s:%s", defaultHostname, pport)}
  740. used = true
  741. }
  742. // update 'initial-cluster' when only the name is specified (e.g. 'etcd --name=abc')
  743. if cfg.Name != DefaultName && cfg.InitialCluster == defaultInitialCluster {
  744. cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
  745. }
  746. cip, cport := cfg.LCUrls[0].Hostname(), cfg.LCUrls[0].Port()
  747. if cfg.defaultClientHost() && cip == "0.0.0.0" {
  748. cfg.ACUrls[0] = url.URL{Scheme: cfg.ACUrls[0].Scheme, Host: fmt.Sprintf("%s:%s", defaultHostname, cport)}
  749. used = true
  750. }
  751. dhost := defaultHostname
  752. if !used {
  753. dhost = ""
  754. }
  755. return dhost, defaultHostStatus
  756. }
  757. // checkBindURLs returns an error if any URL uses a domain name.
  758. func checkBindURLs(urls []url.URL) error {
  759. for _, url := range urls {
  760. if url.Scheme == "unix" || url.Scheme == "unixs" {
  761. continue
  762. }
  763. host, _, err := net.SplitHostPort(url.Host)
  764. if err != nil {
  765. return err
  766. }
  767. if host == "localhost" {
  768. // special case for local address
  769. // TODO: support /etc/hosts ?
  770. continue
  771. }
  772. if net.ParseIP(host) == nil {
  773. return fmt.Errorf("expected IP in URL for binding (%s)", url.String())
  774. }
  775. }
  776. return nil
  777. }
  778. func checkHostURLs(urls []url.URL) error {
  779. for _, url := range urls {
  780. host, _, err := net.SplitHostPort(url.Host)
  781. if err != nil {
  782. return err
  783. }
  784. if host == "" {
  785. return fmt.Errorf("unexpected empty host (%s)", url.String())
  786. }
  787. }
  788. return nil
  789. }