raft_test.go 57 KB

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