config.go 12 KB

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