config.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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. "fmt"
  17. "io/ioutil"
  18. "net"
  19. "net/http"
  20. "net/url"
  21. "strings"
  22. "time"
  23. "github.com/coreos/etcd/etcdserver"
  24. "github.com/coreos/etcd/pkg/cors"
  25. "github.com/coreos/etcd/pkg/netutil"
  26. "github.com/coreos/etcd/pkg/srv"
  27. "github.com/coreos/etcd/pkg/transport"
  28. "github.com/coreos/etcd/pkg/types"
  29. "github.com/ghodss/yaml"
  30. "google.golang.org/grpc"
  31. )
  32. const (
  33. ClusterStateFlagNew = "new"
  34. ClusterStateFlagExisting = "existing"
  35. DefaultName = "default"
  36. DefaultMaxSnapshots = 5
  37. DefaultMaxWALs = 5
  38. DefaultMaxRequestBytes = 1.5 * 1024 * 1024
  39. DefaultGRPCKeepAliveMinTime = 5 * time.Second
  40. DefaultGRPCKeepAliveInterval = 2 * time.Hour
  41. DefaultGRPCKeepAliveTimeout = 20 * time.Second
  42. DefaultListenPeerURLs = "http://localhost:2380"
  43. DefaultListenClientURLs = "http://localhost:2379"
  44. // maxElectionMs specifies the maximum value of election timeout.
  45. // More details are listed in ../Documentation/tuning.md#time-parameters.
  46. maxElectionMs = 50000
  47. )
  48. var (
  49. ErrConflictBootstrapFlags = fmt.Errorf("multiple discovery or bootstrap flags are set. " +
  50. "Choose one of \"initial-cluster\", \"discovery\" or \"discovery-srv\"")
  51. ErrUnsetAdvertiseClientURLsFlag = fmt.Errorf("--advertise-client-urls is required when --listen-client-urls is set explicitly")
  52. DefaultInitialAdvertisePeerURLs = "http://localhost:2380"
  53. DefaultAdvertiseClientURLs = "http://localhost:2379"
  54. defaultHostname string
  55. defaultHostStatus error
  56. )
  57. func init() {
  58. defaultHostname, defaultHostStatus = netutil.GetDefaultHost()
  59. }
  60. // Config holds the arguments for configuring an etcd server.
  61. type Config struct {
  62. // member
  63. CorsInfo *cors.CORSInfo
  64. LPUrls, LCUrls []url.URL
  65. Dir string `json:"data-dir"`
  66. WalDir string `json:"wal-dir"`
  67. MaxSnapFiles uint `json:"max-snapshots"`
  68. MaxWalFiles uint `json:"max-wals"`
  69. Name string `json:"name"`
  70. SnapCount uint64 `json:"snapshot-count"`
  71. AutoCompactionRetention int `json:"auto-compaction-retention"`
  72. // TickMs is the number of milliseconds between heartbeat ticks.
  73. // TODO: decouple tickMs and heartbeat tick (current heartbeat tick = 1).
  74. // make ticks a cluster wide configuration.
  75. TickMs uint `json:"heartbeat-interval"`
  76. ElectionMs uint `json:"election-timeout"`
  77. // InitialElectionTickAdvance is true, then local member fast-forwards
  78. // election ticks to speed up "initial" leader election trigger. This
  79. // benefits the case of larger election ticks. For instance, cross
  80. // datacenter deployment may require longer election timeout of 10-second.
  81. // If true, local node does not need wait up to 10-second. Instead,
  82. // forwards its election ticks to 8-second, and have only 2-second left
  83. // before leader election.
  84. //
  85. // Major assumptions are that:
  86. // - cluster has no active leader thus advancing ticks enables faster
  87. // leader election, or
  88. // - cluster already has an established leader, and rejoining follower
  89. // is likely to receive heartbeats from the leader after tick advance
  90. // and before election timeout.
  91. //
  92. // However, when network from leader to rejoining follower is congested,
  93. // and the follower does not receive leader heartbeat within left election
  94. // ticks, disruptive election has to happen thus affecting cluster
  95. // availabilities.
  96. //
  97. // Disabling this would slow down initial bootstrap process for cross
  98. // datacenter deployments. Make your own tradeoffs by configuring
  99. // --initial-election-tick-advance at the cost of slow initial bootstrap.
  100. //
  101. // If single-node, it advances ticks regardless.
  102. //
  103. // See https://github.com/coreos/etcd/issues/9333 for more detail.
  104. InitialElectionTickAdvance bool `json:"initial-election-tick-advance"`
  105. QuotaBackendBytes int64 `json:"quota-backend-bytes"`
  106. MaxRequestBytes uint `json:"max-request-bytes"`
  107. // gRPC server options
  108. // GRPCKeepAliveMinTime is the minimum interval that a client should
  109. // wait before pinging server. When client pings "too fast", server
  110. // sends goaway and closes the connection (errors: too_many_pings,
  111. // http2.ErrCodeEnhanceYourCalm). When too slow, nothing happens.
  112. // Server expects client pings only when there is any active streams
  113. // (PermitWithoutStream is set false).
  114. GRPCKeepAliveMinTime time.Duration `json:"grpc-keepalive-min-time"`
  115. // GRPCKeepAliveInterval is the frequency of server-to-client ping
  116. // to check if a connection is alive. Close a non-responsive connection
  117. // after an additional duration of Timeout. 0 to disable.
  118. GRPCKeepAliveInterval time.Duration `json:"grpc-keepalive-interval"`
  119. // GRPCKeepAliveTimeout is the additional duration of wait
  120. // before closing a non-responsive connection. 0 to disable.
  121. GRPCKeepAliveTimeout time.Duration `json:"grpc-keepalive-timeout"`
  122. // clustering
  123. APUrls, ACUrls []url.URL
  124. ClusterState string `json:"initial-cluster-state"`
  125. DNSCluster string `json:"discovery-srv"`
  126. Dproxy string `json:"discovery-proxy"`
  127. Durl string `json:"discovery"`
  128. InitialCluster string `json:"initial-cluster"`
  129. InitialClusterToken string `json:"initial-cluster-token"`
  130. StrictReconfigCheck bool `json:"strict-reconfig-check"`
  131. EnableV2 bool `json:"enable-v2"`
  132. // security
  133. ClientTLSInfo transport.TLSInfo
  134. ClientAutoTLS bool
  135. PeerTLSInfo transport.TLSInfo
  136. PeerAutoTLS bool
  137. // debug
  138. Debug bool `json:"debug"`
  139. LogPkgLevels string `json:"log-package-levels"`
  140. EnablePprof bool `json:"enable-pprof"`
  141. Metrics string `json:"metrics"`
  142. // ForceNewCluster starts a new cluster even if previously started; unsafe.
  143. ForceNewCluster bool `json:"force-new-cluster"`
  144. // UserHandlers is for registering users handlers and only used for
  145. // embedding etcd into other applications.
  146. // The map key is the route path for the handler, and
  147. // you must ensure it can't be conflicted with etcd's.
  148. UserHandlers map[string]http.Handler `json:"-"`
  149. // ServiceRegister is for registering users' gRPC services. A simple usage example:
  150. // cfg := embed.NewConfig()
  151. // cfg.ServerRegister = func(s *grpc.Server) {
  152. // pb.RegisterFooServer(s, &fooServer{})
  153. // pb.RegisterBarServer(s, &barServer{})
  154. // }
  155. // embed.StartEtcd(cfg)
  156. ServiceRegister func(*grpc.Server) `json:"-"`
  157. // auth
  158. AuthToken string `json:"auth-token"`
  159. }
  160. // configYAML holds the config suitable for yaml parsing
  161. type configYAML struct {
  162. Config
  163. configJSON
  164. }
  165. // configJSON has file options that are translated into Config options
  166. type configJSON struct {
  167. LPUrlsJSON string `json:"listen-peer-urls"`
  168. LCUrlsJSON string `json:"listen-client-urls"`
  169. CorsJSON string `json:"cors"`
  170. APUrlsJSON string `json:"initial-advertise-peer-urls"`
  171. ACUrlsJSON string `json:"advertise-client-urls"`
  172. ClientSecurityJSON securityConfig `json:"client-transport-security"`
  173. PeerSecurityJSON securityConfig `json:"peer-transport-security"`
  174. }
  175. type securityConfig struct {
  176. CAFile string `json:"ca-file"`
  177. CertFile string `json:"cert-file"`
  178. KeyFile string `json:"key-file"`
  179. CertAuth bool `json:"client-cert-auth"`
  180. TrustedCAFile string `json:"trusted-ca-file"`
  181. AutoTLS bool `json:"auto-tls"`
  182. }
  183. // NewConfig creates a new Config populated with default values.
  184. func NewConfig() *Config {
  185. lpurl, _ := url.Parse(DefaultListenPeerURLs)
  186. apurl, _ := url.Parse(DefaultInitialAdvertisePeerURLs)
  187. lcurl, _ := url.Parse(DefaultListenClientURLs)
  188. acurl, _ := url.Parse(DefaultAdvertiseClientURLs)
  189. cfg := &Config{
  190. CorsInfo: &cors.CORSInfo{},
  191. MaxSnapFiles: DefaultMaxSnapshots,
  192. MaxWalFiles: DefaultMaxWALs,
  193. Name: DefaultName,
  194. SnapCount: etcdserver.DefaultSnapCount,
  195. MaxRequestBytes: DefaultMaxRequestBytes,
  196. GRPCKeepAliveMinTime: DefaultGRPCKeepAliveMinTime,
  197. GRPCKeepAliveInterval: DefaultGRPCKeepAliveInterval,
  198. GRPCKeepAliveTimeout: DefaultGRPCKeepAliveTimeout,
  199. TickMs: 100,
  200. ElectionMs: 1000,
  201. InitialElectionTickAdvance: true,
  202. LPUrls: []url.URL{*lpurl},
  203. LCUrls: []url.URL{*lcurl},
  204. APUrls: []url.URL{*apurl},
  205. ACUrls: []url.URL{*acurl},
  206. ClusterState: ClusterStateFlagNew,
  207. InitialClusterToken: "etcd-cluster",
  208. StrictReconfigCheck: true,
  209. Metrics: "basic",
  210. EnableV2: true,
  211. AuthToken: "simple",
  212. }
  213. cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
  214. return cfg
  215. }
  216. func ConfigFromFile(path string) (*Config, error) {
  217. cfg := &configYAML{Config: *NewConfig()}
  218. if err := cfg.configFromFile(path); err != nil {
  219. return nil, err
  220. }
  221. return &cfg.Config, nil
  222. }
  223. func (cfg *configYAML) configFromFile(path string) error {
  224. b, err := ioutil.ReadFile(path)
  225. if err != nil {
  226. return err
  227. }
  228. defaultInitialCluster := cfg.InitialCluster
  229. err = yaml.Unmarshal(b, cfg)
  230. if err != nil {
  231. return err
  232. }
  233. if cfg.LPUrlsJSON != "" {
  234. u, err := types.NewURLs(strings.Split(cfg.LPUrlsJSON, ","))
  235. if err != nil {
  236. plog.Fatalf("unexpected error setting up listen-peer-urls: %v", err)
  237. }
  238. cfg.LPUrls = []url.URL(u)
  239. }
  240. if cfg.LCUrlsJSON != "" {
  241. u, err := types.NewURLs(strings.Split(cfg.LCUrlsJSON, ","))
  242. if err != nil {
  243. plog.Fatalf("unexpected error setting up listen-client-urls: %v", err)
  244. }
  245. cfg.LCUrls = []url.URL(u)
  246. }
  247. if cfg.CorsJSON != "" {
  248. if err := cfg.CorsInfo.Set(cfg.CorsJSON); err != nil {
  249. plog.Panicf("unexpected error setting up cors: %v", err)
  250. }
  251. }
  252. if cfg.APUrlsJSON != "" {
  253. u, err := types.NewURLs(strings.Split(cfg.APUrlsJSON, ","))
  254. if err != nil {
  255. plog.Fatalf("unexpected error setting up initial-advertise-peer-urls: %v", err)
  256. }
  257. cfg.APUrls = []url.URL(u)
  258. }
  259. if cfg.ACUrlsJSON != "" {
  260. u, err := types.NewURLs(strings.Split(cfg.ACUrlsJSON, ","))
  261. if err != nil {
  262. plog.Fatalf("unexpected error setting up advertise-peer-urls: %v", err)
  263. }
  264. cfg.ACUrls = []url.URL(u)
  265. }
  266. // If a discovery flag is set, clear default initial cluster set by InitialClusterFromName
  267. if (cfg.Durl != "" || cfg.DNSCluster != "") && cfg.InitialCluster == defaultInitialCluster {
  268. cfg.InitialCluster = ""
  269. }
  270. if cfg.ClusterState == "" {
  271. cfg.ClusterState = ClusterStateFlagNew
  272. }
  273. copySecurityDetails := func(tls *transport.TLSInfo, ysc *securityConfig) {
  274. tls.CAFile = ysc.CAFile
  275. tls.CertFile = ysc.CertFile
  276. tls.KeyFile = ysc.KeyFile
  277. tls.ClientCertAuth = ysc.CertAuth
  278. tls.TrustedCAFile = ysc.TrustedCAFile
  279. }
  280. copySecurityDetails(&cfg.ClientTLSInfo, &cfg.ClientSecurityJSON)
  281. copySecurityDetails(&cfg.PeerTLSInfo, &cfg.PeerSecurityJSON)
  282. cfg.ClientAutoTLS = cfg.ClientSecurityJSON.AutoTLS
  283. cfg.PeerAutoTLS = cfg.PeerSecurityJSON.AutoTLS
  284. return cfg.Validate()
  285. }
  286. func (cfg *Config) Validate() error {
  287. if err := checkBindURLs(cfg.LPUrls); err != nil {
  288. return err
  289. }
  290. if err := checkBindURLs(cfg.LCUrls); err != nil {
  291. return err
  292. }
  293. // Check if conflicting flags are passed.
  294. nSet := 0
  295. for _, v := range []bool{cfg.Durl != "", cfg.InitialCluster != "", cfg.DNSCluster != ""} {
  296. if v {
  297. nSet++
  298. }
  299. }
  300. if cfg.ClusterState != ClusterStateFlagNew && cfg.ClusterState != ClusterStateFlagExisting {
  301. return fmt.Errorf("unexpected clusterState %q", cfg.ClusterState)
  302. }
  303. if nSet > 1 {
  304. return ErrConflictBootstrapFlags
  305. }
  306. if 5*cfg.TickMs > cfg.ElectionMs {
  307. return fmt.Errorf("--election-timeout[%vms] should be at least as 5 times as --heartbeat-interval[%vms]", cfg.ElectionMs, cfg.TickMs)
  308. }
  309. if cfg.ElectionMs > maxElectionMs {
  310. return fmt.Errorf("--election-timeout[%vms] is too long, and should be set less than %vms", cfg.ElectionMs, maxElectionMs)
  311. }
  312. // check this last since proxying in etcdmain may make this OK
  313. if cfg.LCUrls != nil && cfg.ACUrls == nil {
  314. return ErrUnsetAdvertiseClientURLsFlag
  315. }
  316. return nil
  317. }
  318. // PeerURLsMapAndToken sets up an initial peer URLsMap and cluster token for bootstrap or discovery.
  319. func (cfg *Config) PeerURLsMapAndToken(which string) (urlsmap types.URLsMap, token string, err error) {
  320. token = cfg.InitialClusterToken
  321. switch {
  322. case cfg.Durl != "":
  323. urlsmap = types.URLsMap{}
  324. // If using discovery, generate a temporary cluster based on
  325. // self's advertised peer URLs
  326. urlsmap[cfg.Name] = cfg.APUrls
  327. token = cfg.Durl
  328. case cfg.DNSCluster != "":
  329. clusterStrs, cerr := srv.GetCluster("etcd-server", cfg.Name, cfg.DNSCluster, cfg.APUrls)
  330. if cerr != nil {
  331. plog.Errorf("couldn't resolve during SRV discovery (%v)", cerr)
  332. return nil, "", cerr
  333. }
  334. for _, s := range clusterStrs {
  335. plog.Noticef("got bootstrap from DNS for etcd-server at %s", s)
  336. }
  337. clusterStr := strings.Join(clusterStrs, ",")
  338. if strings.Contains(clusterStr, "https://") && cfg.PeerTLSInfo.CAFile == "" {
  339. cfg.PeerTLSInfo.ServerName = cfg.DNSCluster
  340. }
  341. urlsmap, err = types.NewURLsMap(clusterStr)
  342. // only etcd member must belong to the discovered cluster.
  343. // proxy does not need to belong to the discovered cluster.
  344. if which == "etcd" {
  345. if _, ok := urlsmap[cfg.Name]; !ok {
  346. return nil, "", fmt.Errorf("cannot find local etcd member %q in SRV records", cfg.Name)
  347. }
  348. }
  349. default:
  350. // We're statically configured, and cluster has appropriately been set.
  351. urlsmap, err = types.NewURLsMap(cfg.InitialCluster)
  352. }
  353. return urlsmap, token, err
  354. }
  355. func (cfg Config) InitialClusterFromName(name string) (ret string) {
  356. if len(cfg.APUrls) == 0 {
  357. return ""
  358. }
  359. n := name
  360. if name == "" {
  361. n = DefaultName
  362. }
  363. for i := range cfg.APUrls {
  364. ret = ret + "," + n + "=" + cfg.APUrls[i].String()
  365. }
  366. return ret[1:]
  367. }
  368. func (cfg Config) IsNewCluster() bool { return cfg.ClusterState == ClusterStateFlagNew }
  369. func (cfg Config) ElectionTicks() int { return int(cfg.ElectionMs / cfg.TickMs) }
  370. func (cfg Config) defaultPeerHost() bool {
  371. return len(cfg.APUrls) == 1 && cfg.APUrls[0].String() == DefaultInitialAdvertisePeerURLs
  372. }
  373. func (cfg Config) defaultClientHost() bool {
  374. return len(cfg.ACUrls) == 1 && cfg.ACUrls[0].String() == DefaultAdvertiseClientURLs
  375. }
  376. // UpdateDefaultClusterFromName updates cluster advertise URLs with, if available, default host,
  377. // if advertise URLs are default values(localhost:2379,2380) AND if listen URL is 0.0.0.0.
  378. // e.g. advertise peer URL localhost:2380 or listen peer URL 0.0.0.0:2380
  379. // then the advertise peer host would be updated with machine's default host,
  380. // while keeping the listen URL's port.
  381. // User can work around this by explicitly setting URL with 127.0.0.1.
  382. // It returns the default hostname, if used, and the error, if any, from getting the machine's default host.
  383. // TODO: check whether fields are set instead of whether fields have default value
  384. func (cfg *Config) UpdateDefaultClusterFromName(defaultInitialCluster string) (string, error) {
  385. if defaultHostname == "" || defaultHostStatus != nil {
  386. // update 'initial-cluster' when only the name is specified (e.g. 'etcd --name=abc')
  387. if cfg.Name != DefaultName && cfg.InitialCluster == defaultInitialCluster {
  388. cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
  389. }
  390. return "", defaultHostStatus
  391. }
  392. used := false
  393. pip, pport := cfg.LPUrls[0].Hostname(), cfg.LPUrls[0].Port()
  394. if cfg.defaultPeerHost() && pip == "0.0.0.0" {
  395. cfg.APUrls[0] = url.URL{Scheme: cfg.APUrls[0].Scheme, Host: fmt.Sprintf("%s:%s", defaultHostname, pport)}
  396. used = true
  397. }
  398. // update 'initial-cluster' when only the name is specified (e.g. 'etcd --name=abc')
  399. if cfg.Name != DefaultName && cfg.InitialCluster == defaultInitialCluster {
  400. cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
  401. }
  402. cip, cport := cfg.LCUrls[0].Hostname(), cfg.LCUrls[0].Port()
  403. if cfg.defaultClientHost() && cip == "0.0.0.0" {
  404. cfg.ACUrls[0] = url.URL{Scheme: cfg.ACUrls[0].Scheme, Host: fmt.Sprintf("%s:%s", defaultHostname, cport)}
  405. used = true
  406. }
  407. dhost := defaultHostname
  408. if !used {
  409. dhost = ""
  410. }
  411. return dhost, defaultHostStatus
  412. }
  413. // checkBindURLs returns an error if any URL uses a domain name.
  414. // TODO: return error in 3.2.0
  415. func checkBindURLs(urls []url.URL) error {
  416. for _, url := range urls {
  417. if url.Scheme == "unix" || url.Scheme == "unixs" {
  418. continue
  419. }
  420. host, _, err := net.SplitHostPort(url.Host)
  421. if err != nil {
  422. return err
  423. }
  424. if host == "localhost" {
  425. // special case for local address
  426. // TODO: support /etc/hosts ?
  427. continue
  428. }
  429. if net.ParseIP(host) == nil {
  430. return fmt.Errorf("expected IP in URL for binding (%s)", url.String())
  431. }
  432. }
  433. return nil
  434. }