server.go 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326
  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. "encoding/json"
  17. "expvar"
  18. "fmt"
  19. "math/rand"
  20. "net/http"
  21. "os"
  22. "path"
  23. "regexp"
  24. "sync"
  25. "sync/atomic"
  26. "time"
  27. "github.com/coreos/etcd/alarm"
  28. "github.com/coreos/etcd/auth"
  29. "github.com/coreos/etcd/compactor"
  30. "github.com/coreos/etcd/discovery"
  31. "github.com/coreos/etcd/etcdserver/api/v2http/httptypes"
  32. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  33. "github.com/coreos/etcd/etcdserver/membership"
  34. "github.com/coreos/etcd/etcdserver/stats"
  35. "github.com/coreos/etcd/lease"
  36. "github.com/coreos/etcd/mvcc"
  37. "github.com/coreos/etcd/mvcc/backend"
  38. "github.com/coreos/etcd/pkg/fileutil"
  39. "github.com/coreos/etcd/pkg/idutil"
  40. "github.com/coreos/etcd/pkg/pbutil"
  41. "github.com/coreos/etcd/pkg/runtime"
  42. "github.com/coreos/etcd/pkg/schedule"
  43. "github.com/coreos/etcd/pkg/types"
  44. "github.com/coreos/etcd/pkg/wait"
  45. "github.com/coreos/etcd/raft"
  46. "github.com/coreos/etcd/raft/raftpb"
  47. "github.com/coreos/etcd/rafthttp"
  48. "github.com/coreos/etcd/snap"
  49. "github.com/coreos/etcd/store"
  50. "github.com/coreos/etcd/version"
  51. "github.com/coreos/etcd/wal"
  52. "github.com/coreos/go-semver/semver"
  53. "github.com/coreos/pkg/capnslog"
  54. "golang.org/x/net/context"
  55. )
  56. const (
  57. // owner can make/remove files inside the directory
  58. privateDirMode = 0700
  59. DefaultSnapCount = 10000
  60. StoreClusterPrefix = "/0"
  61. StoreKeysPrefix = "/1"
  62. purgeFileInterval = 30 * time.Second
  63. // monitorVersionInterval should be smaller than the timeout
  64. // on the connection. Or we will not be able to reuse the connection
  65. // (since it will timeout).
  66. monitorVersionInterval = rafthttp.ConnWriteTimeout - time.Second
  67. databaseFilename = "db"
  68. // max number of in-flight snapshot messages etcdserver allows to have
  69. // This number is more than enough for most clusters with 5 machines.
  70. maxInFlightMsgSnap = 16
  71. releaseDelayAfterSnapshot = 30 * time.Second
  72. )
  73. var (
  74. plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "etcdserver")
  75. storeMemberAttributeRegexp = regexp.MustCompile(path.Join(membership.StoreMembersPrefix, "[[:xdigit:]]{1,16}", "attributes"))
  76. )
  77. func init() {
  78. rand.Seed(time.Now().UnixNano())
  79. expvar.Publish(
  80. "file_descriptor_limit",
  81. expvar.Func(
  82. func() interface{} {
  83. n, _ := runtime.FDLimit()
  84. return n
  85. },
  86. ),
  87. )
  88. }
  89. type Response struct {
  90. Event *store.Event
  91. Watcher store.Watcher
  92. err error
  93. }
  94. type Server interface {
  95. // Start performs any initialization of the Server necessary for it to
  96. // begin serving requests. It must be called before Do or Process.
  97. // Start must be non-blocking; any long-running server functionality
  98. // should be implemented in goroutines.
  99. Start()
  100. // Stop terminates the Server and performs any necessary finalization.
  101. // Do and Process cannot be called after Stop has been invoked.
  102. Stop()
  103. // ID returns the ID of the Server.
  104. ID() types.ID
  105. // Leader returns the ID of the leader Server.
  106. Leader() types.ID
  107. // Do takes a request and attempts to fulfill it, returning a Response.
  108. Do(ctx context.Context, r pb.Request) (Response, error)
  109. // Process takes a raft message and applies it to the server's raft state
  110. // machine, respecting any timeout of the given context.
  111. Process(ctx context.Context, m raftpb.Message) error
  112. // AddMember attempts to add a member into the cluster. It will return
  113. // ErrIDRemoved if member ID is removed from the cluster, or return
  114. // ErrIDExists if member ID exists in the cluster.
  115. AddMember(ctx context.Context, memb membership.Member) error
  116. // RemoveMember attempts to remove a member from the cluster. It will
  117. // return ErrIDRemoved if member ID is removed from the cluster, or return
  118. // ErrIDNotFound if member ID is not in the cluster.
  119. RemoveMember(ctx context.Context, id uint64) error
  120. // UpdateMember attempts to update an existing member in the cluster. It will
  121. // return ErrIDNotFound if the member ID does not exist.
  122. UpdateMember(ctx context.Context, updateMemb membership.Member) error
  123. // ClusterVersion is the cluster-wide minimum major.minor version.
  124. // Cluster version is set to the min version that an etcd member is
  125. // compatible with when first bootstrap.
  126. //
  127. // ClusterVersion is nil until the cluster is bootstrapped (has a quorum).
  128. //
  129. // During a rolling upgrades, the ClusterVersion will be updated
  130. // automatically after a sync. (5 second by default)
  131. //
  132. // The API/raft component can utilize ClusterVersion to determine if
  133. // it can accept a client request or a raft RPC.
  134. // NOTE: ClusterVersion might be nil when etcd 2.1 works with etcd 2.0 and
  135. // the leader is etcd 2.0. etcd 2.0 leader will not update clusterVersion since
  136. // this feature is introduced post 2.0.
  137. ClusterVersion() *semver.Version
  138. }
  139. // EtcdServer is the production implementation of the Server interface
  140. type EtcdServer struct {
  141. // r and inflightSnapshots must be the first elements to keep 64-bit alignment for atomic
  142. // access to fields
  143. // count the number of inflight snapshots.
  144. // MUST use atomic operation to access this field.
  145. inflightSnapshots int64
  146. Cfg *ServerConfig
  147. readych chan struct{}
  148. r raftNode
  149. snapCount uint64
  150. w wait.Wait
  151. stop chan struct{}
  152. done chan struct{}
  153. errorc chan error
  154. id types.ID
  155. attributes membership.Attributes
  156. cluster *membership.RaftCluster
  157. store store.Store
  158. applyV2 ApplierV2
  159. applyV3 applierV3
  160. kv mvcc.ConsistentWatchableKV
  161. lessor lease.Lessor
  162. bemu sync.Mutex
  163. be backend.Backend
  164. authStore auth.AuthStore
  165. alarmStore *alarm.AlarmStore
  166. stats *stats.ServerStats
  167. lstats *stats.LeaderStats
  168. SyncTicker <-chan time.Time
  169. // compactor is used to auto-compact the KV.
  170. compactor *compactor.Periodic
  171. // consistent index used to hold the offset of current executing entry
  172. // It is initialized to 0 before executing any entry.
  173. consistIndex consistentIndex
  174. // peerRt used to send requests (version, lease) to peers.
  175. peerRt http.RoundTripper
  176. reqIDGen *idutil.Generator
  177. // forceVersionC is used to force the version monitor loop
  178. // to detect the cluster version immediately.
  179. forceVersionC chan struct{}
  180. msgSnapC chan raftpb.Message
  181. // wg is used to wait for the go routines that depends on the server state
  182. // to exit when stopping the server.
  183. wg sync.WaitGroup
  184. appliedIndex uint64
  185. }
  186. // NewServer creates a new EtcdServer from the supplied configuration. The
  187. // configuration is considered static for the lifetime of the EtcdServer.
  188. func NewServer(cfg *ServerConfig) (srv *EtcdServer, err error) {
  189. st := store.New(StoreClusterPrefix, StoreKeysPrefix)
  190. var (
  191. w *wal.WAL
  192. n raft.Node
  193. s *raft.MemoryStorage
  194. id types.ID
  195. cl *membership.RaftCluster
  196. )
  197. if terr := fileutil.TouchDirAll(cfg.DataDir); terr != nil {
  198. return nil, fmt.Errorf("cannot access data directory: %v", terr)
  199. }
  200. // Run the migrations.
  201. dataVer, err := version.DetectDataDir(cfg.DataDir)
  202. if err != nil {
  203. return nil, err
  204. }
  205. if err = upgradeDataDir(cfg.DataDir, cfg.Name, dataVer); err != nil {
  206. return nil, err
  207. }
  208. haveWAL := wal.Exist(cfg.WALDir())
  209. if err = os.MkdirAll(cfg.SnapDir(), privateDirMode); err != nil && !os.IsExist(err) {
  210. plog.Fatalf("create snapshot directory error: %v", err)
  211. }
  212. ss := snap.New(cfg.SnapDir())
  213. be := backend.NewDefaultBackend(path.Join(cfg.SnapDir(), databaseFilename))
  214. defer func() {
  215. if err != nil {
  216. be.Close()
  217. }
  218. }()
  219. prt, err := rafthttp.NewRoundTripper(cfg.PeerTLSInfo, cfg.peerDialTimeout())
  220. if err != nil {
  221. return nil, err
  222. }
  223. var remotes []*membership.Member
  224. switch {
  225. case !haveWAL && !cfg.NewCluster:
  226. if err = cfg.VerifyJoinExisting(); err != nil {
  227. return nil, err
  228. }
  229. cl, err = membership.NewClusterFromURLsMap(cfg.InitialClusterToken, cfg.InitialPeerURLsMap)
  230. if err != nil {
  231. return nil, err
  232. }
  233. existingCluster, gerr := GetClusterFromRemotePeers(getRemotePeerURLs(cl, cfg.Name), prt)
  234. if gerr != nil {
  235. return nil, fmt.Errorf("cannot fetch cluster info from peer urls: %v", gerr)
  236. }
  237. if err = membership.ValidateClusterAndAssignIDs(cl, existingCluster); err != nil {
  238. return nil, fmt.Errorf("error validating peerURLs %s: %v", existingCluster, err)
  239. }
  240. if !isCompatibleWithCluster(cl, cl.MemberByName(cfg.Name).ID, prt) {
  241. return nil, fmt.Errorf("incompatible with current running cluster")
  242. }
  243. remotes = existingCluster.Members()
  244. cl.SetID(existingCluster.ID())
  245. cl.SetStore(st)
  246. cl.SetBackend(be)
  247. cfg.Print()
  248. id, n, s, w = startNode(cfg, cl, nil)
  249. case !haveWAL && cfg.NewCluster:
  250. if err = cfg.VerifyBootstrap(); err != nil {
  251. return nil, err
  252. }
  253. cl, err = membership.NewClusterFromURLsMap(cfg.InitialClusterToken, cfg.InitialPeerURLsMap)
  254. if err != nil {
  255. return nil, err
  256. }
  257. m := cl.MemberByName(cfg.Name)
  258. if isMemberBootstrapped(cl, cfg.Name, prt, cfg.bootstrapTimeout()) {
  259. return nil, fmt.Errorf("member %s has already been bootstrapped", m.ID)
  260. }
  261. if cfg.ShouldDiscover() {
  262. var str string
  263. str, err = discovery.JoinCluster(cfg.DiscoveryURL, cfg.DiscoveryProxy, m.ID, cfg.InitialPeerURLsMap.String())
  264. if err != nil {
  265. return nil, &DiscoveryError{Op: "join", Err: err}
  266. }
  267. var urlsmap types.URLsMap
  268. urlsmap, err = types.NewURLsMap(str)
  269. if err != nil {
  270. return nil, err
  271. }
  272. if checkDuplicateURL(urlsmap) {
  273. return nil, fmt.Errorf("discovery cluster %s has duplicate url", urlsmap)
  274. }
  275. if cl, err = membership.NewClusterFromURLsMap(cfg.InitialClusterToken, urlsmap); err != nil {
  276. return nil, err
  277. }
  278. }
  279. cl.SetStore(st)
  280. cl.SetBackend(be)
  281. cfg.PrintWithInitial()
  282. id, n, s, w = startNode(cfg, cl, cl.MemberIDs())
  283. case haveWAL:
  284. if err = fileutil.IsDirWriteable(cfg.MemberDir()); err != nil {
  285. return nil, fmt.Errorf("cannot write to member directory: %v", err)
  286. }
  287. if err = fileutil.IsDirWriteable(cfg.WALDir()); err != nil {
  288. return nil, fmt.Errorf("cannot write to WAL directory: %v", err)
  289. }
  290. if cfg.ShouldDiscover() {
  291. plog.Warningf("discovery token ignored since a cluster has already been initialized. Valid log found at %q", cfg.WALDir())
  292. }
  293. var snapshot *raftpb.Snapshot
  294. snapshot, err = ss.Load()
  295. if err != nil && err != snap.ErrNoSnapshot {
  296. return nil, err
  297. }
  298. if snapshot != nil {
  299. if err = st.Recovery(snapshot.Data); err != nil {
  300. plog.Panicf("recovered store from snapshot error: %v", err)
  301. }
  302. plog.Infof("recovered store from snapshot at index %d", snapshot.Metadata.Index)
  303. }
  304. cfg.Print()
  305. if !cfg.ForceNewCluster {
  306. id, cl, n, s, w = restartNode(cfg, snapshot)
  307. } else {
  308. id, cl, n, s, w = restartAsStandaloneNode(cfg, snapshot)
  309. }
  310. cl.SetStore(st)
  311. cl.SetBackend(be)
  312. cl.Recover()
  313. default:
  314. return nil, fmt.Errorf("unsupported bootstrap config")
  315. }
  316. if terr := fileutil.TouchDirAll(cfg.MemberDir()); terr != nil {
  317. return nil, fmt.Errorf("cannot access member directory: %v", terr)
  318. }
  319. sstats := &stats.ServerStats{
  320. Name: cfg.Name,
  321. ID: id.String(),
  322. }
  323. sstats.Initialize()
  324. lstats := stats.NewLeaderStats(id.String())
  325. srv = &EtcdServer{
  326. readych: make(chan struct{}),
  327. Cfg: cfg,
  328. snapCount: cfg.SnapCount,
  329. errorc: make(chan error, 1),
  330. store: st,
  331. r: raftNode{
  332. Node: n,
  333. ticker: time.Tick(time.Duration(cfg.TickMs) * time.Millisecond),
  334. raftStorage: s,
  335. storage: NewStorage(w, ss),
  336. },
  337. id: id,
  338. attributes: membership.Attributes{Name: cfg.Name, ClientURLs: cfg.ClientURLs.StringSlice()},
  339. cluster: cl,
  340. stats: sstats,
  341. lstats: lstats,
  342. SyncTicker: time.Tick(500 * time.Millisecond),
  343. peerRt: prt,
  344. reqIDGen: idutil.NewGenerator(uint16(id), time.Now()),
  345. forceVersionC: make(chan struct{}),
  346. msgSnapC: make(chan raftpb.Message, maxInFlightMsgSnap),
  347. }
  348. srv.applyV2 = &applierV2store{store: srv.store, cluster: srv.cluster}
  349. srv.be = be
  350. srv.lessor = lease.NewLessor(srv.be)
  351. srv.kv = mvcc.New(srv.be, srv.lessor, &srv.consistIndex)
  352. srv.consistIndex.setConsistentIndex(srv.kv.ConsistentIndex())
  353. srv.authStore = auth.NewAuthStore(srv.be)
  354. if h := cfg.AutoCompactionRetention; h != 0 {
  355. srv.compactor = compactor.NewPeriodic(h, srv.kv, srv)
  356. srv.compactor.Run()
  357. }
  358. if err = srv.restoreAlarms(); err != nil {
  359. return nil, err
  360. }
  361. // TODO: move transport initialization near the definition of remote
  362. tr := &rafthttp.Transport{
  363. TLSInfo: cfg.PeerTLSInfo,
  364. DialTimeout: cfg.peerDialTimeout(),
  365. ID: id,
  366. URLs: cfg.PeerURLs,
  367. ClusterID: cl.ID(),
  368. Raft: srv,
  369. Snapshotter: ss,
  370. ServerStats: sstats,
  371. LeaderStats: lstats,
  372. ErrorC: srv.errorc,
  373. }
  374. if err = tr.Start(); err != nil {
  375. return nil, err
  376. }
  377. // add all remotes into transport
  378. for _, m := range remotes {
  379. if m.ID != id {
  380. tr.AddRemote(m.ID, m.PeerURLs)
  381. }
  382. }
  383. for _, m := range cl.Members() {
  384. if m.ID != id {
  385. tr.AddPeer(m.ID, m.PeerURLs)
  386. }
  387. }
  388. srv.r.transport = tr
  389. return srv, nil
  390. }
  391. // Start prepares and starts server in a new goroutine. It is no longer safe to
  392. // modify a server's fields after it has been sent to Start.
  393. // It also starts a goroutine to publish its server information.
  394. func (s *EtcdServer) Start() {
  395. s.start()
  396. go s.publish(s.Cfg.ReqTimeout())
  397. go s.purgeFile()
  398. go monitorFileDescriptor(s.done)
  399. go s.monitorVersions()
  400. }
  401. // start prepares and starts server in a new goroutine. It is no longer safe to
  402. // modify a server's fields after it has been sent to Start.
  403. // This function is just used for testing.
  404. func (s *EtcdServer) start() {
  405. if s.snapCount == 0 {
  406. plog.Infof("set snapshot count to default %d", DefaultSnapCount)
  407. s.snapCount = DefaultSnapCount
  408. }
  409. s.w = wait.New()
  410. s.done = make(chan struct{})
  411. s.stop = make(chan struct{})
  412. if s.ClusterVersion() != nil {
  413. plog.Infof("starting server... [version: %v, cluster version: %v]", version.Version, version.Cluster(s.ClusterVersion().String()))
  414. } else {
  415. plog.Infof("starting server... [version: %v, cluster version: to_be_decided]", version.Version)
  416. }
  417. // TODO: if this is an empty log, writes all peer infos
  418. // into the first entry
  419. go s.run()
  420. }
  421. func (s *EtcdServer) purgeFile() {
  422. var serrc, werrc <-chan error
  423. if s.Cfg.MaxSnapFiles > 0 {
  424. serrc = fileutil.PurgeFile(s.Cfg.SnapDir(), "snap", s.Cfg.MaxSnapFiles, purgeFileInterval, s.done)
  425. }
  426. if s.Cfg.MaxWALFiles > 0 {
  427. werrc = fileutil.PurgeFile(s.Cfg.WALDir(), "wal", s.Cfg.MaxWALFiles, purgeFileInterval, s.done)
  428. }
  429. select {
  430. case e := <-werrc:
  431. plog.Fatalf("failed to purge wal file %v", e)
  432. case e := <-serrc:
  433. plog.Fatalf("failed to purge snap file %v", e)
  434. case <-s.done:
  435. return
  436. }
  437. }
  438. func (s *EtcdServer) ID() types.ID { return s.id }
  439. func (s *EtcdServer) Cluster() *membership.RaftCluster { return s.cluster }
  440. func (s *EtcdServer) RaftHandler() http.Handler { return s.r.transport.Handler() }
  441. func (s *EtcdServer) Lessor() lease.Lessor { return s.lessor }
  442. func (s *EtcdServer) Process(ctx context.Context, m raftpb.Message) error {
  443. if s.cluster.IsIDRemoved(types.ID(m.From)) {
  444. plog.Warningf("reject message from removed member %s", types.ID(m.From).String())
  445. return httptypes.NewHTTPError(http.StatusForbidden, "cannot process message from removed member")
  446. }
  447. if m.Type == raftpb.MsgApp {
  448. s.stats.RecvAppendReq(types.ID(m.From).String(), m.Size())
  449. }
  450. return s.r.Step(ctx, m)
  451. }
  452. func (s *EtcdServer) IsIDRemoved(id uint64) bool { return s.cluster.IsIDRemoved(types.ID(id)) }
  453. func (s *EtcdServer) ReportUnreachable(id uint64) { s.r.ReportUnreachable(id) }
  454. // ReportSnapshot reports snapshot sent status to the raft state machine,
  455. // and clears the used snapshot from the snapshot store.
  456. func (s *EtcdServer) ReportSnapshot(id uint64, status raft.SnapshotStatus) {
  457. s.r.ReportSnapshot(id, status)
  458. }
  459. type etcdProgress struct {
  460. confState raftpb.ConfState
  461. snapi uint64
  462. appliedi uint64
  463. }
  464. func (s *EtcdServer) run() {
  465. snap, err := s.r.raftStorage.Snapshot()
  466. if err != nil {
  467. plog.Panicf("get snapshot from raft storage error: %v", err)
  468. }
  469. s.r.start(s)
  470. // asynchronously accept apply packets, dispatch progress in-order
  471. sched := schedule.NewFIFOScheduler()
  472. ep := etcdProgress{
  473. confState: snap.Metadata.ConfState,
  474. snapi: snap.Metadata.Index,
  475. appliedi: snap.Metadata.Index,
  476. }
  477. defer func() {
  478. sched.Stop()
  479. // wait for snapshots before closing raft so wal stays open
  480. s.wg.Wait()
  481. // must stop raft after scheduler-- etcdserver can leak rafthttp pipelines
  482. // by adding a peer after raft stops the transport
  483. s.r.stop()
  484. // kv, lessor and backend can be nil if running without v3 enabled
  485. // or running unit tests.
  486. if s.lessor != nil {
  487. s.lessor.Stop()
  488. }
  489. if s.kv != nil {
  490. s.kv.Close()
  491. }
  492. if s.be != nil {
  493. s.be.Close()
  494. }
  495. if s.compactor != nil {
  496. s.compactor.Stop()
  497. }
  498. close(s.done)
  499. }()
  500. var expiredLeaseC <-chan []*lease.Lease
  501. if s.lessor != nil {
  502. expiredLeaseC = s.lessor.ExpiredLeasesC()
  503. }
  504. for {
  505. select {
  506. case ap := <-s.r.apply():
  507. f := func(context.Context) { s.applyAll(&ep, &ap) }
  508. sched.Schedule(f)
  509. case leases := <-expiredLeaseC:
  510. go func() {
  511. for _, l := range leases {
  512. s.LeaseRevoke(context.TODO(), &pb.LeaseRevokeRequest{ID: int64(l.ID)})
  513. }
  514. }()
  515. case err := <-s.errorc:
  516. plog.Errorf("%s", err)
  517. plog.Infof("the data-dir used by this member must be removed.")
  518. return
  519. case <-s.stop:
  520. return
  521. }
  522. }
  523. }
  524. func (s *EtcdServer) applyAll(ep *etcdProgress, apply *apply) {
  525. s.applySnapshot(ep, apply)
  526. s.applyEntries(ep, apply)
  527. // wait for the raft routine to finish the disk writes before triggering a
  528. // snapshot. or applied index might be greater than the last index in raft
  529. // storage, since the raft routine might be slower than apply routine.
  530. <-apply.raftDone
  531. s.triggerSnapshot(ep)
  532. select {
  533. // snapshot requested via send()
  534. case m := <-s.msgSnapC:
  535. merged := s.createMergedSnapshotMessage(m, ep.appliedi, ep.confState)
  536. s.sendMergedSnap(merged)
  537. default:
  538. }
  539. }
  540. func (s *EtcdServer) applySnapshot(ep *etcdProgress, apply *apply) {
  541. if raft.IsEmptySnap(apply.snapshot) {
  542. return
  543. }
  544. plog.Infof("applying snapshot at index %d...", ep.snapi)
  545. defer plog.Infof("finished applying incoming snapshot at index %d", ep.snapi)
  546. if apply.snapshot.Metadata.Index <= ep.appliedi {
  547. plog.Panicf("snapshot index [%d] should > appliedi[%d] + 1",
  548. apply.snapshot.Metadata.Index, ep.appliedi)
  549. }
  550. snapfn, err := s.r.storage.DBFilePath(apply.snapshot.Metadata.Index)
  551. if err != nil {
  552. plog.Panicf("get database snapshot file path error: %v", err)
  553. }
  554. fn := path.Join(s.Cfg.SnapDir(), databaseFilename)
  555. if err := os.Rename(snapfn, fn); err != nil {
  556. plog.Panicf("rename snapshot file error: %v", err)
  557. }
  558. newbe := backend.NewDefaultBackend(fn)
  559. plog.Info("restoring mvcc store...")
  560. if err := s.kv.Restore(newbe); err != nil {
  561. plog.Panicf("restore KV error: %v", err)
  562. }
  563. s.consistIndex.setConsistentIndex(s.kv.ConsistentIndex())
  564. plog.Info("finished restoring mvcc store")
  565. // Closing old backend might block until all the txns
  566. // on the backend are finished.
  567. // We do not want to wait on closing the old backend.
  568. s.bemu.Lock()
  569. oldbe := s.be
  570. go func() {
  571. plog.Info("closing old backend...")
  572. defer plog.Info("finished closing old backend")
  573. if err := oldbe.Close(); err != nil {
  574. plog.Panicf("close backend error: %v", err)
  575. }
  576. }()
  577. s.be = newbe
  578. s.bemu.Unlock()
  579. if s.lessor != nil {
  580. plog.Info("recovering lessor...")
  581. s.lessor.Recover(newbe, s.kv)
  582. plog.Info("finished recovering lessor")
  583. }
  584. plog.Info("recovering alarms...")
  585. if err := s.restoreAlarms(); err != nil {
  586. plog.Panicf("restore alarms error: %v", err)
  587. }
  588. plog.Info("finished recovering alarms")
  589. if s.authStore != nil {
  590. plog.Info("recovering auth store...")
  591. s.authStore.Recover(newbe)
  592. plog.Info("finished recovering auth store")
  593. }
  594. plog.Info("recovering store v2...")
  595. if err := s.store.Recovery(apply.snapshot.Data); err != nil {
  596. plog.Panicf("recovery store error: %v", err)
  597. }
  598. plog.Info("finished recovering store v2")
  599. s.cluster.SetBackend(s.be)
  600. plog.Info("recovering cluster configuration...")
  601. s.cluster.Recover()
  602. plog.Info("finished recovering cluster configuration")
  603. plog.Info("removing old peers from network...")
  604. // recover raft transport
  605. s.r.transport.RemoveAllPeers()
  606. plog.Info("finished removing old peers from network")
  607. plog.Info("adding peers from new cluster configuration into network...")
  608. for _, m := range s.cluster.Members() {
  609. if m.ID == s.ID() {
  610. continue
  611. }
  612. s.r.transport.AddPeer(m.ID, m.PeerURLs)
  613. }
  614. plog.Info("finished adding peers from new cluster configuration into network...")
  615. ep.appliedi = apply.snapshot.Metadata.Index
  616. ep.snapi = ep.appliedi
  617. ep.confState = apply.snapshot.Metadata.ConfState
  618. }
  619. func (s *EtcdServer) applyEntries(ep *etcdProgress, apply *apply) {
  620. if len(apply.entries) == 0 {
  621. return
  622. }
  623. firsti := apply.entries[0].Index
  624. if firsti > ep.appliedi+1 {
  625. plog.Panicf("first index of committed entry[%d] should <= appliedi[%d] + 1", firsti, ep.appliedi)
  626. }
  627. var ents []raftpb.Entry
  628. if ep.appliedi+1-firsti < uint64(len(apply.entries)) {
  629. ents = apply.entries[ep.appliedi+1-firsti:]
  630. }
  631. if len(ents) == 0 {
  632. return
  633. }
  634. var shouldstop bool
  635. if ep.appliedi, shouldstop = s.apply(ents, &ep.confState); shouldstop {
  636. go s.stopWithDelay(10*100*time.Millisecond, fmt.Errorf("the member has been permanently removed from the cluster"))
  637. }
  638. }
  639. func (s *EtcdServer) triggerSnapshot(ep *etcdProgress) {
  640. if ep.appliedi-ep.snapi <= s.snapCount {
  641. return
  642. }
  643. // When sending a snapshot, etcd will pause compaction.
  644. // After receives a snapshot, the slow follower needs to get all the entries right after
  645. // the snapshot sent to catch up. If we do not pause compaction, the log entries right after
  646. // the snapshot sent might already be compacted. It happens when the snapshot takes long time
  647. // to send and save. Pausing compaction avoids triggering a snapshot sending cycle.
  648. if atomic.LoadInt64(&s.inflightSnapshots) != 0 {
  649. return
  650. }
  651. plog.Infof("start to snapshot (applied: %d, lastsnap: %d)", ep.appliedi, ep.snapi)
  652. s.snapshot(ep.appliedi, ep.confState)
  653. ep.snapi = ep.appliedi
  654. }
  655. // Stop stops the server gracefully, and shuts down the running goroutine.
  656. // Stop should be called after a Start(s), otherwise it will block forever.
  657. func (s *EtcdServer) Stop() {
  658. select {
  659. case s.stop <- struct{}{}:
  660. case <-s.done:
  661. return
  662. }
  663. <-s.done
  664. }
  665. // ReadyNotify returns a channel that will be closed when the server
  666. // is ready to serve client requests
  667. func (s *EtcdServer) ReadyNotify() <-chan struct{} { return s.readych }
  668. func (s *EtcdServer) stopWithDelay(d time.Duration, err error) {
  669. select {
  670. case <-time.After(d):
  671. case <-s.done:
  672. }
  673. select {
  674. case s.errorc <- err:
  675. default:
  676. }
  677. }
  678. // StopNotify returns a channel that receives a empty struct
  679. // when the server is stopped.
  680. func (s *EtcdServer) StopNotify() <-chan struct{} { return s.done }
  681. func (s *EtcdServer) SelfStats() []byte { return s.stats.JSON() }
  682. func (s *EtcdServer) LeaderStats() []byte {
  683. lead := atomic.LoadUint64(&s.r.lead)
  684. if lead != uint64(s.id) {
  685. return nil
  686. }
  687. return s.lstats.JSON()
  688. }
  689. func (s *EtcdServer) StoreStats() []byte { return s.store.JsonStats() }
  690. func (s *EtcdServer) AddMember(ctx context.Context, memb membership.Member) error {
  691. if s.Cfg.StrictReconfigCheck && !s.cluster.IsReadyToAddNewMember() {
  692. // If s.cfg.StrictReconfigCheck is false, it means the option --strict-reconfig-check isn't passed to etcd.
  693. // In such a case adding a new member is allowed unconditionally
  694. return ErrNotEnoughStartedMembers
  695. }
  696. // TODO: move Member to protobuf type
  697. b, err := json.Marshal(memb)
  698. if err != nil {
  699. return err
  700. }
  701. cc := raftpb.ConfChange{
  702. Type: raftpb.ConfChangeAddNode,
  703. NodeID: uint64(memb.ID),
  704. Context: b,
  705. }
  706. return s.configure(ctx, cc)
  707. }
  708. func (s *EtcdServer) RemoveMember(ctx context.Context, id uint64) error {
  709. if s.Cfg.StrictReconfigCheck && !s.cluster.IsReadyToRemoveMember(id) {
  710. // If s.cfg.StrictReconfigCheck is false, it means the option --strict-reconfig-check isn't passed to etcd.
  711. // In such a case removing a member is allowed unconditionally
  712. return ErrNotEnoughStartedMembers
  713. }
  714. cc := raftpb.ConfChange{
  715. Type: raftpb.ConfChangeRemoveNode,
  716. NodeID: id,
  717. }
  718. return s.configure(ctx, cc)
  719. }
  720. func (s *EtcdServer) UpdateMember(ctx context.Context, memb membership.Member) error {
  721. b, err := json.Marshal(memb)
  722. if err != nil {
  723. return err
  724. }
  725. cc := raftpb.ConfChange{
  726. Type: raftpb.ConfChangeUpdateNode,
  727. NodeID: uint64(memb.ID),
  728. Context: b,
  729. }
  730. return s.configure(ctx, cc)
  731. }
  732. // Implement the RaftTimer interface
  733. func (s *EtcdServer) Index() uint64 { return atomic.LoadUint64(&s.r.index) }
  734. func (s *EtcdServer) Term() uint64 { return atomic.LoadUint64(&s.r.term) }
  735. // Lead is only for testing purposes.
  736. // TODO: add Raft server interface to expose raft related info:
  737. // Index, Term, Lead, Committed, Applied, LastIndex, etc.
  738. func (s *EtcdServer) Lead() uint64 { return atomic.LoadUint64(&s.r.lead) }
  739. func (s *EtcdServer) Leader() types.ID { return types.ID(s.Lead()) }
  740. func (s *EtcdServer) IsPprofEnabled() bool { return s.Cfg.EnablePprof }
  741. // configure sends a configuration change through consensus and
  742. // then waits for it to be applied to the server. It
  743. // will block until the change is performed or there is an error.
  744. func (s *EtcdServer) configure(ctx context.Context, cc raftpb.ConfChange) error {
  745. cc.ID = s.reqIDGen.Next()
  746. ch := s.w.Register(cc.ID)
  747. start := time.Now()
  748. if err := s.r.ProposeConfChange(ctx, cc); err != nil {
  749. s.w.Trigger(cc.ID, nil)
  750. return err
  751. }
  752. select {
  753. case x := <-ch:
  754. if err, ok := x.(error); ok {
  755. return err
  756. }
  757. if x != nil {
  758. plog.Panicf("return type should always be error")
  759. }
  760. return nil
  761. case <-ctx.Done():
  762. s.w.Trigger(cc.ID, nil) // GC wait
  763. return s.parseProposeCtxErr(ctx.Err(), start)
  764. case <-s.done:
  765. return ErrStopped
  766. }
  767. }
  768. // sync proposes a SYNC request and is non-blocking.
  769. // This makes no guarantee that the request will be proposed or performed.
  770. // The request will be canceled after the given timeout.
  771. func (s *EtcdServer) sync(timeout time.Duration) {
  772. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  773. req := pb.Request{
  774. Method: "SYNC",
  775. ID: s.reqIDGen.Next(),
  776. Time: time.Now().UnixNano(),
  777. }
  778. data := pbutil.MustMarshal(&req)
  779. // There is no promise that node has leader when do SYNC request,
  780. // so it uses goroutine to propose.
  781. go func() {
  782. s.r.Propose(ctx, data)
  783. cancel()
  784. }()
  785. }
  786. // publish registers server information into the cluster. The information
  787. // is the JSON representation of this server's member struct, updated with the
  788. // static clientURLs of the server.
  789. // The function keeps attempting to register until it succeeds,
  790. // or its server is stopped.
  791. func (s *EtcdServer) publish(timeout time.Duration) {
  792. b, err := json.Marshal(s.attributes)
  793. if err != nil {
  794. plog.Panicf("json marshal error: %v", err)
  795. return
  796. }
  797. req := pb.Request{
  798. Method: "PUT",
  799. Path: membership.MemberAttributesStorePath(s.id),
  800. Val: string(b),
  801. }
  802. for {
  803. ctx, cancel := context.WithTimeout(context.Background(), timeout)
  804. _, err := s.Do(ctx, req)
  805. cancel()
  806. switch err {
  807. case nil:
  808. close(s.readych)
  809. plog.Infof("published %+v to cluster %s", s.attributes, s.cluster.ID())
  810. return
  811. case ErrStopped:
  812. plog.Infof("aborting publish because server is stopped")
  813. return
  814. default:
  815. plog.Errorf("publish error: %v", err)
  816. }
  817. }
  818. }
  819. // TODO: move this function into raft.go
  820. func (s *EtcdServer) send(ms []raftpb.Message) {
  821. sentAppResp := false
  822. for i := len(ms) - 1; i >= 0; i-- {
  823. if s.cluster.IsIDRemoved(types.ID(ms[i].To)) {
  824. ms[i].To = 0
  825. }
  826. if ms[i].Type == raftpb.MsgAppResp {
  827. if sentAppResp {
  828. ms[i].To = 0
  829. } else {
  830. sentAppResp = true
  831. }
  832. }
  833. if ms[i].Type == raftpb.MsgSnap {
  834. // There are two separate data store: the store for v2, and the KV for v3.
  835. // The msgSnap only contains the most recent snapshot of store without KV.
  836. // So we need to redirect the msgSnap to etcd server main loop for merging in the
  837. // current store snapshot and KV snapshot.
  838. select {
  839. case s.msgSnapC <- ms[i]:
  840. default:
  841. // drop msgSnap if the inflight chan if full.
  842. }
  843. ms[i].To = 0
  844. }
  845. if ms[i].Type == raftpb.MsgHeartbeat {
  846. ok, exceed := s.r.td.Observe(ms[i].To)
  847. if !ok {
  848. // TODO: limit request rate.
  849. plog.Warningf("failed to send out heartbeat on time (exceeded the %dms timeout for %v)", s.Cfg.TickMs, exceed)
  850. plog.Warningf("server is likely overloaded")
  851. }
  852. }
  853. }
  854. s.r.transport.Send(ms)
  855. }
  856. func (s *EtcdServer) sendMergedSnap(merged snap.Message) {
  857. atomic.AddInt64(&s.inflightSnapshots, 1)
  858. s.r.transport.SendSnapshot(merged)
  859. go func() {
  860. select {
  861. case ok := <-merged.CloseNotify():
  862. // delay releasing inflight snapshot for another 30 seconds to
  863. // block log compaction.
  864. // If the follower still fails to catch up, it is probably just too slow
  865. // to catch up. We cannot avoid the snapshot cycle anyway.
  866. if ok {
  867. select {
  868. case <-time.After(releaseDelayAfterSnapshot):
  869. case <-s.done:
  870. }
  871. }
  872. atomic.AddInt64(&s.inflightSnapshots, -1)
  873. case <-s.done:
  874. return
  875. }
  876. }()
  877. }
  878. // apply takes entries received from Raft (after it has been committed) and
  879. // applies them to the current state of the EtcdServer.
  880. // The given entries should not be empty.
  881. func (s *EtcdServer) apply(es []raftpb.Entry, confState *raftpb.ConfState) (uint64, bool) {
  882. var applied uint64
  883. var shouldstop bool
  884. for i := range es {
  885. e := es[i]
  886. switch e.Type {
  887. case raftpb.EntryNormal:
  888. s.applyEntryNormal(&e)
  889. case raftpb.EntryConfChange:
  890. var cc raftpb.ConfChange
  891. pbutil.MustUnmarshal(&cc, e.Data)
  892. removedSelf, err := s.applyConfChange(cc, confState)
  893. shouldstop = shouldstop || removedSelf
  894. s.w.Trigger(cc.ID, err)
  895. default:
  896. plog.Panicf("entry type should be either EntryNormal or EntryConfChange")
  897. }
  898. atomic.StoreUint64(&s.r.index, e.Index)
  899. atomic.StoreUint64(&s.r.term, e.Term)
  900. applied = e.Index
  901. }
  902. return applied, shouldstop
  903. }
  904. // applyEntryNormal apples an EntryNormal type raftpb request to the EtcdServer
  905. func (s *EtcdServer) applyEntryNormal(e *raftpb.Entry) {
  906. // raft state machine may generate noop entry when leader confirmation.
  907. // skip it in advance to avoid some potential bug in the future
  908. if len(e.Data) == 0 {
  909. select {
  910. case s.forceVersionC <- struct{}{}:
  911. default:
  912. }
  913. return
  914. }
  915. var raftReq pb.InternalRaftRequest
  916. if !pbutil.MaybeUnmarshal(&raftReq, e.Data) { // backward compatible
  917. var r pb.Request
  918. pbutil.MustUnmarshal(&r, e.Data)
  919. s.w.Trigger(r.ID, s.applyV2Request(&r))
  920. return
  921. }
  922. if raftReq.V2 != nil {
  923. req := raftReq.V2
  924. s.w.Trigger(req.ID, s.applyV2Request(req))
  925. return
  926. }
  927. // do not re-apply applied entries.
  928. if e.Index <= s.consistIndex.ConsistentIndex() {
  929. return
  930. }
  931. id := raftReq.ID
  932. if id == 0 {
  933. id = raftReq.Header.ID
  934. }
  935. // set the consistent index of current executing entry
  936. s.consistIndex.setConsistentIndex(e.Index)
  937. ar := s.applyV3Request(&raftReq)
  938. s.setAppliedIndex(e.Index)
  939. if ar.err != ErrNoSpace || len(s.alarmStore.Get(pb.AlarmType_NOSPACE)) > 0 {
  940. s.w.Trigger(id, ar)
  941. return
  942. }
  943. plog.Errorf("applying raft message exceeded backend quota")
  944. go func() {
  945. a := &pb.AlarmRequest{
  946. MemberID: uint64(s.ID()),
  947. Action: pb.AlarmRequest_ACTIVATE,
  948. Alarm: pb.AlarmType_NOSPACE,
  949. }
  950. r := pb.InternalRaftRequest{Alarm: a}
  951. s.processInternalRaftRequest(context.TODO(), r)
  952. s.w.Trigger(id, ar)
  953. }()
  954. }
  955. // applyConfChange applies a ConfChange to the server. It is only
  956. // invoked with a ConfChange that has already passed through Raft
  957. func (s *EtcdServer) applyConfChange(cc raftpb.ConfChange, confState *raftpb.ConfState) (bool, error) {
  958. if err := s.cluster.ValidateConfigurationChange(cc); err != nil {
  959. cc.NodeID = raft.None
  960. s.r.ApplyConfChange(cc)
  961. return false, err
  962. }
  963. *confState = *s.r.ApplyConfChange(cc)
  964. switch cc.Type {
  965. case raftpb.ConfChangeAddNode:
  966. m := new(membership.Member)
  967. if err := json.Unmarshal(cc.Context, m); err != nil {
  968. plog.Panicf("unmarshal member should never fail: %v", err)
  969. }
  970. if cc.NodeID != uint64(m.ID) {
  971. plog.Panicf("nodeID should always be equal to member ID")
  972. }
  973. s.cluster.AddMember(m)
  974. if m.ID != s.id {
  975. s.r.transport.AddPeer(m.ID, m.PeerURLs)
  976. }
  977. case raftpb.ConfChangeRemoveNode:
  978. id := types.ID(cc.NodeID)
  979. s.cluster.RemoveMember(id)
  980. if id == s.id {
  981. return true, nil
  982. }
  983. s.r.transport.RemovePeer(id)
  984. case raftpb.ConfChangeUpdateNode:
  985. m := new(membership.Member)
  986. if err := json.Unmarshal(cc.Context, m); err != nil {
  987. plog.Panicf("unmarshal member should never fail: %v", err)
  988. }
  989. if cc.NodeID != uint64(m.ID) {
  990. plog.Panicf("nodeID should always be equal to member ID")
  991. }
  992. s.cluster.UpdateRaftAttributes(m.ID, m.RaftAttributes)
  993. if m.ID != s.id {
  994. s.r.transport.UpdatePeer(m.ID, m.PeerURLs)
  995. }
  996. }
  997. return false, nil
  998. }
  999. // TODO: non-blocking snapshot
  1000. func (s *EtcdServer) snapshot(snapi uint64, confState raftpb.ConfState) {
  1001. clone := s.store.Clone()
  1002. s.wg.Add(1)
  1003. go func() {
  1004. defer s.wg.Done()
  1005. d, err := clone.SaveNoCopy()
  1006. // TODO: current store will never fail to do a snapshot
  1007. // what should we do if the store might fail?
  1008. if err != nil {
  1009. plog.Panicf("store save should never fail: %v", err)
  1010. }
  1011. snap, err := s.r.raftStorage.CreateSnapshot(snapi, &confState, d)
  1012. if err != nil {
  1013. // the snapshot was done asynchronously with the progress of raft.
  1014. // raft might have already got a newer snapshot.
  1015. if err == raft.ErrSnapOutOfDate {
  1016. return
  1017. }
  1018. plog.Panicf("unexpected create snapshot error %v", err)
  1019. }
  1020. // commit v3 storage because WAL file before snapshot index
  1021. // could be removed after SaveSnap.
  1022. s.KV().Commit()
  1023. // SaveSnap saves the snapshot and releases the locked wal files
  1024. // to the snapshot index.
  1025. if err = s.r.storage.SaveSnap(snap); err != nil {
  1026. plog.Fatalf("save snapshot error: %v", err)
  1027. }
  1028. plog.Infof("saved snapshot at index %d", snap.Metadata.Index)
  1029. // keep some in memory log entries for slow followers.
  1030. compacti := uint64(1)
  1031. if snapi > numberOfCatchUpEntries {
  1032. compacti = snapi - numberOfCatchUpEntries
  1033. }
  1034. err = s.r.raftStorage.Compact(compacti)
  1035. if err != nil {
  1036. // the compaction was done asynchronously with the progress of raft.
  1037. // raft log might already been compact.
  1038. if err == raft.ErrCompacted {
  1039. return
  1040. }
  1041. plog.Panicf("unexpected compaction error %v", err)
  1042. }
  1043. plog.Infof("compacted raft log at %d", compacti)
  1044. }()
  1045. }
  1046. func (s *EtcdServer) PauseSending() { s.r.pauseSending() }
  1047. func (s *EtcdServer) ResumeSending() { s.r.resumeSending() }
  1048. func (s *EtcdServer) ClusterVersion() *semver.Version {
  1049. if s.cluster == nil {
  1050. return nil
  1051. }
  1052. return s.cluster.Version()
  1053. }
  1054. // monitorVersions checks the member's version every monitorVersionInterval.
  1055. // It updates the cluster version if all members agrees on a higher one.
  1056. // It prints out log if there is a member with a higher version than the
  1057. // local version.
  1058. func (s *EtcdServer) monitorVersions() {
  1059. for {
  1060. select {
  1061. case <-s.forceVersionC:
  1062. case <-time.After(monitorVersionInterval):
  1063. case <-s.done:
  1064. return
  1065. }
  1066. if s.Leader() != s.ID() {
  1067. continue
  1068. }
  1069. v := decideClusterVersion(getVersions(s.cluster, s.id, s.peerRt))
  1070. if v != nil {
  1071. // only keep major.minor version for comparison
  1072. v = &semver.Version{
  1073. Major: v.Major,
  1074. Minor: v.Minor,
  1075. }
  1076. }
  1077. // if the current version is nil:
  1078. // 1. use the decided version if possible
  1079. // 2. or use the min cluster version
  1080. if s.cluster.Version() == nil {
  1081. if v != nil {
  1082. go s.updateClusterVersion(v.String())
  1083. } else {
  1084. go s.updateClusterVersion(version.MinClusterVersion)
  1085. }
  1086. continue
  1087. }
  1088. // update cluster version only if the decided version is greater than
  1089. // the current cluster version
  1090. if v != nil && s.cluster.Version().LessThan(*v) {
  1091. go s.updateClusterVersion(v.String())
  1092. }
  1093. }
  1094. }
  1095. func (s *EtcdServer) updateClusterVersion(ver string) {
  1096. if s.cluster.Version() == nil {
  1097. plog.Infof("setting up the initial cluster version to %s", version.Cluster(ver))
  1098. } else {
  1099. plog.Infof("updating the cluster version from %s to %s", version.Cluster(s.cluster.Version().String()), version.Cluster(ver))
  1100. }
  1101. req := pb.Request{
  1102. Method: "PUT",
  1103. Path: membership.StoreClusterVersionKey(),
  1104. Val: ver,
  1105. }
  1106. ctx, cancel := context.WithTimeout(context.Background(), s.Cfg.ReqTimeout())
  1107. _, err := s.Do(ctx, req)
  1108. cancel()
  1109. switch err {
  1110. case nil:
  1111. return
  1112. case ErrStopped:
  1113. plog.Infof("aborting update cluster version because server is stopped")
  1114. return
  1115. default:
  1116. plog.Errorf("error updating cluster version (%v)", err)
  1117. }
  1118. }
  1119. func (s *EtcdServer) parseProposeCtxErr(err error, start time.Time) error {
  1120. switch err {
  1121. case context.Canceled:
  1122. return ErrCanceled
  1123. case context.DeadlineExceeded:
  1124. curLeadElected := s.r.leadElectedTime()
  1125. prevLeadLost := curLeadElected.Add(-2 * time.Duration(s.Cfg.ElectionTicks) * time.Duration(s.Cfg.TickMs) * time.Millisecond)
  1126. if start.After(prevLeadLost) && start.Before(curLeadElected) {
  1127. return ErrTimeoutDueToLeaderFail
  1128. }
  1129. lead := types.ID(atomic.LoadUint64(&s.r.lead))
  1130. switch lead {
  1131. case types.ID(raft.None):
  1132. // TODO: return error to specify it happens because the cluster does not have leader now
  1133. case s.ID():
  1134. if !isConnectedToQuorumSince(s.r.transport, start, s.ID(), s.cluster.Members()) {
  1135. return ErrTimeoutDueToConnectionLost
  1136. }
  1137. default:
  1138. if !isConnectedSince(s.r.transport, start, lead) {
  1139. return ErrTimeoutDueToConnectionLost
  1140. }
  1141. }
  1142. return ErrTimeout
  1143. default:
  1144. return err
  1145. }
  1146. }
  1147. func (s *EtcdServer) KV() mvcc.ConsistentWatchableKV { return s.kv }
  1148. func (s *EtcdServer) Backend() backend.Backend {
  1149. s.bemu.Lock()
  1150. defer s.bemu.Unlock()
  1151. return s.be
  1152. }
  1153. func (s *EtcdServer) AuthStore() auth.AuthStore { return s.authStore }
  1154. func (s *EtcdServer) restoreAlarms() error {
  1155. s.applyV3 = newQuotaApplierV3(s, &applierV3backend{s})
  1156. as, err := alarm.NewAlarmStore(s)
  1157. if err != nil {
  1158. return err
  1159. }
  1160. s.alarmStore = as
  1161. if len(as.Get(pb.AlarmType_NOSPACE)) > 0 {
  1162. s.applyV3 = newApplierV3Capped(s.applyV3)
  1163. }
  1164. return nil
  1165. }
  1166. func (s *EtcdServer) getAppliedIndex() uint64 {
  1167. return atomic.LoadUint64(&s.appliedIndex)
  1168. }
  1169. func (s *EtcdServer) setAppliedIndex(v uint64) {
  1170. atomic.StoreUint64(&s.appliedIndex, v)
  1171. }