config.go 13 KB

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