config.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. // Copyright 2015 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 etcdserver
  15. import (
  16. "context"
  17. "fmt"
  18. "path/filepath"
  19. "sort"
  20. "strings"
  21. "time"
  22. "github.com/coreos/etcd/pkg/netutil"
  23. "github.com/coreos/etcd/pkg/transport"
  24. "github.com/coreos/etcd/pkg/types"
  25. "go.uber.org/zap"
  26. "go.uber.org/zap/zapcore"
  27. )
  28. // ServerConfig holds the configuration of etcd as taken from the command line or discovery.
  29. type ServerConfig struct {
  30. Name string
  31. DiscoveryURL string
  32. DiscoveryProxy string
  33. ClientURLs types.URLs
  34. PeerURLs types.URLs
  35. DataDir string
  36. // DedicatedWALDir config will make the etcd to write the WAL to the WALDir
  37. // rather than the dataDir/member/wal.
  38. DedicatedWALDir string
  39. SnapCount uint64
  40. MaxSnapFiles uint
  41. MaxWALFiles uint
  42. InitialPeerURLsMap types.URLsMap
  43. InitialClusterToken string
  44. NewCluster bool
  45. PeerTLSInfo transport.TLSInfo
  46. CORS map[string]struct{}
  47. // HostWhitelist lists acceptable hostnames from client requests.
  48. // If server is insecure (no TLS), server only accepts requests
  49. // whose Host header value exists in this white list.
  50. HostWhitelist map[string]struct{}
  51. TickMs uint
  52. ElectionTicks int
  53. // InitialElectionTickAdvance is true, then local member fast-forwards
  54. // election ticks to speed up "initial" leader election trigger. This
  55. // benefits the case of larger election ticks. For instance, cross
  56. // datacenter deployment may require longer election timeout of 10-second.
  57. // If true, local node does not need wait up to 10-second. Instead,
  58. // forwards its election ticks to 8-second, and have only 2-second left
  59. // before leader election.
  60. //
  61. // Major assumptions are that:
  62. // - cluster has no active leader thus advancing ticks enables faster
  63. // leader election, or
  64. // - cluster already has an established leader, and rejoining follower
  65. // is likely to receive heartbeats from the leader after tick advance
  66. // and before election timeout.
  67. //
  68. // However, when network from leader to rejoining follower is congested,
  69. // and the follower does not receive leader heartbeat within left election
  70. // ticks, disruptive election has to happen thus affecting cluster
  71. // availabilities.
  72. //
  73. // Disabling this would slow down initial bootstrap process for cross
  74. // datacenter deployments. Make your own tradeoffs by configuring
  75. // --initial-election-tick-advance at the cost of slow initial bootstrap.
  76. //
  77. // If single-node, it advances ticks regardless.
  78. //
  79. // See https://github.com/coreos/etcd/issues/9333 for more detail.
  80. InitialElectionTickAdvance bool
  81. BootstrapTimeout time.Duration
  82. AutoCompactionRetention time.Duration
  83. AutoCompactionMode string
  84. QuotaBackendBytes int64
  85. MaxTxnOps uint
  86. // MaxRequestBytes is the maximum request size to send over raft.
  87. MaxRequestBytes uint
  88. StrictReconfigCheck bool
  89. // ClientCertAuthEnabled is true when cert has been signed by the client CA.
  90. ClientCertAuthEnabled bool
  91. AuthToken string
  92. // InitialCorruptCheck is true to check data corruption on boot
  93. // before serving any peer/client traffic.
  94. InitialCorruptCheck bool
  95. CorruptCheckTime time.Duration
  96. // PreVote is true to enable Raft Pre-Vote.
  97. PreVote bool
  98. // Logger logs server-side operations.
  99. // If not nil, it disables "capnslog" and uses the given logger.
  100. Logger *zap.Logger
  101. // LoggerConfig is server logger configuration for Raft logger.
  102. // Must be either: "LoggerConfig != nil" or "LoggerCore != nil && LoggerWriteSyncer != nil".
  103. LoggerConfig *zap.Config
  104. // LoggerCore is "zapcore.Core" for raft logger.
  105. // Must be either: "LoggerConfig != nil" or "LoggerCore != nil && LoggerWriteSyncer != nil".
  106. LoggerCore zapcore.Core
  107. LoggerWriteSyncer zapcore.WriteSyncer
  108. Debug bool
  109. ForceNewCluster bool
  110. }
  111. // VerifyBootstrap sanity-checks the initial config for bootstrap case
  112. // and returns an error for things that should never happen.
  113. func (c *ServerConfig) VerifyBootstrap() error {
  114. if err := c.hasLocalMember(); err != nil {
  115. return err
  116. }
  117. if err := c.advertiseMatchesCluster(); err != nil {
  118. return err
  119. }
  120. if checkDuplicateURL(c.InitialPeerURLsMap) {
  121. return fmt.Errorf("initial cluster %s has duplicate url", c.InitialPeerURLsMap)
  122. }
  123. if c.InitialPeerURLsMap.String() == "" && c.DiscoveryURL == "" {
  124. return fmt.Errorf("initial cluster unset and no discovery URL found")
  125. }
  126. return nil
  127. }
  128. // VerifyJoinExisting sanity-checks the initial config for join existing cluster
  129. // case and returns an error for things that should never happen.
  130. func (c *ServerConfig) VerifyJoinExisting() error {
  131. // The member has announced its peer urls to the cluster before starting; no need to
  132. // set the configuration again.
  133. if err := c.hasLocalMember(); err != nil {
  134. return err
  135. }
  136. if checkDuplicateURL(c.InitialPeerURLsMap) {
  137. return fmt.Errorf("initial cluster %s has duplicate url", c.InitialPeerURLsMap)
  138. }
  139. if c.DiscoveryURL != "" {
  140. return fmt.Errorf("discovery URL should not be set when joining existing initial cluster")
  141. }
  142. return nil
  143. }
  144. // hasLocalMember checks that the cluster at least contains the local server.
  145. func (c *ServerConfig) hasLocalMember() error {
  146. if urls := c.InitialPeerURLsMap[c.Name]; urls == nil {
  147. return fmt.Errorf("couldn't find local name %q in the initial cluster configuration", c.Name)
  148. }
  149. return nil
  150. }
  151. // advertiseMatchesCluster confirms peer URLs match those in the cluster peer list.
  152. func (c *ServerConfig) advertiseMatchesCluster() error {
  153. urls, apurls := c.InitialPeerURLsMap[c.Name], c.PeerURLs.StringSlice()
  154. urls.Sort()
  155. sort.Strings(apurls)
  156. ctx, cancel := context.WithTimeout(context.TODO(), 30*time.Second)
  157. defer cancel()
  158. ok, err := netutil.URLStringsEqual(ctx, c.Logger, apurls, urls.StringSlice())
  159. if ok {
  160. return nil
  161. }
  162. initMap, apMap := make(map[string]struct{}), make(map[string]struct{})
  163. for _, url := range c.PeerURLs {
  164. apMap[url.String()] = struct{}{}
  165. }
  166. for _, url := range c.InitialPeerURLsMap[c.Name] {
  167. initMap[url.String()] = struct{}{}
  168. }
  169. missing := []string{}
  170. for url := range initMap {
  171. if _, ok := apMap[url]; !ok {
  172. missing = append(missing, url)
  173. }
  174. }
  175. if len(missing) > 0 {
  176. for i := range missing {
  177. missing[i] = c.Name + "=" + missing[i]
  178. }
  179. mstr := strings.Join(missing, ",")
  180. apStr := strings.Join(apurls, ",")
  181. return fmt.Errorf("--initial-cluster has %s but missing from --initial-advertise-peer-urls=%s (%v)", mstr, apStr, err)
  182. }
  183. for url := range apMap {
  184. if _, ok := initMap[url]; !ok {
  185. missing = append(missing, url)
  186. }
  187. }
  188. if len(missing) > 0 {
  189. mstr := strings.Join(missing, ",")
  190. umap := types.URLsMap(map[string]types.URLs{c.Name: c.PeerURLs})
  191. return fmt.Errorf("--initial-advertise-peer-urls has %s but missing from --initial-cluster=%s", mstr, umap.String())
  192. }
  193. // resolved URLs from "--initial-advertise-peer-urls" and "--initial-cluster" did not match or failed
  194. apStr := strings.Join(apurls, ",")
  195. umap := types.URLsMap(map[string]types.URLs{c.Name: c.PeerURLs})
  196. return fmt.Errorf("failed to resolve %s to match --initial-cluster=%s (%v)", apStr, umap.String(), err)
  197. }
  198. func (c *ServerConfig) MemberDir() string { return filepath.Join(c.DataDir, "member") }
  199. func (c *ServerConfig) WALDir() string {
  200. if c.DedicatedWALDir != "" {
  201. return c.DedicatedWALDir
  202. }
  203. return filepath.Join(c.MemberDir(), "wal")
  204. }
  205. func (c *ServerConfig) SnapDir() string { return filepath.Join(c.MemberDir(), "snap") }
  206. func (c *ServerConfig) ShouldDiscover() bool { return c.DiscoveryURL != "" }
  207. // ReqTimeout returns timeout for request to finish.
  208. func (c *ServerConfig) ReqTimeout() time.Duration {
  209. // 5s for queue waiting, computation and disk IO delay
  210. // + 2 * election timeout for possible leader election
  211. return 5*time.Second + 2*time.Duration(c.ElectionTicks*int(c.TickMs))*time.Millisecond
  212. }
  213. func (c *ServerConfig) electionTimeout() time.Duration {
  214. return time.Duration(c.ElectionTicks*int(c.TickMs)) * time.Millisecond
  215. }
  216. func (c *ServerConfig) peerDialTimeout() time.Duration {
  217. // 1s for queue wait and election timeout
  218. return time.Second + time.Duration(c.ElectionTicks*int(c.TickMs))*time.Millisecond
  219. }
  220. func (c *ServerConfig) PrintWithInitial() { c.print(true) }
  221. func (c *ServerConfig) Print() { c.print(false) }
  222. func (c *ServerConfig) print(initial bool) {
  223. // TODO: remove this after dropping "capnslog"
  224. if c.Logger == nil {
  225. plog.Infof("name = %s", c.Name)
  226. if c.ForceNewCluster {
  227. plog.Infof("force new cluster")
  228. }
  229. plog.Infof("data dir = %s", c.DataDir)
  230. plog.Infof("member dir = %s", c.MemberDir())
  231. if c.DedicatedWALDir != "" {
  232. plog.Infof("dedicated WAL dir = %s", c.DedicatedWALDir)
  233. }
  234. plog.Infof("heartbeat = %dms", c.TickMs)
  235. plog.Infof("election = %dms", c.ElectionTicks*int(c.TickMs))
  236. plog.Infof("snapshot count = %d", c.SnapCount)
  237. if len(c.DiscoveryURL) != 0 {
  238. plog.Infof("discovery URL= %s", c.DiscoveryURL)
  239. if len(c.DiscoveryProxy) != 0 {
  240. plog.Infof("discovery proxy = %s", c.DiscoveryProxy)
  241. }
  242. }
  243. plog.Infof("advertise client URLs = %s", c.ClientURLs)
  244. if initial {
  245. plog.Infof("initial advertise peer URLs = %s", c.PeerURLs)
  246. plog.Infof("initial cluster = %s", c.InitialPeerURLsMap)
  247. }
  248. } else {
  249. state := "new"
  250. if !c.NewCluster {
  251. state = "existing"
  252. }
  253. c.Logger.Info(
  254. "server configuration",
  255. zap.String("name", c.Name),
  256. zap.String("data-dir", c.DataDir),
  257. zap.String("member-dir", c.MemberDir()),
  258. zap.String("dedicated-wal-dir", c.DedicatedWALDir),
  259. zap.Bool("force-new-cluster", c.ForceNewCluster),
  260. zap.Uint("heartbeat-tick-ms", c.TickMs),
  261. zap.String("heartbeat-interval", fmt.Sprintf("%v", time.Duration(c.TickMs)*time.Millisecond)),
  262. zap.Int("election-tick-ms", c.ElectionTicks),
  263. zap.String("election-timeout", fmt.Sprintf("%v", time.Duration(c.ElectionTicks*int(c.TickMs))*time.Millisecond)),
  264. zap.Bool("initial-election-tick-advance", c.InitialElectionTickAdvance),
  265. zap.Uint64("snapshot-count", c.SnapCount),
  266. zap.Strings("advertise-client-urls", c.getACURLs()),
  267. zap.Strings("initial-advertise-peer-urls", c.getAPURLs()),
  268. zap.Bool("initial", initial),
  269. zap.String("initial-cluster", c.InitialPeerURLsMap.String()),
  270. zap.String("initial-cluster-state", state),
  271. zap.String("initial-cluster-token", c.InitialClusterToken),
  272. zap.Bool("pre-vote", c.PreVote),
  273. zap.Bool("initial-corrupt-check", c.InitialCorruptCheck),
  274. zap.String("corrupt-check-time-interval", c.CorruptCheckTime.String()),
  275. zap.String("auto-compaction-mode", c.AutoCompactionMode),
  276. zap.Duration("auto-compaction-retention", c.AutoCompactionRetention),
  277. zap.String("auto-compaction-interval", c.AutoCompactionRetention.String()),
  278. zap.String("discovery-url", c.DiscoveryURL),
  279. zap.String("discovery-proxy", c.DiscoveryProxy),
  280. )
  281. }
  282. }
  283. func checkDuplicateURL(urlsmap types.URLsMap) bool {
  284. um := make(map[string]bool)
  285. for _, urls := range urlsmap {
  286. for _, url := range urls {
  287. u := url.String()
  288. if um[u] {
  289. return true
  290. }
  291. um[u] = true
  292. }
  293. }
  294. return false
  295. }
  296. func (c *ServerConfig) bootstrapTimeout() time.Duration {
  297. if c.BootstrapTimeout != 0 {
  298. return c.BootstrapTimeout
  299. }
  300. return time.Second
  301. }
  302. func (c *ServerConfig) backendPath() string { return filepath.Join(c.SnapDir(), "db") }
  303. func (c *ServerConfig) getAPURLs() (ss []string) {
  304. ss = make([]string, len(c.PeerURLs))
  305. for i := range c.PeerURLs {
  306. ss[i] = c.PeerURLs[i].String()
  307. }
  308. return ss
  309. }
  310. func (c *ServerConfig) getACURLs() (ss []string) {
  311. ss = make([]string, len(c.ClientURLs))
  312. for i := range c.ClientURLs {
  313. ss[i] = c.ClientURLs[i].String()
  314. }
  315. return ss
  316. }