config.go 23 KB

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