config.go 21 KB

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