config.go 13 KB

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