raft_test.go 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881
  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. package raft
  15. import (
  16. "bytes"
  17. "fmt"
  18. "math"
  19. "math/rand"
  20. "reflect"
  21. "testing"
  22. pb "github.com/coreos/etcd/raft/raftpb"
  23. )
  24. // nextEnts returns the appliable entries and updates the applied index
  25. func nextEnts(r *raft, s *MemoryStorage) (ents []pb.Entry) {
  26. // Transfer all unstable entries to "stable" storage.
  27. s.Append(r.raftLog.unstableEntries())
  28. r.raftLog.stableTo(r.raftLog.lastIndex(), r.raftLog.lastTerm())
  29. ents = r.raftLog.nextEnts()
  30. r.raftLog.appliedTo(r.raftLog.committed)
  31. return ents
  32. }
  33. type Interface interface {
  34. Step(m pb.Message) error
  35. readMessages() []pb.Message
  36. }
  37. func (r *raft) readMessages() []pb.Message {
  38. msgs := r.msgs
  39. r.msgs = make([]pb.Message, 0)
  40. return msgs
  41. }
  42. func TestBecomeProbe(t *testing.T) {
  43. match := uint64(1)
  44. tests := []struct {
  45. p *Progress
  46. wnext uint64
  47. }{
  48. {
  49. &Progress{State: ProgressStateReplicate, Match: match, Next: 5},
  50. 2,
  51. },
  52. {
  53. // snapshot finish
  54. &Progress{State: ProgressStateSnapshot, Match: match, Next: 5, PendingSnapshot: 10},
  55. 11,
  56. },
  57. {
  58. // snapshot failure
  59. &Progress{State: ProgressStateSnapshot, Match: match, Next: 5, PendingSnapshot: 0},
  60. 2,
  61. },
  62. }
  63. for i, tt := range tests {
  64. tt.p.becomeProbe()
  65. if tt.p.State != ProgressStateProbe {
  66. t.Errorf("#%d: state = %s, want %s", i, tt.p.State, ProgressStateProbe)
  67. }
  68. if tt.p.Match != match {
  69. t.Errorf("#%d: match = %d, want %d", i, tt.p.Match, match)
  70. }
  71. if tt.p.Next != tt.wnext {
  72. t.Errorf("#%d: next = %d, want %d", i, tt.p.Next, tt.wnext)
  73. }
  74. }
  75. }
  76. func TestBecomeReplicate(t *testing.T) {
  77. p := &Progress{State: ProgressStateProbe, Match: 1, Next: 5}
  78. p.becomeReplicate()
  79. if p.State != ProgressStateReplicate {
  80. t.Errorf("state = %s, want %s", p.State, ProgressStateReplicate)
  81. }
  82. if p.Match != 1 {
  83. t.Errorf("match = %d, want 1", p.Match)
  84. }
  85. if w := p.Match + 1; p.Next != w {
  86. t.Errorf("next = %d, want %d", p.Next, w)
  87. }
  88. }
  89. func TestBecomeSnapshot(t *testing.T) {
  90. p := &Progress{State: ProgressStateProbe, Match: 1, Next: 5}
  91. p.becomeSnapshot(10)
  92. if p.State != ProgressStateSnapshot {
  93. t.Errorf("state = %s, want %s", p.State, ProgressStateSnapshot)
  94. }
  95. if p.Match != 1 {
  96. t.Errorf("match = %d, want 1", p.Match)
  97. }
  98. if p.PendingSnapshot != 10 {
  99. t.Errorf("pendingSnapshot = %d, want 10", p.PendingSnapshot)
  100. }
  101. }
  102. func TestProgressUpdate(t *testing.T) {
  103. prevM, prevN := uint64(3), uint64(5)
  104. tests := []struct {
  105. update uint64
  106. wm uint64
  107. wn uint64
  108. wok bool
  109. }{
  110. {prevM - 1, prevM, prevN, false}, // do not decrease match, next
  111. {prevM, prevM, prevN, false}, // do not decrease next
  112. {prevM + 1, prevM + 1, prevN, true}, // increase match, do not decrease next
  113. {prevM + 2, prevM + 2, prevN + 1, true}, // increase match, next
  114. }
  115. for i, tt := range tests {
  116. p := &Progress{
  117. Match: prevM,
  118. Next: prevN,
  119. }
  120. ok := p.maybeUpdate(tt.update)
  121. if ok != tt.wok {
  122. t.Errorf("#%d: ok= %v, want %v", i, ok, tt.wok)
  123. }
  124. if p.Match != tt.wm {
  125. t.Errorf("#%d: match= %d, want %d", i, p.Match, tt.wm)
  126. }
  127. if p.Next != tt.wn {
  128. t.Errorf("#%d: next= %d, want %d", i, p.Next, tt.wn)
  129. }
  130. }
  131. }
  132. func TestProgressMaybeDecr(t *testing.T) {
  133. tests := []struct {
  134. state ProgressStateType
  135. m uint64
  136. n uint64
  137. rejected uint64
  138. last uint64
  139. w bool
  140. wn uint64
  141. }{
  142. {
  143. // state replicate and rejected is not greater than match
  144. ProgressStateReplicate, 5, 10, 5, 5, false, 10,
  145. },
  146. {
  147. // state replicate and rejected is not greater than match
  148. ProgressStateReplicate, 5, 10, 4, 4, false, 10,
  149. },
  150. {
  151. // state replicate and rejected is greater than match
  152. // directly decrease to match+1
  153. ProgressStateReplicate, 5, 10, 9, 9, true, 6,
  154. },
  155. {
  156. // next-1 != rejected is always false
  157. ProgressStateProbe, 0, 0, 0, 0, false, 0,
  158. },
  159. {
  160. // next-1 != rejected is always false
  161. ProgressStateProbe, 0, 10, 5, 5, false, 10,
  162. },
  163. {
  164. // next>1 = decremented by 1
  165. ProgressStateProbe, 0, 10, 9, 9, true, 9,
  166. },
  167. {
  168. // next>1 = decremented by 1
  169. ProgressStateProbe, 0, 2, 1, 1, true, 1,
  170. },
  171. {
  172. // next<=1 = reset to 1
  173. ProgressStateProbe, 0, 1, 0, 0, true, 1,
  174. },
  175. {
  176. // decrease to min(rejected, last+1)
  177. ProgressStateProbe, 0, 10, 9, 2, true, 3,
  178. },
  179. {
  180. // rejected < 1, reset to 1
  181. ProgressStateProbe, 0, 10, 9, 0, true, 1,
  182. },
  183. }
  184. for i, tt := range tests {
  185. p := &Progress{
  186. State: tt.state,
  187. Match: tt.m,
  188. Next: tt.n,
  189. }
  190. if g := p.maybeDecrTo(tt.rejected, tt.last); g != tt.w {
  191. t.Errorf("#%d: maybeDecrTo= %t, want %t", i, g, tt.w)
  192. }
  193. if gm := p.Match; gm != tt.m {
  194. t.Errorf("#%d: match= %d, want %d", i, gm, tt.m)
  195. }
  196. if gn := p.Next; gn != tt.wn {
  197. t.Errorf("#%d: next= %d, want %d", i, gn, tt.wn)
  198. }
  199. }
  200. }
  201. func TestProgressIsPaused(t *testing.T) {
  202. tests := []struct {
  203. state ProgressStateType
  204. paused bool
  205. w bool
  206. }{
  207. {ProgressStateProbe, false, false},
  208. {ProgressStateProbe, true, true},
  209. {ProgressStateReplicate, false, false},
  210. {ProgressStateReplicate, true, false},
  211. {ProgressStateSnapshot, false, true},
  212. {ProgressStateSnapshot, true, true},
  213. }
  214. for i, tt := range tests {
  215. p := &Progress{
  216. State: tt.state,
  217. Paused: tt.paused,
  218. }
  219. if g := p.isPaused(); g != tt.w {
  220. t.Errorf("#%d: shouldwait = %t, want %t", i, g, tt.w)
  221. }
  222. }
  223. }
  224. // TestProgressResume ensures that progress.maybeUpdate and progress.maybeDecrTo
  225. // will reset progress.paused.
  226. func TestProgressResume(t *testing.T) {
  227. p := &Progress{
  228. Next: 2,
  229. Paused: true,
  230. }
  231. p.maybeDecrTo(1, 1)
  232. if p.Paused != false {
  233. t.Errorf("paused= %v, want false", p.Paused)
  234. }
  235. p.Paused = true
  236. p.maybeUpdate(2)
  237. if p.Paused != false {
  238. t.Errorf("paused= %v, want false", p.Paused)
  239. }
  240. }
  241. // TestProgressResumeByHeartbeat ensures raft.heartbeat reset progress.paused by heartbeat.
  242. func TestProgressResumeByHeartbeat(t *testing.T) {
  243. r := newRaft(1, []uint64{1, 2}, 5, 1, NewMemoryStorage(), 0)
  244. r.becomeCandidate()
  245. r.becomeLeader()
  246. r.prs[2].Paused = true
  247. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  248. if r.prs[2].Paused != false {
  249. t.Errorf("paused = %v, want false", r.prs[2].Paused)
  250. }
  251. }
  252. func TestProgressPaused(t *testing.T) {
  253. r := newRaft(1, []uint64{1, 2}, 5, 1, NewMemoryStorage(), 0)
  254. r.becomeCandidate()
  255. r.becomeLeader()
  256. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  257. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  258. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  259. ms := r.readMessages()
  260. if len(ms) != 1 {
  261. t.Errorf("len(ms) = %d, want 1", len(ms))
  262. }
  263. }
  264. func TestLeaderElection(t *testing.T) {
  265. tests := []struct {
  266. *network
  267. state StateType
  268. }{
  269. {newNetwork(nil, nil, nil), StateLeader},
  270. {newNetwork(nil, nil, nopStepper), StateLeader},
  271. {newNetwork(nil, nopStepper, nopStepper), StateCandidate},
  272. {newNetwork(nil, nopStepper, nopStepper, nil), StateCandidate},
  273. {newNetwork(nil, nopStepper, nopStepper, nil, nil), StateLeader},
  274. // three logs further along than 0
  275. {newNetwork(nil, ents(1), ents(2), ents(1, 3), nil), StateFollower},
  276. // logs converge
  277. {newNetwork(ents(1), nil, ents(2), ents(1), nil), StateLeader},
  278. }
  279. for i, tt := range tests {
  280. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  281. sm := tt.network.peers[1].(*raft)
  282. if sm.state != tt.state {
  283. t.Errorf("#%d: state = %s, want %s", i, sm.state, tt.state)
  284. }
  285. if g := sm.Term; g != 1 {
  286. t.Errorf("#%d: term = %d, want %d", i, g, 1)
  287. }
  288. }
  289. }
  290. func TestLogReplication(t *testing.T) {
  291. tests := []struct {
  292. *network
  293. msgs []pb.Message
  294. wcommitted uint64
  295. }{
  296. {
  297. newNetwork(nil, nil, nil),
  298. []pb.Message{
  299. {From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}},
  300. },
  301. 2,
  302. },
  303. {
  304. newNetwork(nil, nil, nil),
  305. []pb.Message{
  306. {From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}},
  307. {From: 1, To: 2, Type: pb.MsgHup},
  308. {From: 1, To: 2, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}},
  309. },
  310. 4,
  311. },
  312. }
  313. for i, tt := range tests {
  314. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  315. for _, m := range tt.msgs {
  316. tt.send(m)
  317. }
  318. for j, x := range tt.network.peers {
  319. sm := x.(*raft)
  320. if sm.raftLog.committed != tt.wcommitted {
  321. t.Errorf("#%d.%d: committed = %d, want %d", i, j, sm.raftLog.committed, tt.wcommitted)
  322. }
  323. ents := []pb.Entry{}
  324. for _, e := range nextEnts(sm, tt.network.storage[j]) {
  325. if e.Data != nil {
  326. ents = append(ents, e)
  327. }
  328. }
  329. props := []pb.Message{}
  330. for _, m := range tt.msgs {
  331. if m.Type == pb.MsgProp {
  332. props = append(props, m)
  333. }
  334. }
  335. for k, m := range props {
  336. if !bytes.Equal(ents[k].Data, m.Entries[0].Data) {
  337. t.Errorf("#%d.%d: data = %d, want %d", i, j, ents[k].Data, m.Entries[0].Data)
  338. }
  339. }
  340. }
  341. }
  342. }
  343. func TestSingleNodeCommit(t *testing.T) {
  344. tt := newNetwork(nil)
  345. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  346. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  347. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  348. sm := tt.peers[1].(*raft)
  349. if sm.raftLog.committed != 3 {
  350. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 3)
  351. }
  352. }
  353. // TestCannotCommitWithoutNewTermEntry tests the entries cannot be committed
  354. // when leader changes, no new proposal comes in and ChangeTerm proposal is
  355. // filtered.
  356. func TestCannotCommitWithoutNewTermEntry(t *testing.T) {
  357. tt := newNetwork(nil, nil, nil, nil, nil)
  358. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  359. // 0 cannot reach 2,3,4
  360. tt.cut(1, 3)
  361. tt.cut(1, 4)
  362. tt.cut(1, 5)
  363. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  364. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  365. sm := tt.peers[1].(*raft)
  366. if sm.raftLog.committed != 1 {
  367. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 1)
  368. }
  369. // network recovery
  370. tt.recover()
  371. // avoid committing ChangeTerm proposal
  372. tt.ignore(pb.MsgApp)
  373. // elect 2 as the new leader with term 2
  374. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  375. // no log entries from previous term should be committed
  376. sm = tt.peers[2].(*raft)
  377. if sm.raftLog.committed != 1 {
  378. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 1)
  379. }
  380. tt.recover()
  381. // send heartbeat; reset wait
  382. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgBeat})
  383. // append an entry at current term
  384. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  385. // expect the committed to be advanced
  386. if sm.raftLog.committed != 5 {
  387. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 5)
  388. }
  389. }
  390. // TestCommitWithoutNewTermEntry tests the entries could be committed
  391. // when leader changes, no new proposal comes in.
  392. func TestCommitWithoutNewTermEntry(t *testing.T) {
  393. tt := newNetwork(nil, nil, nil, nil, nil)
  394. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  395. // 0 cannot reach 2,3,4
  396. tt.cut(1, 3)
  397. tt.cut(1, 4)
  398. tt.cut(1, 5)
  399. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  400. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  401. sm := tt.peers[1].(*raft)
  402. if sm.raftLog.committed != 1 {
  403. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 1)
  404. }
  405. // network recovery
  406. tt.recover()
  407. // elect 1 as the new leader with term 2
  408. // after append a ChangeTerm entry from the current term, all entries
  409. // should be committed
  410. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  411. if sm.raftLog.committed != 4 {
  412. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 4)
  413. }
  414. }
  415. func TestDuelingCandidates(t *testing.T) {
  416. a := newRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage(), 0)
  417. b := newRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage(), 0)
  418. c := newRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage(), 0)
  419. nt := newNetwork(a, b, c)
  420. nt.cut(1, 3)
  421. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  422. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  423. nt.recover()
  424. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  425. wlog := &raftLog{
  426. storage: &MemoryStorage{ents: []pb.Entry{{}, pb.Entry{Data: nil, Term: 1, Index: 1}}},
  427. committed: 1,
  428. unstable: unstable{offset: 2},
  429. }
  430. tests := []struct {
  431. sm *raft
  432. state StateType
  433. term uint64
  434. raftLog *raftLog
  435. }{
  436. {a, StateFollower, 2, wlog},
  437. {b, StateFollower, 2, wlog},
  438. {c, StateFollower, 2, newLog(NewMemoryStorage())},
  439. }
  440. for i, tt := range tests {
  441. if g := tt.sm.state; g != tt.state {
  442. t.Errorf("#%d: state = %s, want %s", i, g, tt.state)
  443. }
  444. if g := tt.sm.Term; g != tt.term {
  445. t.Errorf("#%d: term = %d, want %d", i, g, tt.term)
  446. }
  447. base := ltoa(tt.raftLog)
  448. if sm, ok := nt.peers[1+uint64(i)].(*raft); ok {
  449. l := ltoa(sm.raftLog)
  450. if g := diffu(base, l); g != "" {
  451. t.Errorf("#%d: diff:\n%s", i, g)
  452. }
  453. } else {
  454. t.Logf("#%d: empty log", i)
  455. }
  456. }
  457. }
  458. func TestCandidateConcede(t *testing.T) {
  459. tt := newNetwork(nil, nil, nil)
  460. tt.isolate(1)
  461. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  462. tt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  463. // heal the partition
  464. tt.recover()
  465. // send heartbeat; reset wait
  466. tt.send(pb.Message{From: 3, To: 3, Type: pb.MsgBeat})
  467. data := []byte("force follower")
  468. // send a proposal to 3 to flush out a MsgApp to 1
  469. tt.send(pb.Message{From: 3, To: 3, Type: pb.MsgProp, Entries: []pb.Entry{{Data: data}}})
  470. // send heartbeat; flush out commit
  471. tt.send(pb.Message{From: 3, To: 3, Type: pb.MsgBeat})
  472. a := tt.peers[1].(*raft)
  473. if g := a.state; g != StateFollower {
  474. t.Errorf("state = %s, want %s", g, StateFollower)
  475. }
  476. if g := a.Term; g != 1 {
  477. t.Errorf("term = %d, want %d", g, 1)
  478. }
  479. wantLog := ltoa(&raftLog{
  480. storage: &MemoryStorage{
  481. ents: []pb.Entry{{}, {Data: nil, Term: 1, Index: 1}, {Term: 1, Index: 2, Data: data}},
  482. },
  483. unstable: unstable{offset: 3},
  484. committed: 2,
  485. })
  486. for i, p := range tt.peers {
  487. if sm, ok := p.(*raft); ok {
  488. l := ltoa(sm.raftLog)
  489. if g := diffu(wantLog, l); g != "" {
  490. t.Errorf("#%d: diff:\n%s", i, g)
  491. }
  492. } else {
  493. t.Logf("#%d: empty log", i)
  494. }
  495. }
  496. }
  497. func TestSingleNodeCandidate(t *testing.T) {
  498. tt := newNetwork(nil)
  499. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  500. sm := tt.peers[1].(*raft)
  501. if sm.state != StateLeader {
  502. t.Errorf("state = %d, want %d", sm.state, StateLeader)
  503. }
  504. }
  505. func TestOldMessages(t *testing.T) {
  506. tt := newNetwork(nil, nil, nil)
  507. // make 0 leader @ term 3
  508. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  509. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  510. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  511. // pretend we're an old leader trying to make progress; this entry is expected to be ignored.
  512. tt.send(pb.Message{From: 2, To: 1, Type: pb.MsgApp, Term: 2, Entries: []pb.Entry{{Index: 3, Term: 2}}})
  513. // commit a new entry
  514. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  515. ilog := &raftLog{
  516. storage: &MemoryStorage{
  517. ents: []pb.Entry{
  518. {}, {Data: nil, Term: 1, Index: 1},
  519. {Data: nil, Term: 2, Index: 2}, {Data: nil, Term: 3, Index: 3},
  520. {Data: []byte("somedata"), Term: 3, Index: 4},
  521. },
  522. },
  523. unstable: unstable{offset: 5},
  524. committed: 4,
  525. }
  526. base := ltoa(ilog)
  527. for i, p := range tt.peers {
  528. if sm, ok := p.(*raft); ok {
  529. l := ltoa(sm.raftLog)
  530. if g := diffu(base, l); g != "" {
  531. t.Errorf("#%d: diff:\n%s", i, g)
  532. }
  533. } else {
  534. t.Logf("#%d: empty log", i)
  535. }
  536. }
  537. }
  538. // TestOldMessagesReply - optimization - reply with new term.
  539. func TestProposal(t *testing.T) {
  540. tests := []struct {
  541. *network
  542. success bool
  543. }{
  544. {newNetwork(nil, nil, nil), true},
  545. {newNetwork(nil, nil, nopStepper), true},
  546. {newNetwork(nil, nopStepper, nopStepper), false},
  547. {newNetwork(nil, nopStepper, nopStepper, nil), false},
  548. {newNetwork(nil, nopStepper, nopStepper, nil, nil), true},
  549. }
  550. for j, tt := range tests {
  551. send := func(m pb.Message) {
  552. defer func() {
  553. // only recover is we expect it to panic so
  554. // panics we don't expect go up.
  555. if !tt.success {
  556. e := recover()
  557. if e != nil {
  558. t.Logf("#%d: err: %s", j, e)
  559. }
  560. }
  561. }()
  562. tt.send(m)
  563. }
  564. data := []byte("somedata")
  565. // promote 0 the leader
  566. send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  567. send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: data}}})
  568. wantLog := newLog(NewMemoryStorage())
  569. if tt.success {
  570. wantLog = &raftLog{
  571. storage: &MemoryStorage{
  572. ents: []pb.Entry{{}, {Data: nil, Term: 1, Index: 1}, {Term: 1, Index: 2, Data: data}},
  573. },
  574. unstable: unstable{offset: 3},
  575. committed: 2}
  576. }
  577. base := ltoa(wantLog)
  578. for i, p := range tt.peers {
  579. if sm, ok := p.(*raft); ok {
  580. l := ltoa(sm.raftLog)
  581. if g := diffu(base, l); g != "" {
  582. t.Errorf("#%d: diff:\n%s", i, g)
  583. }
  584. } else {
  585. t.Logf("#%d: empty log", i)
  586. }
  587. }
  588. sm := tt.network.peers[1].(*raft)
  589. if g := sm.Term; g != 1 {
  590. t.Errorf("#%d: term = %d, want %d", j, g, 1)
  591. }
  592. }
  593. }
  594. func TestProposalByProxy(t *testing.T) {
  595. data := []byte("somedata")
  596. tests := []*network{
  597. newNetwork(nil, nil, nil),
  598. newNetwork(nil, nil, nopStepper),
  599. }
  600. for j, tt := range tests {
  601. // promote 0 the leader
  602. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  603. // propose via follower
  604. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  605. wantLog := &raftLog{
  606. storage: &MemoryStorage{
  607. ents: []pb.Entry{{}, {Data: nil, Term: 1, Index: 1}, {Term: 1, Data: data, Index: 2}},
  608. },
  609. unstable: unstable{offset: 3},
  610. committed: 2}
  611. base := ltoa(wantLog)
  612. for i, p := range tt.peers {
  613. if sm, ok := p.(*raft); ok {
  614. l := ltoa(sm.raftLog)
  615. if g := diffu(base, l); g != "" {
  616. t.Errorf("#%d: diff:\n%s", i, g)
  617. }
  618. } else {
  619. t.Logf("#%d: empty log", i)
  620. }
  621. }
  622. sm := tt.peers[1].(*raft)
  623. if g := sm.Term; g != 1 {
  624. t.Errorf("#%d: term = %d, want %d", j, g, 1)
  625. }
  626. }
  627. }
  628. func TestCommit(t *testing.T) {
  629. tests := []struct {
  630. matches []uint64
  631. logs []pb.Entry
  632. smTerm uint64
  633. w uint64
  634. }{
  635. // single
  636. {[]uint64{1}, []pb.Entry{{Index: 1, Term: 1}}, 1, 1},
  637. {[]uint64{1}, []pb.Entry{{Index: 1, Term: 1}}, 2, 0},
  638. {[]uint64{2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 2, 2},
  639. {[]uint64{1}, []pb.Entry{{Index: 1, Term: 2}}, 2, 1},
  640. // odd
  641. {[]uint64{2, 1, 1}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 1, 1},
  642. {[]uint64{2, 1, 1}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}}, 2, 0},
  643. {[]uint64{2, 1, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 2, 2},
  644. {[]uint64{2, 1, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}}, 2, 0},
  645. // even
  646. {[]uint64{2, 1, 1, 1}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 1, 1},
  647. {[]uint64{2, 1, 1, 1}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}}, 2, 0},
  648. {[]uint64{2, 1, 1, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 1, 1},
  649. {[]uint64{2, 1, 1, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}}, 2, 0},
  650. {[]uint64{2, 1, 2, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 2, 2},
  651. {[]uint64{2, 1, 2, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}}, 2, 0},
  652. }
  653. for i, tt := range tests {
  654. storage := NewMemoryStorage()
  655. storage.Append(tt.logs)
  656. storage.hardState = pb.HardState{Term: tt.smTerm}
  657. sm := newRaft(1, []uint64{1}, 5, 1, storage, 0)
  658. for j := 0; j < len(tt.matches); j++ {
  659. sm.setProgress(uint64(j)+1, tt.matches[j], tt.matches[j]+1)
  660. }
  661. sm.maybeCommit()
  662. if g := sm.raftLog.committed; g != tt.w {
  663. t.Errorf("#%d: committed = %d, want %d", i, g, tt.w)
  664. }
  665. }
  666. }
  667. func TestIsElectionTimeout(t *testing.T) {
  668. tests := []struct {
  669. elapse int
  670. wprobability float64
  671. round bool
  672. }{
  673. {5, 0, false},
  674. {13, 0.3, true},
  675. {15, 0.5, true},
  676. {18, 0.8, true},
  677. {20, 1, false},
  678. }
  679. for i, tt := range tests {
  680. sm := newRaft(1, []uint64{1}, 10, 1, NewMemoryStorage(), 0)
  681. sm.elapsed = tt.elapse
  682. c := 0
  683. for j := 0; j < 10000; j++ {
  684. if sm.isElectionTimeout() {
  685. c++
  686. }
  687. }
  688. got := float64(c) / 10000.0
  689. if tt.round {
  690. got = math.Floor(got*10+0.5) / 10.0
  691. }
  692. if got != tt.wprobability {
  693. t.Errorf("#%d: possibility = %v, want %v", i, got, tt.wprobability)
  694. }
  695. }
  696. }
  697. // ensure that the Step function ignores the message from old term and does not pass it to the
  698. // acutal stepX function.
  699. func TestStepIgnoreOldTermMsg(t *testing.T) {
  700. called := false
  701. fakeStep := func(r *raft, m pb.Message) {
  702. called = true
  703. }
  704. sm := newRaft(1, []uint64{1}, 10, 1, NewMemoryStorage(), 0)
  705. sm.step = fakeStep
  706. sm.Term = 2
  707. sm.Step(pb.Message{Type: pb.MsgApp, Term: sm.Term - 1})
  708. if called == true {
  709. t.Errorf("stepFunc called = %v , want %v", called, false)
  710. }
  711. }
  712. // TestHandleMsgApp ensures:
  713. // 1. Reply false if log doesn’t contain an entry at prevLogIndex whose term matches prevLogTerm.
  714. // 2. If an existing entry conflicts with a new one (same index but different terms),
  715. // delete the existing entry and all that follow it; append any new entries not already in the log.
  716. // 3. If leaderCommit > commitIndex, set commitIndex = min(leaderCommit, index of last new entry).
  717. func TestHandleMsgApp(t *testing.T) {
  718. tests := []struct {
  719. m pb.Message
  720. wIndex uint64
  721. wCommit uint64
  722. wReject bool
  723. }{
  724. // Ensure 1
  725. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 3, Index: 2, Commit: 3}, 2, 0, true}, // previous log mismatch
  726. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 3, Index: 3, Commit: 3}, 2, 0, true}, // previous log non-exist
  727. // Ensure 2
  728. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 1, Index: 1, Commit: 1}, 2, 1, false},
  729. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 0, Index: 0, Commit: 1, Entries: []pb.Entry{{Index: 1, Term: 2}}}, 1, 1, false},
  730. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 2, Index: 2, Commit: 3, Entries: []pb.Entry{{Index: 3, Term: 2}, {Index: 4, Term: 2}}}, 4, 3, false},
  731. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 2, Index: 2, Commit: 4, Entries: []pb.Entry{{Index: 3, Term: 2}}}, 3, 3, false},
  732. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 1, Index: 1, Commit: 4, Entries: []pb.Entry{{Index: 2, Term: 2}}}, 2, 2, false},
  733. // Ensure 3
  734. {pb.Message{Type: pb.MsgApp, Term: 1, LogTerm: 1, Index: 1, Commit: 3}, 2, 1, false}, // match entry 1, commit up to last new entry 1
  735. {pb.Message{Type: pb.MsgApp, Term: 1, LogTerm: 1, Index: 1, Commit: 3, Entries: []pb.Entry{{Index: 2, Term: 2}}}, 2, 2, false}, // match entry 1, commit up to last new entry 2
  736. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 2, Index: 2, Commit: 3}, 2, 2, false}, // match entry 2, commit up to last new entry 2
  737. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 2, Index: 2, Commit: 4}, 2, 2, false}, // commit up to log.last()
  738. }
  739. for i, tt := range tests {
  740. storage := NewMemoryStorage()
  741. storage.Append([]pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}})
  742. sm := newRaft(1, []uint64{1}, 10, 1, storage, 0)
  743. sm.becomeFollower(2, None)
  744. sm.handleAppendEntries(tt.m)
  745. if sm.raftLog.lastIndex() != tt.wIndex {
  746. t.Errorf("#%d: lastIndex = %d, want %d", i, sm.raftLog.lastIndex(), tt.wIndex)
  747. }
  748. if sm.raftLog.committed != tt.wCommit {
  749. t.Errorf("#%d: committed = %d, want %d", i, sm.raftLog.committed, tt.wCommit)
  750. }
  751. m := sm.readMessages()
  752. if len(m) != 1 {
  753. t.Fatalf("#%d: msg = nil, want 1", i)
  754. }
  755. if m[0].Reject != tt.wReject {
  756. t.Errorf("#%d: reject = %v, want %v", i, m[0].Reject, tt.wReject)
  757. }
  758. }
  759. }
  760. // TestHandleHeartbeat ensures that the follower commits to the commit in the message.
  761. func TestHandleHeartbeat(t *testing.T) {
  762. commit := uint64(2)
  763. tests := []struct {
  764. m pb.Message
  765. wCommit uint64
  766. }{
  767. {pb.Message{From: 2, To: 1, Type: pb.MsgApp, Term: 2, Commit: commit + 1}, commit + 1},
  768. {pb.Message{From: 2, To: 1, Type: pb.MsgApp, Term: 2, Commit: commit - 1}, commit}, // do not decrease commit
  769. }
  770. for i, tt := range tests {
  771. storage := NewMemoryStorage()
  772. storage.Append([]pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}, {Index: 3, Term: 3}})
  773. sm := newRaft(1, []uint64{1, 2}, 5, 1, storage, 0)
  774. sm.becomeFollower(2, 2)
  775. sm.raftLog.commitTo(commit)
  776. sm.handleHeartbeat(tt.m)
  777. if sm.raftLog.committed != tt.wCommit {
  778. t.Errorf("#%d: committed = %d, want %d", i, sm.raftLog.committed, tt.wCommit)
  779. }
  780. m := sm.readMessages()
  781. if len(m) != 1 {
  782. t.Fatalf("#%d: msg = nil, want 1", i)
  783. }
  784. if m[0].Type != pb.MsgHeartbeatResp {
  785. t.Errorf("#%d: type = %v, want MsgHeartbeatResp", i, m[0].Type)
  786. }
  787. }
  788. }
  789. // TestHandleHeartbeatResp ensures that we re-send log entries when we get a heartbeat response.
  790. func TestHandleHeartbeatResp(t *testing.T) {
  791. storage := NewMemoryStorage()
  792. storage.Append([]pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}, {Index: 3, Term: 3}})
  793. sm := newRaft(1, []uint64{1, 2}, 5, 1, storage, 0)
  794. sm.becomeCandidate()
  795. sm.becomeLeader()
  796. sm.raftLog.commitTo(sm.raftLog.lastIndex())
  797. // A heartbeat response from a node that is behind; re-send MsgApp
  798. sm.Step(pb.Message{From: 2, Type: pb.MsgHeartbeatResp})
  799. msgs := sm.readMessages()
  800. if len(msgs) != 1 {
  801. t.Fatalf("len(msgs) = %d, want 1", len(msgs))
  802. }
  803. if msgs[0].Type != pb.MsgApp {
  804. t.Errorf("type = %v, want MsgApp", msgs[0].Type)
  805. }
  806. // A second heartbeat response with no AppResp does not re-send because we are in the wait state.
  807. sm.Step(pb.Message{From: 2, Type: pb.MsgHeartbeatResp})
  808. msgs = sm.readMessages()
  809. if len(msgs) != 0 {
  810. t.Fatalf("len(msgs) = %d, want 0", len(msgs))
  811. }
  812. // Send a heartbeat to reset the wait state; next heartbeat will re-send MsgApp.
  813. sm.bcastHeartbeat()
  814. sm.Step(pb.Message{From: 2, Type: pb.MsgHeartbeatResp})
  815. msgs = sm.readMessages()
  816. if len(msgs) != 2 {
  817. t.Fatalf("len(msgs) = %d, want 2", len(msgs))
  818. }
  819. if msgs[0].Type != pb.MsgHeartbeat {
  820. t.Errorf("type = %v, want MsgHeartbeat", msgs[0].Type)
  821. }
  822. if msgs[1].Type != pb.MsgApp {
  823. t.Errorf("type = %v, want MsgApp", msgs[1].Type)
  824. }
  825. // Once we have an MsgAppResp, heartbeats no longer send MsgApp.
  826. sm.Step(pb.Message{
  827. From: 2,
  828. Type: pb.MsgAppResp,
  829. Index: msgs[1].Index + uint64(len(msgs[1].Entries)),
  830. })
  831. // Consume the message sent in response to MsgAppResp
  832. sm.readMessages()
  833. sm.bcastHeartbeat() // reset wait state
  834. sm.Step(pb.Message{From: 2, Type: pb.MsgHeartbeatResp})
  835. msgs = sm.readMessages()
  836. if len(msgs) != 1 {
  837. t.Fatalf("len(msgs) = %d, want 1: %+v", len(msgs), msgs)
  838. }
  839. if msgs[0].Type != pb.MsgHeartbeat {
  840. t.Errorf("type = %v, want MsgHeartbeat", msgs[0].Type)
  841. }
  842. }
  843. // TestMsgAppRespWaitReset verifies the waitReset behavior of a leader
  844. // MsgAppResp.
  845. func TestMsgAppRespWaitReset(t *testing.T) {
  846. sm := newRaft(1, []uint64{1, 2, 3}, 5, 1, NewMemoryStorage(), 0)
  847. sm.becomeCandidate()
  848. sm.becomeLeader()
  849. // The new leader has just emitted a new Term 4 entry; consume those messages
  850. // from the outgoing queue.
  851. sm.bcastAppend()
  852. sm.readMessages()
  853. // Node 2 acks the first entry, making it committed.
  854. sm.Step(pb.Message{
  855. From: 2,
  856. Type: pb.MsgAppResp,
  857. Index: 1,
  858. })
  859. if sm.Commit != 1 {
  860. t.Fatalf("expected Commit to be 1, got %d", sm.Commit)
  861. }
  862. // Also consume the MsgApp messages that update Commit on the followers.
  863. sm.readMessages()
  864. // A new command is now proposed on node 1.
  865. sm.Step(pb.Message{
  866. From: 1,
  867. Type: pb.MsgProp,
  868. Entries: []pb.Entry{{}},
  869. })
  870. // The command is broadcast to all nodes not in the wait state.
  871. // Node 2 left the wait state due to its MsgAppResp, but node 3 is still waiting.
  872. msgs := sm.readMessages()
  873. if len(msgs) != 1 {
  874. t.Fatalf("expected 1 message, got %d: %+v", len(msgs), msgs)
  875. }
  876. if msgs[0].Type != pb.MsgApp || msgs[0].To != 2 {
  877. t.Errorf("expected MsgApp to node 2, got %s to %d", msgs[0].Type, msgs[0].To)
  878. }
  879. if len(msgs[0].Entries) != 1 || msgs[0].Entries[0].Index != 2 {
  880. t.Errorf("expected to send entry 2, but got %v", msgs[0].Entries)
  881. }
  882. // Now Node 3 acks the first entry. This releases the wait and entry 2 is sent.
  883. sm.Step(pb.Message{
  884. From: 3,
  885. Type: pb.MsgAppResp,
  886. Index: 1,
  887. })
  888. msgs = sm.readMessages()
  889. if len(msgs) != 1 {
  890. t.Fatalf("expected 1 message, got %d: %+v", len(msgs), msgs)
  891. }
  892. if msgs[0].Type != pb.MsgApp || msgs[0].To != 3 {
  893. t.Errorf("expected MsgApp to node 3, got %s to %d", msgs[0].Type, msgs[0].To)
  894. }
  895. if len(msgs[0].Entries) != 1 || msgs[0].Entries[0].Index != 2 {
  896. t.Errorf("expected to send entry 2, but got %v", msgs[0].Entries)
  897. }
  898. }
  899. func TestRecvMsgVote(t *testing.T) {
  900. tests := []struct {
  901. state StateType
  902. i, term uint64
  903. voteFor uint64
  904. wreject bool
  905. }{
  906. {StateFollower, 0, 0, None, true},
  907. {StateFollower, 0, 1, None, true},
  908. {StateFollower, 0, 2, None, true},
  909. {StateFollower, 0, 3, None, false},
  910. {StateFollower, 1, 0, None, true},
  911. {StateFollower, 1, 1, None, true},
  912. {StateFollower, 1, 2, None, true},
  913. {StateFollower, 1, 3, None, false},
  914. {StateFollower, 2, 0, None, true},
  915. {StateFollower, 2, 1, None, true},
  916. {StateFollower, 2, 2, None, false},
  917. {StateFollower, 2, 3, None, false},
  918. {StateFollower, 3, 0, None, true},
  919. {StateFollower, 3, 1, None, true},
  920. {StateFollower, 3, 2, None, false},
  921. {StateFollower, 3, 3, None, false},
  922. {StateFollower, 3, 2, 2, false},
  923. {StateFollower, 3, 2, 1, true},
  924. {StateLeader, 3, 3, 1, true},
  925. {StateCandidate, 3, 3, 1, true},
  926. }
  927. for i, tt := range tests {
  928. sm := newRaft(1, []uint64{1}, 10, 1, NewMemoryStorage(), 0)
  929. sm.state = tt.state
  930. switch tt.state {
  931. case StateFollower:
  932. sm.step = stepFollower
  933. case StateCandidate:
  934. sm.step = stepCandidate
  935. case StateLeader:
  936. sm.step = stepLeader
  937. }
  938. sm.HardState = pb.HardState{Vote: tt.voteFor}
  939. sm.raftLog = &raftLog{
  940. storage: &MemoryStorage{ents: []pb.Entry{{}, {Index: 1, Term: 2}, {Index: 2, Term: 2}}},
  941. unstable: unstable{offset: 3},
  942. }
  943. sm.Step(pb.Message{Type: pb.MsgVote, From: 2, Index: tt.i, LogTerm: tt.term})
  944. msgs := sm.readMessages()
  945. if g := len(msgs); g != 1 {
  946. t.Fatalf("#%d: len(msgs) = %d, want 1", i, g)
  947. continue
  948. }
  949. if g := msgs[0].Reject; g != tt.wreject {
  950. t.Errorf("#%d, m.Reject = %v, want %v", i, g, tt.wreject)
  951. }
  952. }
  953. }
  954. func TestStateTransition(t *testing.T) {
  955. tests := []struct {
  956. from StateType
  957. to StateType
  958. wallow bool
  959. wterm uint64
  960. wlead uint64
  961. }{
  962. {StateFollower, StateFollower, true, 1, None},
  963. {StateFollower, StateCandidate, true, 1, None},
  964. {StateFollower, StateLeader, false, 0, None},
  965. {StateCandidate, StateFollower, true, 0, None},
  966. {StateCandidate, StateCandidate, true, 1, None},
  967. {StateCandidate, StateLeader, true, 0, 1},
  968. {StateLeader, StateFollower, true, 1, None},
  969. {StateLeader, StateCandidate, false, 1, None},
  970. {StateLeader, StateLeader, true, 0, 1},
  971. }
  972. for i, tt := range tests {
  973. func() {
  974. defer func() {
  975. if r := recover(); r != nil {
  976. if tt.wallow == true {
  977. t.Errorf("%d: allow = %v, want %v", i, false, true)
  978. }
  979. }
  980. }()
  981. sm := newRaft(1, []uint64{1}, 10, 1, NewMemoryStorage(), 0)
  982. sm.state = tt.from
  983. switch tt.to {
  984. case StateFollower:
  985. sm.becomeFollower(tt.wterm, tt.wlead)
  986. case StateCandidate:
  987. sm.becomeCandidate()
  988. case StateLeader:
  989. sm.becomeLeader()
  990. }
  991. if sm.Term != tt.wterm {
  992. t.Errorf("%d: term = %d, want %d", i, sm.Term, tt.wterm)
  993. }
  994. if sm.lead != tt.wlead {
  995. t.Errorf("%d: lead = %d, want %d", i, sm.lead, tt.wlead)
  996. }
  997. }()
  998. }
  999. }
  1000. func TestAllServerStepdown(t *testing.T) {
  1001. tests := []struct {
  1002. state StateType
  1003. wstate StateType
  1004. wterm uint64
  1005. windex uint64
  1006. }{
  1007. {StateFollower, StateFollower, 3, 0},
  1008. {StateCandidate, StateFollower, 3, 0},
  1009. {StateLeader, StateFollower, 3, 1},
  1010. }
  1011. tmsgTypes := [...]pb.MessageType{pb.MsgVote, pb.MsgApp}
  1012. tterm := uint64(3)
  1013. for i, tt := range tests {
  1014. sm := newRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage(), 0)
  1015. switch tt.state {
  1016. case StateFollower:
  1017. sm.becomeFollower(1, None)
  1018. case StateCandidate:
  1019. sm.becomeCandidate()
  1020. case StateLeader:
  1021. sm.becomeCandidate()
  1022. sm.becomeLeader()
  1023. }
  1024. for j, msgType := range tmsgTypes {
  1025. sm.Step(pb.Message{From: 2, Type: msgType, Term: tterm, LogTerm: tterm})
  1026. if sm.state != tt.wstate {
  1027. t.Errorf("#%d.%d state = %v , want %v", i, j, sm.state, tt.wstate)
  1028. }
  1029. if sm.Term != tt.wterm {
  1030. t.Errorf("#%d.%d term = %v , want %v", i, j, sm.Term, tt.wterm)
  1031. }
  1032. if uint64(sm.raftLog.lastIndex()) != tt.windex {
  1033. t.Errorf("#%d.%d index = %v , want %v", i, j, sm.raftLog.lastIndex(), tt.windex)
  1034. }
  1035. if uint64(len(sm.raftLog.allEntries())) != tt.windex {
  1036. t.Errorf("#%d.%d len(ents) = %v , want %v", i, j, len(sm.raftLog.allEntries()), tt.windex)
  1037. }
  1038. wlead := uint64(2)
  1039. if msgType == pb.MsgVote {
  1040. wlead = None
  1041. }
  1042. if sm.lead != wlead {
  1043. t.Errorf("#%d, sm.lead = %d, want %d", i, sm.lead, None)
  1044. }
  1045. }
  1046. }
  1047. }
  1048. func TestLeaderAppResp(t *testing.T) {
  1049. // initial progress: match = 0; next = 3
  1050. tests := []struct {
  1051. index uint64
  1052. reject bool
  1053. // progress
  1054. wmatch uint64
  1055. wnext uint64
  1056. // message
  1057. wmsgNum int
  1058. windex uint64
  1059. wcommitted uint64
  1060. }{
  1061. {3, true, 0, 3, 0, 0, 0}, // stale resp; no replies
  1062. {2, true, 0, 2, 1, 1, 0}, // denied resp; leader does not commit; decrease next and send probing msg
  1063. {2, false, 2, 4, 2, 2, 2}, // accept resp; leader commits; broadcast with commit index
  1064. {0, false, 0, 3, 0, 0, 0}, // ignore heartbeat replies
  1065. }
  1066. for i, tt := range tests {
  1067. // sm term is 1 after it becomes the leader.
  1068. // thus the last log term must be 1 to be committed.
  1069. sm := newRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage(), 0)
  1070. sm.raftLog = &raftLog{
  1071. storage: &MemoryStorage{ents: []pb.Entry{{}, {Index: 1, Term: 0}, {Index: 2, Term: 1}}},
  1072. unstable: unstable{offset: 3},
  1073. }
  1074. sm.becomeCandidate()
  1075. sm.becomeLeader()
  1076. sm.readMessages()
  1077. sm.Step(pb.Message{From: 2, Type: pb.MsgAppResp, Index: tt.index, Term: sm.Term, Reject: tt.reject, RejectHint: tt.index})
  1078. p := sm.prs[2]
  1079. if p.Match != tt.wmatch {
  1080. t.Errorf("#%d match = %d, want %d", i, p.Match, tt.wmatch)
  1081. }
  1082. if p.Next != tt.wnext {
  1083. t.Errorf("#%d next = %d, want %d", i, p.Next, tt.wnext)
  1084. }
  1085. msgs := sm.readMessages()
  1086. if len(msgs) != tt.wmsgNum {
  1087. t.Errorf("#%d msgNum = %d, want %d", i, len(msgs), tt.wmsgNum)
  1088. }
  1089. for j, msg := range msgs {
  1090. if msg.Index != tt.windex {
  1091. t.Errorf("#%d.%d index = %d, want %d", i, j, msg.Index, tt.windex)
  1092. }
  1093. if msg.Commit != tt.wcommitted {
  1094. t.Errorf("#%d.%d commit = %d, want %d", i, j, msg.Commit, tt.wcommitted)
  1095. }
  1096. }
  1097. }
  1098. }
  1099. // When the leader receives a heartbeat tick, it should
  1100. // send a MsgApp with m.Index = 0, m.LogTerm=0 and empty entries.
  1101. func TestBcastBeat(t *testing.T) {
  1102. offset := uint64(1000)
  1103. // make a state machine with log.offset = 1000
  1104. s := pb.Snapshot{
  1105. Metadata: pb.SnapshotMetadata{
  1106. Index: offset,
  1107. Term: 1,
  1108. ConfState: pb.ConfState{Nodes: []uint64{1, 2, 3}},
  1109. },
  1110. }
  1111. storage := NewMemoryStorage()
  1112. storage.ApplySnapshot(s)
  1113. sm := newRaft(1, nil, 10, 1, storage, 0)
  1114. sm.Term = 1
  1115. sm.becomeCandidate()
  1116. sm.becomeLeader()
  1117. for i := 0; i < 10; i++ {
  1118. sm.appendEntry(pb.Entry{Index: uint64(i) + 1})
  1119. }
  1120. // slow follower
  1121. sm.prs[2].Match, sm.prs[2].Next = 5, 6
  1122. // normal follower
  1123. sm.prs[3].Match, sm.prs[3].Next = sm.raftLog.lastIndex(), sm.raftLog.lastIndex()+1
  1124. sm.Step(pb.Message{Type: pb.MsgBeat})
  1125. msgs := sm.readMessages()
  1126. if len(msgs) != 2 {
  1127. t.Fatalf("len(msgs) = %v, want 2", len(msgs))
  1128. }
  1129. wantCommitMap := map[uint64]uint64{
  1130. 2: min(sm.raftLog.committed, sm.prs[2].Match),
  1131. 3: min(sm.raftLog.committed, sm.prs[3].Match),
  1132. }
  1133. for i, m := range msgs {
  1134. if m.Type != pb.MsgHeartbeat {
  1135. t.Fatalf("#%d: type = %v, want = %v", i, m.Type, pb.MsgHeartbeat)
  1136. }
  1137. if m.Index != 0 {
  1138. t.Fatalf("#%d: prevIndex = %d, want %d", i, m.Index, 0)
  1139. }
  1140. if m.LogTerm != 0 {
  1141. t.Fatalf("#%d: prevTerm = %d, want %d", i, m.LogTerm, 0)
  1142. }
  1143. if wantCommitMap[m.To] == 0 {
  1144. t.Fatalf("#%d: unexpected to %d", i, m.To)
  1145. } else {
  1146. if m.Commit != wantCommitMap[m.To] {
  1147. t.Fatalf("#%d: commit = %d, want %d", i, m.Commit, wantCommitMap[m.To])
  1148. }
  1149. delete(wantCommitMap, m.To)
  1150. }
  1151. if len(m.Entries) != 0 {
  1152. t.Fatalf("#%d: len(entries) = %d, want 0", i, len(m.Entries))
  1153. }
  1154. }
  1155. }
  1156. // tests the output of the statemachine when receiving MsgBeat
  1157. func TestRecvMsgBeat(t *testing.T) {
  1158. tests := []struct {
  1159. state StateType
  1160. wMsg int
  1161. }{
  1162. {StateLeader, 2},
  1163. // candidate and follower should ignore MsgBeat
  1164. {StateCandidate, 0},
  1165. {StateFollower, 0},
  1166. }
  1167. for i, tt := range tests {
  1168. sm := newRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage(), 0)
  1169. sm.raftLog = &raftLog{storage: &MemoryStorage{ents: []pb.Entry{{}, {Index: 1, Term: 0}, {Index: 2, Term: 1}}}}
  1170. sm.Term = 1
  1171. sm.state = tt.state
  1172. switch tt.state {
  1173. case StateFollower:
  1174. sm.step = stepFollower
  1175. case StateCandidate:
  1176. sm.step = stepCandidate
  1177. case StateLeader:
  1178. sm.step = stepLeader
  1179. }
  1180. sm.Step(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  1181. msgs := sm.readMessages()
  1182. if len(msgs) != tt.wMsg {
  1183. t.Errorf("%d: len(msgs) = %d, want %d", i, len(msgs), tt.wMsg)
  1184. }
  1185. for _, m := range msgs {
  1186. if m.Type != pb.MsgHeartbeat {
  1187. t.Errorf("%d: msg.type = %v, want %v", i, m.Type, pb.MsgHeartbeat)
  1188. }
  1189. }
  1190. }
  1191. }
  1192. func TestLeaderIncreaseNext(t *testing.T) {
  1193. previousEnts := []pb.Entry{{Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3}}
  1194. tests := []struct {
  1195. // progress
  1196. state ProgressStateType
  1197. next uint64
  1198. wnext uint64
  1199. }{
  1200. // state replicate, optimistically increase next
  1201. // previous entries + noop entry + propose + 1
  1202. {ProgressStateReplicate, 2, uint64(len(previousEnts) + 1 + 1 + 1)},
  1203. // state probe, not optimistically increase next
  1204. {ProgressStateProbe, 2, 2},
  1205. }
  1206. for i, tt := range tests {
  1207. sm := newRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage(), 0)
  1208. sm.raftLog.append(previousEnts...)
  1209. sm.becomeCandidate()
  1210. sm.becomeLeader()
  1211. sm.prs[2].State = tt.state
  1212. sm.prs[2].Next = tt.next
  1213. sm.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  1214. p := sm.prs[2]
  1215. if p.Next != tt.wnext {
  1216. t.Errorf("#%d next = %d, want %d", i, p.Next, tt.wnext)
  1217. }
  1218. }
  1219. }
  1220. func TestSendAppendForProgressProbe(t *testing.T) {
  1221. r := newRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage(), 0)
  1222. r.becomeCandidate()
  1223. r.becomeLeader()
  1224. r.readMessages()
  1225. r.prs[2].becomeProbe()
  1226. // each round is a heartbeat
  1227. for i := 0; i < 3; i++ {
  1228. // we expect that raft will only send out one msgAPP per heartbeat timeout
  1229. r.appendEntry(pb.Entry{Data: []byte("somedata")})
  1230. r.sendAppend(2)
  1231. msg := r.readMessages()
  1232. if len(msg) != 1 {
  1233. t.Errorf("len(msg) = %d, want %d", len(msg), 1)
  1234. }
  1235. if msg[0].Index != 0 {
  1236. t.Errorf("index = %d, want %d", msg[0].Index, 0)
  1237. }
  1238. if r.prs[2].Paused != true {
  1239. t.Errorf("paused = %v, want true", r.prs[2].Paused)
  1240. }
  1241. for j := 0; j < 10; j++ {
  1242. r.appendEntry(pb.Entry{Data: []byte("somedata")})
  1243. r.sendAppend(2)
  1244. if l := len(r.readMessages()); l != 0 {
  1245. t.Errorf("len(msg) = %d, want %d", l, 0)
  1246. }
  1247. }
  1248. // do a heartbeat
  1249. for j := 0; j < r.heartbeatTimeout; j++ {
  1250. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  1251. }
  1252. // consume the heartbeat
  1253. msg = r.readMessages()
  1254. if len(msg) != 1 {
  1255. t.Errorf("len(msg) = %d, want %d", len(msg), 1)
  1256. }
  1257. if msg[0].Type != pb.MsgHeartbeat {
  1258. t.Errorf("type = %s, want %s", msg[0].Type, pb.MsgHeartbeat)
  1259. }
  1260. }
  1261. }
  1262. func TestSendAppendForProgressReplicate(t *testing.T) {
  1263. r := newRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage(), 0)
  1264. r.becomeCandidate()
  1265. r.becomeLeader()
  1266. r.readMessages()
  1267. r.prs[2].becomeReplicate()
  1268. for i := 0; i < 10; i++ {
  1269. r.appendEntry(pb.Entry{Data: []byte("somedata")})
  1270. r.sendAppend(2)
  1271. msgs := r.readMessages()
  1272. if len(msgs) != 1 {
  1273. t.Errorf("len(msg) = %d, want %d", len(msgs), 1)
  1274. }
  1275. }
  1276. }
  1277. func TestSendAppendForProgressSnapshot(t *testing.T) {
  1278. r := newRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage(), 0)
  1279. r.becomeCandidate()
  1280. r.becomeLeader()
  1281. r.readMessages()
  1282. r.prs[2].becomeSnapshot(10)
  1283. for i := 0; i < 10; i++ {
  1284. r.appendEntry(pb.Entry{Data: []byte("somedata")})
  1285. r.sendAppend(2)
  1286. msgs := r.readMessages()
  1287. if len(msgs) != 0 {
  1288. t.Errorf("len(msg) = %d, want %d", len(msgs), 0)
  1289. }
  1290. }
  1291. }
  1292. func TestRecvMsgUnreachable(t *testing.T) {
  1293. previousEnts := []pb.Entry{{Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3}}
  1294. s := NewMemoryStorage()
  1295. s.Append(previousEnts)
  1296. r := newRaft(1, []uint64{1, 2}, 10, 1, s, 0)
  1297. r.becomeCandidate()
  1298. r.becomeLeader()
  1299. r.readMessages()
  1300. // set node 2 to state replicate
  1301. r.prs[2].Match = 3
  1302. r.prs[2].becomeReplicate()
  1303. r.prs[2].optimisticUpdate(5)
  1304. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgUnreachable})
  1305. if r.prs[2].State != ProgressStateProbe {
  1306. t.Errorf("state = %s, want %s", r.prs[2].State, ProgressStateProbe)
  1307. }
  1308. if wnext := r.prs[2].Match + 1; r.prs[2].Next != wnext {
  1309. t.Errorf("next = %d, want %d", r.prs[2].Next, wnext)
  1310. }
  1311. }
  1312. func TestRestore(t *testing.T) {
  1313. s := pb.Snapshot{
  1314. Metadata: pb.SnapshotMetadata{
  1315. Index: 11, // magic number
  1316. Term: 11, // magic number
  1317. ConfState: pb.ConfState{Nodes: []uint64{1, 2, 3}},
  1318. },
  1319. }
  1320. storage := NewMemoryStorage()
  1321. sm := newRaft(1, []uint64{1, 2}, 10, 1, storage, 0)
  1322. if ok := sm.restore(s); !ok {
  1323. t.Fatal("restore fail, want succeed")
  1324. }
  1325. if sm.raftLog.lastIndex() != s.Metadata.Index {
  1326. t.Errorf("log.lastIndex = %d, want %d", sm.raftLog.lastIndex(), s.Metadata.Index)
  1327. }
  1328. if sm.raftLog.term(s.Metadata.Index) != s.Metadata.Term {
  1329. t.Errorf("log.lastTerm = %d, want %d", sm.raftLog.term(s.Metadata.Index), s.Metadata.Term)
  1330. }
  1331. sg := sm.nodes()
  1332. if !reflect.DeepEqual(sg, s.Metadata.ConfState.Nodes) {
  1333. t.Errorf("sm.Nodes = %+v, want %+v", sg, s.Metadata.ConfState.Nodes)
  1334. }
  1335. if ok := sm.restore(s); ok {
  1336. t.Fatal("restore succeed, want fail")
  1337. }
  1338. }
  1339. func TestRestoreIgnoreSnapshot(t *testing.T) {
  1340. previousEnts := []pb.Entry{{Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3}}
  1341. commit := uint64(1)
  1342. storage := NewMemoryStorage()
  1343. sm := newRaft(1, []uint64{1, 2}, 10, 1, storage, 0)
  1344. sm.raftLog.append(previousEnts...)
  1345. sm.raftLog.commitTo(commit)
  1346. s := pb.Snapshot{
  1347. Metadata: pb.SnapshotMetadata{
  1348. Index: commit,
  1349. Term: 1,
  1350. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  1351. },
  1352. }
  1353. // ignore snapshot
  1354. if ok := sm.restore(s); ok {
  1355. t.Errorf("restore = %t, want %t", ok, false)
  1356. }
  1357. if sm.raftLog.committed != commit {
  1358. t.Errorf("commit = %d, want %d", sm.raftLog.committed, commit)
  1359. }
  1360. // ignore snapshot and fast forward commit
  1361. s.Metadata.Index = commit + 1
  1362. if ok := sm.restore(s); ok {
  1363. t.Errorf("restore = %t, want %t", ok, false)
  1364. }
  1365. if sm.raftLog.committed != commit+1 {
  1366. t.Errorf("commit = %d, want %d", sm.raftLog.committed, commit+1)
  1367. }
  1368. }
  1369. func TestProvideSnap(t *testing.T) {
  1370. // restore the statemachin from a snapshot
  1371. // so it has a compacted log and a snapshot
  1372. s := pb.Snapshot{
  1373. Metadata: pb.SnapshotMetadata{
  1374. Index: 11, // magic number
  1375. Term: 11, // magic number
  1376. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  1377. },
  1378. }
  1379. storage := NewMemoryStorage()
  1380. sm := newRaft(1, []uint64{1}, 10, 1, storage, 0)
  1381. sm.restore(s)
  1382. sm.becomeCandidate()
  1383. sm.becomeLeader()
  1384. // force set the next of node 1, so that
  1385. // node 1 needs a snapshot
  1386. sm.prs[2].Next = sm.raftLog.firstIndex()
  1387. sm.Step(pb.Message{From: 2, To: 1, Type: pb.MsgAppResp, Index: sm.prs[2].Next - 1, Reject: true})
  1388. msgs := sm.readMessages()
  1389. if len(msgs) != 1 {
  1390. t.Fatalf("len(msgs) = %d, want 1", len(msgs))
  1391. }
  1392. m := msgs[0]
  1393. if m.Type != pb.MsgSnap {
  1394. t.Errorf("m.Type = %v, want %v", m.Type, pb.MsgSnap)
  1395. }
  1396. }
  1397. func TestRestoreFromSnapMsg(t *testing.T) {
  1398. s := pb.Snapshot{
  1399. Metadata: pb.SnapshotMetadata{
  1400. Index: 11, // magic number
  1401. Term: 11, // magic number
  1402. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  1403. },
  1404. }
  1405. m := pb.Message{Type: pb.MsgSnap, From: 1, Term: 2, Snapshot: s}
  1406. sm := newRaft(2, []uint64{1, 2}, 10, 1, NewMemoryStorage(), 0)
  1407. sm.Step(m)
  1408. // TODO(bdarnell): what should this test?
  1409. }
  1410. func TestSlowNodeRestore(t *testing.T) {
  1411. nt := newNetwork(nil, nil, nil)
  1412. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1413. nt.isolate(3)
  1414. for j := 0; j <= 100; j++ {
  1415. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  1416. }
  1417. lead := nt.peers[1].(*raft)
  1418. nextEnts(lead, nt.storage[1])
  1419. nt.storage[1].CreateSnapshot(lead.raftLog.applied, &pb.ConfState{Nodes: lead.nodes()}, nil)
  1420. nt.storage[1].Compact(lead.raftLog.applied)
  1421. nt.recover()
  1422. // trigger a snapshot
  1423. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  1424. follower := nt.peers[3].(*raft)
  1425. // trigger a commit
  1426. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  1427. if follower.raftLog.committed != lead.raftLog.committed {
  1428. t.Errorf("follower.committed = %d, want %d", follower.raftLog.committed, lead.raftLog.committed)
  1429. }
  1430. }
  1431. // TestStepConfig tests that when raft step msgProp in EntryConfChange type,
  1432. // it appends the entry to log and sets pendingConf to be true.
  1433. func TestStepConfig(t *testing.T) {
  1434. // a raft that cannot make progress
  1435. r := newRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage(), 0)
  1436. r.becomeCandidate()
  1437. r.becomeLeader()
  1438. index := r.raftLog.lastIndex()
  1439. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange}}})
  1440. if g := r.raftLog.lastIndex(); g != index+1 {
  1441. t.Errorf("index = %d, want %d", g, index+1)
  1442. }
  1443. if r.pendingConf != true {
  1444. t.Errorf("pendingConf = %v, want true", r.pendingConf)
  1445. }
  1446. }
  1447. // TestStepIgnoreConfig tests that if raft step the second msgProp in
  1448. // EntryConfChange type when the first one is uncommitted, the node will set
  1449. // the proposal to noop and keep its original state.
  1450. func TestStepIgnoreConfig(t *testing.T) {
  1451. // a raft that cannot make progress
  1452. r := newRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage(), 0)
  1453. r.becomeCandidate()
  1454. r.becomeLeader()
  1455. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange}}})
  1456. index := r.raftLog.lastIndex()
  1457. pendingConf := r.pendingConf
  1458. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange}}})
  1459. wents := []pb.Entry{{Type: pb.EntryNormal, Term: 1, Index: 3, Data: nil}}
  1460. if ents := r.raftLog.entries(index + 1); !reflect.DeepEqual(ents, wents) {
  1461. t.Errorf("ents = %+v, want %+v", ents, wents)
  1462. }
  1463. if r.pendingConf != pendingConf {
  1464. t.Errorf("pendingConf = %v, want %v", r.pendingConf, pendingConf)
  1465. }
  1466. }
  1467. // TestRecoverPendingConfig tests that new leader recovers its pendingConf flag
  1468. // based on uncommitted entries.
  1469. func TestRecoverPendingConfig(t *testing.T) {
  1470. tests := []struct {
  1471. entType pb.EntryType
  1472. wpending bool
  1473. }{
  1474. {pb.EntryNormal, false},
  1475. {pb.EntryConfChange, true},
  1476. }
  1477. for i, tt := range tests {
  1478. r := newRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage(), 0)
  1479. r.appendEntry(pb.Entry{Type: tt.entType})
  1480. r.becomeCandidate()
  1481. r.becomeLeader()
  1482. if r.pendingConf != tt.wpending {
  1483. t.Errorf("#%d: pendingConf = %v, want %v", i, r.pendingConf, tt.wpending)
  1484. }
  1485. }
  1486. }
  1487. // TestRecoverDoublePendingConfig tests that new leader will panic if
  1488. // there exist two uncommitted config entries.
  1489. func TestRecoverDoublePendingConfig(t *testing.T) {
  1490. func() {
  1491. defer func() {
  1492. if err := recover(); err == nil {
  1493. t.Errorf("expect panic, but nothing happens")
  1494. }
  1495. }()
  1496. r := newRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage(), 0)
  1497. r.appendEntry(pb.Entry{Type: pb.EntryConfChange})
  1498. r.appendEntry(pb.Entry{Type: pb.EntryConfChange})
  1499. r.becomeCandidate()
  1500. r.becomeLeader()
  1501. }()
  1502. }
  1503. // TestAddNode tests that addNode could update pendingConf and nodes correctly.
  1504. func TestAddNode(t *testing.T) {
  1505. r := newRaft(1, []uint64{1}, 10, 1, NewMemoryStorage(), 0)
  1506. r.pendingConf = true
  1507. r.addNode(2)
  1508. if r.pendingConf != false {
  1509. t.Errorf("pendingConf = %v, want false", r.pendingConf)
  1510. }
  1511. nodes := r.nodes()
  1512. wnodes := []uint64{1, 2}
  1513. if !reflect.DeepEqual(nodes, wnodes) {
  1514. t.Errorf("nodes = %v, want %v", nodes, wnodes)
  1515. }
  1516. }
  1517. // TestRemoveNode tests that removeNode could update pendingConf, nodes and
  1518. // and removed list correctly.
  1519. func TestRemoveNode(t *testing.T) {
  1520. r := newRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage(), 0)
  1521. r.pendingConf = true
  1522. r.removeNode(2)
  1523. if r.pendingConf != false {
  1524. t.Errorf("pendingConf = %v, want false", r.pendingConf)
  1525. }
  1526. w := []uint64{1}
  1527. if g := r.nodes(); !reflect.DeepEqual(g, w) {
  1528. t.Errorf("nodes = %v, want %v", g, w)
  1529. }
  1530. }
  1531. func TestPromotable(t *testing.T) {
  1532. id := uint64(1)
  1533. tests := []struct {
  1534. peers []uint64
  1535. wp bool
  1536. }{
  1537. {[]uint64{1}, true},
  1538. {[]uint64{1, 2, 3}, true},
  1539. {[]uint64{}, false},
  1540. {[]uint64{2, 3}, false},
  1541. }
  1542. for i, tt := range tests {
  1543. r := newRaft(id, tt.peers, 5, 1, NewMemoryStorage(), 0)
  1544. if g := r.promotable(); g != tt.wp {
  1545. t.Errorf("#%d: promotable = %v, want %v", i, g, tt.wp)
  1546. }
  1547. }
  1548. }
  1549. func TestRaftNodes(t *testing.T) {
  1550. tests := []struct {
  1551. ids []uint64
  1552. wids []uint64
  1553. }{
  1554. {
  1555. []uint64{1, 2, 3},
  1556. []uint64{1, 2, 3},
  1557. },
  1558. {
  1559. []uint64{3, 2, 1},
  1560. []uint64{1, 2, 3},
  1561. },
  1562. }
  1563. for i, tt := range tests {
  1564. r := newRaft(1, tt.ids, 10, 1, NewMemoryStorage(), 0)
  1565. if !reflect.DeepEqual(r.nodes(), tt.wids) {
  1566. t.Errorf("#%d: nodes = %+v, want %+v", i, r.nodes(), tt.wids)
  1567. }
  1568. }
  1569. }
  1570. func ents(terms ...uint64) *raft {
  1571. storage := NewMemoryStorage()
  1572. for i, term := range terms {
  1573. storage.Append([]pb.Entry{{Index: uint64(i + 1), Term: term}})
  1574. }
  1575. sm := newRaft(1, []uint64{}, 5, 1, storage, 0)
  1576. sm.reset(0)
  1577. return sm
  1578. }
  1579. type network struct {
  1580. peers map[uint64]Interface
  1581. storage map[uint64]*MemoryStorage
  1582. dropm map[connem]float64
  1583. ignorem map[pb.MessageType]bool
  1584. }
  1585. // newNetwork initializes a network from peers.
  1586. // A nil node will be replaced with a new *stateMachine.
  1587. // A *stateMachine will get its k, id.
  1588. // When using stateMachine, the address list is always [1, n].
  1589. func newNetwork(peers ...Interface) *network {
  1590. size := len(peers)
  1591. peerAddrs := idsBySize(size)
  1592. npeers := make(map[uint64]Interface, size)
  1593. nstorage := make(map[uint64]*MemoryStorage, size)
  1594. for j, p := range peers {
  1595. id := peerAddrs[j]
  1596. switch v := p.(type) {
  1597. case nil:
  1598. nstorage[id] = NewMemoryStorage()
  1599. sm := newRaft(id, peerAddrs, 10, 1, nstorage[id], 0)
  1600. npeers[id] = sm
  1601. case *raft:
  1602. v.id = id
  1603. v.prs = make(map[uint64]*Progress)
  1604. for i := 0; i < size; i++ {
  1605. v.prs[peerAddrs[i]] = &Progress{}
  1606. }
  1607. v.reset(0)
  1608. npeers[id] = v
  1609. case *blackHole:
  1610. npeers[id] = v
  1611. default:
  1612. panic(fmt.Sprintf("unexpected state machine type: %T", p))
  1613. }
  1614. }
  1615. return &network{
  1616. peers: npeers,
  1617. storage: nstorage,
  1618. dropm: make(map[connem]float64),
  1619. ignorem: make(map[pb.MessageType]bool),
  1620. }
  1621. }
  1622. func (nw *network) send(msgs ...pb.Message) {
  1623. for len(msgs) > 0 {
  1624. m := msgs[0]
  1625. p := nw.peers[m.To]
  1626. p.Step(m)
  1627. msgs = append(msgs[1:], nw.filter(p.readMessages())...)
  1628. }
  1629. }
  1630. func (nw *network) drop(from, to uint64, perc float64) {
  1631. nw.dropm[connem{from, to}] = perc
  1632. }
  1633. func (nw *network) cut(one, other uint64) {
  1634. nw.drop(one, other, 1)
  1635. nw.drop(other, one, 1)
  1636. }
  1637. func (nw *network) isolate(id uint64) {
  1638. for i := 0; i < len(nw.peers); i++ {
  1639. nid := uint64(i) + 1
  1640. if nid != id {
  1641. nw.drop(id, nid, 1.0)
  1642. nw.drop(nid, id, 1.0)
  1643. }
  1644. }
  1645. }
  1646. func (nw *network) ignore(t pb.MessageType) {
  1647. nw.ignorem[t] = true
  1648. }
  1649. func (nw *network) recover() {
  1650. nw.dropm = make(map[connem]float64)
  1651. nw.ignorem = make(map[pb.MessageType]bool)
  1652. }
  1653. func (nw *network) filter(msgs []pb.Message) []pb.Message {
  1654. mm := []pb.Message{}
  1655. for _, m := range msgs {
  1656. if nw.ignorem[m.Type] {
  1657. continue
  1658. }
  1659. switch m.Type {
  1660. case pb.MsgHup:
  1661. // hups never go over the network, so don't drop them but panic
  1662. panic("unexpected msgHup")
  1663. default:
  1664. perc := nw.dropm[connem{m.From, m.To}]
  1665. if n := rand.Float64(); n < perc {
  1666. continue
  1667. }
  1668. }
  1669. mm = append(mm, m)
  1670. }
  1671. return mm
  1672. }
  1673. type connem struct {
  1674. from, to uint64
  1675. }
  1676. type blackHole struct{}
  1677. func (blackHole) Step(pb.Message) error { return nil }
  1678. func (blackHole) readMessages() []pb.Message { return nil }
  1679. var nopStepper = &blackHole{}
  1680. func idsBySize(size int) []uint64 {
  1681. ids := make([]uint64, size)
  1682. for i := 0; i < size; i++ {
  1683. ids[i] = 1 + uint64(i)
  1684. }
  1685. return ids
  1686. }