config.go 14 KB

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