config.go 9.6 KB

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