raft_paper_test.go 28 KB

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