config.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. // Copyright 2016 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package embed
  15. import (
  16. "crypto/tls"
  17. "fmt"
  18. "io/ioutil"
  19. "net"
  20. "net/http"
  21. "net/url"
  22. "os"
  23. "path/filepath"
  24. "strings"
  25. "time"
  26. "github.com/coreos/etcd/etcdserver"
  27. "github.com/coreos/etcd/pkg/cors"
  28. "github.com/coreos/etcd/pkg/netutil"
  29. "github.com/coreos/etcd/pkg/srv"
  30. "github.com/coreos/etcd/pkg/transport"
  31. "github.com/coreos/etcd/pkg/types"
  32. "github.com/coreos/pkg/capnslog"
  33. "github.com/ghodss/yaml"
  34. "google.golang.org/grpc"
  35. "google.golang.org/grpc/grpclog"
  36. )
  37. const (
  38. ClusterStateFlagNew = "new"
  39. ClusterStateFlagExisting = "existing"
  40. DefaultName = "default"
  41. DefaultMaxSnapshots = 5
  42. DefaultMaxWALs = 5
  43. DefaultMaxTxnOps = uint(128)
  44. DefaultMaxRequestBytes = 1.5 * 1024 * 1024
  45. DefaultGRPCKeepAliveMinTime = 5 * time.Second
  46. DefaultGRPCKeepAliveInterval = 2 * time.Hour
  47. DefaultGRPCKeepAliveTimeout = 20 * time.Second
  48. DefaultListenPeerURLs = "http://localhost:2380"
  49. DefaultListenClientURLs = "http://localhost:2379"
  50. DefaultLogOutput = "default"
  51. // maxElectionMs specifies the maximum value of election timeout.
  52. // More details are listed in ../Documentation/tuning.md#time-parameters.
  53. maxElectionMs = 50000
  54. )
  55. var (
  56. ErrConflictBootstrapFlags = fmt.Errorf("multiple discovery or bootstrap flags are set. " +
  57. "Choose one of \"initial-cluster\", \"discovery\" or \"discovery-srv\"")
  58. ErrUnsetAdvertiseClientURLsFlag = fmt.Errorf("--advertise-client-urls is required when --listen-client-urls is set explicitly")
  59. DefaultInitialAdvertisePeerURLs = "http://localhost:2380"
  60. DefaultAdvertiseClientURLs = "http://localhost:2379"
  61. defaultHostname string
  62. defaultHostStatus error
  63. )
  64. func init() {
  65. defaultHostname, defaultHostStatus = netutil.GetDefaultHost()
  66. }
  67. // Config holds the arguments for configuring an etcd server.
  68. type Config struct {
  69. // member
  70. CorsInfo *cors.CORSInfo
  71. LPUrls, LCUrls []url.URL
  72. Dir string `json:"data-dir"`
  73. WalDir string `json:"wal-dir"`
  74. MaxSnapFiles uint `json:"max-snapshots"`
  75. MaxWalFiles uint `json:"max-wals"`
  76. Name string `json:"name"`
  77. SnapCount uint64 `json:"snapshot-count"`
  78. AutoCompactionRetention string `json:"auto-compaction-retention"`
  79. AutoCompactionMode string `json:"auto-compaction-mode"`
  80. // TickMs is the number of milliseconds between heartbeat ticks.
  81. // TODO: decouple tickMs and heartbeat tick (current heartbeat tick = 1).
  82. // make ticks a cluster wide configuration.
  83. TickMs uint `json:"heartbeat-interval"`
  84. ElectionMs uint `json:"election-timeout"`
  85. QuotaBackendBytes int64 `json:"quota-backend-bytes"`
  86. MaxTxnOps uint `json:"max-txn-ops"`
  87. MaxRequestBytes uint `json:"max-request-bytes"`
  88. // gRPC server options
  89. // GRPCKeepAliveMinTime is the minimum interval that a client should
  90. // wait before pinging server. When client pings "too fast", server
  91. // sends goaway and closes the connection (errors: too_many_pings,
  92. // http2.ErrCodeEnhanceYourCalm). When too slow, nothing happens.
  93. // Server expects client pings only when there is any active streams
  94. // (PermitWithoutStream is set false).
  95. GRPCKeepAliveMinTime time.Duration `json:"grpc-keepalive-min-time"`
  96. // GRPCKeepAliveInterval is the frequency of server-to-client ping
  97. // to check if a connection is alive. Close a non-responsive connection
  98. // after an additional duration of Timeout. 0 to disable.
  99. GRPCKeepAliveInterval time.Duration `json:"grpc-keepalive-interval"`
  100. // GRPCKeepAliveTimeout is the additional duration of wait
  101. // before closing a non-responsive connection. 0 to disable.
  102. GRPCKeepAliveTimeout time.Duration `json:"grpc-keepalive-timeout"`
  103. // clustering
  104. APUrls, ACUrls []url.URL
  105. ClusterState string `json:"initial-cluster-state"`
  106. DNSCluster string `json:"discovery-srv"`
  107. Dproxy string `json:"discovery-proxy"`
  108. Durl string `json:"discovery"`
  109. InitialCluster string `json:"initial-cluster"`
  110. InitialClusterToken string `json:"initial-cluster-token"`
  111. StrictReconfigCheck bool `json:"strict-reconfig-check"`
  112. EnableV2 bool `json:"enable-v2"`
  113. // security
  114. ClientTLSInfo transport.TLSInfo
  115. ClientAutoTLS bool
  116. PeerTLSInfo transport.TLSInfo
  117. PeerAutoTLS bool
  118. // debug
  119. Debug bool `json:"debug"`
  120. LogPkgLevels string `json:"log-package-levels"`
  121. LogOutput string `json:"log-output"`
  122. EnablePprof bool `json:"enable-pprof"`
  123. Metrics string `json:"metrics"`
  124. ListenMetricsUrls []url.URL
  125. ListenMetricsUrlsJSON string `json:"listen-metrics-urls"`
  126. // ForceNewCluster starts a new cluster even if previously started; unsafe.
  127. ForceNewCluster bool `json:"force-new-cluster"`
  128. // UserHandlers is for registering users handlers and only used for
  129. // embedding etcd into other applications.
  130. // The map key is the route path for the handler, and
  131. // you must ensure it can't be conflicted with etcd's.
  132. UserHandlers map[string]http.Handler `json:"-"`
  133. // ServiceRegister is for registering users' gRPC services. A simple usage example:
  134. // cfg := embed.NewConfig()
  135. // cfg.ServerRegister = func(s *grpc.Server) {
  136. // pb.RegisterFooServer(s, &fooServer{})
  137. // pb.RegisterBarServer(s, &barServer{})
  138. // }
  139. // embed.StartEtcd(cfg)
  140. ServiceRegister func(*grpc.Server) `json:"-"`
  141. // auth
  142. AuthToken string `json:"auth-token"`
  143. // Experimental flags
  144. ExperimentalCorruptCheckTime time.Duration `json:"experimental-corrupt-check-time"`
  145. ExperimentalEnableV2V3 string `json:"experimental-enable-v2v3"`
  146. }
  147. // configYAML holds the config suitable for yaml parsing
  148. type configYAML struct {
  149. Config
  150. configJSON
  151. }
  152. // configJSON has file options that are translated into Config options
  153. type configJSON struct {
  154. LPUrlsJSON string `json:"listen-peer-urls"`
  155. LCUrlsJSON string `json:"listen-client-urls"`
  156. CorsJSON string `json:"cors"`
  157. APUrlsJSON string `json:"initial-advertise-peer-urls"`
  158. ACUrlsJSON string `json:"advertise-client-urls"`
  159. ClientSecurityJSON securityConfig `json:"client-transport-security"`
  160. PeerSecurityJSON securityConfig `json:"peer-transport-security"`
  161. }
  162. type securityConfig struct {
  163. CAFile string `json:"ca-file"`
  164. CertFile string `json:"cert-file"`
  165. KeyFile string `json:"key-file"`
  166. CertAuth bool `json:"client-cert-auth"`
  167. TrustedCAFile string `json:"trusted-ca-file"`
  168. AutoTLS bool `json:"auto-tls"`
  169. }
  170. // NewConfig creates a new Config populated with default values.
  171. func NewConfig() *Config {
  172. lpurl, _ := url.Parse(DefaultListenPeerURLs)
  173. apurl, _ := url.Parse(DefaultInitialAdvertisePeerURLs)
  174. lcurl, _ := url.Parse(DefaultListenClientURLs)
  175. acurl, _ := url.Parse(DefaultAdvertiseClientURLs)
  176. cfg := &Config{
  177. CorsInfo: &cors.CORSInfo{},
  178. MaxSnapFiles: DefaultMaxSnapshots,
  179. MaxWalFiles: DefaultMaxWALs,
  180. Name: DefaultName,
  181. SnapCount: etcdserver.DefaultSnapCount,
  182. MaxTxnOps: DefaultMaxTxnOps,
  183. MaxRequestBytes: DefaultMaxRequestBytes,
  184. GRPCKeepAliveMinTime: DefaultGRPCKeepAliveMinTime,
  185. GRPCKeepAliveInterval: DefaultGRPCKeepAliveInterval,
  186. GRPCKeepAliveTimeout: DefaultGRPCKeepAliveTimeout,
  187. TickMs: 100,
  188. ElectionMs: 1000,
  189. LPUrls: []url.URL{*lpurl},
  190. LCUrls: []url.URL{*lcurl},
  191. APUrls: []url.URL{*apurl},
  192. ACUrls: []url.URL{*acurl},
  193. ClusterState: ClusterStateFlagNew,
  194. InitialClusterToken: "etcd-cluster",
  195. StrictReconfigCheck: true,
  196. LogOutput: DefaultLogOutput,
  197. Metrics: "basic",
  198. EnableV2: true,
  199. AuthToken: "simple",
  200. }
  201. cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
  202. return cfg
  203. }
  204. // SetupLogging initializes etcd logging.
  205. // Must be called after flag parsing.
  206. func (cfg *Config) SetupLogging() {
  207. cfg.ClientTLSInfo.HandshakeFailure = func(conn *tls.Conn, err error) {
  208. plog.Infof("rejected connection from %q (%v)", conn.RemoteAddr().String(), err)
  209. }
  210. cfg.PeerTLSInfo.HandshakeFailure = cfg.ClientTLSInfo.HandshakeFailure
  211. capnslog.SetGlobalLogLevel(capnslog.INFO)
  212. if cfg.Debug {
  213. capnslog.SetGlobalLogLevel(capnslog.DEBUG)
  214. grpc.EnableTracing = true
  215. } else {
  216. grpclog.SetLoggerV2(grpclog.NewLoggerV2(ioutil.Discard, ioutil.Discard, ioutil.Discard))
  217. }
  218. if cfg.LogPkgLevels != "" {
  219. repoLog := capnslog.MustRepoLogger("github.com/coreos/etcd")
  220. settings, err := repoLog.ParseLogLevelConfig(cfg.LogPkgLevels)
  221. if err != nil {
  222. plog.Warningf("couldn't parse log level string: %s, continuing with default levels", err.Error())
  223. return
  224. }
  225. repoLog.SetLogLevel(settings)
  226. }
  227. // capnslog initially SetFormatter(NewDefaultFormatter(os.Stderr))
  228. // where NewDefaultFormatter returns NewJournaldFormatter when syscall.Getppid() == 1
  229. // specify 'stdout' or 'stderr' to skip journald logging even when running under systemd
  230. switch cfg.LogOutput {
  231. case "stdout":
  232. capnslog.SetFormatter(capnslog.NewPrettyFormatter(os.Stdout, cfg.Debug))
  233. case "stderr":
  234. capnslog.SetFormatter(capnslog.NewPrettyFormatter(os.Stderr, cfg.Debug))
  235. case DefaultLogOutput:
  236. default:
  237. plog.Panicf(`unknown log-output %q (only supports %q, "stdout", "stderr")`, cfg.LogOutput, DefaultLogOutput)
  238. }
  239. }
  240. func ConfigFromFile(path string) (*Config, error) {
  241. cfg := &configYAML{Config: *NewConfig()}
  242. if err := cfg.configFromFile(path); err != nil {
  243. return nil, err
  244. }
  245. return &cfg.Config, nil
  246. }
  247. func (cfg *configYAML) configFromFile(path string) error {
  248. b, err := ioutil.ReadFile(path)
  249. if err != nil {
  250. return err
  251. }
  252. defaultInitialCluster := cfg.InitialCluster
  253. err = yaml.Unmarshal(b, cfg)
  254. if err != nil {
  255. return err
  256. }
  257. if cfg.LPUrlsJSON != "" {
  258. u, err := types.NewURLs(strings.Split(cfg.LPUrlsJSON, ","))
  259. if err != nil {
  260. plog.Fatalf("unexpected error setting up listen-peer-urls: %v", err)
  261. }
  262. cfg.LPUrls = []url.URL(u)
  263. }
  264. if cfg.LCUrlsJSON != "" {
  265. u, err := types.NewURLs(strings.Split(cfg.LCUrlsJSON, ","))
  266. if err != nil {
  267. plog.Fatalf("unexpected error setting up listen-client-urls: %v", err)
  268. }
  269. cfg.LCUrls = []url.URL(u)
  270. }
  271. if cfg.CorsJSON != "" {
  272. if err := cfg.CorsInfo.Set(cfg.CorsJSON); err != nil {
  273. plog.Panicf("unexpected error setting up cors: %v", err)
  274. }
  275. }
  276. if cfg.APUrlsJSON != "" {
  277. u, err := types.NewURLs(strings.Split(cfg.APUrlsJSON, ","))
  278. if err != nil {
  279. plog.Fatalf("unexpected error setting up initial-advertise-peer-urls: %v", err)
  280. }
  281. cfg.APUrls = []url.URL(u)
  282. }
  283. if cfg.ACUrlsJSON != "" {
  284. u, err := types.NewURLs(strings.Split(cfg.ACUrlsJSON, ","))
  285. if err != nil {
  286. plog.Fatalf("unexpected error setting up advertise-peer-urls: %v", err)
  287. }
  288. cfg.ACUrls = []url.URL(u)
  289. }
  290. if cfg.ListenMetricsUrlsJSON != "" {
  291. u, err := types.NewURLs(strings.Split(cfg.ListenMetricsUrlsJSON, ","))
  292. if err != nil {
  293. plog.Fatalf("unexpected error setting up listen-metrics-urls: %v", err)
  294. }
  295. cfg.ListenMetricsUrls = []url.URL(u)
  296. }
  297. // If a discovery flag is set, clear default initial cluster set by InitialClusterFromName
  298. if (cfg.Durl != "" || cfg.DNSCluster != "") && cfg.InitialCluster == defaultInitialCluster {
  299. cfg.InitialCluster = ""
  300. }
  301. if cfg.ClusterState == "" {
  302. cfg.ClusterState = ClusterStateFlagNew
  303. }
  304. copySecurityDetails := func(tls *transport.TLSInfo, ysc *securityConfig) {
  305. tls.CAFile = ysc.CAFile
  306. tls.CertFile = ysc.CertFile
  307. tls.KeyFile = ysc.KeyFile
  308. tls.ClientCertAuth = ysc.CertAuth
  309. tls.TrustedCAFile = ysc.TrustedCAFile
  310. }
  311. copySecurityDetails(&cfg.ClientTLSInfo, &cfg.ClientSecurityJSON)
  312. copySecurityDetails(&cfg.PeerTLSInfo, &cfg.PeerSecurityJSON)
  313. cfg.ClientAutoTLS = cfg.ClientSecurityJSON.AutoTLS
  314. cfg.PeerAutoTLS = cfg.PeerSecurityJSON.AutoTLS
  315. return cfg.Validate()
  316. }
  317. func (cfg *Config) Validate() error {
  318. if err := checkBindURLs(cfg.LPUrls); err != nil {
  319. return err
  320. }
  321. if err := checkBindURLs(cfg.LCUrls); err != nil {
  322. return err
  323. }
  324. if err := checkBindURLs(cfg.ListenMetricsUrls); err != nil {
  325. return err
  326. }
  327. if err := checkHostURLs(cfg.APUrls); err != nil {
  328. // TODO: return err in v3.4
  329. addrs := make([]string, len(cfg.APUrls))
  330. for i := range cfg.APUrls {
  331. addrs[i] = cfg.APUrls[i].String()
  332. }
  333. plog.Warningf("advertise-peer-urls %q is deprecated (%v)", strings.Join(addrs, ","), err)
  334. }
  335. if err := checkHostURLs(cfg.ACUrls); err != nil {
  336. // TODO: return err in v3.4
  337. addrs := make([]string, len(cfg.ACUrls))
  338. for i := range cfg.ACUrls {
  339. addrs[i] = cfg.ACUrls[i].String()
  340. }
  341. plog.Warningf("advertise-client-urls %q is deprecated (%v)", strings.Join(addrs, ","), err)
  342. }
  343. // Check if conflicting flags are passed.
  344. nSet := 0
  345. for _, v := range []bool{cfg.Durl != "", cfg.InitialCluster != "", cfg.DNSCluster != ""} {
  346. if v {
  347. nSet++
  348. }
  349. }
  350. if cfg.ClusterState != ClusterStateFlagNew && cfg.ClusterState != ClusterStateFlagExisting {
  351. return fmt.Errorf("unexpected clusterState %q", cfg.ClusterState)
  352. }
  353. if nSet > 1 {
  354. return ErrConflictBootstrapFlags
  355. }
  356. if 5*cfg.TickMs > cfg.ElectionMs {
  357. return fmt.Errorf("--election-timeout[%vms] should be at least as 5 times as --heartbeat-interval[%vms]", cfg.ElectionMs, cfg.TickMs)
  358. }
  359. if cfg.ElectionMs > maxElectionMs {
  360. return fmt.Errorf("--election-timeout[%vms] is too long, and should be set less than %vms", cfg.ElectionMs, maxElectionMs)
  361. }
  362. // check this last since proxying in etcdmain may make this OK
  363. if cfg.LCUrls != nil && cfg.ACUrls == nil {
  364. return ErrUnsetAdvertiseClientURLsFlag
  365. }
  366. return nil
  367. }
  368. // PeerURLsMapAndToken sets up an initial peer URLsMap and cluster token for bootstrap or discovery.
  369. func (cfg *Config) PeerURLsMapAndToken(which string) (urlsmap types.URLsMap, token string, err error) {
  370. token = cfg.InitialClusterToken
  371. switch {
  372. case cfg.Durl != "":
  373. urlsmap = types.URLsMap{}
  374. // If using discovery, generate a temporary cluster based on
  375. // self's advertised peer URLs
  376. urlsmap[cfg.Name] = cfg.APUrls
  377. token = cfg.Durl
  378. case cfg.DNSCluster != "":
  379. clusterStrs, cerr := srv.GetCluster("etcd-server", cfg.Name, cfg.DNSCluster, cfg.APUrls)
  380. if cerr != nil {
  381. plog.Errorf("couldn't resolve during SRV discovery (%v)", cerr)
  382. return nil, "", cerr
  383. }
  384. for _, s := range clusterStrs {
  385. plog.Noticef("got bootstrap from DNS for etcd-server at %s", s)
  386. }
  387. clusterStr := strings.Join(clusterStrs, ",")
  388. if strings.Contains(clusterStr, "https://") && cfg.PeerTLSInfo.CAFile == "" {
  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. }