raft_paper_test.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. /*
  14. This file contains tests which verify that the scenarios described
  15. in the raft paper (https://ramcloud.stanford.edu/raft.pdf) are
  16. handled by the raft implementation correctly. Each test focuses on
  17. several sentences written in the paper. This could help us to prevent
  18. most implementation bugs.
  19. Each test is composed of three parts: init, test and check.
  20. Init part uses simple and understandable way to simulate the init state.
  21. Test part uses Step function to generate the scenario. Check part checks
  22. outgoing messages and state.
  23. */
  24. package raft
  25. import (
  26. "fmt"
  27. "io/ioutil"
  28. "log"
  29. "os"
  30. "reflect"
  31. "sort"
  32. "testing"
  33. pb "github.com/coreos/etcd/raft/raftpb"
  34. )
  35. func TestFollowerUpdateTermFromMessage(t *testing.T) {
  36. testUpdateTermFromMessage(t, StateFollower)
  37. }
  38. func TestCandidateUpdateTermFromMessage(t *testing.T) {
  39. testUpdateTermFromMessage(t, StateCandidate)
  40. }
  41. func TestLeaderUpdateTermFromMessage(t *testing.T) {
  42. testUpdateTermFromMessage(t, StateLeader)
  43. }
  44. // testUpdateTermFromMessage tests that if one server’s current term is
  45. // smaller than the other’s, then it updates its current term to the larger
  46. // value. If a candidate or leader discovers that its term is out of date,
  47. // it immediately reverts to follower state.
  48. // Reference: section 5.1
  49. func testUpdateTermFromMessage(t *testing.T, state StateType) {
  50. r := newRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  51. switch state {
  52. case StateFollower:
  53. r.becomeFollower(1, 2)
  54. case StateCandidate:
  55. r.becomeCandidate()
  56. case StateLeader:
  57. r.becomeCandidate()
  58. r.becomeLeader()
  59. }
  60. r.Step(pb.Message{Type: pb.MsgApp, Term: 2})
  61. if r.Term != 2 {
  62. t.Errorf("term = %d, want %d", r.Term, 2)
  63. }
  64. if r.state != StateFollower {
  65. t.Errorf("state = %v, want %v", r.state, StateFollower)
  66. }
  67. }
  68. // TestRejectStaleTermMessage tests that if a server receives a request with
  69. // a stale term number, it rejects the request.
  70. // Our implementation ignores the request instead.
  71. // Reference: section 5.1
  72. func TestRejectStaleTermMessage(t *testing.T) {
  73. called := false
  74. fakeStep := func(r *raft, m pb.Message) {
  75. called = true
  76. }
  77. r := newRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  78. r.step = fakeStep
  79. r.loadState(pb.HardState{Term: 2})
  80. r.Step(pb.Message{Type: pb.MsgApp, Term: r.Term - 1})
  81. if called == true {
  82. t.Errorf("stepFunc called = %v, want %v", called, false)
  83. }
  84. }
  85. // TestStartAsFollower tests that when servers start up, they begin as followers.
  86. // Reference: section 5.2
  87. func TestStartAsFollower(t *testing.T) {
  88. r := newRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  89. if r.state != StateFollower {
  90. t.Errorf("state = %s, want %s", r.state, StateFollower)
  91. }
  92. }
  93. // TestLeaderBcastBeat tests that if the leader receives a heartbeat tick,
  94. // it will send a msgApp with m.Index = 0, m.LogTerm=0 and empty entries as
  95. // heartbeat to all followers.
  96. // Reference: section 5.2
  97. func TestLeaderBcastBeat(t *testing.T) {
  98. // heartbeat interval
  99. hi := 1
  100. r := newRaft(1, []uint64{1, 2, 3}, 10, hi, NewMemoryStorage())
  101. r.becomeCandidate()
  102. r.becomeLeader()
  103. for i := 0; i < 10; i++ {
  104. r.appendEntry(pb.Entry{Index: uint64(i) + 1})
  105. }
  106. for i := 0; i < hi; i++ {
  107. r.tick()
  108. }
  109. msgs := r.readMessages()
  110. sort.Sort(messageSlice(msgs))
  111. wmsgs := []pb.Message{
  112. {From: 1, To: 2, Term: 1, Type: pb.MsgHeartbeat},
  113. {From: 1, To: 3, Term: 1, Type: pb.MsgHeartbeat},
  114. }
  115. if !reflect.DeepEqual(msgs, wmsgs) {
  116. t.Errorf("msgs = %v, want %v", msgs, wmsgs)
  117. }
  118. }
  119. func TestFollowerStartElection(t *testing.T) {
  120. testNonleaderStartElection(t, StateFollower)
  121. }
  122. func TestCandidateStartNewElection(t *testing.T) {
  123. testNonleaderStartElection(t, StateCandidate)
  124. }
  125. // testNonleaderStartElection tests that if a follower receives no communication
  126. // over election timeout, it begins an election to choose a new leader. It
  127. // increments its current term and transitions to candidate state. It then
  128. // votes for itself and issues RequestVote RPCs in parallel to each of the
  129. // other servers in the cluster.
  130. // Reference: section 5.2
  131. // Also if a candidate fails to obtain a majority, it will time out and
  132. // start a new election by incrementing its term and initiating another
  133. // round of RequestVote RPCs.
  134. // Reference: section 5.2
  135. func testNonleaderStartElection(t *testing.T, state StateType) {
  136. // election timeout
  137. et := 10
  138. r := newRaft(1, []uint64{1, 2, 3}, et, 1, NewMemoryStorage())
  139. switch state {
  140. case StateFollower:
  141. r.becomeFollower(1, 2)
  142. case StateCandidate:
  143. r.becomeCandidate()
  144. }
  145. for i := 0; i < 2*et; i++ {
  146. r.tick()
  147. }
  148. if r.Term != 2 {
  149. t.Errorf("term = %d, want 2", r.Term)
  150. }
  151. if r.state != StateCandidate {
  152. t.Errorf("state = %s, want %s", r.state, StateCandidate)
  153. }
  154. if r.votes[r.id] != true {
  155. t.Errorf("vote for self = false, want true")
  156. }
  157. msgs := r.readMessages()
  158. sort.Sort(messageSlice(msgs))
  159. wmsgs := []pb.Message{
  160. {From: 1, To: 2, Term: 2, Type: pb.MsgVote},
  161. {From: 1, To: 3, Term: 2, Type: pb.MsgVote},
  162. }
  163. if !reflect.DeepEqual(msgs, wmsgs) {
  164. t.Errorf("msgs = %v, want %v", msgs, wmsgs)
  165. }
  166. }
  167. // TestLeaderElectionInOneRoundRPC tests all cases that may happen in
  168. // leader election during one round of RequestVote RPC:
  169. // a) it wins the election
  170. // b) it loses the election
  171. // c) it is unclear about the result
  172. // Reference: section 5.2
  173. func TestLeaderElectionInOneRoundRPC(t *testing.T) {
  174. tests := []struct {
  175. size int
  176. votes map[uint64]bool
  177. state StateType
  178. }{
  179. // win the election when receiving votes from a majority of the servers
  180. {1, map[uint64]bool{}, StateLeader},
  181. {3, map[uint64]bool{2: true, 3: true}, StateLeader},
  182. {3, map[uint64]bool{2: true}, StateLeader},
  183. {5, map[uint64]bool{2: true, 3: true, 4: true, 5: true}, StateLeader},
  184. {5, map[uint64]bool{2: true, 3: true, 4: true}, StateLeader},
  185. {5, map[uint64]bool{2: true, 3: true}, StateLeader},
  186. // return to follower state if it receives vote denial from a majority
  187. {3, map[uint64]bool{2: false, 3: false}, StateFollower},
  188. {5, map[uint64]bool{2: false, 3: false, 4: false, 5: false}, StateFollower},
  189. {5, map[uint64]bool{2: true, 3: false, 4: false, 5: false}, StateFollower},
  190. // stay in candidate if it does not obtain the majority
  191. {3, map[uint64]bool{}, StateCandidate},
  192. {5, map[uint64]bool{2: true}, StateCandidate},
  193. {5, map[uint64]bool{2: false, 3: false}, StateCandidate},
  194. {5, map[uint64]bool{}, StateCandidate},
  195. }
  196. for i, tt := range tests {
  197. r := newRaft(1, idsBySize(tt.size), 10, 1, NewMemoryStorage())
  198. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  199. for id, vote := range tt.votes {
  200. r.Step(pb.Message{From: id, To: 1, Type: pb.MsgVoteResp, Reject: !vote})
  201. }
  202. if r.state != tt.state {
  203. t.Errorf("#%d: state = %s, want %s", i, r.state, tt.state)
  204. }
  205. if g := r.Term; g != 1 {
  206. t.Errorf("#%d: term = %d, want %d", i, g, 1)
  207. }
  208. }
  209. }
  210. // TestFollowerVote tests that each follower will vote for at most one
  211. // candidate in a given term, on a first-come-first-served basis.
  212. // Reference: section 5.2
  213. func TestFollowerVote(t *testing.T) {
  214. tests := []struct {
  215. vote uint64
  216. nvote uint64
  217. wreject bool
  218. }{
  219. {None, 1, false},
  220. {None, 2, false},
  221. {1, 1, false},
  222. {2, 2, false},
  223. {1, 2, true},
  224. {2, 1, true},
  225. }
  226. for i, tt := range tests {
  227. r := newRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  228. r.loadState(pb.HardState{Term: 1, Vote: tt.vote})
  229. r.Step(pb.Message{From: tt.nvote, To: 1, Term: 1, Type: pb.MsgVote})
  230. msgs := r.readMessages()
  231. wmsgs := []pb.Message{
  232. {From: 1, To: tt.nvote, Term: 1, Type: pb.MsgVoteResp, Reject: tt.wreject},
  233. }
  234. if !reflect.DeepEqual(msgs, wmsgs) {
  235. t.Errorf("#%d: msgs = %v, want %v", i, msgs, wmsgs)
  236. }
  237. }
  238. }
  239. // TestCandidateFallback tests that while waiting for votes,
  240. // if a candidate receives an AppendEntries RPC from another server claiming
  241. // to be leader whose term is at least as large as the candidate's current term,
  242. // it recognizes the leader as legitimate and returns to follower state.
  243. // Reference: section 5.2
  244. func TestCandidateFallback(t *testing.T) {
  245. tests := []pb.Message{
  246. {From: 2, To: 1, Term: 1, Type: pb.MsgApp},
  247. {From: 2, To: 1, Term: 2, Type: pb.MsgApp},
  248. }
  249. for i, tt := range tests {
  250. r := newRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  251. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  252. if r.state != StateCandidate {
  253. t.Fatalf("unexpected state = %s, want %s", r.state, StateCandidate)
  254. }
  255. r.Step(tt)
  256. if g := r.state; g != StateFollower {
  257. t.Errorf("#%d: state = %s, want %s", i, g, StateFollower)
  258. }
  259. if g := r.Term; g != tt.Term {
  260. t.Errorf("#%d: term = %d, want %d", i, g, tt.Term)
  261. }
  262. }
  263. }
  264. func TestFollowerElectionTimeoutRandomized(t *testing.T) {
  265. log.SetOutput(ioutil.Discard)
  266. defer log.SetOutput(os.Stderr)
  267. testNonleaderElectionTimeoutRandomized(t, StateFollower)
  268. }
  269. func TestCandidateElectionTimeoutRandomized(t *testing.T) {
  270. log.SetOutput(ioutil.Discard)
  271. defer log.SetOutput(os.Stderr)
  272. testNonleaderElectionTimeoutRandomized(t, StateCandidate)
  273. }
  274. // testNonleaderElectionTimeoutRandomized tests that election timeout for
  275. // follower or candidate is randomized.
  276. // Reference: section 5.2
  277. func testNonleaderElectionTimeoutRandomized(t *testing.T, state StateType) {
  278. et := 10
  279. r := newRaft(1, []uint64{1, 2, 3}, et, 1, NewMemoryStorage())
  280. timeouts := make(map[int]bool)
  281. for round := 0; round < 50*et; round++ {
  282. switch state {
  283. case StateFollower:
  284. r.becomeFollower(r.Term+1, 2)
  285. case StateCandidate:
  286. r.becomeCandidate()
  287. }
  288. time := 0
  289. for len(r.readMessages()) == 0 {
  290. r.tick()
  291. time++
  292. }
  293. timeouts[time] = true
  294. }
  295. for d := et + 1; d < 2*et; d++ {
  296. if timeouts[d] != true {
  297. t.Errorf("timeout in %d ticks should happen", d)
  298. }
  299. }
  300. }
  301. func TestFollowersElectioinTimeoutNonconflict(t *testing.T) {
  302. log.SetOutput(ioutil.Discard)
  303. defer log.SetOutput(os.Stderr)
  304. testNonleadersElectionTimeoutNonconflict(t, StateFollower)
  305. }
  306. func TestCandidatesElectionTimeoutNonconflict(t *testing.T) {
  307. log.SetOutput(ioutil.Discard)
  308. defer log.SetOutput(os.Stderr)
  309. testNonleadersElectionTimeoutNonconflict(t, StateCandidate)
  310. }
  311. // testNonleadersElectionTimeoutNonconflict tests that in most cases only a
  312. // single server(follower or candidate) will time out, which reduces the
  313. // likelihood of split vote in the new election.
  314. // Reference: section 5.2
  315. func testNonleadersElectionTimeoutNonconflict(t *testing.T, state StateType) {
  316. et := 10
  317. size := 5
  318. rs := make([]*raft, size)
  319. ids := idsBySize(size)
  320. for k := range rs {
  321. rs[k] = newRaft(ids[k], ids, et, 1, NewMemoryStorage())
  322. }
  323. conflicts := 0
  324. for round := 0; round < 1000; round++ {
  325. for _, r := range rs {
  326. switch state {
  327. case StateFollower:
  328. r.becomeFollower(r.Term+1, None)
  329. case StateCandidate:
  330. r.becomeCandidate()
  331. }
  332. }
  333. timeoutNum := 0
  334. for timeoutNum == 0 {
  335. for _, r := range rs {
  336. r.tick()
  337. if len(r.readMessages()) > 0 {
  338. timeoutNum++
  339. }
  340. }
  341. }
  342. // several rafts time out at the same tick
  343. if timeoutNum > 1 {
  344. conflicts++
  345. }
  346. }
  347. if g := float64(conflicts) / 1000; g > 0.4 {
  348. t.Errorf("probability of conflicts = %v, want <= 0.4", g)
  349. }
  350. }
  351. // TestLeaderStartReplication tests that when receiving client proposals,
  352. // the leader appends the proposal to its log as a new entry, then issues
  353. // AppendEntries RPCs in parallel to each of the other servers to replicate
  354. // the entry. Also, when sending an AppendEntries RPC, the leader includes
  355. // the index and term of the entry in its log that immediately precedes
  356. // the new entries.
  357. // Also, it writes the new entry into stable storage.
  358. // Reference: section 5.3
  359. func TestLeaderStartReplication(t *testing.T) {
  360. s := NewMemoryStorage()
  361. r := newRaft(1, []uint64{1, 2, 3}, 10, 1, s)
  362. r.becomeCandidate()
  363. r.becomeLeader()
  364. commitNoopEntry(r, s)
  365. li := r.raftLog.lastIndex()
  366. ents := []pb.Entry{{Data: []byte("some data")}}
  367. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: ents})
  368. if g := r.raftLog.lastIndex(); g != li+1 {
  369. t.Errorf("lastIndex = %d, want %d", g, li+1)
  370. }
  371. if g := r.raftLog.committed; g != li {
  372. t.Errorf("committed = %d, want %d", g, li)
  373. }
  374. msgs := r.readMessages()
  375. sort.Sort(messageSlice(msgs))
  376. wents := []pb.Entry{{Index: li + 1, Term: 1, Data: []byte("some data")}}
  377. wmsgs := []pb.Message{
  378. {From: 1, To: 2, Term: 1, Type: pb.MsgApp, Index: li, LogTerm: 1, Entries: wents, Commit: li},
  379. {From: 1, To: 3, Term: 1, Type: pb.MsgApp, Index: li, LogTerm: 1, Entries: wents, Commit: li},
  380. }
  381. if !reflect.DeepEqual(msgs, wmsgs) {
  382. t.Errorf("msgs = %+v, want %+v", msgs, wmsgs)
  383. }
  384. if g := r.raftLog.unstableEntries(); !reflect.DeepEqual(g, wents) {
  385. t.Errorf("ents = %+v, want %+v", g, wents)
  386. }
  387. }
  388. // TestLeaderCommitEntry tests that when the entry has been safely replicated,
  389. // the leader gives out the applied entries, which can be applied to its state
  390. // machine.
  391. // Also, the leader keeps track of the highest index it knows to be committed,
  392. // and it includes that index in future AppendEntries RPCs so that the other
  393. // servers eventually find out.
  394. // Reference: section 5.3
  395. func TestLeaderCommitEntry(t *testing.T) {
  396. s := NewMemoryStorage()
  397. r := newRaft(1, []uint64{1, 2, 3}, 10, 1, s)
  398. r.becomeCandidate()
  399. r.becomeLeader()
  400. commitNoopEntry(r, s)
  401. li := r.raftLog.lastIndex()
  402. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  403. for _, m := range r.readMessages() {
  404. r.Step(acceptAndReply(m))
  405. }
  406. if g := r.raftLog.committed; g != li+1 {
  407. t.Errorf("committed = %d, want %d", g, li+1)
  408. }
  409. wents := []pb.Entry{{Index: li + 1, Term: 1, Data: []byte("some data")}}
  410. if g := r.raftLog.nextEnts(); !reflect.DeepEqual(g, wents) {
  411. t.Errorf("nextEnts = %+v, want %+v", g, wents)
  412. }
  413. msgs := r.readMessages()
  414. sort.Sort(messageSlice(msgs))
  415. for i, m := range msgs {
  416. if w := uint64(i + 2); m.To != w {
  417. t.Errorf("to = %x, want %x", m.To, w)
  418. }
  419. if m.Type != pb.MsgApp {
  420. t.Errorf("type = %s, want %s", m.Type, pb.MsgApp)
  421. }
  422. if m.Commit != li+1 {
  423. t.Errorf("commit = %d, want %d", m.Commit, li+1)
  424. }
  425. }
  426. }
  427. // TestLeaderAcknowledgeCommit tests that a log entry is committed once the
  428. // leader that created the entry has replicated it on a majority of the servers.
  429. // Reference: section 5.3
  430. func TestLeaderAcknowledgeCommit(t *testing.T) {
  431. tests := []struct {
  432. size int
  433. acceptors map[uint64]bool
  434. wack bool
  435. }{
  436. {1, nil, true},
  437. {3, nil, false},
  438. {3, map[uint64]bool{2: true}, true},
  439. {3, map[uint64]bool{2: true, 3: true}, true},
  440. {5, nil, false},
  441. {5, map[uint64]bool{2: true}, false},
  442. {5, map[uint64]bool{2: true, 3: true}, true},
  443. {5, map[uint64]bool{2: true, 3: true, 4: true}, true},
  444. {5, map[uint64]bool{2: true, 3: true, 4: true, 5: true}, true},
  445. }
  446. for i, tt := range tests {
  447. s := NewMemoryStorage()
  448. r := newRaft(1, idsBySize(tt.size), 10, 1, s)
  449. r.becomeCandidate()
  450. r.becomeLeader()
  451. commitNoopEntry(r, s)
  452. li := r.raftLog.lastIndex()
  453. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  454. for _, m := range r.readMessages() {
  455. if tt.acceptors[m.To] {
  456. r.Step(acceptAndReply(m))
  457. }
  458. }
  459. if g := r.raftLog.committed > li; g != tt.wack {
  460. t.Errorf("#%d: ack commit = %v, want %v", i, g, tt.wack)
  461. }
  462. }
  463. }
  464. // TestLeaderCommitPrecedingEntries tests that when leader commits a log entry,
  465. // it also commits all preceding entries in the leader’s log, including
  466. // entries created by previous leaders.
  467. // Also, it applies the entry to its local state machine (in log order).
  468. // Reference: section 5.3
  469. func TestLeaderCommitPrecedingEntries(t *testing.T) {
  470. tests := [][]pb.Entry{
  471. {},
  472. {{Term: 2, Index: 1}},
  473. {{Term: 1, Index: 1}, {Term: 2, Index: 2}},
  474. {{Term: 1, Index: 1}},
  475. }
  476. for i, tt := range tests {
  477. storage := NewMemoryStorage()
  478. storage.Append(tt)
  479. r := newRaft(1, []uint64{1, 2, 3}, 10, 1, storage)
  480. r.loadState(pb.HardState{Term: 2})
  481. r.becomeCandidate()
  482. r.becomeLeader()
  483. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  484. for _, m := range r.readMessages() {
  485. r.Step(acceptAndReply(m))
  486. }
  487. li := uint64(len(tt))
  488. wents := append(tt, pb.Entry{Term: 3, Index: li + 1}, pb.Entry{Term: 3, Index: li + 2, Data: []byte("some data")})
  489. if g := r.raftLog.nextEnts(); !reflect.DeepEqual(g, wents) {
  490. t.Errorf("#%d: ents = %+v, want %+v", i, g, wents)
  491. }
  492. }
  493. }
  494. // TestFollowerCommitEntry tests that once a follower learns that a log entry
  495. // is committed, it applies the entry to its local state machine (in log order).
  496. // Reference: section 5.3
  497. func TestFollowerCommitEntry(t *testing.T) {
  498. tests := []struct {
  499. ents []pb.Entry
  500. commit uint64
  501. }{
  502. {
  503. []pb.Entry{
  504. {Term: 1, Index: 1, Data: []byte("some data")},
  505. },
  506. 1,
  507. },
  508. {
  509. []pb.Entry{
  510. {Term: 1, Index: 1, Data: []byte("some data")},
  511. {Term: 1, Index: 2, Data: []byte("some data2")},
  512. },
  513. 2,
  514. },
  515. {
  516. []pb.Entry{
  517. {Term: 1, Index: 1, Data: []byte("some data2")},
  518. {Term: 1, Index: 2, Data: []byte("some data")},
  519. },
  520. 2,
  521. },
  522. {
  523. []pb.Entry{
  524. {Term: 1, Index: 1, Data: []byte("some data")},
  525. {Term: 1, Index: 2, Data: []byte("some data2")},
  526. },
  527. 1,
  528. },
  529. }
  530. for i, tt := range tests {
  531. r := newRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  532. r.becomeFollower(1, 2)
  533. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgApp, Term: 1, Entries: tt.ents, Commit: tt.commit})
  534. if g := r.raftLog.committed; g != tt.commit {
  535. t.Errorf("#%d: committed = %d, want %d", i, g, tt.commit)
  536. }
  537. wents := tt.ents[:int(tt.commit)]
  538. if g := r.raftLog.nextEnts(); !reflect.DeepEqual(g, wents) {
  539. t.Errorf("#%d: nextEnts = %v, want %v", i, g, wents)
  540. }
  541. }
  542. }
  543. // TestFollowerCheckMsgApp tests that if the follower does not find an
  544. // entry in its log with the same index and term as the one in AppendEntries RPC,
  545. // then it refuses the new entries. Otherwise it replies that it accepts the
  546. // append entries.
  547. // Reference: section 5.3
  548. func TestFollowerCheckMsgApp(t *testing.T) {
  549. ents := []pb.Entry{{Term: 1, Index: 1}, {Term: 2, Index: 2}}
  550. tests := []struct {
  551. term uint64
  552. index uint64
  553. wreject bool
  554. wrejectHint uint64
  555. }{
  556. {ents[0].Term, ents[0].Index, false, 0},
  557. {ents[0].Term, ents[0].Index + 1, true, 2},
  558. {ents[0].Term + 1, ents[0].Index, true, 2},
  559. {ents[1].Term, ents[1].Index, false, 0},
  560. {3, 3, true, 2},
  561. }
  562. for i, tt := range tests {
  563. storage := NewMemoryStorage()
  564. storage.Append(ents)
  565. r := newRaft(1, []uint64{1, 2, 3}, 10, 1, storage)
  566. r.loadState(pb.HardState{Commit: 2})
  567. r.becomeFollower(2, 2)
  568. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgApp, Term: 2, LogTerm: tt.term, Index: tt.index})
  569. msgs := r.readMessages()
  570. wmsgs := []pb.Message{
  571. {From: 1, To: 2, Type: pb.MsgAppResp, Term: 2, Index: tt.index, Reject: tt.wreject, RejectHint: tt.wrejectHint},
  572. }
  573. if !reflect.DeepEqual(msgs, wmsgs) {
  574. t.Errorf("#%d: msgs = %+v, want %+v", i, msgs, wmsgs)
  575. }
  576. }
  577. }
  578. // TestFollowerAppendEntries tests that when AppendEntries RPC is valid,
  579. // the follower will delete the existing conflict entry and all that follow it,
  580. // and append any new entries not already in the log.
  581. // Also, it writes the new entry into stable storage.
  582. // Reference: section 5.3
  583. func TestFollowerAppendEntries(t *testing.T) {
  584. tests := []struct {
  585. index, term uint64
  586. ents []pb.Entry
  587. wents []pb.Entry
  588. wunstable []pb.Entry
  589. }{
  590. {
  591. 2, 2,
  592. []pb.Entry{{Term: 3, Index: 3}},
  593. []pb.Entry{{Term: 1, Index: 1}, {Term: 2, Index: 2}, {Term: 3, Index: 3}},
  594. []pb.Entry{{Term: 3, Index: 3}},
  595. },
  596. {
  597. 1, 1,
  598. []pb.Entry{{Term: 3, Index: 2}, {Term: 4, Index: 3}},
  599. []pb.Entry{{Term: 1, Index: 1}, {Term: 3, Index: 2}, {Term: 4, Index: 3}},
  600. []pb.Entry{{Term: 3, Index: 2}, {Term: 4, Index: 3}},
  601. },
  602. {
  603. 0, 0,
  604. []pb.Entry{{Term: 1, Index: 1}},
  605. []pb.Entry{{Term: 1, Index: 1}, {Term: 2, Index: 2}},
  606. nil,
  607. },
  608. {
  609. 0, 0,
  610. []pb.Entry{{Term: 3, Index: 1}},
  611. []pb.Entry{{Term: 3, Index: 1}},
  612. []pb.Entry{{Term: 3, Index: 1}},
  613. },
  614. }
  615. for i, tt := range tests {
  616. storage := NewMemoryStorage()
  617. storage.Append([]pb.Entry{{Term: 1, Index: 1}, {Term: 2, Index: 2}})
  618. r := newRaft(1, []uint64{1, 2, 3}, 10, 1, storage)
  619. r.becomeFollower(2, 2)
  620. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgApp, Term: 2, LogTerm: tt.term, Index: tt.index, Entries: tt.ents})
  621. if g := r.raftLog.allEntries(); !reflect.DeepEqual(g, tt.wents) {
  622. t.Errorf("#%d: ents = %+v, want %+v", i, g, tt.wents)
  623. }
  624. if g := r.raftLog.unstableEntries(); !reflect.DeepEqual(g, tt.wunstable) {
  625. t.Errorf("#%d: unstableEnts = %+v, want %+v", i, g, tt.wunstable)
  626. }
  627. }
  628. }
  629. // TestLeaderSyncFollowerLog tests that the leader could bring a follower's log
  630. // into consistency with its own.
  631. // Reference: section 5.3, figure 7
  632. func TestLeaderSyncFollowerLog(t *testing.T) {
  633. ents := []pb.Entry{
  634. {},
  635. {Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3},
  636. {Term: 4, Index: 4}, {Term: 4, Index: 5},
  637. {Term: 5, Index: 6}, {Term: 5, Index: 7},
  638. {Term: 6, Index: 8}, {Term: 6, Index: 9}, {Term: 6, Index: 10},
  639. }
  640. term := uint64(8)
  641. tests := [][]pb.Entry{
  642. {
  643. {},
  644. {Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3},
  645. {Term: 4, Index: 4}, {Term: 4, Index: 5},
  646. {Term: 5, Index: 6}, {Term: 5, Index: 7},
  647. {Term: 6, Index: 8}, {Term: 6, Index: 9},
  648. },
  649. {
  650. {},
  651. {Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3},
  652. {Term: 4, Index: 4},
  653. },
  654. {
  655. {},
  656. {Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3},
  657. {Term: 4, Index: 4}, {Term: 4, Index: 5},
  658. {Term: 5, Index: 6}, {Term: 5, Index: 7},
  659. {Term: 6, Index: 8}, {Term: 6, Index: 9}, {Term: 6, Index: 10}, {Term: 6, Index: 11},
  660. },
  661. {
  662. {},
  663. {Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3},
  664. {Term: 4, Index: 4}, {Term: 4, Index: 5},
  665. {Term: 5, Index: 6}, {Term: 5, Index: 7},
  666. {Term: 6, Index: 8}, {Term: 6, Index: 9}, {Term: 6, Index: 10},
  667. {Term: 7, Index: 11}, {Term: 7, Index: 12},
  668. },
  669. {
  670. {},
  671. {Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3},
  672. {Term: 4, Index: 4}, {Term: 4, Index: 5}, {Term: 4, Index: 6}, {Term: 4, Index: 7},
  673. },
  674. {
  675. {},
  676. {Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3},
  677. {Term: 2, Index: 4}, {Term: 2, Index: 5}, {Term: 2, Index: 6},
  678. {Term: 3, Index: 7}, {Term: 3, Index: 8}, {Term: 3, Index: 9}, {Term: 3, Index: 10}, {Term: 3, Index: 11},
  679. },
  680. }
  681. for i, tt := range tests {
  682. leadStorage := NewMemoryStorage()
  683. leadStorage.Append(ents)
  684. lead := newRaft(1, []uint64{1, 2, 3}, 10, 1, leadStorage)
  685. lead.loadState(pb.HardState{Commit: lead.raftLog.lastIndex(), Term: term})
  686. followerStorage := NewMemoryStorage()
  687. followerStorage.Append(tt)
  688. follower := newRaft(2, []uint64{1, 2, 3}, 10, 1, followerStorage)
  689. follower.loadState(pb.HardState{Term: term - 1})
  690. // It is necessary to have a three-node cluster.
  691. // The second may have more up-to-date log than the first one, so the
  692. // first node needs the vote from the third node to become the leader.
  693. n := newNetwork(lead, follower, nopStepper)
  694. n.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  695. n.send(pb.Message{From: 3, To: 1, Type: pb.MsgVoteResp, Term: 1})
  696. n.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  697. if g := diffu(ltoa(lead.raftLog), ltoa(follower.raftLog)); g != "" {
  698. t.Errorf("#%d: log diff:\n%s", i, g)
  699. }
  700. }
  701. }
  702. // TestVoteRequest tests that the vote request includes information about the candidate’s log
  703. // and are sent to all of the other nodes.
  704. // Reference: section 5.4.1
  705. func TestVoteRequest(t *testing.T) {
  706. tests := []struct {
  707. ents []pb.Entry
  708. wterm uint64
  709. }{
  710. {[]pb.Entry{{Term: 1, Index: 1}}, 2},
  711. {[]pb.Entry{{Term: 1, Index: 1}, {Term: 2, Index: 2}}, 3},
  712. }
  713. for i, tt := range tests {
  714. r := newRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  715. r.Step(pb.Message{
  716. From: 2, To: 1, Type: pb.MsgApp, Term: tt.wterm - 1, LogTerm: 0, Index: 0, Entries: tt.ents,
  717. })
  718. r.readMessages()
  719. for i := 0; i < r.electionTimeout*2; i++ {
  720. r.tickElection()
  721. }
  722. msgs := r.readMessages()
  723. sort.Sort(messageSlice(msgs))
  724. if len(msgs) != 2 {
  725. t.Fatalf("#%d: len(msg) = %d, want %d", i, len(msgs), 2)
  726. }
  727. for i, m := range msgs {
  728. if m.Type != pb.MsgVote {
  729. t.Errorf("#%d: msgType = %d, want %d", i, m.Type, pb.MsgVote)
  730. }
  731. if m.To != uint64(i+2) {
  732. t.Errorf("#%d: to = %d, want %d", i, m.To, i+2)
  733. }
  734. if m.Term != tt.wterm {
  735. t.Errorf("#%d: term = %d, want %d", i, m.Term, tt.wterm)
  736. }
  737. windex, wlogterm := tt.ents[len(tt.ents)-1].Index, tt.ents[len(tt.ents)-1].Term
  738. if m.Index != windex {
  739. t.Errorf("#%d: index = %d, want %d", i, m.Index, windex)
  740. }
  741. if m.LogTerm != wlogterm {
  742. t.Errorf("#%d: logterm = %d, want %d", i, m.LogTerm, wlogterm)
  743. }
  744. }
  745. }
  746. }
  747. // TestVoter tests the voter denies its vote if its own log is more up-to-date
  748. // than that of the candidate.
  749. // Reference: section 5.4.1
  750. func TestVoter(t *testing.T) {
  751. tests := []struct {
  752. ents []pb.Entry
  753. logterm uint64
  754. index uint64
  755. wreject bool
  756. }{
  757. // same logterm
  758. {[]pb.Entry{{Term: 1, Index: 1}}, 1, 1, false},
  759. {[]pb.Entry{{Term: 1, Index: 1}}, 1, 2, false},
  760. {[]pb.Entry{{Term: 1, Index: 1}, {Term: 1, Index: 2}}, 1, 1, true},
  761. // candidate higher logterm
  762. {[]pb.Entry{{Term: 1, Index: 1}}, 2, 1, false},
  763. {[]pb.Entry{{Term: 1, Index: 1}}, 2, 2, false},
  764. {[]pb.Entry{{Term: 1, Index: 1}, {Term: 1, Index: 2}}, 2, 1, false},
  765. // voter higher logterm
  766. {[]pb.Entry{{Term: 2, Index: 1}}, 1, 1, true},
  767. {[]pb.Entry{{Term: 2, Index: 1}}, 1, 2, true},
  768. {[]pb.Entry{{Term: 2, Index: 1}, {Term: 1, Index: 2}}, 1, 1, true},
  769. }
  770. for i, tt := range tests {
  771. storage := NewMemoryStorage()
  772. storage.Append(tt.ents)
  773. r := newRaft(1, []uint64{1, 2}, 10, 1, storage)
  774. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgVote, Term: 3, LogTerm: tt.logterm, Index: tt.index})
  775. msgs := r.readMessages()
  776. if len(msgs) != 1 {
  777. t.Fatalf("#%d: len(msg) = %d, want %d", i, len(msgs), 1)
  778. }
  779. m := msgs[0]
  780. if m.Type != pb.MsgVoteResp {
  781. t.Errorf("#%d: msgType = %d, want %d", i, m.Type, pb.MsgVoteResp)
  782. }
  783. if m.Reject != tt.wreject {
  784. t.Errorf("#%d: reject = %t, want %t", i, m.Reject, tt.wreject)
  785. }
  786. }
  787. }
  788. // TestLeaderOnlyCommitsLogFromCurrentTerm tests that only log entries from the leader’s
  789. // current term are committed by counting replicas.
  790. // Reference: section 5.4.2
  791. func TestLeaderOnlyCommitsLogFromCurrentTerm(t *testing.T) {
  792. ents := []pb.Entry{{Term: 1, Index: 1}, {Term: 2, Index: 2}}
  793. tests := []struct {
  794. index uint64
  795. wcommit uint64
  796. }{
  797. // do not commit log entries in previous terms
  798. {1, 0},
  799. {2, 0},
  800. // commit log in current term
  801. {3, 3},
  802. }
  803. for i, tt := range tests {
  804. storage := NewMemoryStorage()
  805. storage.Append(ents)
  806. r := newRaft(1, []uint64{1, 2}, 10, 1, storage)
  807. r.loadState(pb.HardState{Term: 2})
  808. // become leader at term 3
  809. r.becomeCandidate()
  810. r.becomeLeader()
  811. r.readMessages()
  812. // propose a entry to current term
  813. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  814. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgAppResp, Term: r.Term, Index: tt.index})
  815. if r.raftLog.committed != tt.wcommit {
  816. t.Errorf("#%d: commit = %d, want %d", i, r.raftLog.committed, tt.wcommit)
  817. }
  818. }
  819. }
  820. type messageSlice []pb.Message
  821. func (s messageSlice) Len() int { return len(s) }
  822. func (s messageSlice) Less(i, j int) bool { return fmt.Sprint(s[i]) < fmt.Sprint(s[j]) }
  823. func (s messageSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  824. func commitNoopEntry(r *raft, s *MemoryStorage) {
  825. if r.state != StateLeader {
  826. panic("it should only be used when it is the leader")
  827. }
  828. r.bcastAppend()
  829. // simulate the response of MsgApp
  830. msgs := r.readMessages()
  831. for _, m := range msgs {
  832. if m.Type != pb.MsgApp || len(m.Entries) != 1 || m.Entries[0].Data != nil {
  833. panic("not a message to append noop entry")
  834. }
  835. r.Step(acceptAndReply(m))
  836. }
  837. // ignore further messages to refresh followers' commmit index
  838. r.readMessages()
  839. s.Append(r.raftLog.unstableEntries())
  840. r.raftLog.appliedTo(r.raftLog.committed)
  841. r.raftLog.stableTo(r.raftLog.lastIndex(), r.raftLog.lastTerm())
  842. }
  843. func acceptAndReply(m pb.Message) pb.Message {
  844. if m.Type != pb.MsgApp {
  845. panic("type should be MsgApp")
  846. }
  847. return pb.Message{
  848. From: m.To,
  849. To: m.From,
  850. Term: m.Term,
  851. Type: pb.MsgAppResp,
  852. Index: m.Index + uint64(len(m.Entries)),
  853. }
  854. }