config.go 11 KB

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