config.go 14 KB

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