config.go 22 KB

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