raft.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  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. rh.updateLeadership(newLeader)
  166. r.td.Reset()
  167. }
  168. if len(rd.ReadStates) != 0 {
  169. select {
  170. case r.readStateC <- rd.ReadStates[len(rd.ReadStates)-1]:
  171. case <-time.After(internalTimeout):
  172. plog.Warningf("timed out sending read state")
  173. case <-r.stopped:
  174. return
  175. }
  176. }
  177. notifyc := make(chan struct{}, 1)
  178. ap := apply{
  179. entries: rd.CommittedEntries,
  180. snapshot: rd.Snapshot,
  181. notifyc: notifyc,
  182. }
  183. updateCommittedIndex(&ap, rh)
  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.transport.Send(r.processMessages(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. // etcdserver now claim the snapshot has been persisted onto the disk
  210. notifyc <- struct{}{}
  211. // gofail: var raftAfterSaveSnap struct{}
  212. r.raftStorage.ApplySnapshot(rd.Snapshot)
  213. plog.Infof("raft applied incoming snapshot at index %d", rd.Snapshot.Metadata.Index)
  214. // gofail: var raftAfterApplySnap struct{}
  215. }
  216. r.raftStorage.Append(rd.Entries)
  217. if !islead {
  218. // finish processing incoming messages before we signal raftdone chan
  219. msgs := r.processMessages(rd.Messages)
  220. // now unblocks 'applyAll' that waits on Raft log disk writes before triggering snapshots
  221. notifyc <- struct{}{}
  222. // Candidate or follower needs to wait for all pending configuration
  223. // changes to be applied before sending messages.
  224. // Otherwise we might incorrectly count votes (e.g. votes from removed members).
  225. // Also slow machine's follower raft-layer could proceed to become the leader
  226. // on its own single-node cluster, before apply-layer applies the config change.
  227. // We simply wait for ALL pending entries to be applied for now.
  228. // We might improve this later on if it causes unnecessary long blocking issues.
  229. waitApply := false
  230. for _, ent := range rd.CommittedEntries {
  231. if ent.Type == raftpb.EntryConfChange {
  232. waitApply = true
  233. break
  234. }
  235. }
  236. if waitApply {
  237. // blocks until 'applyAll' calls 'applyWait.Trigger'
  238. // to be in sync with scheduled config-change job
  239. // (assume notifyc has cap of 1)
  240. select {
  241. case notifyc <- struct{}{}:
  242. case <-r.stopped:
  243. return
  244. }
  245. }
  246. // gofail: var raftBeforeFollowerSend struct{}
  247. r.transport.Send(msgs)
  248. } else {
  249. // leader already processed 'MsgSnap' and signaled
  250. notifyc <- struct{}{}
  251. }
  252. r.Advance()
  253. case <-r.stopped:
  254. return
  255. }
  256. }
  257. }()
  258. }
  259. func updateCommittedIndex(ap *apply, rh *raftReadyHandler) {
  260. var ci uint64
  261. if len(ap.entries) != 0 {
  262. ci = ap.entries[len(ap.entries)-1].Index
  263. }
  264. if ap.snapshot.Metadata.Index > ci {
  265. ci = ap.snapshot.Metadata.Index
  266. }
  267. if ci != 0 {
  268. rh.updateCommittedIndex(ci)
  269. }
  270. }
  271. func (r *raftNode) processMessages(ms []raftpb.Message) []raftpb.Message {
  272. sentAppResp := false
  273. for i := len(ms) - 1; i >= 0; i-- {
  274. if r.isIDRemoved(ms[i].To) {
  275. ms[i].To = 0
  276. }
  277. if ms[i].Type == raftpb.MsgAppResp {
  278. if sentAppResp {
  279. ms[i].To = 0
  280. } else {
  281. sentAppResp = true
  282. }
  283. }
  284. if ms[i].Type == raftpb.MsgSnap {
  285. // There are two separate data store: the store for v2, and the KV for v3.
  286. // The msgSnap only contains the most recent snapshot of store without KV.
  287. // So we need to redirect the msgSnap to etcd server main loop for merging in the
  288. // current store snapshot and KV snapshot.
  289. select {
  290. case r.msgSnapC <- ms[i]:
  291. default:
  292. // drop msgSnap if the inflight chan if full.
  293. }
  294. ms[i].To = 0
  295. }
  296. if ms[i].Type == raftpb.MsgHeartbeat {
  297. ok, exceed := r.td.Observe(ms[i].To)
  298. if !ok {
  299. // TODO: limit request rate.
  300. plog.Warningf("failed to send out heartbeat on time (exceeded the %v timeout for %v)", r.heartbeat, exceed)
  301. plog.Warningf("server is likely overloaded")
  302. }
  303. }
  304. }
  305. return ms
  306. }
  307. func (r *raftNode) apply() chan apply {
  308. return r.applyc
  309. }
  310. func (r *raftNode) stop() {
  311. r.stopped <- struct{}{}
  312. <-r.done
  313. }
  314. func (r *raftNode) onStop() {
  315. r.Stop()
  316. r.ticker.Stop()
  317. r.transport.Stop()
  318. if err := r.storage.Close(); err != nil {
  319. plog.Panicf("raft close storage error: %v", err)
  320. }
  321. close(r.done)
  322. }
  323. // for testing
  324. func (r *raftNode) pauseSending() {
  325. p := r.transport.(rafthttp.Pausable)
  326. p.Pause()
  327. }
  328. func (r *raftNode) resumeSending() {
  329. p := r.transport.(rafthttp.Pausable)
  330. p.Resume()
  331. }
  332. // advanceTicks advances ticks of Raft node.
  333. // This can be used for fast-forwarding election
  334. // ticks in multi data-center deployments, thus
  335. // speeding up election process.
  336. func (r *raftNode) advanceTicks(ticks int) {
  337. for i := 0; i < ticks; i++ {
  338. r.tick()
  339. }
  340. }
  341. func startNode(cfg ServerConfig, cl *membership.RaftCluster, ids []types.ID) (id types.ID, n raft.Node, s *raft.MemoryStorage, w *wal.WAL) {
  342. var err error
  343. member := cl.MemberByName(cfg.Name)
  344. metadata := pbutil.MustMarshal(
  345. &pb.Metadata{
  346. NodeID: uint64(member.ID),
  347. ClusterID: uint64(cl.ID()),
  348. },
  349. )
  350. if w, err = wal.Create(cfg.WALDir(), metadata); err != nil {
  351. plog.Fatalf("create wal error: %v", err)
  352. }
  353. peers := make([]raft.Peer, len(ids))
  354. for i, id := range ids {
  355. ctx, err := json.Marshal((*cl).Member(id))
  356. if err != nil {
  357. plog.Panicf("marshal member should never fail: %v", err)
  358. }
  359. peers[i] = raft.Peer{ID: uint64(id), Context: ctx}
  360. }
  361. id = member.ID
  362. plog.Infof("starting member %s in cluster %s", id, cl.ID())
  363. s = raft.NewMemoryStorage()
  364. c := &raft.Config{
  365. ID: uint64(id),
  366. ElectionTick: cfg.ElectionTicks,
  367. HeartbeatTick: 1,
  368. Storage: s,
  369. MaxSizePerMsg: maxSizePerMsg,
  370. MaxInflightMsgs: maxInflightMsgs,
  371. CheckQuorum: true,
  372. }
  373. n = raft.StartNode(c, peers)
  374. raftStatusMu.Lock()
  375. raftStatus = n.Status
  376. raftStatusMu.Unlock()
  377. return id, n, s, w
  378. }
  379. func restartNode(cfg ServerConfig, snapshot *raftpb.Snapshot) (types.ID, *membership.RaftCluster, raft.Node, *raft.MemoryStorage, *wal.WAL) {
  380. var walsnap walpb.Snapshot
  381. if snapshot != nil {
  382. walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
  383. }
  384. w, id, cid, st, ents := readWAL(cfg.WALDir(), walsnap)
  385. plog.Infof("restarting member %s in cluster %s at commit index %d", id, cid, st.Commit)
  386. cl := membership.NewCluster("")
  387. cl.SetID(cid)
  388. s := raft.NewMemoryStorage()
  389. if snapshot != nil {
  390. s.ApplySnapshot(*snapshot)
  391. }
  392. s.SetHardState(st)
  393. s.Append(ents)
  394. c := &raft.Config{
  395. ID: uint64(id),
  396. ElectionTick: cfg.ElectionTicks,
  397. HeartbeatTick: 1,
  398. Storage: s,
  399. MaxSizePerMsg: maxSizePerMsg,
  400. MaxInflightMsgs: maxInflightMsgs,
  401. CheckQuorum: true,
  402. }
  403. n := raft.RestartNode(c)
  404. raftStatusMu.Lock()
  405. raftStatus = n.Status
  406. raftStatusMu.Unlock()
  407. return id, cl, n, s, w
  408. }
  409. func restartAsStandaloneNode(cfg ServerConfig, snapshot *raftpb.Snapshot) (types.ID, *membership.RaftCluster, raft.Node, *raft.MemoryStorage, *wal.WAL) {
  410. var walsnap walpb.Snapshot
  411. if snapshot != nil {
  412. walsnap.Index, walsnap.Term = snapshot.Metadata.Index, snapshot.Metadata.Term
  413. }
  414. w, id, cid, st, ents := readWAL(cfg.WALDir(), walsnap)
  415. // discard the previously uncommitted entries
  416. for i, ent := range ents {
  417. if ent.Index > st.Commit {
  418. plog.Infof("discarding %d uncommitted WAL entries ", len(ents)-i)
  419. ents = ents[:i]
  420. break
  421. }
  422. }
  423. // force append the configuration change entries
  424. toAppEnts := createConfigChangeEnts(getIDs(snapshot, ents), uint64(id), st.Term, st.Commit)
  425. ents = append(ents, toAppEnts...)
  426. // force commit newly appended entries
  427. err := w.Save(raftpb.HardState{}, toAppEnts)
  428. if err != nil {
  429. plog.Fatalf("%v", err)
  430. }
  431. if len(ents) != 0 {
  432. st.Commit = ents[len(ents)-1].Index
  433. }
  434. plog.Printf("forcing restart of member %s in cluster %s at commit index %d", id, cid, st.Commit)
  435. cl := membership.NewCluster("")
  436. cl.SetID(cid)
  437. s := raft.NewMemoryStorage()
  438. if snapshot != nil {
  439. s.ApplySnapshot(*snapshot)
  440. }
  441. s.SetHardState(st)
  442. s.Append(ents)
  443. c := &raft.Config{
  444. ID: uint64(id),
  445. ElectionTick: cfg.ElectionTicks,
  446. HeartbeatTick: 1,
  447. Storage: s,
  448. MaxSizePerMsg: maxSizePerMsg,
  449. MaxInflightMsgs: maxInflightMsgs,
  450. CheckQuorum: true,
  451. }
  452. n := raft.RestartNode(c)
  453. raftStatus = n.Status
  454. return id, cl, n, s, w
  455. }
  456. // getIDs returns an ordered set of IDs included in the given snapshot and
  457. // the entries. The given snapshot/entries can contain two kinds of
  458. // ID-related entry:
  459. // - ConfChangeAddNode, in which case the contained ID will be added into the set.
  460. // - ConfChangeRemoveNode, in which case the contained ID will be removed from the set.
  461. func getIDs(snap *raftpb.Snapshot, ents []raftpb.Entry) []uint64 {
  462. ids := make(map[uint64]bool)
  463. if snap != nil {
  464. for _, id := range snap.Metadata.ConfState.Nodes {
  465. ids[id] = true
  466. }
  467. }
  468. for _, e := range ents {
  469. if e.Type != raftpb.EntryConfChange {
  470. continue
  471. }
  472. var cc raftpb.ConfChange
  473. pbutil.MustUnmarshal(&cc, e.Data)
  474. switch cc.Type {
  475. case raftpb.ConfChangeAddNode:
  476. ids[cc.NodeID] = true
  477. case raftpb.ConfChangeRemoveNode:
  478. delete(ids, cc.NodeID)
  479. case raftpb.ConfChangeUpdateNode:
  480. // do nothing
  481. default:
  482. plog.Panicf("ConfChange Type should be either ConfChangeAddNode or ConfChangeRemoveNode!")
  483. }
  484. }
  485. sids := make(types.Uint64Slice, 0, len(ids))
  486. for id := range ids {
  487. sids = append(sids, id)
  488. }
  489. sort.Sort(sids)
  490. return []uint64(sids)
  491. }
  492. // createConfigChangeEnts creates a series of Raft entries (i.e.
  493. // EntryConfChange) to remove the set of given IDs from the cluster. The ID
  494. // `self` is _not_ removed, even if present in the set.
  495. // If `self` is not inside the given ids, it creates a Raft entry to add a
  496. // default member with the given `self`.
  497. func createConfigChangeEnts(ids []uint64, self uint64, term, index uint64) []raftpb.Entry {
  498. ents := make([]raftpb.Entry, 0)
  499. next := index + 1
  500. found := false
  501. for _, id := range ids {
  502. if id == self {
  503. found = true
  504. continue
  505. }
  506. cc := &raftpb.ConfChange{
  507. Type: raftpb.ConfChangeRemoveNode,
  508. NodeID: id,
  509. }
  510. e := raftpb.Entry{
  511. Type: raftpb.EntryConfChange,
  512. Data: pbutil.MustMarshal(cc),
  513. Term: term,
  514. Index: next,
  515. }
  516. ents = append(ents, e)
  517. next++
  518. }
  519. if !found {
  520. m := membership.Member{
  521. ID: types.ID(self),
  522. RaftAttributes: membership.RaftAttributes{PeerURLs: []string{"http://localhost:2380"}},
  523. }
  524. ctx, err := json.Marshal(m)
  525. if err != nil {
  526. plog.Panicf("marshal member should never fail: %v", err)
  527. }
  528. cc := &raftpb.ConfChange{
  529. Type: raftpb.ConfChangeAddNode,
  530. NodeID: self,
  531. Context: ctx,
  532. }
  533. e := raftpb.Entry{
  534. Type: raftpb.EntryConfChange,
  535. Data: pbutil.MustMarshal(cc),
  536. Term: term,
  537. Index: next,
  538. }
  539. ents = append(ents, e)
  540. }
  541. return ents
  542. }