raft.go 16 KB

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