config.go 11 KB

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