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