config.go 14 KB

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