config.go 15 KB

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