config.go 20 KB

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