raft.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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. "sort"
  19. "sync"
  20. "sync/atomic"
  21. "time"
  22. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  23. "github.com/coreos/etcd/etcdserver/membership"
  24. "github.com/coreos/etcd/pkg/contention"
  25. "github.com/coreos/etcd/pkg/pbutil"
  26. "github.com/coreos/etcd/pkg/types"
  27. "github.com/coreos/etcd/raft"
  28. "github.com/coreos/etcd/raft/raftpb"
  29. "github.com/coreos/etcd/rafthttp"
  30. "github.com/coreos/etcd/wal"
  31. "github.com/coreos/etcd/wal/walpb"
  32. "github.com/coreos/pkg/capnslog"
  33. )
  34. const (
  35. // Number of entries for slow follower to catch-up after compacting
  36. // the raft storage entries.
  37. // We expect the follower has a millisecond level latency with the leader.
  38. // The max throughput is around 10K. Keep a 5K entries is enough for helping
  39. // follower to catch up.
  40. numberOfCatchUpEntries = 5000
  41. // The max throughput of etcd will not exceed 100MB/s (100K * 1KB value).
  42. // Assuming the RTT is around 10ms, 1MB max size is large enough.
  43. maxSizePerMsg = 1 * 1024 * 1024
  44. // Never overflow the rafthttp buffer, which is 4096.
  45. // TODO: a better const?
  46. maxInflightMsgs = 4096 / 8
  47. )
  48. var (
  49. // protects raftStatus
  50. raftStatusMu sync.Mutex
  51. // indirection for expvar func interface
  52. // expvar panics when publishing duplicate name
  53. // expvar does not support remove a registered name
  54. // so only register a func that calls raftStatus
  55. // and change raftStatus as we need.
  56. raftStatus func() raft.Status
  57. )
  58. func init() {
  59. raft.SetLogger(capnslog.NewPackageLogger("github.com/coreos/etcd", "raft"))
  60. expvar.Publish("raft.status", expvar.Func(func() interface{} {
  61. raftStatusMu.Lock()
  62. defer raftStatusMu.Unlock()
  63. return raftStatus()
  64. }))
  65. }
  66. type RaftTimer interface {
  67. Index() uint64
  68. Term() uint64
  69. }
  70. // apply contains entries, snapshot to be applied. Once
  71. // an apply is consumed, the entries will be persisted to
  72. // to raft storage concurrently; the application must read
  73. // raftDone before assuming the raft messages are stable.
  74. type apply struct {
  75. entries []raftpb.Entry
  76. snapshot raftpb.Snapshot
  77. raftDone <-chan struct{} // rx {} after raft has persisted messages
  78. }
  79. type raftNode struct {
  80. // Cache of the latest raft index and raft term the server has seen.
  81. // These three unit64 fields must be the first elements to keep 64-bit
  82. // alignment for atomic access to the fields.
  83. index uint64
  84. term uint64
  85. lead uint64
  86. mu sync.Mutex
  87. // last lead elected time
  88. lt time.Time
  89. raft.Node
  90. // a chan to send out apply
  91. applyc chan apply
  92. // a chan to send out readState
  93. readStateC chan raft.ReadState
  94. // TODO: remove the etcdserver related logic from raftNode
  95. // TODO: add a state machine interface to apply the commit entries
  96. // and do snapshot/recover
  97. s *EtcdServer
  98. // utility
  99. ticker <-chan time.Time
  100. raftStorage *raft.MemoryStorage
  101. storage Storage
  102. // transport specifies the transport to send and receive msgs to members.
  103. // Sending messages MUST NOT block. It is okay to drop messages, since
  104. // clients should timeout and reissue their messages.
  105. // If transport is nil, server will panic.
  106. transport rafthttp.Transporter
  107. td *contention.TimeoutDetector
  108. stopped chan struct{}
  109. done chan struct{}
  110. }
  111. // start prepares and starts raftNode in a new goroutine. It is no longer safe
  112. // to modify the fields after it has been started.
  113. // TODO: Ideally raftNode should get rid of the passed in server structure.
  114. func (r *raftNode) start(s *EtcdServer) {
  115. r.s = s
  116. r.applyc = make(chan apply)
  117. r.stopped = make(chan struct{})
  118. r.done = make(chan struct{})
  119. heartbeat := 200 * time.Millisecond
  120. if s.Cfg != nil {
  121. heartbeat = time.Duration(s.Cfg.TickMs) * time.Millisecond
  122. }
  123. // set up contention detectors for raft heartbeat message.
  124. // expect to send a heartbeat within 2 heartbeat intervals.
  125. r.td = contention.NewTimeoutDetector(2 * heartbeat)
  126. go func() {
  127. var syncC <-chan time.Time
  128. defer r.onStop()
  129. islead := false
  130. for {
  131. select {
  132. case <-r.ticker:
  133. r.Tick()
  134. case rd := <-r.Ready():
  135. if rd.SoftState != nil {
  136. if lead := atomic.LoadUint64(&r.lead); rd.SoftState.Lead != raft.None && lead != rd.SoftState.Lead {
  137. r.mu.Lock()
  138. r.lt = time.Now()
  139. r.mu.Unlock()
  140. leaderChanges.Inc()
  141. }
  142. if rd.SoftState.Lead == raft.None {
  143. hasLeader.Set(0)
  144. } else {
  145. hasLeader.Set(1)
  146. }
  147. atomic.StoreUint64(&r.lead, rd.SoftState.Lead)
  148. if rd.RaftState == raft.StateLeader {
  149. islead = true
  150. syncC = r.s.SyncTicker
  151. // TODO: remove the nil checking
  152. // current test utility does not provide the stats
  153. if r.s.stats != nil {
  154. r.s.stats.BecomeLeader()
  155. }
  156. if r.s.compactor != nil {
  157. r.s.compactor.Resume()
  158. }
  159. r.td.Reset()
  160. } else {
  161. islead = false
  162. if r.s.lessor != nil {
  163. r.s.lessor.Demote()
  164. }
  165. if r.s.compactor != nil {
  166. r.s.compactor.Pause()
  167. }
  168. syncC = nil
  169. }
  170. }
  171. if len(rd.ReadStates) != 0 {
  172. select {
  173. case r.readStateC <- rd.ReadStates[len(rd.ReadStates)-1]:
  174. case <-r.stopped:
  175. return
  176. }
  177. }
  178. raftDone := make(chan struct{}, 1)
  179. ap := apply{
  180. entries: rd.CommittedEntries,
  181. snapshot: rd.Snapshot,
  182. raftDone: raftDone,
  183. }
  184. select {
  185. case r.applyc <- ap:
  186. case <-r.stopped:
  187. return
  188. }
  189. // the leader can write to its disk in parallel with replicating to the followers and them
  190. // writing to their disks.
  191. // For more details, check raft thesis 10.2.1
  192. if islead {
  193. // gofail: var raftBeforeLeaderSend struct{}
  194. r.s.send(rd.Messages)
  195. }
  196. // gofail: var raftBeforeSave struct{}
  197. if err := r.storage.Save(rd.HardState, rd.Entries); err != nil {
  198. plog.Fatalf("raft save state and entries error: %v", err)
  199. }
  200. if !raft.IsEmptyHardState(rd.HardState) {
  201. proposalsCommitted.Set(float64(rd.HardState.Commit))
  202. }
  203. // gofail: var raftAfterSave struct{}
  204. if !raft.IsEmptySnap(rd.Snapshot) {
  205. // gofail: var raftBeforeSaveSnap struct{}
  206. if err := r.storage.SaveSnap(rd.Snapshot); err != nil {
  207. plog.Fatalf("raft save snapshot error: %v", err)
  208. }
  209. // gofail: var raftAfterSaveSnap struct{}
  210. r.raftStorage.ApplySnapshot(rd.Snapshot)
  211. plog.Infof("raft applied incoming snapshot at index %d", rd.Snapshot.Metadata.Index)
  212. // gofail: var raftAfterApplySnap struct{}
  213. }
  214. r.raftStorage.Append(rd.Entries)
  215. if !islead {
  216. // gofail: var raftBeforeFollowerSend struct{}
  217. r.s.send(rd.Messages)
  218. }
  219. raftDone <- struct{}{}
  220. r.Advance()
  221. case <-syncC:
  222. r.s.sync(r.s.Cfg.ReqTimeout())
  223. case <-r.stopped:
  224. return
  225. }
  226. }
  227. }()
  228. }
  229. func (r *raftNode) apply() chan apply {
  230. return r.applyc
  231. }
  232. func (r *raftNode) leadElectedTime() time.Time {
  233. r.mu.Lock()
  234. defer r.mu.Unlock()
  235. return r.lt
  236. }
  237. func (r *raftNode) stop() {
  238. r.stopped <- struct{}{}
  239. <-r.done
  240. }
  241. func (r *raftNode) onStop() {
  242. r.Stop()
  243. r.transport.Stop()
  244. if err := r.storage.Close(); err != nil {
  245. plog.Panicf("raft close storage error: %v", err)
  246. }
  247. close(r.done)
  248. }
  249. // for testing
  250. func (r *raftNode) pauseSending() {
  251. p := r.transport.(rafthttp.Pausable)
  252. p.Pause()
  253. }
  254. func (r *raftNode) resumeSending() {
  255. p := r.transport.(rafthttp.Pausable)
  256. p.Resume()
  257. }
  258. // advanceTicksForElection advances ticks to the node for fast election.
  259. // This reduces the time to wait for first leader election if bootstrapping the whole
  260. // cluster, while leaving at least 1 heartbeat for possible existing leader
  261. // to contact it.
  262. func advanceTicksForElection(n raft.Node, electionTicks int) {
  263. for i := 0; i < electionTicks-1; i++ {
  264. n.Tick()
  265. }
  266. }
  267. func startNode(cfg *ServerConfig, cl *membership.RaftCluster, ids []types.ID) (id types.ID, n raft.Node, s *raft.MemoryStorage, w *wal.WAL) {
  268. var err error
  269. member := cl.MemberByName(cfg.Name)
  270. metadata := pbutil.MustMarshal(
  271. &pb.Metadata{
  272. NodeID: uint64(member.ID),
  273. ClusterID: uint64(cl.ID()),
  274. },
  275. )
  276. if w, err = wal.Create(cfg.WALDir(), metadata); err != nil {
  277. plog.Fatalf("create wal error: %v", err)
  278. }
  279. peers := make([]raft.Peer, len(ids))
  280. for i, id := range ids {
  281. ctx, err := json.Marshal((*cl).Member(id))
  282. if err != nil {
  283. plog.Panicf("marshal member should never fail: %v", err)
  284. }
  285. peers[i] = raft.Peer{ID: uint64(id), Context: ctx}
  286. }
  287. id = member.ID
  288. plog.Infof("starting member %s in cluster %s", id, cl.ID())
  289. s = raft.NewMemoryStorage()
  290. c := &raft.Config{
  291. ID: uint64(id),
  292. ElectionTick: cfg.ElectionTicks,
  293. HeartbeatTick: 1,
  294. Storage: s,
  295. MaxSizePerMsg: maxSizePerMsg,
  296. MaxInflightMsgs: maxInflightMsgs,
  297. CheckQuorum: true,
  298. }
  299. n = raft.StartNode(c, peers)
  300. raftStatusMu.Lock()
  301. raftStatus = n.Status
  302. raftStatusMu.Unlock()
  303. advanceTicksForElection(n, c.ElectionTick)
  304. return
  305. }
  306. func restartNode(cfg *ServerConfig, snapshot *raftpb.Snapshot) (types.ID, *membership.RaftCluster, raft.Node, *raft.MemoryStorage, *wal.WAL) {
  307. var walsnap walpb.Snapshot
  308. if snapshot != nil {
  309. walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
  310. }
  311. w, id, cid, st, ents := readWAL(cfg.WALDir(), walsnap)
  312. plog.Infof("restarting member %s in cluster %s at commit index %d", id, cid, st.Commit)
  313. cl := membership.NewCluster("")
  314. cl.SetID(cid)
  315. s := raft.NewMemoryStorage()
  316. if snapshot != nil {
  317. s.ApplySnapshot(*snapshot)
  318. }
  319. s.SetHardState(st)
  320. s.Append(ents)
  321. c := &raft.Config{
  322. ID: uint64(id),
  323. ElectionTick: cfg.ElectionTicks,
  324. HeartbeatTick: 1,
  325. Storage: s,
  326. MaxSizePerMsg: maxSizePerMsg,
  327. MaxInflightMsgs: maxInflightMsgs,
  328. CheckQuorum: true,
  329. }
  330. n := raft.RestartNode(c)
  331. raftStatusMu.Lock()
  332. raftStatus = n.Status
  333. raftStatusMu.Unlock()
  334. advanceTicksForElection(n, c.ElectionTick)
  335. return id, cl, n, s, w
  336. }
  337. func restartAsStandaloneNode(cfg *ServerConfig, snapshot *raftpb.Snapshot) (types.ID, *membership.RaftCluster, raft.Node, *raft.MemoryStorage, *wal.WAL) {
  338. var walsnap walpb.Snapshot
  339. if snapshot != nil {
  340. walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
  341. }
  342. w, id, cid, st, ents := readWAL(cfg.WALDir(), walsnap)
  343. // discard the previously uncommitted entries
  344. for i, ent := range ents {
  345. if ent.Index > st.Commit {
  346. plog.Infof("discarding %d uncommitted WAL entries ", len(ents)-i)
  347. ents = ents[:i]
  348. break
  349. }
  350. }
  351. // force append the configuration change entries
  352. toAppEnts := createConfigChangeEnts(getIDs(snapshot, ents), uint64(id), st.Term, st.Commit)
  353. ents = append(ents, toAppEnts...)
  354. // force commit newly appended entries
  355. err := w.Save(raftpb.HardState{}, toAppEnts)
  356. if err != nil {
  357. plog.Fatalf("%v", err)
  358. }
  359. if len(ents) != 0 {
  360. st.Commit = ents[len(ents)-1].Index
  361. }
  362. plog.Printf("forcing restart of member %s in cluster %s at commit index %d", id, cid, st.Commit)
  363. cl := membership.NewCluster("")
  364. cl.SetID(cid)
  365. s := raft.NewMemoryStorage()
  366. if snapshot != nil {
  367. s.ApplySnapshot(*snapshot)
  368. }
  369. s.SetHardState(st)
  370. s.Append(ents)
  371. c := &raft.Config{
  372. ID: uint64(id),
  373. ElectionTick: cfg.ElectionTicks,
  374. HeartbeatTick: 1,
  375. Storage: s,
  376. MaxSizePerMsg: maxSizePerMsg,
  377. MaxInflightMsgs: maxInflightMsgs,
  378. }
  379. n := raft.RestartNode(c)
  380. raftStatus = n.Status
  381. return id, cl, n, s, w
  382. }
  383. // getIDs returns an ordered set of IDs included in the given snapshot and
  384. // the entries. The given snapshot/entries can contain two kinds of
  385. // ID-related entry:
  386. // - ConfChangeAddNode, in which case the contained ID will be added into the set.
  387. // - ConfChangeRemoveNode, in which case the contained ID will be removed from the set.
  388. func getIDs(snap *raftpb.Snapshot, ents []raftpb.Entry) []uint64 {
  389. ids := make(map[uint64]bool)
  390. if snap != nil {
  391. for _, id := range snap.Metadata.ConfState.Nodes {
  392. ids[id] = true
  393. }
  394. }
  395. for _, e := range ents {
  396. if e.Type != raftpb.EntryConfChange {
  397. continue
  398. }
  399. var cc raftpb.ConfChange
  400. pbutil.MustUnmarshal(&cc, e.Data)
  401. switch cc.Type {
  402. case raftpb.ConfChangeAddNode:
  403. ids[cc.NodeID] = true
  404. case raftpb.ConfChangeRemoveNode:
  405. delete(ids, cc.NodeID)
  406. case raftpb.ConfChangeUpdateNode:
  407. // do nothing
  408. default:
  409. plog.Panicf("ConfChange Type should be either ConfChangeAddNode or ConfChangeRemoveNode!")
  410. }
  411. }
  412. sids := make(types.Uint64Slice, 0, len(ids))
  413. for id := range ids {
  414. sids = append(sids, id)
  415. }
  416. sort.Sort(sids)
  417. return []uint64(sids)
  418. }
  419. // createConfigChangeEnts creates a series of Raft entries (i.e.
  420. // EntryConfChange) to remove the set of given IDs from the cluster. The ID
  421. // `self` is _not_ removed, even if present in the set.
  422. // If `self` is not inside the given ids, it creates a Raft entry to add a
  423. // default member with the given `self`.
  424. func createConfigChangeEnts(ids []uint64, self uint64, term, index uint64) []raftpb.Entry {
  425. ents := make([]raftpb.Entry, 0)
  426. next := index + 1
  427. found := false
  428. for _, id := range ids {
  429. if id == self {
  430. found = true
  431. continue
  432. }
  433. cc := &raftpb.ConfChange{
  434. Type: raftpb.ConfChangeRemoveNode,
  435. NodeID: id,
  436. }
  437. e := raftpb.Entry{
  438. Type: raftpb.EntryConfChange,
  439. Data: pbutil.MustMarshal(cc),
  440. Term: term,
  441. Index: next,
  442. }
  443. ents = append(ents, e)
  444. next++
  445. }
  446. if !found {
  447. m := membership.Member{
  448. ID: types.ID(self),
  449. RaftAttributes: membership.RaftAttributes{PeerURLs: []string{"http://localhost:2380"}},
  450. }
  451. ctx, err := json.Marshal(m)
  452. if err != nil {
  453. plog.Panicf("marshal member should never fail: %v", err)
  454. }
  455. cc := &raftpb.ConfChange{
  456. Type: raftpb.ConfChangeAddNode,
  457. NodeID: self,
  458. Context: ctx,
  459. }
  460. e := raftpb.Entry{
  461. Type: raftpb.EntryConfChange,
  462. Data: pbutil.MustMarshal(cc),
  463. Term: term,
  464. Index: next,
  465. }
  466. ents = append(ents, e)
  467. }
  468. return ents
  469. }