config.go 35 KB

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