config.go 9.4 KB

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