raft_paper_test.go 29 KB

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