raft.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  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. AppliedIndex() uint64
  69. Term() uint64
  70. }
  71. // apply contains entries, snapshot to be applied. Once
  72. // an apply is consumed, the entries will be persisted to
  73. // to raft storage concurrently; the application must read
  74. // raftDone before assuming the raft messages are stable.
  75. type apply struct {
  76. entries []raftpb.Entry
  77. snapshot raftpb.Snapshot
  78. // notifyc synchronizes etcd server applies with the raft node
  79. notifyc chan struct{}
  80. }
  81. type raftNode struct {
  82. // Cache of the latest raft index and raft term the server has seen.
  83. // These three unit64 fields must be the first elements to keep 64-bit
  84. // alignment for atomic access to the fields.
  85. index uint64
  86. appliedindex uint64
  87. term uint64
  88. lead uint64
  89. tickMu *sync.Mutex
  90. raftNodeConfig
  91. // a chan to send/receive snapshot
  92. msgSnapC chan raftpb.Message
  93. // a chan to send out apply
  94. applyc chan apply
  95. // a chan to send out readState
  96. readStateC chan raft.ReadState
  97. // utility
  98. ticker *time.Ticker
  99. // contention detectors for raft heartbeat message
  100. td *contention.TimeoutDetector
  101. stopped chan struct{}
  102. done chan struct{}
  103. }
  104. type raftNodeConfig struct {
  105. // to check if msg receiver is removed from cluster
  106. isIDRemoved func(id uint64) bool
  107. raft.Node
  108. raftStorage *raft.MemoryStorage
  109. storage Storage
  110. heartbeat time.Duration // for logging
  111. // transport specifies the transport to send and receive msgs to members.
  112. // Sending messages MUST NOT block. It is okay to drop messages, since
  113. // clients should timeout and reissue their messages.
  114. // If transport is nil, server will panic.
  115. transport rafthttp.Transporter
  116. }
  117. func newRaftNode(cfg raftNodeConfig) *raftNode {
  118. r := &raftNode{
  119. tickMu: new(sync.Mutex),
  120. raftNodeConfig: cfg,
  121. // set up contention detectors for raft heartbeat message.
  122. // expect to send a heartbeat within 2 heartbeat intervals.
  123. td: contention.NewTimeoutDetector(2 * cfg.heartbeat),
  124. readStateC: make(chan raft.ReadState, 1),
  125. msgSnapC: make(chan raftpb.Message, maxInFlightMsgSnap),
  126. applyc: make(chan apply),
  127. stopped: make(chan struct{}),
  128. done: make(chan struct{}),
  129. }
  130. if r.heartbeat == 0 {
  131. r.ticker = &time.Ticker{}
  132. } else {
  133. r.ticker = time.NewTicker(r.heartbeat)
  134. }
  135. return r
  136. }
  137. // raft.Node does not have locks in Raft package
  138. func (r *raftNode) tick() {
  139. r.tickMu.Lock()
  140. r.Tick()
  141. r.tickMu.Unlock()
  142. }
  143. // start prepares and starts raftNode in a new goroutine. It is no longer safe
  144. // to modify the fields after it has been started.
  145. func (r *raftNode) start(rh *raftReadyHandler) {
  146. internalTimeout := time.Second
  147. go func() {
  148. defer r.onStop()
  149. islead := false
  150. for {
  151. select {
  152. case <-r.ticker.C:
  153. r.tick()
  154. case rd := <-r.Ready():
  155. if rd.SoftState != nil {
  156. newLeader := rd.SoftState.Lead != raft.None && atomic.LoadUint64(&r.lead) != rd.SoftState.Lead
  157. if newLeader {
  158. leaderChanges.Inc()
  159. }
  160. if rd.SoftState.Lead == raft.None {
  161. hasLeader.Set(0)
  162. } else {
  163. hasLeader.Set(1)
  164. }
  165. atomic.StoreUint64(&r.lead, rd.SoftState.Lead)
  166. islead = rd.RaftState == raft.StateLeader
  167. rh.updateLeadership(newLeader)
  168. r.td.Reset()
  169. }
  170. if len(rd.ReadStates) != 0 {
  171. select {
  172. case r.readStateC <- rd.ReadStates[len(rd.ReadStates)-1]:
  173. case <-time.After(internalTimeout):
  174. plog.Warningf("timed out sending read state")
  175. case <-r.stopped:
  176. return
  177. }
  178. }
  179. notifyc := make(chan struct{}, 1)
  180. ap := apply{
  181. entries: rd.CommittedEntries,
  182. snapshot: rd.Snapshot,
  183. notifyc: notifyc,
  184. }
  185. updateCommittedIndex(&ap, rh)
  186. select {
  187. case r.applyc <- ap:
  188. case <-r.stopped:
  189. return
  190. }
  191. // the leader can write to its disk in parallel with replicating to the followers and them
  192. // writing to their disks.
  193. // For more details, check raft thesis 10.2.1
  194. if islead {
  195. // gofail: var raftBeforeLeaderSend struct{}
  196. r.transport.Send(r.processMessages(rd.Messages))
  197. }
  198. // gofail: var raftBeforeSave struct{}
  199. if err := r.storage.Save(rd.HardState, rd.Entries); err != nil {
  200. plog.Fatalf("raft save state and entries error: %v", err)
  201. }
  202. if !raft.IsEmptyHardState(rd.HardState) {
  203. proposalsCommitted.Set(float64(rd.HardState.Commit))
  204. }
  205. // gofail: var raftAfterSave struct{}
  206. if !raft.IsEmptySnap(rd.Snapshot) {
  207. // gofail: var raftBeforeSaveSnap struct{}
  208. if err := r.storage.SaveSnap(rd.Snapshot); err != nil {
  209. plog.Fatalf("raft save snapshot error: %v", err)
  210. }
  211. // etcdserver now claim the snapshot has been persisted onto the disk
  212. notifyc <- struct{}{}
  213. // gofail: var raftAfterSaveSnap struct{}
  214. r.raftStorage.ApplySnapshot(rd.Snapshot)
  215. plog.Infof("raft applied incoming snapshot at index %d", rd.Snapshot.Metadata.Index)
  216. // gofail: var raftAfterApplySnap struct{}
  217. }
  218. r.raftStorage.Append(rd.Entries)
  219. if !islead {
  220. // finish processing incoming messages before we signal raftdone chan
  221. msgs := r.processMessages(rd.Messages)
  222. // now unblocks 'applyAll' that waits on Raft log disk writes before triggering snapshots
  223. notifyc <- struct{}{}
  224. // Candidate or follower needs to wait for all pending configuration
  225. // changes to be applied before sending messages.
  226. // Otherwise we might incorrectly count votes (e.g. votes from removed members).
  227. // Also slow machine's follower raft-layer could proceed to become the leader
  228. // on its own single-node cluster, before apply-layer applies the config change.
  229. // We simply wait for ALL pending entries to be applied for now.
  230. // We might improve this later on if it causes unnecessary long blocking issues.
  231. waitApply := false
  232. for _, ent := range rd.CommittedEntries {
  233. if ent.Type == raftpb.EntryConfChange {
  234. waitApply = true
  235. break
  236. }
  237. }
  238. if waitApply {
  239. // blocks until 'applyAll' calls 'applyWait.Trigger'
  240. // to be in sync with scheduled config-change job
  241. // (assume notifyc has cap of 1)
  242. select {
  243. case notifyc <- struct{}{}:
  244. case <-r.stopped:
  245. return
  246. }
  247. }
  248. // gofail: var raftBeforeFollowerSend struct{}
  249. r.transport.Send(msgs)
  250. } else {
  251. // leader already processed 'MsgSnap' and signaled
  252. notifyc <- struct{}{}
  253. }
  254. r.Advance()
  255. case <-r.stopped:
  256. return
  257. }
  258. }
  259. }()
  260. }
  261. func updateCommittedIndex(ap *apply, rh *raftReadyHandler) {
  262. var ci uint64
  263. if len(ap.entries) != 0 {
  264. ci = ap.entries[len(ap.entries)-1].Index
  265. }
  266. if ap.snapshot.Metadata.Index > ci {
  267. ci = ap.snapshot.Metadata.Index
  268. }
  269. if ci != 0 {
  270. rh.updateCommittedIndex(ci)
  271. }
  272. }
  273. func (r *raftNode) processMessages(ms []raftpb.Message) []raftpb.Message {
  274. sentAppResp := false
  275. for i := len(ms) - 1; i >= 0; i-- {
  276. if r.isIDRemoved(ms[i].To) {
  277. ms[i].To = 0
  278. }
  279. if ms[i].Type == raftpb.MsgAppResp {
  280. if sentAppResp {
  281. ms[i].To = 0
  282. } else {
  283. sentAppResp = true
  284. }
  285. }
  286. if ms[i].Type == raftpb.MsgSnap {
  287. // There are two separate data store: the store for v2, and the KV for v3.
  288. // The msgSnap only contains the most recent snapshot of store without KV.
  289. // So we need to redirect the msgSnap to etcd server main loop for merging in the
  290. // current store snapshot and KV snapshot.
  291. select {
  292. case r.msgSnapC <- ms[i]:
  293. default:
  294. // drop msgSnap if the inflight chan if full.
  295. }
  296. ms[i].To = 0
  297. }
  298. if ms[i].Type == raftpb.MsgHeartbeat {
  299. ok, exceed := r.td.Observe(ms[i].To)
  300. if !ok {
  301. // TODO: limit request rate.
  302. plog.Warningf("failed to send out heartbeat on time (exceeded the %v timeout for %v)", r.heartbeat, exceed)
  303. plog.Warningf("server is likely overloaded")
  304. }
  305. }
  306. }
  307. return ms
  308. }
  309. func (r *raftNode) apply() chan apply {
  310. return r.applyc
  311. }
  312. func (r *raftNode) stop() {
  313. r.stopped <- struct{}{}
  314. <-r.done
  315. }
  316. func (r *raftNode) onStop() {
  317. r.Stop()
  318. r.ticker.Stop()
  319. r.transport.Stop()
  320. if err := r.storage.Close(); err != nil {
  321. plog.Panicf("raft close storage error: %v", err)
  322. }
  323. close(r.done)
  324. }
  325. // for testing
  326. func (r *raftNode) pauseSending() {
  327. p := r.transport.(rafthttp.Pausable)
  328. p.Pause()
  329. }
  330. func (r *raftNode) resumeSending() {
  331. p := r.transport.(rafthttp.Pausable)
  332. p.Resume()
  333. }
  334. // advanceTicks advances ticks of Raft node.
  335. // This can be used for fast-forwarding election
  336. // ticks in multi data-center deployments, thus
  337. // speeding up election process.
  338. func (r *raftNode) advanceTicks(ticks int) {
  339. for i := 0; i < ticks; i++ {
  340. r.tick()
  341. }
  342. }
  343. func startNode(cfg ServerConfig, cl *membership.RaftCluster, ids []types.ID) (id types.ID, n raft.Node, s *raft.MemoryStorage, w *wal.WAL) {
  344. var err error
  345. member := cl.MemberByName(cfg.Name)
  346. metadata := pbutil.MustMarshal(
  347. &pb.Metadata{
  348. NodeID: uint64(member.ID),
  349. ClusterID: uint64(cl.ID()),
  350. },
  351. )
  352. if w, err = wal.Create(cfg.WALDir(), metadata); err != nil {
  353. plog.Fatalf("create wal error: %v", err)
  354. }
  355. peers := make([]raft.Peer, len(ids))
  356. for i, id := range ids {
  357. ctx, err := json.Marshal((*cl).Member(id))
  358. if err != nil {
  359. plog.Panicf("marshal member should never fail: %v", err)
  360. }
  361. peers[i] = raft.Peer{ID: uint64(id), Context: ctx}
  362. }
  363. id = member.ID
  364. plog.Infof("starting member %s in cluster %s", id, cl.ID())
  365. s = raft.NewMemoryStorage()
  366. c := &raft.Config{
  367. ID: uint64(id),
  368. ElectionTick: cfg.ElectionTicks,
  369. HeartbeatTick: 1,
  370. Storage: s,
  371. MaxSizePerMsg: maxSizePerMsg,
  372. MaxInflightMsgs: maxInflightMsgs,
  373. CheckQuorum: true,
  374. PreVote: cfg.PreVote,
  375. }
  376. n = raft.StartNode(c, peers)
  377. raftStatusMu.Lock()
  378. raftStatus = n.Status
  379. raftStatusMu.Unlock()
  380. return id, n, s, w
  381. }
  382. func restartNode(cfg ServerConfig, snapshot *raftpb.Snapshot) (types.ID, *membership.RaftCluster, raft.Node, *raft.MemoryStorage, *wal.WAL) {
  383. var walsnap walpb.Snapshot
  384. if snapshot != nil {
  385. walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
  386. }
  387. w, id, cid, st, ents := readWAL(cfg.WALDir(), walsnap)
  388. plog.Infof("restarting member %s in cluster %s at commit index %d", id, cid, st.Commit)
  389. cl := membership.NewCluster("")
  390. cl.SetID(cid)
  391. s := raft.NewMemoryStorage()
  392. if snapshot != nil {
  393. s.ApplySnapshot(*snapshot)
  394. }
  395. s.SetHardState(st)
  396. s.Append(ents)
  397. c := &raft.Config{
  398. ID: uint64(id),
  399. ElectionTick: cfg.ElectionTicks,
  400. HeartbeatTick: 1,
  401. Storage: s,
  402. MaxSizePerMsg: maxSizePerMsg,
  403. MaxInflightMsgs: maxInflightMsgs,
  404. CheckQuorum: true,
  405. PreVote: cfg.PreVote,
  406. }
  407. n := raft.RestartNode(c)
  408. raftStatusMu.Lock()
  409. raftStatus = n.Status
  410. raftStatusMu.Unlock()
  411. return id, cl, n, s, w
  412. }
  413. func restartAsStandaloneNode(cfg ServerConfig, snapshot *raftpb.Snapshot) (types.ID, *membership.RaftCluster, raft.Node, *raft.MemoryStorage, *wal.WAL) {
  414. var walsnap walpb.Snapshot
  415. if snapshot != nil {
  416. walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
  417. }
  418. w, id, cid, st, ents := readWAL(cfg.WALDir(), walsnap)
  419. // discard the previously uncommitted entries
  420. for i, ent := range ents {
  421. if ent.Index > st.Commit {
  422. plog.Infof("discarding %d uncommitted WAL entries ", len(ents)-i)
  423. ents = ents[:i]
  424. break
  425. }
  426. }
  427. // force append the configuration change entries
  428. toAppEnts := createConfigChangeEnts(getIDs(snapshot, ents), uint64(id), st.Term, st.Commit)
  429. ents = append(ents, toAppEnts...)
  430. // force commit newly appended entries
  431. err := w.Save(raftpb.HardState{}, toAppEnts)
  432. if err != nil {
  433. plog.Fatalf("%v", err)
  434. }
  435. if len(ents) != 0 {
  436. st.Commit = ents[len(ents)-1].Index
  437. }
  438. plog.Printf("forcing restart of member %s in cluster %s at commit index %d", id, cid, st.Commit)
  439. cl := membership.NewCluster("")
  440. cl.SetID(cid)
  441. s := raft.NewMemoryStorage()
  442. if snapshot != nil {
  443. s.ApplySnapshot(*snapshot)
  444. }
  445. s.SetHardState(st)
  446. s.Append(ents)
  447. c := &raft.Config{
  448. ID: uint64(id),
  449. ElectionTick: cfg.ElectionTicks,
  450. HeartbeatTick: 1,
  451. Storage: s,
  452. MaxSizePerMsg: maxSizePerMsg,
  453. MaxInflightMsgs: maxInflightMsgs,
  454. CheckQuorum: true,
  455. PreVote: cfg.PreVote,
  456. }
  457. n := raft.RestartNode(c)
  458. raftStatus = n.Status
  459. return id, cl, n, s, w
  460. }
  461. // getIDs returns an ordered set of IDs included in the given snapshot and
  462. // the entries. The given snapshot/entries can contain two kinds of
  463. // ID-related entry:
  464. // - ConfChangeAddNode, in which case the contained ID will be added into the set.
  465. // - ConfChangeRemoveNode, in which case the contained ID will be removed from the set.
  466. func getIDs(snap *raftpb.Snapshot, ents []raftpb.Entry) []uint64 {
  467. ids := make(map[uint64]bool)
  468. if snap != nil {
  469. for _, id := range snap.Metadata.ConfState.Nodes {
  470. ids[id] = true
  471. }
  472. }
  473. for _, e := range ents {
  474. if e.Type != raftpb.EntryConfChange {
  475. continue
  476. }
  477. var cc raftpb.ConfChange
  478. pbutil.MustUnmarshal(&cc, e.Data)
  479. switch cc.Type {
  480. case raftpb.ConfChangeAddNode:
  481. ids[cc.NodeID] = true
  482. case raftpb.ConfChangeRemoveNode:
  483. delete(ids, cc.NodeID)
  484. case raftpb.ConfChangeUpdateNode:
  485. // do nothing
  486. default:
  487. plog.Panicf("ConfChange Type should be either ConfChangeAddNode or ConfChangeRemoveNode!")
  488. }
  489. }
  490. sids := make(types.Uint64Slice, 0, len(ids))
  491. for id := range ids {
  492. sids = append(sids, id)
  493. }
  494. sort.Sort(sids)
  495. return []uint64(sids)
  496. }
  497. // createConfigChangeEnts creates a series of Raft entries (i.e.
  498. // EntryConfChange) to remove the set of given IDs from the cluster. The ID
  499. // `self` is _not_ removed, even if present in the set.
  500. // If `self` is not inside the given ids, it creates a Raft entry to add a
  501. // default member with the given `self`.
  502. func createConfigChangeEnts(ids []uint64, self uint64, term, index uint64) []raftpb.Entry {
  503. ents := make([]raftpb.Entry, 0)
  504. next := index + 1
  505. found := false
  506. for _, id := range ids {
  507. if id == self {
  508. found = true
  509. continue
  510. }
  511. cc := &raftpb.ConfChange{
  512. Type: raftpb.ConfChangeRemoveNode,
  513. NodeID: id,
  514. }
  515. e := raftpb.Entry{
  516. Type: raftpb.EntryConfChange,
  517. Data: pbutil.MustMarshal(cc),
  518. Term: term,
  519. Index: next,
  520. }
  521. ents = append(ents, e)
  522. next++
  523. }
  524. if !found {
  525. m := membership.Member{
  526. ID: types.ID(self),
  527. RaftAttributes: membership.RaftAttributes{PeerURLs: []string{"http://localhost:2380"}},
  528. }
  529. ctx, err := json.Marshal(m)
  530. if err != nil {
  531. plog.Panicf("marshal member should never fail: %v", err)
  532. }
  533. cc := &raftpb.ConfChange{
  534. Type: raftpb.ConfChangeAddNode,
  535. NodeID: self,
  536. Context: ctx,
  537. }
  538. e := raftpb.Entry{
  539. Type: raftpb.EntryConfChange,
  540. Data: pbutil.MustMarshal(cc),
  541. Term: term,
  542. Index: next,
  543. }
  544. ents = append(ents, e)
  545. }
  546. return ents
  547. }