config.go 24 KB

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