raft.go 17 KB

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