config.go 21 KB

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