config.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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/http"
  19. "net/url"
  20. "strings"
  21. "github.com/coreos/etcd/discovery"
  22. "github.com/coreos/etcd/etcdserver"
  23. "github.com/coreos/etcd/pkg/cors"
  24. "github.com/coreos/etcd/pkg/transport"
  25. "github.com/coreos/etcd/pkg/types"
  26. "github.com/ghodss/yaml"
  27. )
  28. const (
  29. ClusterStateFlagNew = "new"
  30. ClusterStateFlagExisting = "existing"
  31. DefaultName = "default"
  32. DefaultInitialAdvertisePeerURLs = "http://localhost:2380"
  33. DefaultAdvertiseClientURLs = "http://localhost:2379"
  34. DefaultListenPeerURLs = "http://localhost:2380"
  35. DefaultListenClientURLs = "http://localhost:2379"
  36. DefaultMaxSnapshots = 5
  37. DefaultMaxWALs = 5
  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. )
  47. // Config holds the arguments for configuring an etcd server.
  48. type Config struct {
  49. // member
  50. CorsInfo *cors.CORSInfo
  51. LPUrls, LCUrls []url.URL
  52. Dir string `json:"data-dir"`
  53. WalDir string `json:"wal-dir"`
  54. MaxSnapFiles uint `json:"max-snapshots"`
  55. MaxWalFiles uint `json:"max-wals"`
  56. Name string `json:"name"`
  57. SnapCount uint64 `json:"snapshot-count"`
  58. AutoCompactionRetention int `json:"auto-compaction-retention"`
  59. // TickMs is the number of milliseconds between heartbeat ticks.
  60. // TODO: decouple tickMs and heartbeat tick (current heartbeat tick = 1).
  61. // make ticks a cluster wide configuration.
  62. TickMs uint `json:"heartbeat-interval"`
  63. ElectionMs uint `json:"election-timeout"`
  64. QuotaBackendBytes int64 `json:"quota-backend-bytes"`
  65. // clustering
  66. APUrls, ACUrls []url.URL
  67. ClusterState string `json:"initial-cluster-state"`
  68. DNSCluster string `json:"discovery-srv"`
  69. Dproxy string `json:"discovery-proxy"`
  70. Durl string `json:"discovery"`
  71. InitialCluster string `json:"initial-cluster"`
  72. InitialClusterToken string `json:"initial-cluster-token"`
  73. StrictReconfigCheck bool `json:"strict-reconfig-check"`
  74. // security
  75. ClientTLSInfo transport.TLSInfo
  76. ClientAutoTLS bool
  77. PeerTLSInfo transport.TLSInfo
  78. PeerAutoTLS bool
  79. // debug
  80. Debug bool `json:"debug"`
  81. LogPkgLevels string `json:"log-package-levels"`
  82. EnablePprof bool
  83. // ForceNewCluster starts a new cluster even if previously started; unsafe.
  84. ForceNewCluster bool `json:"force-new-cluster"`
  85. // UserHandlers is for registering users handlers and only used for
  86. // embedding etcd into other applications.
  87. // The map key is the route path for the handler, and
  88. // you must ensure it can't be conflicted with etcd's.
  89. UserHandlers map[string]http.Handler `json:"-"`
  90. }
  91. // configYAML holds the config suitable for yaml parsing
  92. type configYAML struct {
  93. Config
  94. configJSON
  95. }
  96. // configJSON has file options that are translated into Config options
  97. type configJSON struct {
  98. LPUrlsJSON string `json:"listen-peer-urls"`
  99. LCUrlsJSON string `json:"listen-client-urls"`
  100. CorsJSON string `json:"cors"`
  101. APUrlsJSON string `json:"initial-advertise-peer-urls"`
  102. ACUrlsJSON string `json:"advertise-client-urls"`
  103. ClientSecurityJSON securityConfig `json:"client-transport-security"`
  104. PeerSecurityJSON securityConfig `json:"peer-transport-security"`
  105. }
  106. type securityConfig struct {
  107. CAFile string `json:"ca-file"`
  108. CertFile string `json:"cert-file"`
  109. KeyFile string `json:"key-file"`
  110. CertAuth bool `json:"client-cert-auth"`
  111. TrustedCAFile string `json:"trusted-ca-file"`
  112. AutoTLS bool `json:"auto-tls"`
  113. }
  114. // NewConfig creates a new Config populated with default values.
  115. func NewConfig() *Config {
  116. lpurl, _ := url.Parse(DefaultListenPeerURLs)
  117. apurl, _ := url.Parse(DefaultInitialAdvertisePeerURLs)
  118. lcurl, _ := url.Parse(DefaultListenClientURLs)
  119. acurl, _ := url.Parse(DefaultAdvertiseClientURLs)
  120. cfg := &Config{
  121. CorsInfo: &cors.CORSInfo{},
  122. MaxSnapFiles: DefaultMaxSnapshots,
  123. MaxWalFiles: DefaultMaxWALs,
  124. Name: DefaultName,
  125. SnapCount: etcdserver.DefaultSnapCount,
  126. TickMs: 100,
  127. ElectionMs: 1000,
  128. LPUrls: []url.URL{*lpurl},
  129. LCUrls: []url.URL{*lcurl},
  130. APUrls: []url.URL{*apurl},
  131. ACUrls: []url.URL{*acurl},
  132. ClusterState: ClusterStateFlagNew,
  133. InitialClusterToken: "etcd-cluster",
  134. StrictReconfigCheck: true,
  135. }
  136. cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
  137. return cfg
  138. }
  139. func ConfigFromFile(path string) (*Config, error) {
  140. cfg := &configYAML{Config: *NewConfig()}
  141. if err := cfg.configFromFile(path); err != nil {
  142. return nil, err
  143. }
  144. return &cfg.Config, nil
  145. }
  146. func (cfg *configYAML) configFromFile(path string) error {
  147. b, err := ioutil.ReadFile(path)
  148. if err != nil {
  149. return err
  150. }
  151. err = yaml.Unmarshal(b, cfg)
  152. if err != nil {
  153. return err
  154. }
  155. if cfg.LPUrlsJSON != "" {
  156. u, err := types.NewURLs(strings.Split(cfg.LPUrlsJSON, ","))
  157. if err != nil {
  158. plog.Fatalf("unexpected error setting up listen-peer-urls: %v", err)
  159. }
  160. cfg.LPUrls = []url.URL(u)
  161. }
  162. if cfg.LCUrlsJSON != "" {
  163. u, err := types.NewURLs(strings.Split(cfg.LCUrlsJSON, ","))
  164. if err != nil {
  165. plog.Fatalf("unexpected error setting up listen-client-urls: %v", err)
  166. }
  167. cfg.LCUrls = []url.URL(u)
  168. }
  169. if cfg.CorsJSON != "" {
  170. if err := cfg.CorsInfo.Set(cfg.CorsJSON); err != nil {
  171. plog.Panicf("unexpected error setting up cors: %v", err)
  172. }
  173. }
  174. if cfg.APUrlsJSON != "" {
  175. u, err := types.NewURLs(strings.Split(cfg.APUrlsJSON, ","))
  176. if err != nil {
  177. plog.Fatalf("unexpected error setting up initial-advertise-peer-urls: %v", err)
  178. }
  179. cfg.APUrls = []url.URL(u)
  180. }
  181. if cfg.ACUrlsJSON != "" {
  182. u, err := types.NewURLs(strings.Split(cfg.ACUrlsJSON, ","))
  183. if err != nil {
  184. plog.Fatalf("unexpected error setting up advertise-peer-urls: %v", err)
  185. }
  186. cfg.ACUrls = []url.URL(u)
  187. }
  188. if cfg.ClusterState == "" {
  189. cfg.ClusterState = ClusterStateFlagNew
  190. }
  191. copySecurityDetails := func(tls *transport.TLSInfo, ysc *securityConfig) {
  192. tls.CAFile = ysc.CAFile
  193. tls.CertFile = ysc.CertFile
  194. tls.KeyFile = ysc.KeyFile
  195. tls.ClientCertAuth = ysc.CertAuth
  196. tls.TrustedCAFile = ysc.TrustedCAFile
  197. }
  198. copySecurityDetails(&cfg.ClientTLSInfo, &cfg.ClientSecurityJSON)
  199. copySecurityDetails(&cfg.PeerTLSInfo, &cfg.PeerSecurityJSON)
  200. cfg.ClientAutoTLS = cfg.ClientSecurityJSON.AutoTLS
  201. cfg.PeerAutoTLS = cfg.PeerSecurityJSON.AutoTLS
  202. return cfg.Validate()
  203. }
  204. func (cfg *Config) Validate() error {
  205. // Check if conflicting flags are passed.
  206. nSet := 0
  207. for _, v := range []bool{cfg.Durl != "", cfg.InitialCluster != "", cfg.DNSCluster != ""} {
  208. if v {
  209. nSet++
  210. }
  211. }
  212. if cfg.ClusterState != ClusterStateFlagNew && cfg.ClusterState != ClusterStateFlagExisting {
  213. return fmt.Errorf("unexpected clusterState %q", cfg.ClusterState)
  214. }
  215. if nSet > 1 {
  216. return ErrConflictBootstrapFlags
  217. }
  218. if 5*cfg.TickMs > cfg.ElectionMs {
  219. return fmt.Errorf("--election-timeout[%vms] should be at least as 5 times as --heartbeat-interval[%vms]", cfg.ElectionMs, cfg.TickMs)
  220. }
  221. if cfg.ElectionMs > maxElectionMs {
  222. return fmt.Errorf("--election-timeout[%vms] is too long, and should be set less than %vms", cfg.ElectionMs, maxElectionMs)
  223. }
  224. // check this last since proxying in etcdmain may make this OK
  225. if cfg.LCUrls != nil && cfg.ACUrls == nil {
  226. return ErrUnsetAdvertiseClientURLsFlag
  227. }
  228. return nil
  229. }
  230. // PeerURLsMapAndToken sets up an initial peer URLsMap and cluster token for bootstrap or discovery.
  231. func (cfg *Config) PeerURLsMapAndToken(which string) (urlsmap types.URLsMap, token string, err error) {
  232. switch {
  233. case cfg.Durl != "":
  234. urlsmap = types.URLsMap{}
  235. // If using discovery, generate a temporary cluster based on
  236. // self's advertised peer URLs
  237. urlsmap[cfg.Name] = cfg.APUrls
  238. token = cfg.Durl
  239. case cfg.DNSCluster != "":
  240. var clusterStr string
  241. clusterStr, token, err = discovery.SRVGetCluster(cfg.Name, cfg.DNSCluster, cfg.InitialClusterToken, cfg.APUrls)
  242. if err != nil {
  243. return nil, "", err
  244. }
  245. if strings.Contains(clusterStr, "https://") && cfg.PeerTLSInfo.CAFile == "" {
  246. cfg.PeerTLSInfo.ServerName = cfg.DNSCluster
  247. }
  248. urlsmap, err = types.NewURLsMap(clusterStr)
  249. // only etcd member must belong to the discovered cluster.
  250. // proxy does not need to belong to the discovered cluster.
  251. if which == "etcd" {
  252. if _, ok := urlsmap[cfg.Name]; !ok {
  253. return nil, "", fmt.Errorf("cannot find local etcd member %q in SRV records", cfg.Name)
  254. }
  255. }
  256. default:
  257. // We're statically configured, and cluster has appropriately been set.
  258. urlsmap, err = types.NewURLsMap(cfg.InitialCluster)
  259. token = cfg.InitialClusterToken
  260. }
  261. return urlsmap, token, err
  262. }
  263. func (cfg Config) InitialClusterFromName(name string) (ret string) {
  264. if len(cfg.APUrls) == 0 {
  265. return ""
  266. }
  267. n := name
  268. if name == "" {
  269. n = DefaultName
  270. }
  271. for i := range cfg.APUrls {
  272. ret = ret + "," + n + "=" + cfg.APUrls[i].String()
  273. }
  274. return ret[1:]
  275. }
  276. func (cfg Config) IsNewCluster() bool { return cfg.ClusterState == ClusterStateFlagNew }
  277. func (cfg Config) ElectionTicks() int { return int(cfg.ElectionMs / cfg.TickMs) }