config.go 20 KB

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