config.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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. BootstrapTimeout time.Duration
  53. AutoCompactionRetention time.Duration
  54. AutoCompactionMode string
  55. QuotaBackendBytes int64
  56. MaxTxnOps uint
  57. // MaxRequestBytes is the maximum request size to send over raft.
  58. MaxRequestBytes uint
  59. StrictReconfigCheck bool
  60. // ClientCertAuthEnabled is true when cert has been signed by the client CA.
  61. ClientCertAuthEnabled bool
  62. AuthToken string
  63. // InitialCorruptCheck is true to check data corruption on boot
  64. // before serving any peer/client traffic.
  65. InitialCorruptCheck bool
  66. CorruptCheckTime time.Duration
  67. // PreVote is true to enable Raft Pre-Vote.
  68. PreVote bool
  69. // Logger logs server-side operations.
  70. // If not nil, it disables "capnslog" and uses the given logger.
  71. Logger *zap.Logger
  72. // LoggerConfig is server logger configuration for Raft logger.
  73. LoggerConfig zap.Config
  74. Debug bool
  75. ForceNewCluster bool
  76. }
  77. // VerifyBootstrap sanity-checks the initial config for bootstrap case
  78. // and returns an error for things that should never happen.
  79. func (c *ServerConfig) VerifyBootstrap() error {
  80. if err := c.hasLocalMember(); err != nil {
  81. return err
  82. }
  83. if err := c.advertiseMatchesCluster(); err != nil {
  84. return err
  85. }
  86. if checkDuplicateURL(c.InitialPeerURLsMap) {
  87. return fmt.Errorf("initial cluster %s has duplicate url", c.InitialPeerURLsMap)
  88. }
  89. if c.InitialPeerURLsMap.String() == "" && c.DiscoveryURL == "" {
  90. return fmt.Errorf("initial cluster unset and no discovery URL found")
  91. }
  92. return nil
  93. }
  94. // VerifyJoinExisting sanity-checks the initial config for join existing cluster
  95. // case and returns an error for things that should never happen.
  96. func (c *ServerConfig) VerifyJoinExisting() error {
  97. // The member has announced its peer urls to the cluster before starting; no need to
  98. // set the configuration again.
  99. if err := c.hasLocalMember(); err != nil {
  100. return err
  101. }
  102. if checkDuplicateURL(c.InitialPeerURLsMap) {
  103. return fmt.Errorf("initial cluster %s has duplicate url", c.InitialPeerURLsMap)
  104. }
  105. if c.DiscoveryURL != "" {
  106. return fmt.Errorf("discovery URL should not be set when joining existing initial cluster")
  107. }
  108. return nil
  109. }
  110. // hasLocalMember checks that the cluster at least contains the local server.
  111. func (c *ServerConfig) hasLocalMember() error {
  112. if urls := c.InitialPeerURLsMap[c.Name]; urls == nil {
  113. return fmt.Errorf("couldn't find local name %q in the initial cluster configuration", c.Name)
  114. }
  115. return nil
  116. }
  117. // advertiseMatchesCluster confirms peer URLs match those in the cluster peer list.
  118. func (c *ServerConfig) advertiseMatchesCluster() error {
  119. urls, apurls := c.InitialPeerURLsMap[c.Name], c.PeerURLs.StringSlice()
  120. urls.Sort()
  121. sort.Strings(apurls)
  122. ctx, cancel := context.WithTimeout(context.TODO(), 30*time.Second)
  123. defer cancel()
  124. ok, err := netutil.URLStringsEqual(ctx, apurls, urls.StringSlice())
  125. if ok {
  126. return nil
  127. }
  128. initMap, apMap := make(map[string]struct{}), make(map[string]struct{})
  129. for _, url := range c.PeerURLs {
  130. apMap[url.String()] = struct{}{}
  131. }
  132. for _, url := range c.InitialPeerURLsMap[c.Name] {
  133. initMap[url.String()] = struct{}{}
  134. }
  135. missing := []string{}
  136. for url := range initMap {
  137. if _, ok := apMap[url]; !ok {
  138. missing = append(missing, url)
  139. }
  140. }
  141. if len(missing) > 0 {
  142. for i := range missing {
  143. missing[i] = c.Name + "=" + missing[i]
  144. }
  145. mstr := strings.Join(missing, ",")
  146. apStr := strings.Join(apurls, ",")
  147. return fmt.Errorf("--initial-cluster has %s but missing from --initial-advertise-peer-urls=%s (%v)", mstr, apStr, err)
  148. }
  149. for url := range apMap {
  150. if _, ok := initMap[url]; !ok {
  151. missing = append(missing, url)
  152. }
  153. }
  154. if len(missing) > 0 {
  155. mstr := strings.Join(missing, ",")
  156. umap := types.URLsMap(map[string]types.URLs{c.Name: c.PeerURLs})
  157. return fmt.Errorf("--initial-advertise-peer-urls has %s but missing from --initial-cluster=%s", mstr, umap.String())
  158. }
  159. // resolved URLs from "--initial-advertise-peer-urls" and "--initial-cluster" did not match or failed
  160. apStr := strings.Join(apurls, ",")
  161. umap := types.URLsMap(map[string]types.URLs{c.Name: c.PeerURLs})
  162. return fmt.Errorf("failed to resolve %s to match --initial-cluster=%s (%v)", apStr, umap.String(), err)
  163. }
  164. func (c *ServerConfig) MemberDir() string { return filepath.Join(c.DataDir, "member") }
  165. func (c *ServerConfig) WALDir() string {
  166. if c.DedicatedWALDir != "" {
  167. return c.DedicatedWALDir
  168. }
  169. return filepath.Join(c.MemberDir(), "wal")
  170. }
  171. func (c *ServerConfig) SnapDir() string { return filepath.Join(c.MemberDir(), "snap") }
  172. func (c *ServerConfig) ShouldDiscover() bool { return c.DiscoveryURL != "" }
  173. // ReqTimeout returns timeout for request to finish.
  174. func (c *ServerConfig) ReqTimeout() time.Duration {
  175. // 5s for queue waiting, computation and disk IO delay
  176. // + 2 * election timeout for possible leader election
  177. return 5*time.Second + 2*time.Duration(c.ElectionTicks*int(c.TickMs))*time.Millisecond
  178. }
  179. func (c *ServerConfig) electionTimeout() time.Duration {
  180. return time.Duration(c.ElectionTicks*int(c.TickMs)) * time.Millisecond
  181. }
  182. func (c *ServerConfig) peerDialTimeout() time.Duration {
  183. // 1s for queue wait and election timeout
  184. return time.Second + time.Duration(c.ElectionTicks*int(c.TickMs))*time.Millisecond
  185. }
  186. func (c *ServerConfig) PrintWithInitial() { c.print(true) }
  187. func (c *ServerConfig) Print() { c.print(false) }
  188. func (c *ServerConfig) print(initial bool) {
  189. // TODO: remove this after dropping "capnslog"
  190. if c.Logger == nil {
  191. plog.Infof("name = %s", c.Name)
  192. if c.ForceNewCluster {
  193. plog.Infof("force new cluster")
  194. }
  195. plog.Infof("data dir = %s", c.DataDir)
  196. plog.Infof("member dir = %s", c.MemberDir())
  197. if c.DedicatedWALDir != "" {
  198. plog.Infof("dedicated WAL dir = %s", c.DedicatedWALDir)
  199. }
  200. plog.Infof("heartbeat = %dms", c.TickMs)
  201. plog.Infof("election = %dms", c.ElectionTicks*int(c.TickMs))
  202. plog.Infof("snapshot count = %d", c.SnapCount)
  203. if len(c.DiscoveryURL) != 0 {
  204. plog.Infof("discovery URL= %s", c.DiscoveryURL)
  205. if len(c.DiscoveryProxy) != 0 {
  206. plog.Infof("discovery proxy = %s", c.DiscoveryProxy)
  207. }
  208. }
  209. plog.Infof("advertise client URLs = %s", c.ClientURLs)
  210. if initial {
  211. plog.Infof("initial advertise peer URLs = %s", c.PeerURLs)
  212. plog.Infof("initial cluster = %s", c.InitialPeerURLsMap)
  213. }
  214. } else {
  215. state := "new"
  216. if !c.NewCluster {
  217. state = "existing"
  218. }
  219. c.Logger.Info(
  220. "server configuration",
  221. zap.String("name", c.Name),
  222. zap.String("data-dir", c.DataDir),
  223. zap.String("member-dir", c.MemberDir()),
  224. zap.String("dedicated-wal-dir", c.DedicatedWALDir),
  225. zap.Bool("force-new-cluster", c.ForceNewCluster),
  226. zap.Uint("heartbeat-tick-ms", c.TickMs),
  227. zap.String("heartbeat-interval", fmt.Sprintf("%v", time.Duration(c.TickMs)*time.Millisecond)),
  228. zap.Int("election-tick-ms", c.ElectionTicks),
  229. zap.String("election-timeout", fmt.Sprintf("%v", time.Duration(c.ElectionTicks*int(c.TickMs))*time.Millisecond)),
  230. zap.Uint64("snapshot-count", c.SnapCount),
  231. zap.Strings("advertise-client-urls", c.getACURLs()),
  232. zap.Strings("initial-advertise-peer-urls", c.getAPURLs()),
  233. zap.Bool("initial", initial),
  234. zap.String("initial-cluster", c.InitialPeerURLsMap.String()),
  235. zap.String("initial-cluster-state", state),
  236. zap.String("initial-cluster-token", c.InitialClusterToken),
  237. zap.Bool("pre-vote", c.PreVote),
  238. zap.Bool("initial-corrupt-check", c.InitialCorruptCheck),
  239. zap.Duration("corrupt-check-time", c.CorruptCheckTime),
  240. zap.String("discovery-url", c.DiscoveryURL),
  241. zap.String("discovery-proxy", c.DiscoveryProxy),
  242. )
  243. }
  244. }
  245. func checkDuplicateURL(urlsmap types.URLsMap) bool {
  246. um := make(map[string]bool)
  247. for _, urls := range urlsmap {
  248. for _, url := range urls {
  249. u := url.String()
  250. if um[u] {
  251. return true
  252. }
  253. um[u] = true
  254. }
  255. }
  256. return false
  257. }
  258. func (c *ServerConfig) bootstrapTimeout() time.Duration {
  259. if c.BootstrapTimeout != 0 {
  260. return c.BootstrapTimeout
  261. }
  262. return time.Second
  263. }
  264. func (c *ServerConfig) backendPath() string { return filepath.Join(c.SnapDir(), "db") }
  265. func (c *ServerConfig) getAPURLs() (ss []string) {
  266. ss = make([]string, len(c.PeerURLs))
  267. for i := range c.PeerURLs {
  268. ss[i] = c.PeerURLs[i].String()
  269. }
  270. return ss
  271. }
  272. func (c *ServerConfig) getACURLs() (ss []string) {
  273. ss = make([]string, len(c.ClientURLs))
  274. for i := range c.ClientURLs {
  275. ss[i] = c.ClientURLs[i].String()
  276. }
  277. return ss
  278. }