config.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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. ExperimentalInitialCorruptCheck bool `json:"experimental-initial-corrupt-check"`
  145. ExperimentalCorruptCheckTime time.Duration `json:"experimental-corrupt-check-time"`
  146. ExperimentalEnableV2V3 string `json:"experimental-enable-v2v3"`
  147. }
  148. // configYAML holds the config suitable for yaml parsing
  149. type configYAML struct {
  150. Config
  151. configJSON
  152. }
  153. // configJSON has file options that are translated into Config options
  154. type configJSON struct {
  155. LPUrlsJSON string `json:"listen-peer-urls"`
  156. LCUrlsJSON string `json:"listen-client-urls"`
  157. CorsJSON string `json:"cors"`
  158. APUrlsJSON string `json:"initial-advertise-peer-urls"`
  159. ACUrlsJSON string `json:"advertise-client-urls"`
  160. ClientSecurityJSON securityConfig `json:"client-transport-security"`
  161. PeerSecurityJSON securityConfig `json:"peer-transport-security"`
  162. }
  163. type securityConfig struct {
  164. CAFile string `json:"ca-file"`
  165. CertFile string `json:"cert-file"`
  166. KeyFile string `json:"key-file"`
  167. CertAuth bool `json:"client-cert-auth"`
  168. TrustedCAFile string `json:"trusted-ca-file"`
  169. AutoTLS bool `json:"auto-tls"`
  170. }
  171. // NewConfig creates a new Config populated with default values.
  172. func NewConfig() *Config {
  173. lpurl, _ := url.Parse(DefaultListenPeerURLs)
  174. apurl, _ := url.Parse(DefaultInitialAdvertisePeerURLs)
  175. lcurl, _ := url.Parse(DefaultListenClientURLs)
  176. acurl, _ := url.Parse(DefaultAdvertiseClientURLs)
  177. cfg := &Config{
  178. CorsInfo: &cors.CORSInfo{},
  179. MaxSnapFiles: DefaultMaxSnapshots,
  180. MaxWalFiles: DefaultMaxWALs,
  181. Name: DefaultName,
  182. SnapCount: etcdserver.DefaultSnapCount,
  183. MaxTxnOps: DefaultMaxTxnOps,
  184. MaxRequestBytes: DefaultMaxRequestBytes,
  185. GRPCKeepAliveMinTime: DefaultGRPCKeepAliveMinTime,
  186. GRPCKeepAliveInterval: DefaultGRPCKeepAliveInterval,
  187. GRPCKeepAliveTimeout: DefaultGRPCKeepAliveTimeout,
  188. TickMs: 100,
  189. ElectionMs: 1000,
  190. LPUrls: []url.URL{*lpurl},
  191. LCUrls: []url.URL{*lcurl},
  192. APUrls: []url.URL{*apurl},
  193. ACUrls: []url.URL{*acurl},
  194. ClusterState: ClusterStateFlagNew,
  195. InitialClusterToken: "etcd-cluster",
  196. StrictReconfigCheck: true,
  197. LogOutput: DefaultLogOutput,
  198. Metrics: "basic",
  199. EnableV2: true,
  200. AuthToken: "simple",
  201. }
  202. cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
  203. return cfg
  204. }
  205. // SetupLogging initializes etcd logging.
  206. // Must be called after flag parsing.
  207. func (cfg *Config) SetupLogging() {
  208. cfg.ClientTLSInfo.HandshakeFailure = func(conn *tls.Conn, err error) {
  209. plog.Infof("rejected connection from %q (%v)", conn.RemoteAddr().String(), err)
  210. }
  211. cfg.PeerTLSInfo.HandshakeFailure = cfg.ClientTLSInfo.HandshakeFailure
  212. capnslog.SetGlobalLogLevel(capnslog.INFO)
  213. if cfg.Debug {
  214. capnslog.SetGlobalLogLevel(capnslog.DEBUG)
  215. grpc.EnableTracing = true
  216. } else {
  217. grpclog.SetLoggerV2(grpclog.NewLoggerV2(ioutil.Discard, ioutil.Discard, ioutil.Discard))
  218. }
  219. if cfg.LogPkgLevels != "" {
  220. repoLog := capnslog.MustRepoLogger("github.com/coreos/etcd")
  221. settings, err := repoLog.ParseLogLevelConfig(cfg.LogPkgLevels)
  222. if err != nil {
  223. plog.Warningf("couldn't parse log level string: %s, continuing with default levels", err.Error())
  224. return
  225. }
  226. repoLog.SetLogLevel(settings)
  227. }
  228. // capnslog initially SetFormatter(NewDefaultFormatter(os.Stderr))
  229. // where NewDefaultFormatter returns NewJournaldFormatter when syscall.Getppid() == 1
  230. // specify 'stdout' or 'stderr' to skip journald logging even when running under systemd
  231. switch cfg.LogOutput {
  232. case "stdout":
  233. capnslog.SetFormatter(capnslog.NewPrettyFormatter(os.Stdout, cfg.Debug))
  234. case "stderr":
  235. capnslog.SetFormatter(capnslog.NewPrettyFormatter(os.Stderr, cfg.Debug))
  236. case DefaultLogOutput:
  237. default:
  238. plog.Panicf(`unknown log-output %q (only supports %q, "stdout", "stderr")`, cfg.LogOutput, DefaultLogOutput)
  239. }
  240. }
  241. func ConfigFromFile(path string) (*Config, error) {
  242. cfg := &configYAML{Config: *NewConfig()}
  243. if err := cfg.configFromFile(path); err != nil {
  244. return nil, err
  245. }
  246. return &cfg.Config, nil
  247. }
  248. func (cfg *configYAML) configFromFile(path string) error {
  249. b, err := ioutil.ReadFile(path)
  250. if err != nil {
  251. return err
  252. }
  253. defaultInitialCluster := cfg.InitialCluster
  254. err = yaml.Unmarshal(b, cfg)
  255. if err != nil {
  256. return err
  257. }
  258. if cfg.LPUrlsJSON != "" {
  259. u, err := types.NewURLs(strings.Split(cfg.LPUrlsJSON, ","))
  260. if err != nil {
  261. plog.Fatalf("unexpected error setting up listen-peer-urls: %v", err)
  262. }
  263. cfg.LPUrls = []url.URL(u)
  264. }
  265. if cfg.LCUrlsJSON != "" {
  266. u, err := types.NewURLs(strings.Split(cfg.LCUrlsJSON, ","))
  267. if err != nil {
  268. plog.Fatalf("unexpected error setting up listen-client-urls: %v", err)
  269. }
  270. cfg.LCUrls = []url.URL(u)
  271. }
  272. if cfg.CorsJSON != "" {
  273. if err := cfg.CorsInfo.Set(cfg.CorsJSON); err != nil {
  274. plog.Panicf("unexpected error setting up cors: %v", err)
  275. }
  276. }
  277. if cfg.APUrlsJSON != "" {
  278. u, err := types.NewURLs(strings.Split(cfg.APUrlsJSON, ","))
  279. if err != nil {
  280. plog.Fatalf("unexpected error setting up initial-advertise-peer-urls: %v", err)
  281. }
  282. cfg.APUrls = []url.URL(u)
  283. }
  284. if cfg.ACUrlsJSON != "" {
  285. u, err := types.NewURLs(strings.Split(cfg.ACUrlsJSON, ","))
  286. if err != nil {
  287. plog.Fatalf("unexpected error setting up advertise-peer-urls: %v", err)
  288. }
  289. cfg.ACUrls = []url.URL(u)
  290. }
  291. if cfg.ListenMetricsUrlsJSON != "" {
  292. u, err := types.NewURLs(strings.Split(cfg.ListenMetricsUrlsJSON, ","))
  293. if err != nil {
  294. plog.Fatalf("unexpected error setting up listen-metrics-urls: %v", err)
  295. }
  296. cfg.ListenMetricsUrls = []url.URL(u)
  297. }
  298. // If a discovery flag is set, clear default initial cluster set by InitialClusterFromName
  299. if (cfg.Durl != "" || cfg.DNSCluster != "") && cfg.InitialCluster == defaultInitialCluster {
  300. cfg.InitialCluster = ""
  301. }
  302. if cfg.ClusterState == "" {
  303. cfg.ClusterState = ClusterStateFlagNew
  304. }
  305. copySecurityDetails := func(tls *transport.TLSInfo, ysc *securityConfig) {
  306. tls.CAFile = ysc.CAFile
  307. tls.CertFile = ysc.CertFile
  308. tls.KeyFile = ysc.KeyFile
  309. tls.ClientCertAuth = ysc.CertAuth
  310. tls.TrustedCAFile = ysc.TrustedCAFile
  311. }
  312. copySecurityDetails(&cfg.ClientTLSInfo, &cfg.ClientSecurityJSON)
  313. copySecurityDetails(&cfg.PeerTLSInfo, &cfg.PeerSecurityJSON)
  314. cfg.ClientAutoTLS = cfg.ClientSecurityJSON.AutoTLS
  315. cfg.PeerAutoTLS = cfg.PeerSecurityJSON.AutoTLS
  316. return cfg.Validate()
  317. }
  318. func (cfg *Config) Validate() error {
  319. if err := checkBindURLs(cfg.LPUrls); err != nil {
  320. return err
  321. }
  322. if err := checkBindURLs(cfg.LCUrls); err != nil {
  323. return err
  324. }
  325. if err := checkBindURLs(cfg.ListenMetricsUrls); err != nil {
  326. return err
  327. }
  328. if err := checkHostURLs(cfg.APUrls); err != nil {
  329. // TODO: return err in v3.4
  330. addrs := make([]string, len(cfg.APUrls))
  331. for i := range cfg.APUrls {
  332. addrs[i] = cfg.APUrls[i].String()
  333. }
  334. plog.Warningf("advertise-peer-urls %q is deprecated (%v)", strings.Join(addrs, ","), err)
  335. }
  336. if err := checkHostURLs(cfg.ACUrls); err != nil {
  337. // TODO: return err in v3.4
  338. addrs := make([]string, len(cfg.ACUrls))
  339. for i := range cfg.ACUrls {
  340. addrs[i] = cfg.ACUrls[i].String()
  341. }
  342. plog.Warningf("advertise-client-urls %q is deprecated (%v)", strings.Join(addrs, ","), err)
  343. }
  344. // Check if conflicting flags are passed.
  345. nSet := 0
  346. for _, v := range []bool{cfg.Durl != "", cfg.InitialCluster != "", cfg.DNSCluster != ""} {
  347. if v {
  348. nSet++
  349. }
  350. }
  351. if cfg.ClusterState != ClusterStateFlagNew && cfg.ClusterState != ClusterStateFlagExisting {
  352. return fmt.Errorf("unexpected clusterState %q", cfg.ClusterState)
  353. }
  354. if nSet > 1 {
  355. return ErrConflictBootstrapFlags
  356. }
  357. if 5*cfg.TickMs > cfg.ElectionMs {
  358. return fmt.Errorf("--election-timeout[%vms] should be at least as 5 times as --heartbeat-interval[%vms]", cfg.ElectionMs, cfg.TickMs)
  359. }
  360. if cfg.ElectionMs > maxElectionMs {
  361. return fmt.Errorf("--election-timeout[%vms] is too long, and should be set less than %vms", cfg.ElectionMs, maxElectionMs)
  362. }
  363. // check this last since proxying in etcdmain may make this OK
  364. if cfg.LCUrls != nil && cfg.ACUrls == nil {
  365. return ErrUnsetAdvertiseClientURLsFlag
  366. }
  367. return nil
  368. }
  369. // PeerURLsMapAndToken sets up an initial peer URLsMap and cluster token for bootstrap or discovery.
  370. func (cfg *Config) PeerURLsMapAndToken(which string) (urlsmap types.URLsMap, token string, err error) {
  371. token = cfg.InitialClusterToken
  372. switch {
  373. case cfg.Durl != "":
  374. urlsmap = types.URLsMap{}
  375. // If using discovery, generate a temporary cluster based on
  376. // self's advertised peer URLs
  377. urlsmap[cfg.Name] = cfg.APUrls
  378. token = cfg.Durl
  379. case cfg.DNSCluster != "":
  380. clusterStrs, cerr := srv.GetCluster("etcd-server", cfg.Name, cfg.DNSCluster, cfg.APUrls)
  381. if cerr != nil {
  382. plog.Errorf("couldn't resolve during SRV discovery (%v)", cerr)
  383. return nil, "", cerr
  384. }
  385. for _, s := range clusterStrs {
  386. plog.Noticef("got bootstrap from DNS for etcd-server at %s", s)
  387. }
  388. clusterStr := strings.Join(clusterStrs, ",")
  389. if strings.Contains(clusterStr, "https://") && cfg.PeerTLSInfo.CAFile == "" {
  390. cfg.PeerTLSInfo.ServerName = cfg.DNSCluster
  391. }
  392. urlsmap, err = types.NewURLsMap(clusterStr)
  393. // only etcd member must belong to the discovered cluster.
  394. // proxy does not need to belong to the discovered cluster.
  395. if which == "etcd" {
  396. if _, ok := urlsmap[cfg.Name]; !ok {
  397. return nil, "", fmt.Errorf("cannot find local etcd member %q in SRV records", cfg.Name)
  398. }
  399. }
  400. default:
  401. // We're statically configured, and cluster has appropriately been set.
  402. urlsmap, err = types.NewURLsMap(cfg.InitialCluster)
  403. }
  404. return urlsmap, token, err
  405. }
  406. func (cfg Config) InitialClusterFromName(name string) (ret string) {
  407. if len(cfg.APUrls) == 0 {
  408. return ""
  409. }
  410. n := name
  411. if name == "" {
  412. n = DefaultName
  413. }
  414. for i := range cfg.APUrls {
  415. ret = ret + "," + n + "=" + cfg.APUrls[i].String()
  416. }
  417. return ret[1:]
  418. }
  419. func (cfg Config) IsNewCluster() bool { return cfg.ClusterState == ClusterStateFlagNew }
  420. func (cfg Config) ElectionTicks() int { return int(cfg.ElectionMs / cfg.TickMs) }
  421. func (cfg Config) defaultPeerHost() bool {
  422. return len(cfg.APUrls) == 1 && cfg.APUrls[0].String() == DefaultInitialAdvertisePeerURLs
  423. }
  424. func (cfg Config) defaultClientHost() bool {
  425. return len(cfg.ACUrls) == 1 && cfg.ACUrls[0].String() == DefaultAdvertiseClientURLs
  426. }
  427. func (cfg *Config) ClientSelfCert() (err error) {
  428. if cfg.ClientAutoTLS && cfg.ClientTLSInfo.Empty() {
  429. chosts := make([]string, len(cfg.LCUrls))
  430. for i, u := range cfg.LCUrls {
  431. chosts[i] = u.Host
  432. }
  433. cfg.ClientTLSInfo, err = transport.SelfCert(filepath.Join(cfg.Dir, "fixtures", "client"), chosts)
  434. return err
  435. } else if cfg.ClientAutoTLS {
  436. plog.Warningf("ignoring client auto TLS since certs given")
  437. }
  438. return nil
  439. }
  440. func (cfg *Config) PeerSelfCert() (err error) {
  441. if cfg.PeerAutoTLS && cfg.PeerTLSInfo.Empty() {
  442. phosts := make([]string, len(cfg.LPUrls))
  443. for i, u := range cfg.LPUrls {
  444. phosts[i] = u.Host
  445. }
  446. cfg.PeerTLSInfo, err = transport.SelfCert(filepath.Join(cfg.Dir, "fixtures", "peer"), phosts)
  447. return err
  448. } else if cfg.PeerAutoTLS {
  449. plog.Warningf("ignoring peer auto TLS since certs given")
  450. }
  451. return nil
  452. }
  453. // UpdateDefaultClusterFromName updates cluster advertise URLs with, if available, default host,
  454. // if advertise URLs are default values(localhost:2379,2380) AND if listen URL is 0.0.0.0.
  455. // e.g. advertise peer URL localhost:2380 or listen peer URL 0.0.0.0:2380
  456. // then the advertise peer host would be updated with machine's default host,
  457. // while keeping the listen URL's port.
  458. // User can work around this by explicitly setting URL with 127.0.0.1.
  459. // It returns the default hostname, if used, and the error, if any, from getting the machine's default host.
  460. // TODO: check whether fields are set instead of whether fields have default value
  461. func (cfg *Config) UpdateDefaultClusterFromName(defaultInitialCluster string) (string, error) {
  462. if defaultHostname == "" || defaultHostStatus != nil {
  463. // update 'initial-cluster' when only the name is specified (e.g. 'etcd --name=abc')
  464. if cfg.Name != DefaultName && cfg.InitialCluster == defaultInitialCluster {
  465. cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
  466. }
  467. return "", defaultHostStatus
  468. }
  469. used := false
  470. pip, pport := cfg.LPUrls[0].Hostname(), cfg.LPUrls[0].Port()
  471. if cfg.defaultPeerHost() && pip == "0.0.0.0" {
  472. cfg.APUrls[0] = url.URL{Scheme: cfg.APUrls[0].Scheme, Host: fmt.Sprintf("%s:%s", defaultHostname, pport)}
  473. used = true
  474. }
  475. // update 'initial-cluster' when only the name is specified (e.g. 'etcd --name=abc')
  476. if cfg.Name != DefaultName && cfg.InitialCluster == defaultInitialCluster {
  477. cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
  478. }
  479. cip, cport := cfg.LCUrls[0].Hostname(), cfg.LCUrls[0].Port()
  480. if cfg.defaultClientHost() && cip == "0.0.0.0" {
  481. cfg.ACUrls[0] = url.URL{Scheme: cfg.ACUrls[0].Scheme, Host: fmt.Sprintf("%s:%s", defaultHostname, cport)}
  482. used = true
  483. }
  484. dhost := defaultHostname
  485. if !used {
  486. dhost = ""
  487. }
  488. return dhost, defaultHostStatus
  489. }
  490. // checkBindURLs returns an error if any URL uses a domain name.
  491. // TODO: return error in 3.2.0
  492. func checkBindURLs(urls []url.URL) error {
  493. for _, url := range urls {
  494. if url.Scheme == "unix" || url.Scheme == "unixs" {
  495. continue
  496. }
  497. host, _, err := net.SplitHostPort(url.Host)
  498. if err != nil {
  499. return err
  500. }
  501. if host == "localhost" {
  502. // special case for local address
  503. // TODO: support /etc/hosts ?
  504. continue
  505. }
  506. if net.ParseIP(host) == nil {
  507. return fmt.Errorf("expected IP in URL for binding (%s)", url.String())
  508. }
  509. }
  510. return nil
  511. }
  512. func checkHostURLs(urls []url.URL) error {
  513. for _, url := range urls {
  514. host, _, err := net.SplitHostPort(url.Host)
  515. if err != nil {
  516. return err
  517. }
  518. if host == "" {
  519. return fmt.Errorf("unexpected empty host (%s)", url.String())
  520. }
  521. }
  522. return nil
  523. }