config.go 15 KB

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