config.go 32 KB

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