config.go 16 KB

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