config.go 13 KB

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