config.go 22 KB

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