config.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. }
  135. cfg.InitialCluster = cfg.InitialClusterFromName(cfg.Name)
  136. return cfg
  137. }
  138. func ConfigFromFile(path string) (*Config, error) {
  139. cfg := &configYAML{}
  140. if err := cfg.configFromFile(path); err != nil {
  141. return nil, err
  142. }
  143. return &cfg.Config, nil
  144. }
  145. func (cfg *configYAML) configFromFile(path string) error {
  146. b, err := ioutil.ReadFile(path)
  147. if err != nil {
  148. return err
  149. }
  150. err = yaml.Unmarshal(b, cfg)
  151. if err != nil {
  152. return err
  153. }
  154. if cfg.LPUrlsJSON != "" {
  155. u, err := types.NewURLs(strings.Split(cfg.LPUrlsJSON, ","))
  156. if err != nil {
  157. plog.Fatalf("unexpected error setting up listen-peer-urls: %v", err)
  158. }
  159. cfg.LPUrls = []url.URL(u)
  160. }
  161. if cfg.LCUrlsJSON != "" {
  162. u, err := types.NewURLs(strings.Split(cfg.LCUrlsJSON, ","))
  163. if err != nil {
  164. plog.Fatalf("unexpected error setting up listen-client-urls: %v", err)
  165. }
  166. cfg.LCUrls = []url.URL(u)
  167. }
  168. if cfg.CorsJSON != "" {
  169. if err := cfg.CorsInfo.Set(cfg.CorsJSON); err != nil {
  170. plog.Panicf("unexpected error setting up cors: %v", err)
  171. }
  172. }
  173. if cfg.APUrlsJSON != "" {
  174. u, err := types.NewURLs(strings.Split(cfg.APUrlsJSON, ","))
  175. if err != nil {
  176. plog.Fatalf("unexpected error setting up initial-advertise-peer-urls: %v", err)
  177. }
  178. cfg.APUrls = []url.URL(u)
  179. }
  180. if cfg.ACUrlsJSON != "" {
  181. u, err := types.NewURLs(strings.Split(cfg.ACUrlsJSON, ","))
  182. if err != nil {
  183. plog.Fatalf("unexpected error setting up advertise-peer-urls: %v", err)
  184. }
  185. cfg.ACUrls = []url.URL(u)
  186. }
  187. if cfg.ClusterState == "" {
  188. cfg.ClusterState = ClusterStateFlagNew
  189. }
  190. copySecurityDetails := func(tls *transport.TLSInfo, ysc *securityConfig) {
  191. tls.CAFile = ysc.CAFile
  192. tls.CertFile = ysc.CertFile
  193. tls.KeyFile = ysc.KeyFile
  194. tls.ClientCertAuth = ysc.CertAuth
  195. tls.TrustedCAFile = ysc.TrustedCAFile
  196. }
  197. copySecurityDetails(&cfg.ClientTLSInfo, &cfg.ClientSecurityJSON)
  198. copySecurityDetails(&cfg.PeerTLSInfo, &cfg.PeerSecurityJSON)
  199. cfg.ClientAutoTLS = cfg.ClientSecurityJSON.AutoTLS
  200. cfg.PeerAutoTLS = cfg.PeerSecurityJSON.AutoTLS
  201. return cfg.Validate()
  202. }
  203. func (cfg *Config) Validate() error {
  204. // Check if conflicting flags are passed.
  205. nSet := 0
  206. for _, v := range []bool{cfg.Durl != "", cfg.InitialCluster != "", cfg.DNSCluster != ""} {
  207. if v {
  208. nSet++
  209. }
  210. }
  211. if cfg.ClusterState != ClusterStateFlagNew && cfg.ClusterState != ClusterStateFlagExisting {
  212. return fmt.Errorf("unexpected clusterState %q", cfg.ClusterState)
  213. }
  214. if nSet > 1 {
  215. return ErrConflictBootstrapFlags
  216. }
  217. if 5*cfg.TickMs > cfg.ElectionMs {
  218. return fmt.Errorf("--election-timeout[%vms] should be at least as 5 times as --heartbeat-interval[%vms]", cfg.ElectionMs, cfg.TickMs)
  219. }
  220. if cfg.ElectionMs > maxElectionMs {
  221. return fmt.Errorf("--election-timeout[%vms] is too long, and should be set less than %vms", cfg.ElectionMs, maxElectionMs)
  222. }
  223. // check this last since proxying in etcdmain may make this OK
  224. if cfg.LCUrls != nil && cfg.ACUrls == nil {
  225. return ErrUnsetAdvertiseClientURLsFlag
  226. }
  227. return nil
  228. }
  229. // PeerURLsMapAndToken sets up an initial peer URLsMap and cluster token for bootstrap or discovery.
  230. func (cfg *Config) PeerURLsMapAndToken(which string) (urlsmap types.URLsMap, token string, err error) {
  231. switch {
  232. case cfg.Durl != "":
  233. urlsmap = types.URLsMap{}
  234. // If using discovery, generate a temporary cluster based on
  235. // self's advertised peer URLs
  236. urlsmap[cfg.Name] = cfg.APUrls
  237. token = cfg.Durl
  238. case cfg.DNSCluster != "":
  239. var clusterStr string
  240. clusterStr, token, err = discovery.SRVGetCluster(cfg.Name, cfg.DNSCluster, cfg.InitialClusterToken, cfg.APUrls)
  241. if err != nil {
  242. return nil, "", err
  243. }
  244. urlsmap, err = types.NewURLsMap(clusterStr)
  245. // only etcd member must belong to the discovered cluster.
  246. // proxy does not need to belong to the discovered cluster.
  247. if which == "etcd" {
  248. if _, ok := urlsmap[cfg.Name]; !ok {
  249. return nil, "", fmt.Errorf("cannot find local etcd member %q in SRV records", cfg.Name)
  250. }
  251. }
  252. default:
  253. // We're statically configured, and cluster has appropriately been set.
  254. urlsmap, err = types.NewURLsMap(cfg.InitialCluster)
  255. token = cfg.InitialClusterToken
  256. }
  257. return urlsmap, token, err
  258. }
  259. func (cfg Config) InitialClusterFromName(name string) (ret string) {
  260. if len(cfg.APUrls) == 0 {
  261. return ""
  262. }
  263. n := name
  264. if name == "" {
  265. n = DefaultName
  266. }
  267. for i := range cfg.APUrls {
  268. ret = ret + "," + n + "=" + cfg.APUrls[i].String()
  269. }
  270. return ret[1:]
  271. }
  272. func (cfg Config) IsNewCluster() bool { return cfg.ClusterState == ClusterStateFlagNew }
  273. func (cfg Config) ElectionTicks() int { return int(cfg.ElectionMs / cfg.TickMs) }