config.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  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. "time"
  26. "github.com/coreos/etcd/compactor"
  27. "github.com/coreos/etcd/etcdserver"
  28. "github.com/coreos/etcd/pkg/cors"
  29. "github.com/coreos/etcd/pkg/netutil"
  30. "github.com/coreos/etcd/pkg/srv"
  31. "github.com/coreos/etcd/pkg/tlsutil"
  32. "github.com/coreos/etcd/pkg/transport"
  33. "github.com/coreos/etcd/pkg/types"
  34. "github.com/coreos/pkg/capnslog"
  35. "github.com/ghodss/yaml"
  36. "google.golang.org/grpc"
  37. "google.golang.org/grpc/grpclog"
  38. )
  39. const (
  40. ClusterStateFlagNew = "new"
  41. ClusterStateFlagExisting = "existing"
  42. DefaultName = "default"
  43. DefaultMaxSnapshots = 5
  44. DefaultMaxWALs = 5
  45. DefaultMaxTxnOps = uint(128)
  46. DefaultMaxRequestBytes = 1.5 * 1024 * 1024
  47. DefaultGRPCKeepAliveMinTime = 5 * time.Second
  48. DefaultGRPCKeepAliveInterval = 2 * time.Hour
  49. DefaultGRPCKeepAliveTimeout = 20 * time.Second
  50. DefaultListenPeerURLs = "http://localhost:2380"
  51. DefaultListenClientURLs = "http://localhost:2379"
  52. DefaultLogOutput = "default"
  53. // DefaultStrictReconfigCheck is the default value for "--strict-reconfig-check" flag.
  54. // It's enabled by default.
  55. DefaultStrictReconfigCheck = true
  56. // DefaultEnableV2 is the default value for "--enable-v2" flag.
  57. // v2 is enabled by default.
  58. // TODO: disable v2 when deprecated.
  59. DefaultEnableV2 = true
  60. // maxElectionMs specifies the maximum value of election timeout.
  61. // More details are listed in ../Documentation/tuning.md#time-parameters.
  62. maxElectionMs = 50000
  63. )
  64. var (
  65. ErrConflictBootstrapFlags = fmt.Errorf("multiple discovery or bootstrap flags are set. " +
  66. "Choose one of \"initial-cluster\", \"discovery\" or \"discovery-srv\"")
  67. ErrUnsetAdvertiseClientURLsFlag = fmt.Errorf("--advertise-client-urls is required when --listen-client-urls is set explicitly")
  68. DefaultInitialAdvertisePeerURLs = "http://localhost:2380"
  69. DefaultAdvertiseClientURLs = "http://localhost:2379"
  70. defaultHostname string
  71. defaultHostStatus error
  72. )
  73. func init() {
  74. defaultHostname, defaultHostStatus = netutil.GetDefaultHost()
  75. }
  76. // Config holds the arguments for configuring an etcd server.
  77. type Config struct {
  78. // member
  79. CorsInfo *cors.CORSInfo
  80. LPUrls, LCUrls []url.URL
  81. Dir string `json:"data-dir"`
  82. WalDir string `json:"wal-dir"`
  83. MaxSnapFiles uint `json:"max-snapshots"`
  84. MaxWalFiles uint `json:"max-wals"`
  85. Name string `json:"name"`
  86. SnapCount uint64 `json:"snapshot-count"`
  87. // AutoCompactionMode is either 'periodic' or 'revision'.
  88. AutoCompactionMode string `json:"auto-compaction-mode"`
  89. // AutoCompactionRetention is either duration string with time unit
  90. // (e.g. '5m' for 5-minute), or revision unit (e.g. '5000').
  91. // If no time unit is provided and compaction mode is 'periodic',
  92. // the unit defaults to hour. For example, '5' translates into 5-hour.
  93. AutoCompactionRetention string `json:"auto-compaction-retention"`
  94. // TickMs is the number of milliseconds between heartbeat ticks.
  95. // TODO: decouple tickMs and heartbeat tick (current heartbeat tick = 1).
  96. // make ticks a cluster wide configuration.
  97. TickMs uint `json:"heartbeat-interval"`
  98. ElectionMs uint `json:"election-timeout"`
  99. // InitialElectionTickAdvance is true, then local member fast-forwards
  100. // election ticks to speed up "initial" leader election trigger. This
  101. // benefits the case of larger election ticks. For instance, cross
  102. // datacenter deployment may require longer election timeout of 10-second.
  103. // If true, local node does not need wait up to 10-second. Instead,
  104. // forwards its election ticks to 8-second, and have only 2-second left
  105. // before leader election.
  106. //
  107. // Major assumptions are that:
  108. // - cluster has no active leader thus advancing ticks enables faster
  109. // leader election, or
  110. // - cluster already has an established leader, and rejoining follower
  111. // is likely to receive heartbeats from the leader after tick advance
  112. // and before election timeout.
  113. //
  114. // However, when network from leader to rejoining follower is congested,
  115. // and the follower does not receive leader heartbeat within left election
  116. // ticks, disruptive election has to happen thus affecting cluster
  117. // availabilities.
  118. //
  119. // Disabling this would slow down initial bootstrap process for cross
  120. // datacenter deployments. Make your own tradeoffs by configuring
  121. // --initial-election-tick-advance at the cost of slow initial bootstrap.
  122. //
  123. // If single-node, it advances ticks regardless.
  124. //
  125. // See https://github.com/coreos/etcd/issues/9333 for more detail.
  126. InitialElectionTickAdvance bool `json:"initial-election-tick-advance"`
  127. QuotaBackendBytes int64 `json:"quota-backend-bytes"`
  128. MaxTxnOps uint `json:"max-txn-ops"`
  129. MaxRequestBytes uint `json:"max-request-bytes"`
  130. // gRPC server options
  131. // GRPCKeepAliveMinTime is the minimum interval that a client should
  132. // wait before pinging server. When client pings "too fast", server
  133. // sends goaway and closes the connection (errors: too_many_pings,
  134. // http2.ErrCodeEnhanceYourCalm). When too slow, nothing happens.
  135. // Server expects client pings only when there is any active streams
  136. // (PermitWithoutStream is set false).
  137. GRPCKeepAliveMinTime time.Duration `json:"grpc-keepalive-min-time"`
  138. // GRPCKeepAliveInterval is the frequency of server-to-client ping
  139. // to check if a connection is alive. Close a non-responsive connection
  140. // after an additional duration of Timeout. 0 to disable.
  141. GRPCKeepAliveInterval time.Duration `json:"grpc-keepalive-interval"`
  142. // GRPCKeepAliveTimeout is the additional duration of wait
  143. // before closing a non-responsive connection. 0 to disable.
  144. GRPCKeepAliveTimeout time.Duration `json:"grpc-keepalive-timeout"`
  145. // clustering
  146. APUrls, ACUrls []url.URL
  147. ClusterState string `json:"initial-cluster-state"`
  148. DNSCluster string `json:"discovery-srv"`
  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. // security
  156. ClientTLSInfo transport.TLSInfo
  157. ClientAutoTLS bool
  158. PeerTLSInfo transport.TLSInfo
  159. PeerAutoTLS bool
  160. // CipherSuites is a list of supported TLS cipher suites between
  161. // client/server and peers. If empty, Go auto-populates the list.
  162. // Note that cipher suites are prioritized in the given order.
  163. CipherSuites []string `json:"cipher-suites"`
  164. // debug
  165. Debug bool `json:"debug"`
  166. LogPkgLevels string `json:"log-package-levels"`
  167. LogOutput string `json:"log-output"`
  168. EnablePprof bool `json:"enable-pprof"`
  169. Metrics string `json:"metrics"`
  170. ListenMetricsUrls []url.URL
  171. ListenMetricsUrlsJSON string `json:"listen-metrics-urls"`
  172. // ForceNewCluster starts a new cluster even if previously started; unsafe.
  173. ForceNewCluster bool `json:"force-new-cluster"`
  174. // UserHandlers is for registering users handlers and only used for
  175. // embedding etcd into other applications.
  176. // The map key is the route path for the handler, and
  177. // you must ensure it can't be conflicted with etcd's.
  178. UserHandlers map[string]http.Handler `json:"-"`
  179. // ServiceRegister is for registering users' gRPC services. A simple usage example:
  180. // cfg := embed.NewConfig()
  181. // cfg.ServerRegister = func(s *grpc.Server) {
  182. // pb.RegisterFooServer(s, &fooServer{})
  183. // pb.RegisterBarServer(s, &barServer{})
  184. // }
  185. // embed.StartEtcd(cfg)
  186. ServiceRegister func(*grpc.Server) `json:"-"`
  187. // auth
  188. AuthToken string `json:"auth-token"`
  189. // Experimental flags
  190. ExperimentalInitialCorruptCheck bool `json:"experimental-initial-corrupt-check"`
  191. ExperimentalCorruptCheckTime time.Duration `json:"experimental-corrupt-check-time"`
  192. ExperimentalEnableV2V3 string `json:"experimental-enable-v2v3"`
  193. }
  194. // configYAML holds the config suitable for yaml parsing
  195. type configYAML struct {
  196. Config
  197. configJSON
  198. }
  199. // configJSON has file options that are translated into Config options
  200. type configJSON struct {
  201. LPUrlsJSON string `json:"listen-peer-urls"`
  202. LCUrlsJSON string `json:"listen-client-urls"`
  203. CorsJSON string `json:"cors"`
  204. APUrlsJSON string `json:"initial-advertise-peer-urls"`
  205. ACUrlsJSON string `json:"advertise-client-urls"`
  206. ClientSecurityJSON securityConfig `json:"client-transport-security"`
  207. PeerSecurityJSON securityConfig `json:"peer-transport-security"`
  208. }
  209. type securityConfig struct {
  210. CAFile string `json:"ca-file"`
  211. CertFile string `json:"cert-file"`
  212. KeyFile string `json:"key-file"`
  213. CertAuth bool `json:"client-cert-auth"`
  214. TrustedCAFile string `json:"trusted-ca-file"`
  215. AutoTLS bool `json:"auto-tls"`
  216. }
  217. // NewConfig creates a new Config populated with default values.
  218. func NewConfig() *Config {
  219. lpurl, _ := url.Parse(DefaultListenPeerURLs)
  220. apurl, _ := url.Parse(DefaultInitialAdvertisePeerURLs)
  221. lcurl, _ := url.Parse(DefaultListenClientURLs)
  222. acurl, _ := url.Parse(DefaultAdvertiseClientURLs)
  223. cfg := &Config{
  224. CorsInfo: &cors.CORSInfo{},
  225. MaxSnapFiles: DefaultMaxSnapshots,
  226. MaxWalFiles: DefaultMaxWALs,
  227. Name: DefaultName,
  228. SnapCount: etcdserver.DefaultSnapCount,
  229. MaxTxnOps: DefaultMaxTxnOps,
  230. MaxRequestBytes: DefaultMaxRequestBytes,
  231. GRPCKeepAliveMinTime: DefaultGRPCKeepAliveMinTime,
  232. GRPCKeepAliveInterval: DefaultGRPCKeepAliveInterval,
  233. GRPCKeepAliveTimeout: DefaultGRPCKeepAliveTimeout,
  234. TickMs: 100,
  235. ElectionMs: 1000,
  236. InitialElectionTickAdvance: true,
  237. LPUrls: []url.URL{*lpurl},
  238. LCUrls: []url.URL{*lcurl},
  239. APUrls: []url.URL{*apurl},
  240. ACUrls: []url.URL{*acurl},
  241. ClusterState: ClusterStateFlagNew,
  242. InitialClusterToken: "etcd-cluster",
  243. StrictReconfigCheck: DefaultStrictReconfigCheck,
  244. LogOutput: DefaultLogOutput,
  245. Metrics: "basic",
  246. EnableV2: DefaultEnableV2,
  247. AuthToken: "simple",
  248. }
  249. cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
  250. return cfg
  251. }
  252. func logTLSHandshakeFailure(conn *tls.Conn, err error) {
  253. state := conn.ConnectionState()
  254. remoteAddr := conn.RemoteAddr().String()
  255. serverName := state.ServerName
  256. if len(state.PeerCertificates) > 0 {
  257. cert := state.PeerCertificates[0]
  258. ips, dns := cert.IPAddresses, cert.DNSNames
  259. plog.Infof("rejected connection from %q (error %q, ServerName %q, IPAddresses %q, DNSNames %q)", remoteAddr, err.Error(), serverName, ips, dns)
  260. } else {
  261. plog.Infof("rejected connection from %q (error %q, ServerName %q)", remoteAddr, err.Error(), serverName)
  262. }
  263. }
  264. // SetupLogging initializes etcd logging.
  265. // Must be called after flag parsing.
  266. func (cfg *Config) SetupLogging() {
  267. cfg.ClientTLSInfo.HandshakeFailure = logTLSHandshakeFailure
  268. cfg.PeerTLSInfo.HandshakeFailure = logTLSHandshakeFailure
  269. capnslog.SetGlobalLogLevel(capnslog.INFO)
  270. if cfg.Debug {
  271. capnslog.SetGlobalLogLevel(capnslog.DEBUG)
  272. grpc.EnableTracing = true
  273. // enable info, warning, error
  274. grpclog.SetLoggerV2(grpclog.NewLoggerV2(os.Stderr, os.Stderr, os.Stderr))
  275. } else {
  276. // only discard info
  277. grpclog.SetLoggerV2(grpclog.NewLoggerV2(ioutil.Discard, os.Stderr, os.Stderr))
  278. }
  279. if cfg.LogPkgLevels != "" {
  280. repoLog := capnslog.MustRepoLogger("github.com/coreos/etcd")
  281. settings, err := repoLog.ParseLogLevelConfig(cfg.LogPkgLevels)
  282. if err != nil {
  283. plog.Warningf("couldn't parse log level string: %s, continuing with default levels", err.Error())
  284. return
  285. }
  286. repoLog.SetLogLevel(settings)
  287. }
  288. // capnslog initially SetFormatter(NewDefaultFormatter(os.Stderr))
  289. // where NewDefaultFormatter returns NewJournaldFormatter when syscall.Getppid() == 1
  290. // specify 'stdout' or 'stderr' to skip journald logging even when running under systemd
  291. switch cfg.LogOutput {
  292. case "stdout":
  293. capnslog.SetFormatter(capnslog.NewPrettyFormatter(os.Stdout, cfg.Debug))
  294. case "stderr":
  295. capnslog.SetFormatter(capnslog.NewPrettyFormatter(os.Stderr, cfg.Debug))
  296. case DefaultLogOutput:
  297. default:
  298. plog.Panicf(`unknown log-output %q (only supports %q, "stdout", "stderr")`, cfg.LogOutput, DefaultLogOutput)
  299. }
  300. }
  301. func ConfigFromFile(path string) (*Config, error) {
  302. cfg := &configYAML{Config: *NewConfig()}
  303. if err := cfg.configFromFile(path); err != nil {
  304. return nil, err
  305. }
  306. return &cfg.Config, nil
  307. }
  308. func (cfg *configYAML) configFromFile(path string) error {
  309. b, err := ioutil.ReadFile(path)
  310. if err != nil {
  311. return err
  312. }
  313. defaultInitialCluster := cfg.InitialCluster
  314. err = yaml.Unmarshal(b, cfg)
  315. if err != nil {
  316. return err
  317. }
  318. if cfg.LPUrlsJSON != "" {
  319. u, err := types.NewURLs(strings.Split(cfg.LPUrlsJSON, ","))
  320. if err != nil {
  321. plog.Fatalf("unexpected error setting up listen-peer-urls: %v", err)
  322. }
  323. cfg.LPUrls = []url.URL(u)
  324. }
  325. if cfg.LCUrlsJSON != "" {
  326. u, err := types.NewURLs(strings.Split(cfg.LCUrlsJSON, ","))
  327. if err != nil {
  328. plog.Fatalf("unexpected error setting up listen-client-urls: %v", err)
  329. }
  330. cfg.LCUrls = []url.URL(u)
  331. }
  332. if cfg.CorsJSON != "" {
  333. if err := cfg.CorsInfo.Set(cfg.CorsJSON); err != nil {
  334. plog.Panicf("unexpected error setting up cors: %v", err)
  335. }
  336. }
  337. if cfg.APUrlsJSON != "" {
  338. u, err := types.NewURLs(strings.Split(cfg.APUrlsJSON, ","))
  339. if err != nil {
  340. plog.Fatalf("unexpected error setting up initial-advertise-peer-urls: %v", err)
  341. }
  342. cfg.APUrls = []url.URL(u)
  343. }
  344. if cfg.ACUrlsJSON != "" {
  345. u, err := types.NewURLs(strings.Split(cfg.ACUrlsJSON, ","))
  346. if err != nil {
  347. plog.Fatalf("unexpected error setting up advertise-peer-urls: %v", err)
  348. }
  349. cfg.ACUrls = []url.URL(u)
  350. }
  351. if cfg.ListenMetricsUrlsJSON != "" {
  352. u, err := types.NewURLs(strings.Split(cfg.ListenMetricsUrlsJSON, ","))
  353. if err != nil {
  354. plog.Fatalf("unexpected error setting up listen-metrics-urls: %v", err)
  355. }
  356. cfg.ListenMetricsUrls = []url.URL(u)
  357. }
  358. // If a discovery flag is set, clear default initial cluster set by InitialClusterFromName
  359. if (cfg.Durl != "" || cfg.DNSCluster != "") && cfg.InitialCluster == defaultInitialCluster {
  360. cfg.InitialCluster = ""
  361. }
  362. if cfg.ClusterState == "" {
  363. cfg.ClusterState = ClusterStateFlagNew
  364. }
  365. copySecurityDetails := func(tls *transport.TLSInfo, ysc *securityConfig) {
  366. tls.CAFile = ysc.CAFile
  367. tls.CertFile = ysc.CertFile
  368. tls.KeyFile = ysc.KeyFile
  369. tls.ClientCertAuth = ysc.CertAuth
  370. tls.TrustedCAFile = ysc.TrustedCAFile
  371. }
  372. copySecurityDetails(&cfg.ClientTLSInfo, &cfg.ClientSecurityJSON)
  373. copySecurityDetails(&cfg.PeerTLSInfo, &cfg.PeerSecurityJSON)
  374. cfg.ClientAutoTLS = cfg.ClientSecurityJSON.AutoTLS
  375. cfg.PeerAutoTLS = cfg.PeerSecurityJSON.AutoTLS
  376. return cfg.Validate()
  377. }
  378. func updateCipherSuites(tls *transport.TLSInfo, ss []string) error {
  379. if len(tls.CipherSuites) > 0 && len(ss) > 0 {
  380. return fmt.Errorf("TLSInfo.CipherSuites is already specified (given %v)", ss)
  381. }
  382. if len(ss) > 0 {
  383. cs := make([]uint16, len(ss))
  384. for i, s := range ss {
  385. var ok bool
  386. cs[i], ok = tlsutil.GetCipherSuite(s)
  387. if !ok {
  388. return fmt.Errorf("unexpected TLS cipher suite %q", s)
  389. }
  390. }
  391. tls.CipherSuites = cs
  392. }
  393. return nil
  394. }
  395. // Validate ensures that '*embed.Config' fields are properly configured.
  396. func (cfg *Config) Validate() error {
  397. if err := checkBindURLs(cfg.LPUrls); err != nil {
  398. return err
  399. }
  400. if err := checkBindURLs(cfg.LCUrls); err != nil {
  401. return err
  402. }
  403. if err := checkBindURLs(cfg.ListenMetricsUrls); err != nil {
  404. return err
  405. }
  406. if err := checkHostURLs(cfg.APUrls); err != nil {
  407. // TODO: return err in v3.4
  408. addrs := make([]string, len(cfg.APUrls))
  409. for i := range cfg.APUrls {
  410. addrs[i] = cfg.APUrls[i].String()
  411. }
  412. plog.Warningf("advertise-peer-urls %q is deprecated (%v)", strings.Join(addrs, ","), err)
  413. }
  414. if err := checkHostURLs(cfg.ACUrls); err != nil {
  415. // TODO: return err in v3.4
  416. addrs := make([]string, len(cfg.ACUrls))
  417. for i := range cfg.ACUrls {
  418. addrs[i] = cfg.ACUrls[i].String()
  419. }
  420. plog.Warningf("advertise-client-urls %q is deprecated (%v)", strings.Join(addrs, ","), err)
  421. }
  422. // Check if conflicting flags are passed.
  423. nSet := 0
  424. for _, v := range []bool{cfg.Durl != "", cfg.InitialCluster != "", cfg.DNSCluster != ""} {
  425. if v {
  426. nSet++
  427. }
  428. }
  429. if cfg.ClusterState != ClusterStateFlagNew && cfg.ClusterState != ClusterStateFlagExisting {
  430. return fmt.Errorf("unexpected clusterState %q", cfg.ClusterState)
  431. }
  432. if nSet > 1 {
  433. return ErrConflictBootstrapFlags
  434. }
  435. if cfg.TickMs <= 0 {
  436. return fmt.Errorf("--heartbeat-interval must be >0 (set to %dms)", cfg.TickMs)
  437. }
  438. if cfg.ElectionMs <= 0 {
  439. return fmt.Errorf("--election-timeout must be >0 (set to %dms)", cfg.ElectionMs)
  440. }
  441. if 5*cfg.TickMs > cfg.ElectionMs {
  442. return fmt.Errorf("--election-timeout[%vms] should be at least as 5 times as --heartbeat-interval[%vms]", cfg.ElectionMs, cfg.TickMs)
  443. }
  444. if cfg.ElectionMs > maxElectionMs {
  445. return fmt.Errorf("--election-timeout[%vms] is too long, and should be set less than %vms", cfg.ElectionMs, maxElectionMs)
  446. }
  447. // check this last since proxying in etcdmain may make this OK
  448. if cfg.LCUrls != nil && cfg.ACUrls == nil {
  449. return ErrUnsetAdvertiseClientURLsFlag
  450. }
  451. switch cfg.AutoCompactionMode {
  452. case "":
  453. case compactor.ModeRevision, compactor.ModePeriodic:
  454. default:
  455. return fmt.Errorf("unknown auto-compaction-mode %q", cfg.AutoCompactionMode)
  456. }
  457. return nil
  458. }
  459. // PeerURLsMapAndToken sets up an initial peer URLsMap and cluster token for bootstrap or discovery.
  460. func (cfg *Config) PeerURLsMapAndToken(which string) (urlsmap types.URLsMap, token string, err error) {
  461. token = cfg.InitialClusterToken
  462. switch {
  463. case cfg.Durl != "":
  464. urlsmap = types.URLsMap{}
  465. // If using discovery, generate a temporary cluster based on
  466. // self's advertised peer URLs
  467. urlsmap[cfg.Name] = cfg.APUrls
  468. token = cfg.Durl
  469. case cfg.DNSCluster != "":
  470. clusterStrs, cerr := srv.GetCluster("etcd-server", cfg.Name, cfg.DNSCluster, cfg.APUrls)
  471. if cerr != nil {
  472. plog.Errorf("couldn't resolve during SRV discovery (%v)", cerr)
  473. return nil, "", cerr
  474. }
  475. for _, s := range clusterStrs {
  476. plog.Noticef("got bootstrap from DNS for etcd-server at %s", s)
  477. }
  478. clusterStr := strings.Join(clusterStrs, ",")
  479. if strings.Contains(clusterStr, "https://") && cfg.PeerTLSInfo.CAFile == "" {
  480. cfg.PeerTLSInfo.ServerName = cfg.DNSCluster
  481. }
  482. urlsmap, err = types.NewURLsMap(clusterStr)
  483. // only etcd member must belong to the discovered cluster.
  484. // proxy does not need to belong to the discovered cluster.
  485. if which == "etcd" {
  486. if _, ok := urlsmap[cfg.Name]; !ok {
  487. return nil, "", fmt.Errorf("cannot find local etcd member %q in SRV records", cfg.Name)
  488. }
  489. }
  490. default:
  491. // We're statically configured, and cluster has appropriately been set.
  492. urlsmap, err = types.NewURLsMap(cfg.InitialCluster)
  493. }
  494. return urlsmap, token, err
  495. }
  496. func (cfg Config) InitialClusterFromName(name string) (ret string) {
  497. if len(cfg.APUrls) == 0 {
  498. return ""
  499. }
  500. n := name
  501. if name == "" {
  502. n = DefaultName
  503. }
  504. for i := range cfg.APUrls {
  505. ret = ret + "," + n + "=" + cfg.APUrls[i].String()
  506. }
  507. return ret[1:]
  508. }
  509. func (cfg Config) IsNewCluster() bool { return cfg.ClusterState == ClusterStateFlagNew }
  510. func (cfg Config) ElectionTicks() int { return int(cfg.ElectionMs / cfg.TickMs) }
  511. func (cfg Config) defaultPeerHost() bool {
  512. return len(cfg.APUrls) == 1 && cfg.APUrls[0].String() == DefaultInitialAdvertisePeerURLs
  513. }
  514. func (cfg Config) defaultClientHost() bool {
  515. return len(cfg.ACUrls) == 1 && cfg.ACUrls[0].String() == DefaultAdvertiseClientURLs
  516. }
  517. func (cfg *Config) ClientSelfCert() (err error) {
  518. if !cfg.ClientAutoTLS {
  519. return nil
  520. }
  521. if !cfg.ClientTLSInfo.Empty() {
  522. plog.Warningf("ignoring client auto TLS since certs given")
  523. return nil
  524. }
  525. chosts := make([]string, len(cfg.LCUrls))
  526. for i, u := range cfg.LCUrls {
  527. chosts[i] = u.Host
  528. }
  529. cfg.ClientTLSInfo, err = transport.SelfCert(filepath.Join(cfg.Dir, "fixtures", "client"), chosts)
  530. if err != nil {
  531. return err
  532. }
  533. return updateCipherSuites(&cfg.ClientTLSInfo, cfg.CipherSuites)
  534. }
  535. func (cfg *Config) PeerSelfCert() (err error) {
  536. if !cfg.PeerAutoTLS {
  537. return nil
  538. }
  539. if !cfg.PeerTLSInfo.Empty() {
  540. plog.Warningf("ignoring peer auto TLS since certs given")
  541. return nil
  542. }
  543. phosts := make([]string, len(cfg.LPUrls))
  544. for i, u := range cfg.LPUrls {
  545. phosts[i] = u.Host
  546. }
  547. cfg.PeerTLSInfo, err = transport.SelfCert(filepath.Join(cfg.Dir, "fixtures", "peer"), phosts)
  548. if err != nil {
  549. return err
  550. }
  551. return updateCipherSuites(&cfg.PeerTLSInfo, cfg.CipherSuites)
  552. }
  553. // UpdateDefaultClusterFromName updates cluster advertise URLs with, if available, default host,
  554. // if advertise URLs are default values(localhost:2379,2380) AND if listen URL is 0.0.0.0.
  555. // e.g. advertise peer URL localhost:2380 or listen peer URL 0.0.0.0:2380
  556. // then the advertise peer host would be updated with machine's default host,
  557. // while keeping the listen URL's port.
  558. // User can work around this by explicitly setting URL with 127.0.0.1.
  559. // It returns the default hostname, if used, and the error, if any, from getting the machine's default host.
  560. // TODO: check whether fields are set instead of whether fields have default value
  561. func (cfg *Config) UpdateDefaultClusterFromName(defaultInitialCluster string) (string, error) {
  562. if defaultHostname == "" || defaultHostStatus != nil {
  563. // update 'initial-cluster' when only the name is specified (e.g. 'etcd --name=abc')
  564. if cfg.Name != DefaultName && cfg.InitialCluster == defaultInitialCluster {
  565. cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
  566. }
  567. return "", defaultHostStatus
  568. }
  569. used := false
  570. pip, pport := cfg.LPUrls[0].Hostname(), cfg.LPUrls[0].Port()
  571. if cfg.defaultPeerHost() && pip == "0.0.0.0" {
  572. cfg.APUrls[0] = url.URL{Scheme: cfg.APUrls[0].Scheme, Host: fmt.Sprintf("%s:%s", defaultHostname, pport)}
  573. used = true
  574. }
  575. // update 'initial-cluster' when only the name is specified (e.g. 'etcd --name=abc')
  576. if cfg.Name != DefaultName && cfg.InitialCluster == defaultInitialCluster {
  577. cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
  578. }
  579. cip, cport := cfg.LCUrls[0].Hostname(), cfg.LCUrls[0].Port()
  580. if cfg.defaultClientHost() && cip == "0.0.0.0" {
  581. cfg.ACUrls[0] = url.URL{Scheme: cfg.ACUrls[0].Scheme, Host: fmt.Sprintf("%s:%s", defaultHostname, cport)}
  582. used = true
  583. }
  584. dhost := defaultHostname
  585. if !used {
  586. dhost = ""
  587. }
  588. return dhost, defaultHostStatus
  589. }
  590. // checkBindURLs returns an error if any URL uses a domain name.
  591. func checkBindURLs(urls []url.URL) error {
  592. for _, url := range urls {
  593. if url.Scheme == "unix" || url.Scheme == "unixs" {
  594. continue
  595. }
  596. host, _, err := net.SplitHostPort(url.Host)
  597. if err != nil {
  598. return err
  599. }
  600. if host == "localhost" {
  601. // special case for local address
  602. // TODO: support /etc/hosts ?
  603. continue
  604. }
  605. if net.ParseIP(host) == nil {
  606. return fmt.Errorf("expected IP in URL for binding (%s)", url.String())
  607. }
  608. }
  609. return nil
  610. }
  611. func checkHostURLs(urls []url.URL) error {
  612. for _, url := range urls {
  613. host, _, err := net.SplitHostPort(url.Host)
  614. if err != nil {
  615. return err
  616. }
  617. if host == "" {
  618. return fmt.Errorf("unexpected empty host (%s)", url.String())
  619. }
  620. }
  621. return nil
  622. }