config.go 16 KB

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