raft_test.go 111 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894
  1. // Copyright 2015 The etcd Authors
  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 {
  234. t.Errorf("paused= %v, want false", p.Paused)
  235. }
  236. p.Paused = true
  237. p.maybeUpdate(2)
  238. if p.Paused {
  239. t.Errorf("paused= %v, want false", p.Paused)
  240. }
  241. }
  242. // TestProgressResumeByHeartbeatResp ensures raft.heartbeat reset progress.paused by heartbeat response.
  243. func TestProgressResumeByHeartbeatResp(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 {
  250. t.Errorf("paused = %v, want true", r.prs[2].Paused)
  251. }
  252. r.prs[2].becomeReplicate()
  253. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgHeartbeatResp})
  254. if r.prs[2].Paused {
  255. t.Errorf("paused = %v, want false", r.prs[2].Paused)
  256. }
  257. }
  258. func TestProgressPaused(t *testing.T) {
  259. r := newTestRaft(1, []uint64{1, 2}, 5, 1, NewMemoryStorage())
  260. r.becomeCandidate()
  261. r.becomeLeader()
  262. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  263. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  264. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  265. ms := r.readMessages()
  266. if len(ms) != 1 {
  267. t.Errorf("len(ms) = %d, want 1", len(ms))
  268. }
  269. }
  270. func TestLeaderElection(t *testing.T) {
  271. testLeaderElection(t, false)
  272. }
  273. func TestLeaderElectionPreVote(t *testing.T) {
  274. testLeaderElection(t, true)
  275. }
  276. func testLeaderElection(t *testing.T, preVote bool) {
  277. var cfg func(*Config)
  278. if preVote {
  279. cfg = preVoteConfig
  280. }
  281. tests := []struct {
  282. *network
  283. state StateType
  284. expTerm uint64
  285. }{
  286. {newNetworkWithConfig(cfg, nil, nil, nil), StateLeader, 1},
  287. {newNetworkWithConfig(cfg, nil, nil, nopStepper), StateLeader, 1},
  288. {newNetworkWithConfig(cfg, nil, nopStepper, nopStepper), StateCandidate, 1},
  289. {newNetworkWithConfig(cfg, nil, nopStepper, nopStepper, nil), StateCandidate, 1},
  290. {newNetworkWithConfig(cfg, nil, nopStepper, nopStepper, nil, nil), StateLeader, 1},
  291. // three logs further along than 0, but in the same term so rejections
  292. // are returned instead of the votes being ignored.
  293. {newNetworkWithConfig(cfg,
  294. nil, entsWithConfig(cfg, 1), entsWithConfig(cfg, 1), entsWithConfig(cfg, 1, 1), nil),
  295. StateFollower, 1},
  296. }
  297. for i, tt := range tests {
  298. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  299. sm := tt.network.peers[1].(*raft)
  300. var expState StateType
  301. var expTerm uint64
  302. if tt.state == StateCandidate && preVote {
  303. // In pre-vote mode, an election that fails to complete
  304. // leaves the node in pre-candidate state without advancing
  305. // the term.
  306. expState = StatePreCandidate
  307. expTerm = 0
  308. } else {
  309. expState = tt.state
  310. expTerm = tt.expTerm
  311. }
  312. if sm.state != expState {
  313. t.Errorf("#%d: state = %s, want %s", i, sm.state, expState)
  314. }
  315. if g := sm.Term; g != expTerm {
  316. t.Errorf("#%d: term = %d, want %d", i, g, expTerm)
  317. }
  318. }
  319. }
  320. // TestLearnerElectionTimeout verfies that the leader should not start election even
  321. // when times out.
  322. func TestLearnerElectionTimeout(t *testing.T) {
  323. n1 := newTestLearnerRaft(1, []uint64{1}, []uint64{2}, 10, 1, NewMemoryStorage())
  324. n2 := newTestLearnerRaft(2, []uint64{1}, []uint64{2}, 10, 1, NewMemoryStorage())
  325. n1.becomeFollower(1, None)
  326. n2.becomeFollower(1, None)
  327. // n2 is learner. Learner should not start election even when times out.
  328. setRandomizedElectionTimeout(n2, n2.electionTimeout)
  329. for i := 0; i < n2.electionTimeout; i++ {
  330. n2.tick()
  331. }
  332. if n2.state != StateFollower {
  333. t.Errorf("peer 2 state: %s, want %s", n2.state, StateFollower)
  334. }
  335. }
  336. // TestLearnerPromotion verifies that the learner should not election until
  337. // it is promoted to a normal peer.
  338. func TestLearnerPromotion(t *testing.T) {
  339. n1 := newTestLearnerRaft(1, []uint64{1}, []uint64{2}, 10, 1, NewMemoryStorage())
  340. n2 := newTestLearnerRaft(2, []uint64{1}, []uint64{2}, 10, 1, NewMemoryStorage())
  341. n1.becomeFollower(1, None)
  342. n2.becomeFollower(1, None)
  343. nt := newNetwork(n1, n2)
  344. if n1.state == StateLeader {
  345. t.Error("peer 1 state is leader, want not", n1.state)
  346. }
  347. // n1 should become leader
  348. setRandomizedElectionTimeout(n1, n1.electionTimeout)
  349. for i := 0; i < n1.electionTimeout; i++ {
  350. n1.tick()
  351. }
  352. if n1.state != StateLeader {
  353. t.Errorf("peer 1 state: %s, want %s", n1.state, StateLeader)
  354. }
  355. if n2.state != StateFollower {
  356. t.Errorf("peer 2 state: %s, want %s", n2.state, StateFollower)
  357. }
  358. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  359. n1.addNode(2)
  360. n2.addNode(2)
  361. if n2.isLearner {
  362. t.Error("peer 2 is learner, want not")
  363. }
  364. // n2 start election, should become leader
  365. setRandomizedElectionTimeout(n2, n2.electionTimeout)
  366. for i := 0; i < n2.electionTimeout; i++ {
  367. n2.tick()
  368. }
  369. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgBeat})
  370. if n1.state != StateFollower {
  371. t.Errorf("peer 1 state: %s, want %s", n1.state, StateFollower)
  372. }
  373. if n2.state != StateLeader {
  374. t.Errorf("peer 2 state: %s, want %s", n2.state, StateLeader)
  375. }
  376. }
  377. // TestLearnerCannotVote checks that a learner can't vote even it receives a valid Vote request.
  378. func TestLearnerCannotVote(t *testing.T) {
  379. n2 := newTestLearnerRaft(2, []uint64{1}, []uint64{2}, 10, 1, NewMemoryStorage())
  380. n2.becomeFollower(1, None)
  381. n2.Step(pb.Message{From: 1, To: 2, Term: 2, Type: pb.MsgVote, LogTerm: 11, Index: 11})
  382. if len(n2.msgs) != 0 {
  383. t.Errorf("expect learner not to vote, but received %v messages", n2.msgs)
  384. }
  385. }
  386. func TestLeaderCycle(t *testing.T) {
  387. testLeaderCycle(t, false)
  388. }
  389. func TestLeaderCyclePreVote(t *testing.T) {
  390. testLeaderCycle(t, true)
  391. }
  392. // testLeaderCycle verifies that each node in a cluster can campaign
  393. // and be elected in turn. This ensures that elections (including
  394. // pre-vote) work when not starting from a clean slate (as they do in
  395. // TestLeaderElection)
  396. func testLeaderCycle(t *testing.T, preVote bool) {
  397. var cfg func(*Config)
  398. if preVote {
  399. cfg = preVoteConfig
  400. }
  401. n := newNetworkWithConfig(cfg, nil, nil, nil)
  402. for campaignerID := uint64(1); campaignerID <= 3; campaignerID++ {
  403. n.send(pb.Message{From: campaignerID, To: campaignerID, Type: pb.MsgHup})
  404. for _, peer := range n.peers {
  405. sm := peer.(*raft)
  406. if sm.id == campaignerID && sm.state != StateLeader {
  407. t.Errorf("preVote=%v: campaigning node %d state = %v, want StateLeader",
  408. preVote, sm.id, sm.state)
  409. } else if sm.id != campaignerID && sm.state != StateFollower {
  410. t.Errorf("preVote=%v: after campaign of node %d, "+
  411. "node %d had state = %v, want StateFollower",
  412. preVote, campaignerID, sm.id, sm.state)
  413. }
  414. }
  415. }
  416. }
  417. // TestLeaderElectionOverwriteNewerLogs tests a scenario in which a
  418. // newly-elected leader does *not* have the newest (i.e. highest term)
  419. // log entries, and must overwrite higher-term log entries with
  420. // lower-term ones.
  421. func TestLeaderElectionOverwriteNewerLogs(t *testing.T) {
  422. testLeaderElectionOverwriteNewerLogs(t, false)
  423. }
  424. func TestLeaderElectionOverwriteNewerLogsPreVote(t *testing.T) {
  425. testLeaderElectionOverwriteNewerLogs(t, true)
  426. }
  427. func testLeaderElectionOverwriteNewerLogs(t *testing.T, preVote bool) {
  428. var cfg func(*Config)
  429. if preVote {
  430. cfg = preVoteConfig
  431. }
  432. // This network represents the results of the following sequence of
  433. // events:
  434. // - Node 1 won the election in term 1.
  435. // - Node 1 replicated a log entry to node 2 but died before sending
  436. // it to other nodes.
  437. // - Node 3 won the second election in term 2.
  438. // - Node 3 wrote an entry to its logs but died without sending it
  439. // to any other nodes.
  440. //
  441. // At this point, nodes 1, 2, and 3 all have uncommitted entries in
  442. // their logs and could win an election at term 3. The winner's log
  443. // entry overwrites the losers'. (TestLeaderSyncFollowerLog tests
  444. // the case where older log entries are overwritten, so this test
  445. // focuses on the case where the newer entries are lost).
  446. n := newNetworkWithConfig(cfg,
  447. entsWithConfig(cfg, 1), // Node 1: Won first election
  448. entsWithConfig(cfg, 1), // Node 2: Got logs from node 1
  449. entsWithConfig(cfg, 2), // Node 3: Won second election
  450. votedWithConfig(cfg, 3, 2), // Node 4: Voted but didn't get logs
  451. votedWithConfig(cfg, 3, 2)) // Node 5: Voted but didn't get logs
  452. // Node 1 campaigns. The election fails because a quorum of nodes
  453. // know about the election that already happened at term 2. Node 1's
  454. // term is pushed ahead to 2.
  455. n.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  456. sm1 := n.peers[1].(*raft)
  457. if sm1.state != StateFollower {
  458. t.Errorf("state = %s, want StateFollower", sm1.state)
  459. }
  460. if sm1.Term != 2 {
  461. t.Errorf("term = %d, want 2", sm1.Term)
  462. }
  463. // Node 1 campaigns again with a higher term. This time it succeeds.
  464. n.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  465. if sm1.state != StateLeader {
  466. t.Errorf("state = %s, want StateLeader", sm1.state)
  467. }
  468. if sm1.Term != 3 {
  469. t.Errorf("term = %d, want 3", sm1.Term)
  470. }
  471. // Now all nodes agree on a log entry with term 1 at index 1 (and
  472. // term 3 at index 2).
  473. for i := range n.peers {
  474. sm := n.peers[i].(*raft)
  475. entries := sm.raftLog.allEntries()
  476. if len(entries) != 2 {
  477. t.Fatalf("node %d: len(entries) == %d, want 2", i, len(entries))
  478. }
  479. if entries[0].Term != 1 {
  480. t.Errorf("node %d: term at index 1 == %d, want 1", i, entries[0].Term)
  481. }
  482. if entries[1].Term != 3 {
  483. t.Errorf("node %d: term at index 2 == %d, want 3", i, entries[1].Term)
  484. }
  485. }
  486. }
  487. func TestVoteFromAnyState(t *testing.T) {
  488. testVoteFromAnyState(t, pb.MsgVote)
  489. }
  490. func TestPreVoteFromAnyState(t *testing.T) {
  491. testVoteFromAnyState(t, pb.MsgPreVote)
  492. }
  493. func testVoteFromAnyState(t *testing.T, vt pb.MessageType) {
  494. for st := StateType(0); st < numStates; st++ {
  495. r := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  496. r.Term = 1
  497. switch st {
  498. case StateFollower:
  499. r.becomeFollower(r.Term, 3)
  500. case StatePreCandidate:
  501. r.becomePreCandidate()
  502. case StateCandidate:
  503. r.becomeCandidate()
  504. case StateLeader:
  505. r.becomeCandidate()
  506. r.becomeLeader()
  507. }
  508. // Note that setting our state above may have advanced r.Term
  509. // past its initial value.
  510. origTerm := r.Term
  511. newTerm := r.Term + 1
  512. msg := pb.Message{
  513. From: 2,
  514. To: 1,
  515. Type: vt,
  516. Term: newTerm,
  517. LogTerm: newTerm,
  518. Index: 42,
  519. }
  520. if err := r.Step(msg); err != nil {
  521. t.Errorf("%s,%s: Step failed: %s", vt, st, err)
  522. }
  523. if len(r.msgs) != 1 {
  524. t.Errorf("%s,%s: %d response messages, want 1: %+v", vt, st, len(r.msgs), r.msgs)
  525. } else {
  526. resp := r.msgs[0]
  527. if resp.Type != voteRespMsgType(vt) {
  528. t.Errorf("%s,%s: response message is %s, want %s",
  529. vt, st, resp.Type, voteRespMsgType(vt))
  530. }
  531. if resp.Reject {
  532. t.Errorf("%s,%s: unexpected rejection", vt, st)
  533. }
  534. }
  535. // If this was a real vote, we reset our state and term.
  536. if vt == pb.MsgVote {
  537. if r.state != StateFollower {
  538. t.Errorf("%s,%s: state %s, want %s", vt, st, r.state, StateFollower)
  539. }
  540. if r.Term != newTerm {
  541. t.Errorf("%s,%s: term %d, want %d", vt, st, r.Term, newTerm)
  542. }
  543. if r.Vote != 2 {
  544. t.Errorf("%s,%s: vote %d, want 2", vt, st, r.Vote)
  545. }
  546. } else {
  547. // In a prevote, nothing changes.
  548. if r.state != st {
  549. t.Errorf("%s,%s: state %s, want %s", vt, st, r.state, st)
  550. }
  551. if r.Term != origTerm {
  552. t.Errorf("%s,%s: term %d, want %d", vt, st, r.Term, origTerm)
  553. }
  554. // if st == StateFollower or StatePreCandidate, r hasn't voted yet.
  555. // In StateCandidate or StateLeader, it's voted for itself.
  556. if r.Vote != None && r.Vote != 1 {
  557. t.Errorf("%s,%s: vote %d, want %d or 1", vt, st, r.Vote, None)
  558. }
  559. }
  560. }
  561. }
  562. func TestLogReplication(t *testing.T) {
  563. tests := []struct {
  564. *network
  565. msgs []pb.Message
  566. wcommitted uint64
  567. }{
  568. {
  569. newNetwork(nil, nil, nil),
  570. []pb.Message{
  571. {From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}},
  572. },
  573. 2,
  574. },
  575. {
  576. newNetwork(nil, nil, nil),
  577. []pb.Message{
  578. {From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}},
  579. {From: 1, To: 2, Type: pb.MsgHup},
  580. {From: 1, To: 2, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}},
  581. },
  582. 4,
  583. },
  584. }
  585. for i, tt := range tests {
  586. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  587. for _, m := range tt.msgs {
  588. tt.send(m)
  589. }
  590. for j, x := range tt.network.peers {
  591. sm := x.(*raft)
  592. if sm.raftLog.committed != tt.wcommitted {
  593. t.Errorf("#%d.%d: committed = %d, want %d", i, j, sm.raftLog.committed, tt.wcommitted)
  594. }
  595. ents := []pb.Entry{}
  596. for _, e := range nextEnts(sm, tt.network.storage[j]) {
  597. if e.Data != nil {
  598. ents = append(ents, e)
  599. }
  600. }
  601. props := []pb.Message{}
  602. for _, m := range tt.msgs {
  603. if m.Type == pb.MsgProp {
  604. props = append(props, m)
  605. }
  606. }
  607. for k, m := range props {
  608. if !bytes.Equal(ents[k].Data, m.Entries[0].Data) {
  609. t.Errorf("#%d.%d: data = %d, want %d", i, j, ents[k].Data, m.Entries[0].Data)
  610. }
  611. }
  612. }
  613. }
  614. }
  615. // TestLearnerLogReplication tests that a learner can receive entries from the leader.
  616. func TestLearnerLogReplication(t *testing.T) {
  617. n1 := newTestLearnerRaft(1, []uint64{1}, []uint64{2}, 10, 1, NewMemoryStorage())
  618. n2 := newTestLearnerRaft(2, []uint64{1}, []uint64{2}, 10, 1, NewMemoryStorage())
  619. nt := newNetwork(n1, n2)
  620. n1.becomeFollower(1, None)
  621. n2.becomeFollower(1, None)
  622. setRandomizedElectionTimeout(n1, n1.electionTimeout)
  623. for i := 0; i < n1.electionTimeout; i++ {
  624. n1.tick()
  625. }
  626. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  627. // n1 is leader and n2 is learner
  628. if n1.state != StateLeader {
  629. t.Errorf("peer 1 state: %s, want %s", n1.state, StateLeader)
  630. }
  631. if !n2.isLearner {
  632. t.Error("peer 2 state: not learner, want yes")
  633. }
  634. nextCommitted := n1.raftLog.committed + 1
  635. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  636. if n1.raftLog.committed != nextCommitted {
  637. t.Errorf("peer 1 wants committed to %d, but still %d", nextCommitted, n1.raftLog.committed)
  638. }
  639. if n1.raftLog.committed != n2.raftLog.committed {
  640. t.Errorf("peer 2 wants committed to %d, but still %d", n1.raftLog.committed, n2.raftLog.committed)
  641. }
  642. match := n1.getProgress(2).Match
  643. if match != n2.raftLog.committed {
  644. t.Errorf("progresss 2 of leader 1 wants match %d, but got %d", n2.raftLog.committed, match)
  645. }
  646. }
  647. func TestSingleNodeCommit(t *testing.T) {
  648. tt := newNetwork(nil)
  649. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  650. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  651. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  652. sm := tt.peers[1].(*raft)
  653. if sm.raftLog.committed != 3 {
  654. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 3)
  655. }
  656. }
  657. // TestCannotCommitWithoutNewTermEntry tests the entries cannot be committed
  658. // when leader changes, no new proposal comes in and ChangeTerm proposal is
  659. // filtered.
  660. func TestCannotCommitWithoutNewTermEntry(t *testing.T) {
  661. tt := newNetwork(nil, nil, nil, nil, nil)
  662. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  663. // 0 cannot reach 2,3,4
  664. tt.cut(1, 3)
  665. tt.cut(1, 4)
  666. tt.cut(1, 5)
  667. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  668. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  669. sm := tt.peers[1].(*raft)
  670. if sm.raftLog.committed != 1 {
  671. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 1)
  672. }
  673. // network recovery
  674. tt.recover()
  675. // avoid committing ChangeTerm proposal
  676. tt.ignore(pb.MsgApp)
  677. // elect 2 as the new leader with term 2
  678. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  679. // no log entries from previous term should be committed
  680. sm = tt.peers[2].(*raft)
  681. if sm.raftLog.committed != 1 {
  682. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 1)
  683. }
  684. tt.recover()
  685. // send heartbeat; reset wait
  686. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgBeat})
  687. // append an entry at current term
  688. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  689. // expect the committed to be advanced
  690. if sm.raftLog.committed != 5 {
  691. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 5)
  692. }
  693. }
  694. // TestCommitWithoutNewTermEntry tests the entries could be committed
  695. // when leader changes, no new proposal comes in.
  696. func TestCommitWithoutNewTermEntry(t *testing.T) {
  697. tt := newNetwork(nil, nil, nil, nil, nil)
  698. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  699. // 0 cannot reach 2,3,4
  700. tt.cut(1, 3)
  701. tt.cut(1, 4)
  702. tt.cut(1, 5)
  703. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  704. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  705. sm := tt.peers[1].(*raft)
  706. if sm.raftLog.committed != 1 {
  707. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 1)
  708. }
  709. // network recovery
  710. tt.recover()
  711. // elect 1 as the new leader with term 2
  712. // after append a ChangeTerm entry from the current term, all entries
  713. // should be committed
  714. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  715. if sm.raftLog.committed != 4 {
  716. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 4)
  717. }
  718. }
  719. func TestDuelingCandidates(t *testing.T) {
  720. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  721. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  722. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  723. nt := newNetwork(a, b, c)
  724. nt.cut(1, 3)
  725. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  726. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  727. // 1 becomes leader since it receives votes from 1 and 2
  728. sm := nt.peers[1].(*raft)
  729. if sm.state != StateLeader {
  730. t.Errorf("state = %s, want %s", sm.state, StateLeader)
  731. }
  732. // 3 stays as candidate since it receives a vote from 3 and a rejection from 2
  733. sm = nt.peers[3].(*raft)
  734. if sm.state != StateCandidate {
  735. t.Errorf("state = %s, want %s", sm.state, StateCandidate)
  736. }
  737. nt.recover()
  738. // candidate 3 now increases its term and tries to vote again
  739. // we expect it to disrupt the leader 1 since it has a higher term
  740. // 3 will be follower again since both 1 and 2 rejects its vote request since 3 does not have a long enough log
  741. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  742. wlog := &raftLog{
  743. storage: &MemoryStorage{ents: []pb.Entry{{}, {Data: nil, Term: 1, Index: 1}}},
  744. committed: 1,
  745. unstable: unstable{offset: 2},
  746. }
  747. tests := []struct {
  748. sm *raft
  749. state StateType
  750. term uint64
  751. raftLog *raftLog
  752. }{
  753. {a, StateFollower, 2, wlog},
  754. {b, StateFollower, 2, wlog},
  755. {c, StateFollower, 2, newLog(NewMemoryStorage(), raftLogger)},
  756. }
  757. for i, tt := range tests {
  758. if g := tt.sm.state; g != tt.state {
  759. t.Errorf("#%d: state = %s, want %s", i, g, tt.state)
  760. }
  761. if g := tt.sm.Term; g != tt.term {
  762. t.Errorf("#%d: term = %d, want %d", i, g, tt.term)
  763. }
  764. base := ltoa(tt.raftLog)
  765. if sm, ok := nt.peers[1+uint64(i)].(*raft); ok {
  766. l := ltoa(sm.raftLog)
  767. if g := diffu(base, l); g != "" {
  768. t.Errorf("#%d: diff:\n%s", i, g)
  769. }
  770. } else {
  771. t.Logf("#%d: empty log", i)
  772. }
  773. }
  774. }
  775. func TestDuelingPreCandidates(t *testing.T) {
  776. cfgA := newTestConfig(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  777. cfgB := newTestConfig(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  778. cfgC := newTestConfig(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  779. cfgA.PreVote = true
  780. cfgB.PreVote = true
  781. cfgC.PreVote = true
  782. a := newRaft(cfgA)
  783. b := newRaft(cfgB)
  784. c := newRaft(cfgC)
  785. nt := newNetwork(a, b, c)
  786. nt.cut(1, 3)
  787. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  788. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  789. // 1 becomes leader since it receives votes from 1 and 2
  790. sm := nt.peers[1].(*raft)
  791. if sm.state != StateLeader {
  792. t.Errorf("state = %s, want %s", sm.state, StateLeader)
  793. }
  794. // 3 campaigns then reverts to follower when its PreVote is rejected
  795. sm = nt.peers[3].(*raft)
  796. if sm.state != StateFollower {
  797. t.Errorf("state = %s, want %s", sm.state, StateFollower)
  798. }
  799. nt.recover()
  800. // Candidate 3 now increases its term and tries to vote again.
  801. // With PreVote, it does not disrupt the leader.
  802. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  803. wlog := &raftLog{
  804. storage: &MemoryStorage{ents: []pb.Entry{{}, {Data: nil, Term: 1, Index: 1}}},
  805. committed: 1,
  806. unstable: unstable{offset: 2},
  807. }
  808. tests := []struct {
  809. sm *raft
  810. state StateType
  811. term uint64
  812. raftLog *raftLog
  813. }{
  814. {a, StateLeader, 1, wlog},
  815. {b, StateFollower, 1, wlog},
  816. {c, StateFollower, 1, newLog(NewMemoryStorage(), raftLogger)},
  817. }
  818. for i, tt := range tests {
  819. if g := tt.sm.state; g != tt.state {
  820. t.Errorf("#%d: state = %s, want %s", i, g, tt.state)
  821. }
  822. if g := tt.sm.Term; g != tt.term {
  823. t.Errorf("#%d: term = %d, want %d", i, g, tt.term)
  824. }
  825. base := ltoa(tt.raftLog)
  826. if sm, ok := nt.peers[1+uint64(i)].(*raft); ok {
  827. l := ltoa(sm.raftLog)
  828. if g := diffu(base, l); g != "" {
  829. t.Errorf("#%d: diff:\n%s", i, g)
  830. }
  831. } else {
  832. t.Logf("#%d: empty log", i)
  833. }
  834. }
  835. }
  836. func TestCandidateConcede(t *testing.T) {
  837. tt := newNetwork(nil, nil, nil)
  838. tt.isolate(1)
  839. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  840. tt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  841. // heal the partition
  842. tt.recover()
  843. // send heartbeat; reset wait
  844. tt.send(pb.Message{From: 3, To: 3, Type: pb.MsgBeat})
  845. data := []byte("force follower")
  846. // send a proposal to 3 to flush out a MsgApp to 1
  847. tt.send(pb.Message{From: 3, To: 3, Type: pb.MsgProp, Entries: []pb.Entry{{Data: data}}})
  848. // send heartbeat; flush out commit
  849. tt.send(pb.Message{From: 3, To: 3, Type: pb.MsgBeat})
  850. a := tt.peers[1].(*raft)
  851. if g := a.state; g != StateFollower {
  852. t.Errorf("state = %s, want %s", g, StateFollower)
  853. }
  854. if g := a.Term; g != 1 {
  855. t.Errorf("term = %d, want %d", g, 1)
  856. }
  857. wantLog := ltoa(&raftLog{
  858. storage: &MemoryStorage{
  859. ents: []pb.Entry{{}, {Data: nil, Term: 1, Index: 1}, {Term: 1, Index: 2, Data: data}},
  860. },
  861. unstable: unstable{offset: 3},
  862. committed: 2,
  863. })
  864. for i, p := range tt.peers {
  865. if sm, ok := p.(*raft); ok {
  866. l := ltoa(sm.raftLog)
  867. if g := diffu(wantLog, l); g != "" {
  868. t.Errorf("#%d: diff:\n%s", i, g)
  869. }
  870. } else {
  871. t.Logf("#%d: empty log", i)
  872. }
  873. }
  874. }
  875. func TestSingleNodeCandidate(t *testing.T) {
  876. tt := newNetwork(nil)
  877. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  878. sm := tt.peers[1].(*raft)
  879. if sm.state != StateLeader {
  880. t.Errorf("state = %d, want %d", sm.state, StateLeader)
  881. }
  882. }
  883. func TestSingleNodePreCandidate(t *testing.T) {
  884. tt := newNetworkWithConfig(preVoteConfig, nil)
  885. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  886. sm := tt.peers[1].(*raft)
  887. if sm.state != StateLeader {
  888. t.Errorf("state = %d, want %d", sm.state, StateLeader)
  889. }
  890. }
  891. func TestOldMessages(t *testing.T) {
  892. tt := newNetwork(nil, nil, nil)
  893. // make 0 leader @ term 3
  894. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  895. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  896. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  897. // pretend we're an old leader trying to make progress; this entry is expected to be ignored.
  898. tt.send(pb.Message{From: 2, To: 1, Type: pb.MsgApp, Term: 2, Entries: []pb.Entry{{Index: 3, Term: 2}}})
  899. // commit a new entry
  900. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  901. ilog := &raftLog{
  902. storage: &MemoryStorage{
  903. ents: []pb.Entry{
  904. {}, {Data: nil, Term: 1, Index: 1},
  905. {Data: nil, Term: 2, Index: 2}, {Data: nil, Term: 3, Index: 3},
  906. {Data: []byte("somedata"), Term: 3, Index: 4},
  907. },
  908. },
  909. unstable: unstable{offset: 5},
  910. committed: 4,
  911. }
  912. base := ltoa(ilog)
  913. for i, p := range tt.peers {
  914. if sm, ok := p.(*raft); ok {
  915. l := ltoa(sm.raftLog)
  916. if g := diffu(base, l); g != "" {
  917. t.Errorf("#%d: diff:\n%s", i, g)
  918. }
  919. } else {
  920. t.Logf("#%d: empty log", i)
  921. }
  922. }
  923. }
  924. // TestOldMessagesReply - optimization - reply with new term.
  925. func TestProposal(t *testing.T) {
  926. tests := []struct {
  927. *network
  928. success bool
  929. }{
  930. {newNetwork(nil, nil, nil), true},
  931. {newNetwork(nil, nil, nopStepper), true},
  932. {newNetwork(nil, nopStepper, nopStepper), false},
  933. {newNetwork(nil, nopStepper, nopStepper, nil), false},
  934. {newNetwork(nil, nopStepper, nopStepper, nil, nil), true},
  935. }
  936. for j, tt := range tests {
  937. send := func(m pb.Message) {
  938. defer func() {
  939. // only recover is we expect it to panic so
  940. // panics we don't expect go up.
  941. if !tt.success {
  942. e := recover()
  943. if e != nil {
  944. t.Logf("#%d: err: %s", j, e)
  945. }
  946. }
  947. }()
  948. tt.send(m)
  949. }
  950. data := []byte("somedata")
  951. // promote 0 the leader
  952. send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  953. send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: data}}})
  954. wantLog := newLog(NewMemoryStorage(), raftLogger)
  955. if tt.success {
  956. wantLog = &raftLog{
  957. storage: &MemoryStorage{
  958. ents: []pb.Entry{{}, {Data: nil, Term: 1, Index: 1}, {Term: 1, Index: 2, Data: data}},
  959. },
  960. unstable: unstable{offset: 3},
  961. committed: 2}
  962. }
  963. base := ltoa(wantLog)
  964. for i, p := range tt.peers {
  965. if sm, ok := p.(*raft); ok {
  966. l := ltoa(sm.raftLog)
  967. if g := diffu(base, l); g != "" {
  968. t.Errorf("#%d: diff:\n%s", i, g)
  969. }
  970. } else {
  971. t.Logf("#%d: empty log", i)
  972. }
  973. }
  974. sm := tt.network.peers[1].(*raft)
  975. if g := sm.Term; g != 1 {
  976. t.Errorf("#%d: term = %d, want %d", j, g, 1)
  977. }
  978. }
  979. }
  980. func TestProposalByProxy(t *testing.T) {
  981. data := []byte("somedata")
  982. tests := []*network{
  983. newNetwork(nil, nil, nil),
  984. newNetwork(nil, nil, nopStepper),
  985. }
  986. for j, tt := range tests {
  987. // promote 0 the leader
  988. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  989. // propose via follower
  990. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  991. wantLog := &raftLog{
  992. storage: &MemoryStorage{
  993. ents: []pb.Entry{{}, {Data: nil, Term: 1, Index: 1}, {Term: 1, Data: data, Index: 2}},
  994. },
  995. unstable: unstable{offset: 3},
  996. committed: 2}
  997. base := ltoa(wantLog)
  998. for i, p := range tt.peers {
  999. if sm, ok := p.(*raft); ok {
  1000. l := ltoa(sm.raftLog)
  1001. if g := diffu(base, l); g != "" {
  1002. t.Errorf("#%d: diff:\n%s", i, g)
  1003. }
  1004. } else {
  1005. t.Logf("#%d: empty log", i)
  1006. }
  1007. }
  1008. sm := tt.peers[1].(*raft)
  1009. if g := sm.Term; g != 1 {
  1010. t.Errorf("#%d: term = %d, want %d", j, g, 1)
  1011. }
  1012. }
  1013. }
  1014. func TestCommit(t *testing.T) {
  1015. tests := []struct {
  1016. matches []uint64
  1017. logs []pb.Entry
  1018. smTerm uint64
  1019. w uint64
  1020. }{
  1021. // single
  1022. {[]uint64{1}, []pb.Entry{{Index: 1, Term: 1}}, 1, 1},
  1023. {[]uint64{1}, []pb.Entry{{Index: 1, Term: 1}}, 2, 0},
  1024. {[]uint64{2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 2, 2},
  1025. {[]uint64{1}, []pb.Entry{{Index: 1, Term: 2}}, 2, 1},
  1026. // odd
  1027. {[]uint64{2, 1, 1}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 1, 1},
  1028. {[]uint64{2, 1, 1}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}}, 2, 0},
  1029. {[]uint64{2, 1, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 2, 2},
  1030. {[]uint64{2, 1, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}}, 2, 0},
  1031. // even
  1032. {[]uint64{2, 1, 1, 1}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 1, 1},
  1033. {[]uint64{2, 1, 1, 1}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}}, 2, 0},
  1034. {[]uint64{2, 1, 1, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 1, 1},
  1035. {[]uint64{2, 1, 1, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}}, 2, 0},
  1036. {[]uint64{2, 1, 2, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 2, 2},
  1037. {[]uint64{2, 1, 2, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}}, 2, 0},
  1038. }
  1039. for i, tt := range tests {
  1040. storage := NewMemoryStorage()
  1041. storage.Append(tt.logs)
  1042. storage.hardState = pb.HardState{Term: tt.smTerm}
  1043. sm := newTestRaft(1, []uint64{1}, 5, 1, storage)
  1044. for j := 0; j < len(tt.matches); j++ {
  1045. sm.setProgress(uint64(j)+1, tt.matches[j], tt.matches[j]+1, false)
  1046. }
  1047. sm.maybeCommit()
  1048. if g := sm.raftLog.committed; g != tt.w {
  1049. t.Errorf("#%d: committed = %d, want %d", i, g, tt.w)
  1050. }
  1051. }
  1052. }
  1053. func TestPastElectionTimeout(t *testing.T) {
  1054. tests := []struct {
  1055. elapse int
  1056. wprobability float64
  1057. round bool
  1058. }{
  1059. {5, 0, false},
  1060. {10, 0.1, true},
  1061. {13, 0.4, true},
  1062. {15, 0.6, true},
  1063. {18, 0.9, true},
  1064. {20, 1, false},
  1065. }
  1066. for i, tt := range tests {
  1067. sm := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  1068. sm.electionElapsed = tt.elapse
  1069. c := 0
  1070. for j := 0; j < 10000; j++ {
  1071. sm.resetRandomizedElectionTimeout()
  1072. if sm.pastElectionTimeout() {
  1073. c++
  1074. }
  1075. }
  1076. got := float64(c) / 10000.0
  1077. if tt.round {
  1078. got = math.Floor(got*10+0.5) / 10.0
  1079. }
  1080. if got != tt.wprobability {
  1081. t.Errorf("#%d: probability = %v, want %v", i, got, tt.wprobability)
  1082. }
  1083. }
  1084. }
  1085. // ensure that the Step function ignores the message from old term and does not pass it to the
  1086. // actual stepX function.
  1087. func TestStepIgnoreOldTermMsg(t *testing.T) {
  1088. called := false
  1089. fakeStep := func(r *raft, m pb.Message) error {
  1090. called = true
  1091. return nil
  1092. }
  1093. sm := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  1094. sm.step = fakeStep
  1095. sm.Term = 2
  1096. sm.Step(pb.Message{Type: pb.MsgApp, Term: sm.Term - 1})
  1097. if called {
  1098. t.Errorf("stepFunc called = %v , want %v", called, false)
  1099. }
  1100. }
  1101. // TestHandleMsgApp ensures:
  1102. // 1. Reply false if log doesn’t contain an entry at prevLogIndex whose term matches prevLogTerm.
  1103. // 2. If an existing entry conflicts with a new one (same index but different terms),
  1104. // delete the existing entry and all that follow it; append any new entries not already in the log.
  1105. // 3. If leaderCommit > commitIndex, set commitIndex = min(leaderCommit, index of last new entry).
  1106. func TestHandleMsgApp(t *testing.T) {
  1107. tests := []struct {
  1108. m pb.Message
  1109. wIndex uint64
  1110. wCommit uint64
  1111. wReject bool
  1112. }{
  1113. // Ensure 1
  1114. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 3, Index: 2, Commit: 3}, 2, 0, true}, // previous log mismatch
  1115. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 3, Index: 3, Commit: 3}, 2, 0, true}, // previous log non-exist
  1116. // Ensure 2
  1117. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 1, Index: 1, Commit: 1}, 2, 1, false},
  1118. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 0, Index: 0, Commit: 1, Entries: []pb.Entry{{Index: 1, Term: 2}}}, 1, 1, false},
  1119. {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},
  1120. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 2, Index: 2, Commit: 4, Entries: []pb.Entry{{Index: 3, Term: 2}}}, 3, 3, false},
  1121. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 1, Index: 1, Commit: 4, Entries: []pb.Entry{{Index: 2, Term: 2}}}, 2, 2, false},
  1122. // Ensure 3
  1123. {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
  1124. {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
  1125. {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
  1126. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 2, Index: 2, Commit: 4}, 2, 2, false}, // commit up to log.last()
  1127. }
  1128. for i, tt := range tests {
  1129. storage := NewMemoryStorage()
  1130. storage.Append([]pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}})
  1131. sm := newTestRaft(1, []uint64{1}, 10, 1, storage)
  1132. sm.becomeFollower(2, None)
  1133. sm.handleAppendEntries(tt.m)
  1134. if sm.raftLog.lastIndex() != tt.wIndex {
  1135. t.Errorf("#%d: lastIndex = %d, want %d", i, sm.raftLog.lastIndex(), tt.wIndex)
  1136. }
  1137. if sm.raftLog.committed != tt.wCommit {
  1138. t.Errorf("#%d: committed = %d, want %d", i, sm.raftLog.committed, tt.wCommit)
  1139. }
  1140. m := sm.readMessages()
  1141. if len(m) != 1 {
  1142. t.Fatalf("#%d: msg = nil, want 1", i)
  1143. }
  1144. if m[0].Reject != tt.wReject {
  1145. t.Errorf("#%d: reject = %v, want %v", i, m[0].Reject, tt.wReject)
  1146. }
  1147. }
  1148. }
  1149. // TestHandleHeartbeat ensures that the follower commits to the commit in the message.
  1150. func TestHandleHeartbeat(t *testing.T) {
  1151. commit := uint64(2)
  1152. tests := []struct {
  1153. m pb.Message
  1154. wCommit uint64
  1155. }{
  1156. {pb.Message{From: 2, To: 1, Type: pb.MsgHeartbeat, Term: 2, Commit: commit + 1}, commit + 1},
  1157. {pb.Message{From: 2, To: 1, Type: pb.MsgHeartbeat, Term: 2, Commit: commit - 1}, commit}, // do not decrease commit
  1158. }
  1159. for i, tt := range tests {
  1160. storage := NewMemoryStorage()
  1161. storage.Append([]pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}, {Index: 3, Term: 3}})
  1162. sm := newTestRaft(1, []uint64{1, 2}, 5, 1, storage)
  1163. sm.becomeFollower(2, 2)
  1164. sm.raftLog.commitTo(commit)
  1165. sm.handleHeartbeat(tt.m)
  1166. if sm.raftLog.committed != tt.wCommit {
  1167. t.Errorf("#%d: committed = %d, want %d", i, sm.raftLog.committed, tt.wCommit)
  1168. }
  1169. m := sm.readMessages()
  1170. if len(m) != 1 {
  1171. t.Fatalf("#%d: msg = nil, want 1", i)
  1172. }
  1173. if m[0].Type != pb.MsgHeartbeatResp {
  1174. t.Errorf("#%d: type = %v, want MsgHeartbeatResp", i, m[0].Type)
  1175. }
  1176. }
  1177. }
  1178. // TestHandleHeartbeatResp ensures that we re-send log entries when we get a heartbeat response.
  1179. func TestHandleHeartbeatResp(t *testing.T) {
  1180. storage := NewMemoryStorage()
  1181. storage.Append([]pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}, {Index: 3, Term: 3}})
  1182. sm := newTestRaft(1, []uint64{1, 2}, 5, 1, storage)
  1183. sm.becomeCandidate()
  1184. sm.becomeLeader()
  1185. sm.raftLog.commitTo(sm.raftLog.lastIndex())
  1186. // A heartbeat response from a node that is behind; re-send MsgApp
  1187. sm.Step(pb.Message{From: 2, Type: pb.MsgHeartbeatResp})
  1188. msgs := sm.readMessages()
  1189. if len(msgs) != 1 {
  1190. t.Fatalf("len(msgs) = %d, want 1", len(msgs))
  1191. }
  1192. if msgs[0].Type != pb.MsgApp {
  1193. t.Errorf("type = %v, want MsgApp", msgs[0].Type)
  1194. }
  1195. // A second heartbeat response generates another MsgApp re-send
  1196. sm.Step(pb.Message{From: 2, Type: pb.MsgHeartbeatResp})
  1197. msgs = sm.readMessages()
  1198. if len(msgs) != 1 {
  1199. t.Fatalf("len(msgs) = %d, want 1", len(msgs))
  1200. }
  1201. if msgs[0].Type != pb.MsgApp {
  1202. t.Errorf("type = %v, want MsgApp", msgs[0].Type)
  1203. }
  1204. // Once we have an MsgAppResp, heartbeats no longer send MsgApp.
  1205. sm.Step(pb.Message{
  1206. From: 2,
  1207. Type: pb.MsgAppResp,
  1208. Index: msgs[0].Index + uint64(len(msgs[0].Entries)),
  1209. })
  1210. // Consume the message sent in response to MsgAppResp
  1211. sm.readMessages()
  1212. sm.Step(pb.Message{From: 2, Type: pb.MsgHeartbeatResp})
  1213. msgs = sm.readMessages()
  1214. if len(msgs) != 0 {
  1215. t.Fatalf("len(msgs) = %d, want 0: %+v", len(msgs), msgs)
  1216. }
  1217. }
  1218. // TestRaftFreesReadOnlyMem ensures raft will free read request from
  1219. // readOnly readIndexQueue and pendingReadIndex map.
  1220. // related issue: https://github.com/coreos/etcd/issues/7571
  1221. func TestRaftFreesReadOnlyMem(t *testing.T) {
  1222. sm := newTestRaft(1, []uint64{1, 2}, 5, 1, NewMemoryStorage())
  1223. sm.becomeCandidate()
  1224. sm.becomeLeader()
  1225. sm.raftLog.commitTo(sm.raftLog.lastIndex())
  1226. ctx := []byte("ctx")
  1227. // leader starts linearizable read request.
  1228. // more info: raft dissertation 6.4, step 2.
  1229. sm.Step(pb.Message{From: 2, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: ctx}}})
  1230. msgs := sm.readMessages()
  1231. if len(msgs) != 1 {
  1232. t.Fatalf("len(msgs) = %d, want 1", len(msgs))
  1233. }
  1234. if msgs[0].Type != pb.MsgHeartbeat {
  1235. t.Fatalf("type = %v, want MsgHeartbeat", msgs[0].Type)
  1236. }
  1237. if !bytes.Equal(msgs[0].Context, ctx) {
  1238. t.Fatalf("Context = %v, want %v", msgs[0].Context, ctx)
  1239. }
  1240. if len(sm.readOnly.readIndexQueue) != 1 {
  1241. t.Fatalf("len(readIndexQueue) = %v, want 1", len(sm.readOnly.readIndexQueue))
  1242. }
  1243. if len(sm.readOnly.pendingReadIndex) != 1 {
  1244. t.Fatalf("len(pendingReadIndex) = %v, want 1", len(sm.readOnly.pendingReadIndex))
  1245. }
  1246. if _, ok := sm.readOnly.pendingReadIndex[string(ctx)]; !ok {
  1247. t.Fatalf("can't find context %v in pendingReadIndex ", ctx)
  1248. }
  1249. // heartbeat responses from majority of followers (1 in this case)
  1250. // acknowledge the authority of the leader.
  1251. // more info: raft dissertation 6.4, step 3.
  1252. sm.Step(pb.Message{From: 2, Type: pb.MsgHeartbeatResp, Context: ctx})
  1253. if len(sm.readOnly.readIndexQueue) != 0 {
  1254. t.Fatalf("len(readIndexQueue) = %v, want 0", len(sm.readOnly.readIndexQueue))
  1255. }
  1256. if len(sm.readOnly.pendingReadIndex) != 0 {
  1257. t.Fatalf("len(pendingReadIndex) = %v, want 0", len(sm.readOnly.pendingReadIndex))
  1258. }
  1259. if _, ok := sm.readOnly.pendingReadIndex[string(ctx)]; ok {
  1260. t.Fatalf("found context %v in pendingReadIndex, want none", ctx)
  1261. }
  1262. }
  1263. // TestMsgAppRespWaitReset verifies the resume behavior of a leader
  1264. // MsgAppResp.
  1265. func TestMsgAppRespWaitReset(t *testing.T) {
  1266. sm := newTestRaft(1, []uint64{1, 2, 3}, 5, 1, NewMemoryStorage())
  1267. sm.becomeCandidate()
  1268. sm.becomeLeader()
  1269. // The new leader has just emitted a new Term 4 entry; consume those messages
  1270. // from the outgoing queue.
  1271. sm.bcastAppend()
  1272. sm.readMessages()
  1273. // Node 2 acks the first entry, making it committed.
  1274. sm.Step(pb.Message{
  1275. From: 2,
  1276. Type: pb.MsgAppResp,
  1277. Index: 1,
  1278. })
  1279. if sm.raftLog.committed != 1 {
  1280. t.Fatalf("expected committed to be 1, got %d", sm.raftLog.committed)
  1281. }
  1282. // Also consume the MsgApp messages that update Commit on the followers.
  1283. sm.readMessages()
  1284. // A new command is now proposed on node 1.
  1285. sm.Step(pb.Message{
  1286. From: 1,
  1287. Type: pb.MsgProp,
  1288. Entries: []pb.Entry{{}},
  1289. })
  1290. // The command is broadcast to all nodes not in the wait state.
  1291. // Node 2 left the wait state due to its MsgAppResp, but node 3 is still waiting.
  1292. msgs := sm.readMessages()
  1293. if len(msgs) != 1 {
  1294. t.Fatalf("expected 1 message, got %d: %+v", len(msgs), msgs)
  1295. }
  1296. if msgs[0].Type != pb.MsgApp || msgs[0].To != 2 {
  1297. t.Errorf("expected MsgApp to node 2, got %v to %d", msgs[0].Type, msgs[0].To)
  1298. }
  1299. if len(msgs[0].Entries) != 1 || msgs[0].Entries[0].Index != 2 {
  1300. t.Errorf("expected to send entry 2, but got %v", msgs[0].Entries)
  1301. }
  1302. // Now Node 3 acks the first entry. This releases the wait and entry 2 is sent.
  1303. sm.Step(pb.Message{
  1304. From: 3,
  1305. Type: pb.MsgAppResp,
  1306. Index: 1,
  1307. })
  1308. msgs = sm.readMessages()
  1309. if len(msgs) != 1 {
  1310. t.Fatalf("expected 1 message, got %d: %+v", len(msgs), msgs)
  1311. }
  1312. if msgs[0].Type != pb.MsgApp || msgs[0].To != 3 {
  1313. t.Errorf("expected MsgApp to node 3, got %v to %d", msgs[0].Type, msgs[0].To)
  1314. }
  1315. if len(msgs[0].Entries) != 1 || msgs[0].Entries[0].Index != 2 {
  1316. t.Errorf("expected to send entry 2, but got %v", msgs[0].Entries)
  1317. }
  1318. }
  1319. func TestRecvMsgVote(t *testing.T) {
  1320. testRecvMsgVote(t, pb.MsgVote)
  1321. }
  1322. func TestRecvMsgPreVote(t *testing.T) {
  1323. testRecvMsgVote(t, pb.MsgPreVote)
  1324. }
  1325. func testRecvMsgVote(t *testing.T, msgType pb.MessageType) {
  1326. tests := []struct {
  1327. state StateType
  1328. index, logTerm uint64
  1329. voteFor uint64
  1330. wreject bool
  1331. }{
  1332. {StateFollower, 0, 0, None, true},
  1333. {StateFollower, 0, 1, None, true},
  1334. {StateFollower, 0, 2, None, true},
  1335. {StateFollower, 0, 3, None, false},
  1336. {StateFollower, 1, 0, None, true},
  1337. {StateFollower, 1, 1, None, true},
  1338. {StateFollower, 1, 2, None, true},
  1339. {StateFollower, 1, 3, None, false},
  1340. {StateFollower, 2, 0, None, true},
  1341. {StateFollower, 2, 1, None, true},
  1342. {StateFollower, 2, 2, None, false},
  1343. {StateFollower, 2, 3, None, false},
  1344. {StateFollower, 3, 0, None, true},
  1345. {StateFollower, 3, 1, None, true},
  1346. {StateFollower, 3, 2, None, false},
  1347. {StateFollower, 3, 3, None, false},
  1348. {StateFollower, 3, 2, 2, false},
  1349. {StateFollower, 3, 2, 1, true},
  1350. {StateLeader, 3, 3, 1, true},
  1351. {StatePreCandidate, 3, 3, 1, true},
  1352. {StateCandidate, 3, 3, 1, true},
  1353. }
  1354. max := func(a, b uint64) uint64 {
  1355. if a > b {
  1356. return a
  1357. }
  1358. return b
  1359. }
  1360. for i, tt := range tests {
  1361. sm := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  1362. sm.state = tt.state
  1363. switch tt.state {
  1364. case StateFollower:
  1365. sm.step = stepFollower
  1366. case StateCandidate, StatePreCandidate:
  1367. sm.step = stepCandidate
  1368. case StateLeader:
  1369. sm.step = stepLeader
  1370. }
  1371. sm.Vote = tt.voteFor
  1372. sm.raftLog = &raftLog{
  1373. storage: &MemoryStorage{ents: []pb.Entry{{}, {Index: 1, Term: 2}, {Index: 2, Term: 2}}},
  1374. unstable: unstable{offset: 3},
  1375. }
  1376. // raft.Term is greater than or equal to raft.raftLog.lastTerm. In this
  1377. // test we're only testing MsgVote responses when the campaigning node
  1378. // has a different raft log compared to the recipient node.
  1379. // Additionally we're verifying behaviour when the recipient node has
  1380. // already given out its vote for its current term. We're not testing
  1381. // what the recipient node does when receiving a message with a
  1382. // different term number, so we simply initialize both term numbers to
  1383. // be the same.
  1384. term := max(sm.raftLog.lastTerm(), tt.logTerm)
  1385. sm.Term = term
  1386. sm.Step(pb.Message{Type: msgType, Term: term, From: 2, Index: tt.index, LogTerm: tt.logTerm})
  1387. msgs := sm.readMessages()
  1388. if g := len(msgs); g != 1 {
  1389. t.Fatalf("#%d: len(msgs) = %d, want 1", i, g)
  1390. continue
  1391. }
  1392. if g := msgs[0].Type; g != voteRespMsgType(msgType) {
  1393. t.Errorf("#%d, m.Type = %v, want %v", i, g, voteRespMsgType(msgType))
  1394. }
  1395. if g := msgs[0].Reject; g != tt.wreject {
  1396. t.Errorf("#%d, m.Reject = %v, want %v", i, g, tt.wreject)
  1397. }
  1398. }
  1399. }
  1400. func TestStateTransition(t *testing.T) {
  1401. tests := []struct {
  1402. from StateType
  1403. to StateType
  1404. wallow bool
  1405. wterm uint64
  1406. wlead uint64
  1407. }{
  1408. {StateFollower, StateFollower, true, 1, None},
  1409. {StateFollower, StatePreCandidate, true, 0, None},
  1410. {StateFollower, StateCandidate, true, 1, None},
  1411. {StateFollower, StateLeader, false, 0, None},
  1412. {StatePreCandidate, StateFollower, true, 0, None},
  1413. {StatePreCandidate, StatePreCandidate, true, 0, None},
  1414. {StatePreCandidate, StateCandidate, true, 1, None},
  1415. {StatePreCandidate, StateLeader, true, 0, 1},
  1416. {StateCandidate, StateFollower, true, 0, None},
  1417. {StateCandidate, StatePreCandidate, true, 0, None},
  1418. {StateCandidate, StateCandidate, true, 1, None},
  1419. {StateCandidate, StateLeader, true, 0, 1},
  1420. {StateLeader, StateFollower, true, 1, None},
  1421. {StateLeader, StatePreCandidate, false, 0, None},
  1422. {StateLeader, StateCandidate, false, 1, None},
  1423. {StateLeader, StateLeader, true, 0, 1},
  1424. }
  1425. for i, tt := range tests {
  1426. func() {
  1427. defer func() {
  1428. if r := recover(); r != nil {
  1429. if tt.wallow {
  1430. t.Errorf("%d: allow = %v, want %v", i, false, true)
  1431. }
  1432. }
  1433. }()
  1434. sm := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  1435. sm.state = tt.from
  1436. switch tt.to {
  1437. case StateFollower:
  1438. sm.becomeFollower(tt.wterm, tt.wlead)
  1439. case StatePreCandidate:
  1440. sm.becomePreCandidate()
  1441. case StateCandidate:
  1442. sm.becomeCandidate()
  1443. case StateLeader:
  1444. sm.becomeLeader()
  1445. }
  1446. if sm.Term != tt.wterm {
  1447. t.Errorf("%d: term = %d, want %d", i, sm.Term, tt.wterm)
  1448. }
  1449. if sm.lead != tt.wlead {
  1450. t.Errorf("%d: lead = %d, want %d", i, sm.lead, tt.wlead)
  1451. }
  1452. }()
  1453. }
  1454. }
  1455. func TestAllServerStepdown(t *testing.T) {
  1456. tests := []struct {
  1457. state StateType
  1458. wstate StateType
  1459. wterm uint64
  1460. windex uint64
  1461. }{
  1462. {StateFollower, StateFollower, 3, 0},
  1463. {StatePreCandidate, StateFollower, 3, 0},
  1464. {StateCandidate, StateFollower, 3, 0},
  1465. {StateLeader, StateFollower, 3, 1},
  1466. }
  1467. tmsgTypes := [...]pb.MessageType{pb.MsgVote, pb.MsgApp}
  1468. tterm := uint64(3)
  1469. for i, tt := range tests {
  1470. sm := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1471. switch tt.state {
  1472. case StateFollower:
  1473. sm.becomeFollower(1, None)
  1474. case StatePreCandidate:
  1475. sm.becomePreCandidate()
  1476. case StateCandidate:
  1477. sm.becomeCandidate()
  1478. case StateLeader:
  1479. sm.becomeCandidate()
  1480. sm.becomeLeader()
  1481. }
  1482. for j, msgType := range tmsgTypes {
  1483. sm.Step(pb.Message{From: 2, Type: msgType, Term: tterm, LogTerm: tterm})
  1484. if sm.state != tt.wstate {
  1485. t.Errorf("#%d.%d state = %v , want %v", i, j, sm.state, tt.wstate)
  1486. }
  1487. if sm.Term != tt.wterm {
  1488. t.Errorf("#%d.%d term = %v , want %v", i, j, sm.Term, tt.wterm)
  1489. }
  1490. if uint64(sm.raftLog.lastIndex()) != tt.windex {
  1491. t.Errorf("#%d.%d index = %v , want %v", i, j, sm.raftLog.lastIndex(), tt.windex)
  1492. }
  1493. if uint64(len(sm.raftLog.allEntries())) != tt.windex {
  1494. t.Errorf("#%d.%d len(ents) = %v , want %v", i, j, len(sm.raftLog.allEntries()), tt.windex)
  1495. }
  1496. wlead := uint64(2)
  1497. if msgType == pb.MsgVote {
  1498. wlead = None
  1499. }
  1500. if sm.lead != wlead {
  1501. t.Errorf("#%d, sm.lead = %d, want %d", i, sm.lead, None)
  1502. }
  1503. }
  1504. }
  1505. }
  1506. func TestLeaderStepdownWhenQuorumActive(t *testing.T) {
  1507. sm := newTestRaft(1, []uint64{1, 2, 3}, 5, 1, NewMemoryStorage())
  1508. sm.checkQuorum = true
  1509. sm.becomeCandidate()
  1510. sm.becomeLeader()
  1511. for i := 0; i < sm.electionTimeout+1; i++ {
  1512. sm.Step(pb.Message{From: 2, Type: pb.MsgHeartbeatResp, Term: sm.Term})
  1513. sm.tick()
  1514. }
  1515. if sm.state != StateLeader {
  1516. t.Errorf("state = %v, want %v", sm.state, StateLeader)
  1517. }
  1518. }
  1519. func TestLeaderStepdownWhenQuorumLost(t *testing.T) {
  1520. sm := newTestRaft(1, []uint64{1, 2, 3}, 5, 1, NewMemoryStorage())
  1521. sm.checkQuorum = true
  1522. sm.becomeCandidate()
  1523. sm.becomeLeader()
  1524. for i := 0; i < sm.electionTimeout+1; i++ {
  1525. sm.tick()
  1526. }
  1527. if sm.state != StateFollower {
  1528. t.Errorf("state = %v, want %v", sm.state, StateFollower)
  1529. }
  1530. }
  1531. func TestLeaderSupersedingWithCheckQuorum(t *testing.T) {
  1532. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1533. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1534. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1535. a.checkQuorum = true
  1536. b.checkQuorum = true
  1537. c.checkQuorum = true
  1538. nt := newNetwork(a, b, c)
  1539. setRandomizedElectionTimeout(b, b.electionTimeout+1)
  1540. for i := 0; i < b.electionTimeout; i++ {
  1541. b.tick()
  1542. }
  1543. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1544. if a.state != StateLeader {
  1545. t.Errorf("state = %s, want %s", a.state, StateLeader)
  1546. }
  1547. if c.state != StateFollower {
  1548. t.Errorf("state = %s, want %s", c.state, StateFollower)
  1549. }
  1550. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  1551. // Peer b rejected c's vote since its electionElapsed had not reached to electionTimeout
  1552. if c.state != StateCandidate {
  1553. t.Errorf("state = %s, want %s", c.state, StateCandidate)
  1554. }
  1555. // Letting b's electionElapsed reach to electionTimeout
  1556. for i := 0; i < b.electionTimeout; i++ {
  1557. b.tick()
  1558. }
  1559. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  1560. if c.state != StateLeader {
  1561. t.Errorf("state = %s, want %s", c.state, StateLeader)
  1562. }
  1563. }
  1564. func TestLeaderElectionWithCheckQuorum(t *testing.T) {
  1565. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1566. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1567. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1568. a.checkQuorum = true
  1569. b.checkQuorum = true
  1570. c.checkQuorum = true
  1571. nt := newNetwork(a, b, c)
  1572. setRandomizedElectionTimeout(a, a.electionTimeout+1)
  1573. setRandomizedElectionTimeout(b, b.electionTimeout+2)
  1574. // Immediately after creation, votes are cast regardless of the
  1575. // election timeout.
  1576. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1577. if a.state != StateLeader {
  1578. t.Errorf("state = %s, want %s", a.state, StateLeader)
  1579. }
  1580. if c.state != StateFollower {
  1581. t.Errorf("state = %s, want %s", c.state, StateFollower)
  1582. }
  1583. // need to reset randomizedElectionTimeout larger than electionTimeout again,
  1584. // because the value might be reset to electionTimeout since the last state changes
  1585. setRandomizedElectionTimeout(a, a.electionTimeout+1)
  1586. setRandomizedElectionTimeout(b, b.electionTimeout+2)
  1587. for i := 0; i < a.electionTimeout; i++ {
  1588. a.tick()
  1589. }
  1590. for i := 0; i < b.electionTimeout; i++ {
  1591. b.tick()
  1592. }
  1593. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  1594. if a.state != StateFollower {
  1595. t.Errorf("state = %s, want %s", a.state, StateFollower)
  1596. }
  1597. if c.state != StateLeader {
  1598. t.Errorf("state = %s, want %s", c.state, StateLeader)
  1599. }
  1600. }
  1601. // TestFreeStuckCandidateWithCheckQuorum ensures that a candidate with a higher term
  1602. // can disrupt the leader even if the leader still "officially" holds the lease, The
  1603. // leader is expected to step down and adopt the candidate's term
  1604. func TestFreeStuckCandidateWithCheckQuorum(t *testing.T) {
  1605. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1606. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1607. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1608. a.checkQuorum = true
  1609. b.checkQuorum = true
  1610. c.checkQuorum = true
  1611. nt := newNetwork(a, b, c)
  1612. setRandomizedElectionTimeout(b, b.electionTimeout+1)
  1613. for i := 0; i < b.electionTimeout; i++ {
  1614. b.tick()
  1615. }
  1616. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1617. nt.isolate(1)
  1618. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  1619. if b.state != StateFollower {
  1620. t.Errorf("state = %s, want %s", b.state, StateFollower)
  1621. }
  1622. if c.state != StateCandidate {
  1623. t.Errorf("state = %s, want %s", c.state, StateCandidate)
  1624. }
  1625. if c.Term != b.Term+1 {
  1626. t.Errorf("term = %d, want %d", c.Term, b.Term+1)
  1627. }
  1628. // Vote again for safety
  1629. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  1630. if b.state != StateFollower {
  1631. t.Errorf("state = %s, want %s", b.state, StateFollower)
  1632. }
  1633. if c.state != StateCandidate {
  1634. t.Errorf("state = %s, want %s", c.state, StateCandidate)
  1635. }
  1636. if c.Term != b.Term+2 {
  1637. t.Errorf("term = %d, want %d", c.Term, b.Term+2)
  1638. }
  1639. nt.recover()
  1640. nt.send(pb.Message{From: 1, To: 3, Type: pb.MsgHeartbeat, Term: a.Term})
  1641. // Disrupt the leader so that the stuck peer is freed
  1642. if a.state != StateFollower {
  1643. t.Errorf("state = %s, want %s", a.state, StateFollower)
  1644. }
  1645. if c.Term != a.Term {
  1646. t.Errorf("term = %d, want %d", c.Term, a.Term)
  1647. }
  1648. // Vote again, should become leader this time
  1649. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  1650. if c.state != StateLeader {
  1651. t.Errorf("peer 3 state: %s, want %s", c.state, StateLeader)
  1652. }
  1653. }
  1654. func TestNonPromotableVoterWithCheckQuorum(t *testing.T) {
  1655. a := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  1656. b := newTestRaft(2, []uint64{1}, 10, 1, NewMemoryStorage())
  1657. a.checkQuorum = true
  1658. b.checkQuorum = true
  1659. nt := newNetwork(a, b)
  1660. setRandomizedElectionTimeout(b, b.electionTimeout+1)
  1661. // Need to remove 2 again to make it a non-promotable node since newNetwork overwritten some internal states
  1662. b.delProgress(2)
  1663. if b.promotable() {
  1664. t.Fatalf("promotable = %v, want false", b.promotable())
  1665. }
  1666. for i := 0; i < b.electionTimeout; i++ {
  1667. b.tick()
  1668. }
  1669. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1670. if a.state != StateLeader {
  1671. t.Errorf("state = %s, want %s", a.state, StateLeader)
  1672. }
  1673. if b.state != StateFollower {
  1674. t.Errorf("state = %s, want %s", b.state, StateFollower)
  1675. }
  1676. if b.lead != 1 {
  1677. t.Errorf("lead = %d, want 1", b.lead)
  1678. }
  1679. }
  1680. func TestReadOnlyOptionSafe(t *testing.T) {
  1681. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1682. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1683. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1684. nt := newNetwork(a, b, c)
  1685. setRandomizedElectionTimeout(b, b.electionTimeout+1)
  1686. for i := 0; i < b.electionTimeout; i++ {
  1687. b.tick()
  1688. }
  1689. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1690. if a.state != StateLeader {
  1691. t.Fatalf("state = %s, want %s", a.state, StateLeader)
  1692. }
  1693. tests := []struct {
  1694. sm *raft
  1695. proposals int
  1696. wri uint64
  1697. wctx []byte
  1698. }{
  1699. {a, 10, 11, []byte("ctx1")},
  1700. {b, 10, 21, []byte("ctx2")},
  1701. {c, 10, 31, []byte("ctx3")},
  1702. {a, 10, 41, []byte("ctx4")},
  1703. {b, 10, 51, []byte("ctx5")},
  1704. {c, 10, 61, []byte("ctx6")},
  1705. }
  1706. for i, tt := range tests {
  1707. for j := 0; j < tt.proposals; j++ {
  1708. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  1709. }
  1710. nt.send(pb.Message{From: tt.sm.id, To: tt.sm.id, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: tt.wctx}}})
  1711. r := tt.sm
  1712. if len(r.readStates) == 0 {
  1713. t.Errorf("#%d: len(readStates) = 0, want non-zero", i)
  1714. }
  1715. rs := r.readStates[0]
  1716. if rs.Index != tt.wri {
  1717. t.Errorf("#%d: readIndex = %d, want %d", i, rs.Index, tt.wri)
  1718. }
  1719. if !bytes.Equal(rs.RequestCtx, tt.wctx) {
  1720. t.Errorf("#%d: requestCtx = %v, want %v", i, rs.RequestCtx, tt.wctx)
  1721. }
  1722. r.readStates = nil
  1723. }
  1724. }
  1725. func TestReadOnlyOptionLease(t *testing.T) {
  1726. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1727. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1728. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1729. a.readOnly.option = ReadOnlyLeaseBased
  1730. b.readOnly.option = ReadOnlyLeaseBased
  1731. c.readOnly.option = ReadOnlyLeaseBased
  1732. a.checkQuorum = true
  1733. b.checkQuorum = true
  1734. c.checkQuorum = true
  1735. nt := newNetwork(a, b, c)
  1736. setRandomizedElectionTimeout(b, b.electionTimeout+1)
  1737. for i := 0; i < b.electionTimeout; i++ {
  1738. b.tick()
  1739. }
  1740. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1741. if a.state != StateLeader {
  1742. t.Fatalf("state = %s, want %s", a.state, StateLeader)
  1743. }
  1744. tests := []struct {
  1745. sm *raft
  1746. proposals int
  1747. wri uint64
  1748. wctx []byte
  1749. }{
  1750. {a, 10, 11, []byte("ctx1")},
  1751. {b, 10, 21, []byte("ctx2")},
  1752. {c, 10, 31, []byte("ctx3")},
  1753. {a, 10, 41, []byte("ctx4")},
  1754. {b, 10, 51, []byte("ctx5")},
  1755. {c, 10, 61, []byte("ctx6")},
  1756. }
  1757. for i, tt := range tests {
  1758. for j := 0; j < tt.proposals; j++ {
  1759. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  1760. }
  1761. nt.send(pb.Message{From: tt.sm.id, To: tt.sm.id, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: tt.wctx}}})
  1762. r := tt.sm
  1763. rs := r.readStates[0]
  1764. if rs.Index != tt.wri {
  1765. t.Errorf("#%d: readIndex = %d, want %d", i, rs.Index, tt.wri)
  1766. }
  1767. if !bytes.Equal(rs.RequestCtx, tt.wctx) {
  1768. t.Errorf("#%d: requestCtx = %v, want %v", i, rs.RequestCtx, tt.wctx)
  1769. }
  1770. r.readStates = nil
  1771. }
  1772. }
  1773. // TestReadOnlyForNewLeader ensures that a leader only accepts MsgReadIndex message
  1774. // when it commits at least one log entry at it term.
  1775. func TestReadOnlyForNewLeader(t *testing.T) {
  1776. nodeConfigs := []struct {
  1777. id uint64
  1778. committed uint64
  1779. applied uint64
  1780. compact_index uint64
  1781. }{
  1782. {1, 1, 1, 0},
  1783. {2, 2, 2, 2},
  1784. {3, 2, 2, 2},
  1785. }
  1786. peers := make([]stateMachine, 0)
  1787. for _, c := range nodeConfigs {
  1788. storage := NewMemoryStorage()
  1789. storage.Append([]pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}})
  1790. storage.SetHardState(pb.HardState{Term: 1, Commit: c.committed})
  1791. if c.compact_index != 0 {
  1792. storage.Compact(c.compact_index)
  1793. }
  1794. cfg := newTestConfig(c.id, []uint64{1, 2, 3}, 10, 1, storage)
  1795. cfg.Applied = c.applied
  1796. raft := newRaft(cfg)
  1797. peers = append(peers, raft)
  1798. }
  1799. nt := newNetwork(peers...)
  1800. // Drop MsgApp to forbid peer a to commit any log entry at its term after it becomes leader.
  1801. nt.ignore(pb.MsgApp)
  1802. // Force peer a to become leader.
  1803. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1804. sm := nt.peers[1].(*raft)
  1805. if sm.state != StateLeader {
  1806. t.Fatalf("state = %s, want %s", sm.state, StateLeader)
  1807. }
  1808. // Ensure peer a drops read only request.
  1809. var windex uint64 = 4
  1810. wctx := []byte("ctx")
  1811. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: wctx}}})
  1812. if len(sm.readStates) != 0 {
  1813. t.Fatalf("len(readStates) = %d, want zero", len(sm.readStates))
  1814. }
  1815. nt.recover()
  1816. // Force peer a to commit a log entry at its term
  1817. for i := 0; i < sm.heartbeatTimeout; i++ {
  1818. sm.tick()
  1819. }
  1820. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  1821. if sm.raftLog.committed != 4 {
  1822. t.Fatalf("committed = %d, want 4", sm.raftLog.committed)
  1823. }
  1824. lastLogTerm := sm.raftLog.zeroTermOnErrCompacted(sm.raftLog.term(sm.raftLog.committed))
  1825. if lastLogTerm != sm.Term {
  1826. t.Fatalf("last log term = %d, want %d", lastLogTerm, sm.Term)
  1827. }
  1828. // Ensure peer a accepts read only request after it commits a entry at its term.
  1829. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: wctx}}})
  1830. if len(sm.readStates) != 1 {
  1831. t.Fatalf("len(readStates) = %d, want 1", len(sm.readStates))
  1832. }
  1833. rs := sm.readStates[0]
  1834. if rs.Index != windex {
  1835. t.Fatalf("readIndex = %d, want %d", rs.Index, windex)
  1836. }
  1837. if !bytes.Equal(rs.RequestCtx, wctx) {
  1838. t.Fatalf("requestCtx = %v, want %v", rs.RequestCtx, wctx)
  1839. }
  1840. }
  1841. func TestLeaderAppResp(t *testing.T) {
  1842. // initial progress: match = 0; next = 3
  1843. tests := []struct {
  1844. index uint64
  1845. reject bool
  1846. // progress
  1847. wmatch uint64
  1848. wnext uint64
  1849. // message
  1850. wmsgNum int
  1851. windex uint64
  1852. wcommitted uint64
  1853. }{
  1854. {3, true, 0, 3, 0, 0, 0}, // stale resp; no replies
  1855. {2, true, 0, 2, 1, 1, 0}, // denied resp; leader does not commit; decrease next and send probing msg
  1856. {2, false, 2, 4, 2, 2, 2}, // accept resp; leader commits; broadcast with commit index
  1857. {0, false, 0, 3, 0, 0, 0}, // ignore heartbeat replies
  1858. }
  1859. for i, tt := range tests {
  1860. // sm term is 1 after it becomes the leader.
  1861. // thus the last log term must be 1 to be committed.
  1862. sm := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1863. sm.raftLog = &raftLog{
  1864. storage: &MemoryStorage{ents: []pb.Entry{{}, {Index: 1, Term: 0}, {Index: 2, Term: 1}}},
  1865. unstable: unstable{offset: 3},
  1866. }
  1867. sm.becomeCandidate()
  1868. sm.becomeLeader()
  1869. sm.readMessages()
  1870. sm.Step(pb.Message{From: 2, Type: pb.MsgAppResp, Index: tt.index, Term: sm.Term, Reject: tt.reject, RejectHint: tt.index})
  1871. p := sm.prs[2]
  1872. if p.Match != tt.wmatch {
  1873. t.Errorf("#%d match = %d, want %d", i, p.Match, tt.wmatch)
  1874. }
  1875. if p.Next != tt.wnext {
  1876. t.Errorf("#%d next = %d, want %d", i, p.Next, tt.wnext)
  1877. }
  1878. msgs := sm.readMessages()
  1879. if len(msgs) != tt.wmsgNum {
  1880. t.Errorf("#%d msgNum = %d, want %d", i, len(msgs), tt.wmsgNum)
  1881. }
  1882. for j, msg := range msgs {
  1883. if msg.Index != tt.windex {
  1884. t.Errorf("#%d.%d index = %d, want %d", i, j, msg.Index, tt.windex)
  1885. }
  1886. if msg.Commit != tt.wcommitted {
  1887. t.Errorf("#%d.%d commit = %d, want %d", i, j, msg.Commit, tt.wcommitted)
  1888. }
  1889. }
  1890. }
  1891. }
  1892. // When the leader receives a heartbeat tick, it should
  1893. // send a MsgApp with m.Index = 0, m.LogTerm=0 and empty entries.
  1894. func TestBcastBeat(t *testing.T) {
  1895. offset := uint64(1000)
  1896. // make a state machine with log.offset = 1000
  1897. s := pb.Snapshot{
  1898. Metadata: pb.SnapshotMetadata{
  1899. Index: offset,
  1900. Term: 1,
  1901. ConfState: pb.ConfState{Nodes: []uint64{1, 2, 3}},
  1902. },
  1903. }
  1904. storage := NewMemoryStorage()
  1905. storage.ApplySnapshot(s)
  1906. sm := newTestRaft(1, nil, 10, 1, storage)
  1907. sm.Term = 1
  1908. sm.becomeCandidate()
  1909. sm.becomeLeader()
  1910. for i := 0; i < 10; i++ {
  1911. sm.appendEntry(pb.Entry{Index: uint64(i) + 1})
  1912. }
  1913. // slow follower
  1914. sm.prs[2].Match, sm.prs[2].Next = 5, 6
  1915. // normal follower
  1916. sm.prs[3].Match, sm.prs[3].Next = sm.raftLog.lastIndex(), sm.raftLog.lastIndex()+1
  1917. sm.Step(pb.Message{Type: pb.MsgBeat})
  1918. msgs := sm.readMessages()
  1919. if len(msgs) != 2 {
  1920. t.Fatalf("len(msgs) = %v, want 2", len(msgs))
  1921. }
  1922. wantCommitMap := map[uint64]uint64{
  1923. 2: min(sm.raftLog.committed, sm.prs[2].Match),
  1924. 3: min(sm.raftLog.committed, sm.prs[3].Match),
  1925. }
  1926. for i, m := range msgs {
  1927. if m.Type != pb.MsgHeartbeat {
  1928. t.Fatalf("#%d: type = %v, want = %v", i, m.Type, pb.MsgHeartbeat)
  1929. }
  1930. if m.Index != 0 {
  1931. t.Fatalf("#%d: prevIndex = %d, want %d", i, m.Index, 0)
  1932. }
  1933. if m.LogTerm != 0 {
  1934. t.Fatalf("#%d: prevTerm = %d, want %d", i, m.LogTerm, 0)
  1935. }
  1936. if wantCommitMap[m.To] == 0 {
  1937. t.Fatalf("#%d: unexpected to %d", i, m.To)
  1938. } else {
  1939. if m.Commit != wantCommitMap[m.To] {
  1940. t.Fatalf("#%d: commit = %d, want %d", i, m.Commit, wantCommitMap[m.To])
  1941. }
  1942. delete(wantCommitMap, m.To)
  1943. }
  1944. if len(m.Entries) != 0 {
  1945. t.Fatalf("#%d: len(entries) = %d, want 0", i, len(m.Entries))
  1946. }
  1947. }
  1948. }
  1949. // tests the output of the state machine when receiving MsgBeat
  1950. func TestRecvMsgBeat(t *testing.T) {
  1951. tests := []struct {
  1952. state StateType
  1953. wMsg int
  1954. }{
  1955. {StateLeader, 2},
  1956. // candidate and follower should ignore MsgBeat
  1957. {StateCandidate, 0},
  1958. {StateFollower, 0},
  1959. }
  1960. for i, tt := range tests {
  1961. sm := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1962. sm.raftLog = &raftLog{storage: &MemoryStorage{ents: []pb.Entry{{}, {Index: 1, Term: 0}, {Index: 2, Term: 1}}}}
  1963. sm.Term = 1
  1964. sm.state = tt.state
  1965. switch tt.state {
  1966. case StateFollower:
  1967. sm.step = stepFollower
  1968. case StateCandidate:
  1969. sm.step = stepCandidate
  1970. case StateLeader:
  1971. sm.step = stepLeader
  1972. }
  1973. sm.Step(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  1974. msgs := sm.readMessages()
  1975. if len(msgs) != tt.wMsg {
  1976. t.Errorf("%d: len(msgs) = %d, want %d", i, len(msgs), tt.wMsg)
  1977. }
  1978. for _, m := range msgs {
  1979. if m.Type != pb.MsgHeartbeat {
  1980. t.Errorf("%d: msg.type = %v, want %v", i, m.Type, pb.MsgHeartbeat)
  1981. }
  1982. }
  1983. }
  1984. }
  1985. func TestLeaderIncreaseNext(t *testing.T) {
  1986. previousEnts := []pb.Entry{{Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3}}
  1987. tests := []struct {
  1988. // progress
  1989. state ProgressStateType
  1990. next uint64
  1991. wnext uint64
  1992. }{
  1993. // state replicate, optimistically increase next
  1994. // previous entries + noop entry + propose + 1
  1995. {ProgressStateReplicate, 2, uint64(len(previousEnts) + 1 + 1 + 1)},
  1996. // state probe, not optimistically increase next
  1997. {ProgressStateProbe, 2, 2},
  1998. }
  1999. for i, tt := range tests {
  2000. sm := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2001. sm.raftLog.append(previousEnts...)
  2002. sm.becomeCandidate()
  2003. sm.becomeLeader()
  2004. sm.prs[2].State = tt.state
  2005. sm.prs[2].Next = tt.next
  2006. sm.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  2007. p := sm.prs[2]
  2008. if p.Next != tt.wnext {
  2009. t.Errorf("#%d next = %d, want %d", i, p.Next, tt.wnext)
  2010. }
  2011. }
  2012. }
  2013. func TestSendAppendForProgressProbe(t *testing.T) {
  2014. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2015. r.becomeCandidate()
  2016. r.becomeLeader()
  2017. r.readMessages()
  2018. r.prs[2].becomeProbe()
  2019. // each round is a heartbeat
  2020. for i := 0; i < 3; i++ {
  2021. if i == 0 {
  2022. // we expect that raft will only send out one msgAPP on the first
  2023. // loop. After that, the follower is paused until a heartbeat response is
  2024. // received.
  2025. r.appendEntry(pb.Entry{Data: []byte("somedata")})
  2026. r.sendAppend(2)
  2027. msg := r.readMessages()
  2028. if len(msg) != 1 {
  2029. t.Errorf("len(msg) = %d, want %d", len(msg), 1)
  2030. }
  2031. if msg[0].Index != 0 {
  2032. t.Errorf("index = %d, want %d", msg[0].Index, 0)
  2033. }
  2034. }
  2035. if !r.prs[2].Paused {
  2036. t.Errorf("paused = %v, want true", r.prs[2].Paused)
  2037. }
  2038. for j := 0; j < 10; j++ {
  2039. r.appendEntry(pb.Entry{Data: []byte("somedata")})
  2040. r.sendAppend(2)
  2041. if l := len(r.readMessages()); l != 0 {
  2042. t.Errorf("len(msg) = %d, want %d", l, 0)
  2043. }
  2044. }
  2045. // do a heartbeat
  2046. for j := 0; j < r.heartbeatTimeout; j++ {
  2047. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  2048. }
  2049. if !r.prs[2].Paused {
  2050. t.Errorf("paused = %v, want true", r.prs[2].Paused)
  2051. }
  2052. // consume the heartbeat
  2053. msg := r.readMessages()
  2054. if len(msg) != 1 {
  2055. t.Errorf("len(msg) = %d, want %d", len(msg), 1)
  2056. }
  2057. if msg[0].Type != pb.MsgHeartbeat {
  2058. t.Errorf("type = %v, want %v", msg[0].Type, pb.MsgHeartbeat)
  2059. }
  2060. }
  2061. // a heartbeat response will allow another message to be sent
  2062. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgHeartbeatResp})
  2063. msg := r.readMessages()
  2064. if len(msg) != 1 {
  2065. t.Errorf("len(msg) = %d, want %d", len(msg), 1)
  2066. }
  2067. if msg[0].Index != 0 {
  2068. t.Errorf("index = %d, want %d", msg[0].Index, 0)
  2069. }
  2070. if !r.prs[2].Paused {
  2071. t.Errorf("paused = %v, want true", r.prs[2].Paused)
  2072. }
  2073. }
  2074. func TestSendAppendForProgressReplicate(t *testing.T) {
  2075. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2076. r.becomeCandidate()
  2077. r.becomeLeader()
  2078. r.readMessages()
  2079. r.prs[2].becomeReplicate()
  2080. for i := 0; i < 10; i++ {
  2081. r.appendEntry(pb.Entry{Data: []byte("somedata")})
  2082. r.sendAppend(2)
  2083. msgs := r.readMessages()
  2084. if len(msgs) != 1 {
  2085. t.Errorf("len(msg) = %d, want %d", len(msgs), 1)
  2086. }
  2087. }
  2088. }
  2089. func TestSendAppendForProgressSnapshot(t *testing.T) {
  2090. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2091. r.becomeCandidate()
  2092. r.becomeLeader()
  2093. r.readMessages()
  2094. r.prs[2].becomeSnapshot(10)
  2095. for i := 0; i < 10; i++ {
  2096. r.appendEntry(pb.Entry{Data: []byte("somedata")})
  2097. r.sendAppend(2)
  2098. msgs := r.readMessages()
  2099. if len(msgs) != 0 {
  2100. t.Errorf("len(msg) = %d, want %d", len(msgs), 0)
  2101. }
  2102. }
  2103. }
  2104. func TestRecvMsgUnreachable(t *testing.T) {
  2105. previousEnts := []pb.Entry{{Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3}}
  2106. s := NewMemoryStorage()
  2107. s.Append(previousEnts)
  2108. r := newTestRaft(1, []uint64{1, 2}, 10, 1, s)
  2109. r.becomeCandidate()
  2110. r.becomeLeader()
  2111. r.readMessages()
  2112. // set node 2 to state replicate
  2113. r.prs[2].Match = 3
  2114. r.prs[2].becomeReplicate()
  2115. r.prs[2].optimisticUpdate(5)
  2116. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgUnreachable})
  2117. if r.prs[2].State != ProgressStateProbe {
  2118. t.Errorf("state = %s, want %s", r.prs[2].State, ProgressStateProbe)
  2119. }
  2120. if wnext := r.prs[2].Match + 1; r.prs[2].Next != wnext {
  2121. t.Errorf("next = %d, want %d", r.prs[2].Next, wnext)
  2122. }
  2123. }
  2124. func TestRestore(t *testing.T) {
  2125. s := pb.Snapshot{
  2126. Metadata: pb.SnapshotMetadata{
  2127. Index: 11, // magic number
  2128. Term: 11, // magic number
  2129. ConfState: pb.ConfState{Nodes: []uint64{1, 2, 3}},
  2130. },
  2131. }
  2132. storage := NewMemoryStorage()
  2133. sm := newTestRaft(1, []uint64{1, 2}, 10, 1, storage)
  2134. if ok := sm.restore(s); !ok {
  2135. t.Fatal("restore fail, want succeed")
  2136. }
  2137. if sm.raftLog.lastIndex() != s.Metadata.Index {
  2138. t.Errorf("log.lastIndex = %d, want %d", sm.raftLog.lastIndex(), s.Metadata.Index)
  2139. }
  2140. if mustTerm(sm.raftLog.term(s.Metadata.Index)) != s.Metadata.Term {
  2141. t.Errorf("log.lastTerm = %d, want %d", mustTerm(sm.raftLog.term(s.Metadata.Index)), s.Metadata.Term)
  2142. }
  2143. sg := sm.nodes()
  2144. if !reflect.DeepEqual(sg, s.Metadata.ConfState.Nodes) {
  2145. t.Errorf("sm.Nodes = %+v, want %+v", sg, s.Metadata.ConfState.Nodes)
  2146. }
  2147. if ok := sm.restore(s); ok {
  2148. t.Fatal("restore succeed, want fail")
  2149. }
  2150. }
  2151. // TestRestoreWithLearner restores a snapshot which contains learners.
  2152. func TestRestoreWithLearner(t *testing.T) {
  2153. s := pb.Snapshot{
  2154. Metadata: pb.SnapshotMetadata{
  2155. Index: 11, // magic number
  2156. Term: 11, // magic number
  2157. ConfState: pb.ConfState{Nodes: []uint64{1, 2}, Learners: []uint64{3}},
  2158. },
  2159. }
  2160. storage := NewMemoryStorage()
  2161. sm := newTestLearnerRaft(3, []uint64{1, 2}, []uint64{3}, 10, 1, storage)
  2162. if ok := sm.restore(s); !ok {
  2163. t.Error("restore fail, want succeed")
  2164. }
  2165. if sm.raftLog.lastIndex() != s.Metadata.Index {
  2166. t.Errorf("log.lastIndex = %d, want %d", sm.raftLog.lastIndex(), s.Metadata.Index)
  2167. }
  2168. if mustTerm(sm.raftLog.term(s.Metadata.Index)) != s.Metadata.Term {
  2169. t.Errorf("log.lastTerm = %d, want %d", mustTerm(sm.raftLog.term(s.Metadata.Index)), s.Metadata.Term)
  2170. }
  2171. sg := sm.nodes()
  2172. if len(sg) != len(s.Metadata.ConfState.Nodes) {
  2173. t.Errorf("sm.Nodes = %+v, length not equal with %+v", sg, s.Metadata.ConfState.Nodes)
  2174. }
  2175. lns := sm.learnerNodes()
  2176. if len(lns) != len(s.Metadata.ConfState.Learners) {
  2177. t.Errorf("sm.LearnerNodes = %+v, length not equal with %+v", sg, s.Metadata.ConfState.Learners)
  2178. }
  2179. for _, n := range s.Metadata.ConfState.Nodes {
  2180. if sm.prs[n].IsLearner {
  2181. t.Errorf("sm.Node %x isLearner = %s, want %t", n, sm.prs[n], false)
  2182. }
  2183. }
  2184. for _, n := range s.Metadata.ConfState.Learners {
  2185. if !sm.learnerPrs[n].IsLearner {
  2186. t.Errorf("sm.Node %x isLearner = %s, want %t", n, sm.prs[n], true)
  2187. }
  2188. }
  2189. if ok := sm.restore(s); ok {
  2190. t.Error("restore succeed, want fail")
  2191. }
  2192. }
  2193. // TestRestoreInvalidLearner verfies that a normal peer can't become learner again
  2194. // when restores snapshot.
  2195. func TestRestoreInvalidLearner(t *testing.T) {
  2196. s := pb.Snapshot{
  2197. Metadata: pb.SnapshotMetadata{
  2198. Index: 11, // magic number
  2199. Term: 11, // magic number
  2200. ConfState: pb.ConfState{Nodes: []uint64{1, 2}, Learners: []uint64{3}},
  2201. },
  2202. }
  2203. storage := NewMemoryStorage()
  2204. sm := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, storage)
  2205. if sm.isLearner {
  2206. t.Errorf("%x is learner, want not", sm.id)
  2207. }
  2208. if ok := sm.restore(s); ok {
  2209. t.Error("restore succeed, want fail")
  2210. }
  2211. }
  2212. // TestRestoreLearnerPromotion checks that a learner can become to a follower after
  2213. // restoring snapshot.
  2214. func TestRestoreLearnerPromotion(t *testing.T) {
  2215. s := pb.Snapshot{
  2216. Metadata: pb.SnapshotMetadata{
  2217. Index: 11, // magic number
  2218. Term: 11, // magic number
  2219. ConfState: pb.ConfState{Nodes: []uint64{1, 2, 3}},
  2220. },
  2221. }
  2222. storage := NewMemoryStorage()
  2223. sm := newTestLearnerRaft(3, []uint64{1, 2}, []uint64{3}, 10, 1, storage)
  2224. if !sm.isLearner {
  2225. t.Errorf("%x is not learner, want yes", sm.id)
  2226. }
  2227. if ok := sm.restore(s); !ok {
  2228. t.Error("restore fail, want succeed")
  2229. }
  2230. if sm.isLearner {
  2231. t.Errorf("%x is learner, want not", sm.id)
  2232. }
  2233. }
  2234. // TestLearnerReceiveSnapshot tests that a learner can receive a snpahost from leader
  2235. func TestLearnerReceiveSnapshot(t *testing.T) {
  2236. // restore the state machine from a snapshot so it has a compacted log and a snapshot
  2237. s := pb.Snapshot{
  2238. Metadata: pb.SnapshotMetadata{
  2239. Index: 11, // magic number
  2240. Term: 11, // magic number
  2241. ConfState: pb.ConfState{Nodes: []uint64{1}, Learners: []uint64{2}},
  2242. },
  2243. }
  2244. n1 := newTestLearnerRaft(1, []uint64{1}, []uint64{2}, 10, 1, NewMemoryStorage())
  2245. n2 := newTestLearnerRaft(2, []uint64{1}, []uint64{2}, 10, 1, NewMemoryStorage())
  2246. n1.restore(s)
  2247. // Force set n1 appplied index.
  2248. n1.raftLog.appliedTo(n1.raftLog.committed)
  2249. nt := newNetwork(n1, n2)
  2250. setRandomizedElectionTimeout(n1, n1.electionTimeout)
  2251. for i := 0; i < n1.electionTimeout; i++ {
  2252. n1.tick()
  2253. }
  2254. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  2255. if n2.raftLog.committed != n1.raftLog.committed {
  2256. t.Errorf("peer 2 must commit to %d, but %d", n1.raftLog.committed, n2.raftLog.committed)
  2257. }
  2258. }
  2259. func TestRestoreIgnoreSnapshot(t *testing.T) {
  2260. previousEnts := []pb.Entry{{Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3}}
  2261. commit := uint64(1)
  2262. storage := NewMemoryStorage()
  2263. sm := newTestRaft(1, []uint64{1, 2}, 10, 1, storage)
  2264. sm.raftLog.append(previousEnts...)
  2265. sm.raftLog.commitTo(commit)
  2266. s := pb.Snapshot{
  2267. Metadata: pb.SnapshotMetadata{
  2268. Index: commit,
  2269. Term: 1,
  2270. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  2271. },
  2272. }
  2273. // ignore snapshot
  2274. if ok := sm.restore(s); ok {
  2275. t.Errorf("restore = %t, want %t", ok, false)
  2276. }
  2277. if sm.raftLog.committed != commit {
  2278. t.Errorf("commit = %d, want %d", sm.raftLog.committed, commit)
  2279. }
  2280. // ignore snapshot and fast forward commit
  2281. s.Metadata.Index = commit + 1
  2282. if ok := sm.restore(s); ok {
  2283. t.Errorf("restore = %t, want %t", ok, false)
  2284. }
  2285. if sm.raftLog.committed != commit+1 {
  2286. t.Errorf("commit = %d, want %d", sm.raftLog.committed, commit+1)
  2287. }
  2288. }
  2289. func TestProvideSnap(t *testing.T) {
  2290. // restore the state machine from a snapshot so it has a compacted log and a snapshot
  2291. s := pb.Snapshot{
  2292. Metadata: pb.SnapshotMetadata{
  2293. Index: 11, // magic number
  2294. Term: 11, // magic number
  2295. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  2296. },
  2297. }
  2298. storage := NewMemoryStorage()
  2299. sm := newTestRaft(1, []uint64{1}, 10, 1, storage)
  2300. sm.restore(s)
  2301. sm.becomeCandidate()
  2302. sm.becomeLeader()
  2303. // force set the next of node 2, so that node 2 needs a snapshot
  2304. sm.prs[2].Next = sm.raftLog.firstIndex()
  2305. sm.Step(pb.Message{From: 2, To: 1, Type: pb.MsgAppResp, Index: sm.prs[2].Next - 1, Reject: true})
  2306. msgs := sm.readMessages()
  2307. if len(msgs) != 1 {
  2308. t.Fatalf("len(msgs) = %d, want 1", len(msgs))
  2309. }
  2310. m := msgs[0]
  2311. if m.Type != pb.MsgSnap {
  2312. t.Errorf("m.Type = %v, want %v", m.Type, pb.MsgSnap)
  2313. }
  2314. }
  2315. func TestIgnoreProvidingSnap(t *testing.T) {
  2316. // restore the state machine from a snapshot so it has a compacted log and a snapshot
  2317. s := pb.Snapshot{
  2318. Metadata: pb.SnapshotMetadata{
  2319. Index: 11, // magic number
  2320. Term: 11, // magic number
  2321. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  2322. },
  2323. }
  2324. storage := NewMemoryStorage()
  2325. sm := newTestRaft(1, []uint64{1}, 10, 1, storage)
  2326. sm.restore(s)
  2327. sm.becomeCandidate()
  2328. sm.becomeLeader()
  2329. // force set the next of node 2, so that node 2 needs a snapshot
  2330. // change node 2 to be inactive, expect node 1 ignore sending snapshot to 2
  2331. sm.prs[2].Next = sm.raftLog.firstIndex() - 1
  2332. sm.prs[2].RecentActive = false
  2333. sm.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  2334. msgs := sm.readMessages()
  2335. if len(msgs) != 0 {
  2336. t.Errorf("len(msgs) = %d, want 0", len(msgs))
  2337. }
  2338. }
  2339. func TestRestoreFromSnapMsg(t *testing.T) {
  2340. s := pb.Snapshot{
  2341. Metadata: pb.SnapshotMetadata{
  2342. Index: 11, // magic number
  2343. Term: 11, // magic number
  2344. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  2345. },
  2346. }
  2347. m := pb.Message{Type: pb.MsgSnap, From: 1, Term: 2, Snapshot: s}
  2348. sm := newTestRaft(2, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2349. sm.Step(m)
  2350. if sm.lead != uint64(1) {
  2351. t.Errorf("sm.lead = %d, want 1", sm.lead)
  2352. }
  2353. // TODO(bdarnell): what should this test?
  2354. }
  2355. func TestSlowNodeRestore(t *testing.T) {
  2356. nt := newNetwork(nil, nil, nil)
  2357. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2358. nt.isolate(3)
  2359. for j := 0; j <= 100; j++ {
  2360. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2361. }
  2362. lead := nt.peers[1].(*raft)
  2363. nextEnts(lead, nt.storage[1])
  2364. nt.storage[1].CreateSnapshot(lead.raftLog.applied, &pb.ConfState{Nodes: lead.nodes()}, nil)
  2365. nt.storage[1].Compact(lead.raftLog.applied)
  2366. nt.recover()
  2367. // send heartbeats so that the leader can learn everyone is active.
  2368. // node 3 will only be considered as active when node 1 receives a reply from it.
  2369. for {
  2370. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  2371. if lead.prs[3].RecentActive {
  2372. break
  2373. }
  2374. }
  2375. // trigger a snapshot
  2376. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2377. follower := nt.peers[3].(*raft)
  2378. // trigger a commit
  2379. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2380. if follower.raftLog.committed != lead.raftLog.committed {
  2381. t.Errorf("follower.committed = %d, want %d", follower.raftLog.committed, lead.raftLog.committed)
  2382. }
  2383. }
  2384. // TestStepConfig tests that when raft step msgProp in EntryConfChange type,
  2385. // it appends the entry to log and sets pendingConf to be true.
  2386. func TestStepConfig(t *testing.T) {
  2387. // a raft that cannot make progress
  2388. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2389. r.becomeCandidate()
  2390. r.becomeLeader()
  2391. index := r.raftLog.lastIndex()
  2392. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange}}})
  2393. if g := r.raftLog.lastIndex(); g != index+1 {
  2394. t.Errorf("index = %d, want %d", g, index+1)
  2395. }
  2396. if r.pendingConfIndex != index+1 {
  2397. t.Errorf("pendingConfIndex = %d, want %d", r.pendingConfIndex, index+1)
  2398. }
  2399. }
  2400. // TestStepIgnoreConfig tests that if raft step the second msgProp in
  2401. // EntryConfChange type when the first one is uncommitted, the node will set
  2402. // the proposal to noop and keep its original state.
  2403. func TestStepIgnoreConfig(t *testing.T) {
  2404. // a raft that cannot make progress
  2405. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2406. r.becomeCandidate()
  2407. r.becomeLeader()
  2408. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange}}})
  2409. index := r.raftLog.lastIndex()
  2410. pendingConfIndex := r.pendingConfIndex
  2411. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange}}})
  2412. wents := []pb.Entry{{Type: pb.EntryNormal, Term: 1, Index: 3, Data: nil}}
  2413. ents, err := r.raftLog.entries(index+1, noLimit)
  2414. if err != nil {
  2415. t.Fatalf("unexpected error %v", err)
  2416. }
  2417. if !reflect.DeepEqual(ents, wents) {
  2418. t.Errorf("ents = %+v, want %+v", ents, wents)
  2419. }
  2420. if r.pendingConfIndex != pendingConfIndex {
  2421. t.Errorf("pendingConfIndex = %d, want %d", r.pendingConfIndex, pendingConfIndex)
  2422. }
  2423. }
  2424. // TestNewLeaderPendingConfig tests that new leader sets its pendingConfigIndex
  2425. // based on uncommitted entries.
  2426. func TestNewLeaderPendingConfig(t *testing.T) {
  2427. tests := []struct {
  2428. addEntry bool
  2429. wpendingIndex uint64
  2430. }{
  2431. {false, 0},
  2432. {true, 1},
  2433. }
  2434. for i, tt := range tests {
  2435. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2436. if tt.addEntry {
  2437. r.appendEntry(pb.Entry{Type: pb.EntryNormal})
  2438. }
  2439. r.becomeCandidate()
  2440. r.becomeLeader()
  2441. if r.pendingConfIndex != tt.wpendingIndex {
  2442. t.Errorf("#%d: pendingConfIndex = %d, want %d",
  2443. i, r.pendingConfIndex, tt.wpendingIndex)
  2444. }
  2445. }
  2446. }
  2447. // TestAddNode tests that addNode could update nodes correctly.
  2448. func TestAddNode(t *testing.T) {
  2449. r := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  2450. r.addNode(2)
  2451. nodes := r.nodes()
  2452. wnodes := []uint64{1, 2}
  2453. if !reflect.DeepEqual(nodes, wnodes) {
  2454. t.Errorf("nodes = %v, want %v", nodes, wnodes)
  2455. }
  2456. }
  2457. // TestAddLearner tests that addLearner could update nodes correctly.
  2458. func TestAddLearner(t *testing.T) {
  2459. r := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  2460. r.addLearner(2)
  2461. nodes := r.learnerNodes()
  2462. wnodes := []uint64{2}
  2463. if !reflect.DeepEqual(nodes, wnodes) {
  2464. t.Errorf("nodes = %v, want %v", nodes, wnodes)
  2465. }
  2466. if !r.learnerPrs[2].IsLearner {
  2467. t.Errorf("node 2 is learner %t, want %t", r.prs[2].IsLearner, true)
  2468. }
  2469. }
  2470. // TestAddNodeCheckQuorum tests that addNode does not trigger a leader election
  2471. // immediately when checkQuorum is set.
  2472. func TestAddNodeCheckQuorum(t *testing.T) {
  2473. r := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  2474. r.checkQuorum = true
  2475. r.becomeCandidate()
  2476. r.becomeLeader()
  2477. for i := 0; i < r.electionTimeout-1; i++ {
  2478. r.tick()
  2479. }
  2480. r.addNode(2)
  2481. // This tick will reach electionTimeout, which triggers a quorum check.
  2482. r.tick()
  2483. // Node 1 should still be the leader after a single tick.
  2484. if r.state != StateLeader {
  2485. t.Errorf("state = %v, want %v", r.state, StateLeader)
  2486. }
  2487. // After another electionTimeout ticks without hearing from node 2,
  2488. // node 1 should step down.
  2489. for i := 0; i < r.electionTimeout; i++ {
  2490. r.tick()
  2491. }
  2492. if r.state != StateFollower {
  2493. t.Errorf("state = %v, want %v", r.state, StateFollower)
  2494. }
  2495. }
  2496. // TestRemoveNode tests that removeNode could update nodes and
  2497. // and removed list correctly.
  2498. func TestRemoveNode(t *testing.T) {
  2499. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2500. r.removeNode(2)
  2501. w := []uint64{1}
  2502. if g := r.nodes(); !reflect.DeepEqual(g, w) {
  2503. t.Errorf("nodes = %v, want %v", g, w)
  2504. }
  2505. // remove all nodes from cluster
  2506. r.removeNode(1)
  2507. w = []uint64{}
  2508. if g := r.nodes(); !reflect.DeepEqual(g, w) {
  2509. t.Errorf("nodes = %v, want %v", g, w)
  2510. }
  2511. }
  2512. // TestRemoveLearner tests that removeNode could update nodes and
  2513. // and removed list correctly.
  2514. func TestRemoveLearner(t *testing.T) {
  2515. r := newTestLearnerRaft(1, []uint64{1}, []uint64{2}, 10, 1, NewMemoryStorage())
  2516. r.removeNode(2)
  2517. w := []uint64{1}
  2518. if g := r.nodes(); !reflect.DeepEqual(g, w) {
  2519. t.Errorf("nodes = %v, want %v", g, w)
  2520. }
  2521. w = []uint64{}
  2522. if g := r.learnerNodes(); !reflect.DeepEqual(g, w) {
  2523. t.Errorf("nodes = %v, want %v", g, w)
  2524. }
  2525. // remove all nodes from cluster
  2526. r.removeNode(1)
  2527. if g := r.nodes(); !reflect.DeepEqual(g, w) {
  2528. t.Errorf("nodes = %v, want %v", g, w)
  2529. }
  2530. }
  2531. func TestPromotable(t *testing.T) {
  2532. id := uint64(1)
  2533. tests := []struct {
  2534. peers []uint64
  2535. wp bool
  2536. }{
  2537. {[]uint64{1}, true},
  2538. {[]uint64{1, 2, 3}, true},
  2539. {[]uint64{}, false},
  2540. {[]uint64{2, 3}, false},
  2541. }
  2542. for i, tt := range tests {
  2543. r := newTestRaft(id, tt.peers, 5, 1, NewMemoryStorage())
  2544. if g := r.promotable(); g != tt.wp {
  2545. t.Errorf("#%d: promotable = %v, want %v", i, g, tt.wp)
  2546. }
  2547. }
  2548. }
  2549. func TestRaftNodes(t *testing.T) {
  2550. tests := []struct {
  2551. ids []uint64
  2552. wids []uint64
  2553. }{
  2554. {
  2555. []uint64{1, 2, 3},
  2556. []uint64{1, 2, 3},
  2557. },
  2558. {
  2559. []uint64{3, 2, 1},
  2560. []uint64{1, 2, 3},
  2561. },
  2562. }
  2563. for i, tt := range tests {
  2564. r := newTestRaft(1, tt.ids, 10, 1, NewMemoryStorage())
  2565. if !reflect.DeepEqual(r.nodes(), tt.wids) {
  2566. t.Errorf("#%d: nodes = %+v, want %+v", i, r.nodes(), tt.wids)
  2567. }
  2568. }
  2569. }
  2570. func TestCampaignWhileLeader(t *testing.T) {
  2571. testCampaignWhileLeader(t, false)
  2572. }
  2573. func TestPreCampaignWhileLeader(t *testing.T) {
  2574. testCampaignWhileLeader(t, true)
  2575. }
  2576. func testCampaignWhileLeader(t *testing.T, preVote bool) {
  2577. cfg := newTestConfig(1, []uint64{1}, 5, 1, NewMemoryStorage())
  2578. cfg.PreVote = preVote
  2579. r := newRaft(cfg)
  2580. if r.state != StateFollower {
  2581. t.Errorf("expected new node to be follower but got %s", r.state)
  2582. }
  2583. // We don't call campaign() directly because it comes after the check
  2584. // for our current state.
  2585. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2586. if r.state != StateLeader {
  2587. t.Errorf("expected single-node election to become leader but got %s", r.state)
  2588. }
  2589. term := r.Term
  2590. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2591. if r.state != StateLeader {
  2592. t.Errorf("expected to remain leader but got %s", r.state)
  2593. }
  2594. if r.Term != term {
  2595. t.Errorf("expected to remain in term %v but got %v", term, r.Term)
  2596. }
  2597. }
  2598. // TestCommitAfterRemoveNode verifies that pending commands can become
  2599. // committed when a config change reduces the quorum requirements.
  2600. func TestCommitAfterRemoveNode(t *testing.T) {
  2601. // Create a cluster with two nodes.
  2602. s := NewMemoryStorage()
  2603. r := newTestRaft(1, []uint64{1, 2}, 5, 1, s)
  2604. r.becomeCandidate()
  2605. r.becomeLeader()
  2606. // Begin to remove the second node.
  2607. cc := pb.ConfChange{
  2608. Type: pb.ConfChangeRemoveNode,
  2609. NodeID: 2,
  2610. }
  2611. ccData, err := cc.Marshal()
  2612. if err != nil {
  2613. t.Fatal(err)
  2614. }
  2615. r.Step(pb.Message{
  2616. Type: pb.MsgProp,
  2617. Entries: []pb.Entry{
  2618. {Type: pb.EntryConfChange, Data: ccData},
  2619. },
  2620. })
  2621. // Stabilize the log and make sure nothing is committed yet.
  2622. if ents := nextEnts(r, s); len(ents) > 0 {
  2623. t.Fatalf("unexpected committed entries: %v", ents)
  2624. }
  2625. ccIndex := r.raftLog.lastIndex()
  2626. // While the config change is pending, make another proposal.
  2627. r.Step(pb.Message{
  2628. Type: pb.MsgProp,
  2629. Entries: []pb.Entry{
  2630. {Type: pb.EntryNormal, Data: []byte("hello")},
  2631. },
  2632. })
  2633. // Node 2 acknowledges the config change, committing it.
  2634. r.Step(pb.Message{
  2635. Type: pb.MsgAppResp,
  2636. From: 2,
  2637. Index: ccIndex,
  2638. })
  2639. ents := nextEnts(r, s)
  2640. if len(ents) != 2 {
  2641. t.Fatalf("expected two committed entries, got %v", ents)
  2642. }
  2643. if ents[0].Type != pb.EntryNormal || ents[0].Data != nil {
  2644. t.Fatalf("expected ents[0] to be empty, but got %v", ents[0])
  2645. }
  2646. if ents[1].Type != pb.EntryConfChange {
  2647. t.Fatalf("expected ents[1] to be EntryConfChange, got %v", ents[1])
  2648. }
  2649. // Apply the config change. This reduces quorum requirements so the
  2650. // pending command can now commit.
  2651. r.removeNode(2)
  2652. ents = nextEnts(r, s)
  2653. if len(ents) != 1 || ents[0].Type != pb.EntryNormal ||
  2654. string(ents[0].Data) != "hello" {
  2655. t.Fatalf("expected one committed EntryNormal, got %v", ents)
  2656. }
  2657. }
  2658. // TestLeaderTransferToUpToDateNode verifies transferring should succeed
  2659. // if the transferee has the most up-to-date log entries when transfer starts.
  2660. func TestLeaderTransferToUpToDateNode(t *testing.T) {
  2661. nt := newNetwork(nil, nil, nil)
  2662. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2663. lead := nt.peers[1].(*raft)
  2664. if lead.lead != 1 {
  2665. t.Fatalf("after election leader is %x, want 1", lead.lead)
  2666. }
  2667. // Transfer leadership to 2.
  2668. nt.send(pb.Message{From: 2, To: 1, Type: pb.MsgTransferLeader})
  2669. checkLeaderTransferState(t, lead, StateFollower, 2)
  2670. // After some log replication, transfer leadership back to 1.
  2671. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2672. nt.send(pb.Message{From: 1, To: 2, Type: pb.MsgTransferLeader})
  2673. checkLeaderTransferState(t, lead, StateLeader, 1)
  2674. }
  2675. // TestLeaderTransferToUpToDateNodeFromFollower verifies transferring should succeed
  2676. // if the transferee has the most up-to-date log entries when transfer starts.
  2677. // Not like TestLeaderTransferToUpToDateNode, where the leader transfer message
  2678. // is sent to the leader, in this test case every leader transfer message is sent
  2679. // to the follower.
  2680. func TestLeaderTransferToUpToDateNodeFromFollower(t *testing.T) {
  2681. nt := newNetwork(nil, nil, nil)
  2682. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2683. lead := nt.peers[1].(*raft)
  2684. if lead.lead != 1 {
  2685. t.Fatalf("after election leader is %x, want 1", lead.lead)
  2686. }
  2687. // Transfer leadership to 2.
  2688. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgTransferLeader})
  2689. checkLeaderTransferState(t, lead, StateFollower, 2)
  2690. // After some log replication, transfer leadership back to 1.
  2691. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2692. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgTransferLeader})
  2693. checkLeaderTransferState(t, lead, StateLeader, 1)
  2694. }
  2695. // TestLeaderTransferWithCheckQuorum ensures transferring leader still works
  2696. // even the current leader is still under its leader lease
  2697. func TestLeaderTransferWithCheckQuorum(t *testing.T) {
  2698. nt := newNetwork(nil, nil, nil)
  2699. for i := 1; i < 4; i++ {
  2700. r := nt.peers[uint64(i)].(*raft)
  2701. r.checkQuorum = true
  2702. setRandomizedElectionTimeout(r, r.electionTimeout+i)
  2703. }
  2704. // Letting peer 2 electionElapsed reach to timeout so that it can vote for peer 1
  2705. f := nt.peers[2].(*raft)
  2706. for i := 0; i < f.electionTimeout; i++ {
  2707. f.tick()
  2708. }
  2709. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2710. lead := nt.peers[1].(*raft)
  2711. if lead.lead != 1 {
  2712. t.Fatalf("after election leader is %x, want 1", lead.lead)
  2713. }
  2714. // Transfer leadership to 2.
  2715. nt.send(pb.Message{From: 2, To: 1, Type: pb.MsgTransferLeader})
  2716. checkLeaderTransferState(t, lead, StateFollower, 2)
  2717. // After some log replication, transfer leadership back to 1.
  2718. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2719. nt.send(pb.Message{From: 1, To: 2, Type: pb.MsgTransferLeader})
  2720. checkLeaderTransferState(t, lead, StateLeader, 1)
  2721. }
  2722. func TestLeaderTransferToSlowFollower(t *testing.T) {
  2723. defaultLogger.EnableDebug()
  2724. nt := newNetwork(nil, nil, nil)
  2725. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2726. nt.isolate(3)
  2727. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2728. nt.recover()
  2729. lead := nt.peers[1].(*raft)
  2730. if lead.prs[3].Match != 1 {
  2731. t.Fatalf("node 1 has match %x for node 3, want %x", lead.prs[3].Match, 1)
  2732. }
  2733. // Transfer leadership to 3 when node 3 is lack of log.
  2734. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2735. checkLeaderTransferState(t, lead, StateFollower, 3)
  2736. }
  2737. func TestLeaderTransferAfterSnapshot(t *testing.T) {
  2738. nt := newNetwork(nil, nil, nil)
  2739. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2740. nt.isolate(3)
  2741. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2742. lead := nt.peers[1].(*raft)
  2743. nextEnts(lead, nt.storage[1])
  2744. nt.storage[1].CreateSnapshot(lead.raftLog.applied, &pb.ConfState{Nodes: lead.nodes()}, nil)
  2745. nt.storage[1].Compact(lead.raftLog.applied)
  2746. nt.recover()
  2747. if lead.prs[3].Match != 1 {
  2748. t.Fatalf("node 1 has match %x for node 3, want %x", lead.prs[3].Match, 1)
  2749. }
  2750. // Transfer leadership to 3 when node 3 is lack of snapshot.
  2751. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2752. // Send pb.MsgHeartbeatResp to leader to trigger a snapshot for node 3.
  2753. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgHeartbeatResp})
  2754. checkLeaderTransferState(t, lead, StateFollower, 3)
  2755. }
  2756. func TestLeaderTransferToSelf(t *testing.T) {
  2757. nt := newNetwork(nil, nil, nil)
  2758. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2759. lead := nt.peers[1].(*raft)
  2760. // Transfer leadership to self, there will be noop.
  2761. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgTransferLeader})
  2762. checkLeaderTransferState(t, lead, StateLeader, 1)
  2763. }
  2764. func TestLeaderTransferToNonExistingNode(t *testing.T) {
  2765. nt := newNetwork(nil, nil, nil)
  2766. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2767. lead := nt.peers[1].(*raft)
  2768. // Transfer leadership to non-existing node, there will be noop.
  2769. nt.send(pb.Message{From: 4, To: 1, Type: pb.MsgTransferLeader})
  2770. checkLeaderTransferState(t, lead, StateLeader, 1)
  2771. }
  2772. func TestLeaderTransferTimeout(t *testing.T) {
  2773. nt := newNetwork(nil, nil, nil)
  2774. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2775. nt.isolate(3)
  2776. lead := nt.peers[1].(*raft)
  2777. // Transfer leadership to isolated node, wait for timeout.
  2778. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2779. if lead.leadTransferee != 3 {
  2780. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2781. }
  2782. for i := 0; i < lead.heartbeatTimeout; i++ {
  2783. lead.tick()
  2784. }
  2785. if lead.leadTransferee != 3 {
  2786. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2787. }
  2788. for i := 0; i < lead.electionTimeout-lead.heartbeatTimeout; i++ {
  2789. lead.tick()
  2790. }
  2791. checkLeaderTransferState(t, lead, StateLeader, 1)
  2792. }
  2793. func TestLeaderTransferIgnoreProposal(t *testing.T) {
  2794. nt := newNetwork(nil, nil, nil)
  2795. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2796. nt.isolate(3)
  2797. lead := nt.peers[1].(*raft)
  2798. // Transfer leadership to isolated node to let transfer pending, then send proposal.
  2799. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2800. if lead.leadTransferee != 3 {
  2801. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2802. }
  2803. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2804. err := lead.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2805. if err != ErrProposalDropped {
  2806. t.Fatalf("should return drop proposal error while transferring")
  2807. }
  2808. if lead.prs[1].Match != 1 {
  2809. t.Fatalf("node 1 has match %x, want %x", lead.prs[1].Match, 1)
  2810. }
  2811. }
  2812. func TestLeaderTransferReceiveHigherTermVote(t *testing.T) {
  2813. nt := newNetwork(nil, nil, nil)
  2814. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2815. nt.isolate(3)
  2816. lead := nt.peers[1].(*raft)
  2817. // Transfer leadership to isolated node to let transfer pending.
  2818. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2819. if lead.leadTransferee != 3 {
  2820. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2821. }
  2822. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup, Index: 1, Term: 2})
  2823. checkLeaderTransferState(t, lead, StateFollower, 2)
  2824. }
  2825. func TestLeaderTransferRemoveNode(t *testing.T) {
  2826. nt := newNetwork(nil, nil, nil)
  2827. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2828. nt.ignore(pb.MsgTimeoutNow)
  2829. lead := nt.peers[1].(*raft)
  2830. // The leadTransferee is removed when leadship transferring.
  2831. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2832. if lead.leadTransferee != 3 {
  2833. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2834. }
  2835. lead.removeNode(3)
  2836. checkLeaderTransferState(t, lead, StateLeader, 1)
  2837. }
  2838. // TestLeaderTransferBack verifies leadership can transfer back to self when last transfer is pending.
  2839. func TestLeaderTransferBack(t *testing.T) {
  2840. nt := newNetwork(nil, nil, nil)
  2841. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2842. nt.isolate(3)
  2843. lead := nt.peers[1].(*raft)
  2844. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2845. if lead.leadTransferee != 3 {
  2846. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2847. }
  2848. // Transfer leadership back to self.
  2849. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgTransferLeader})
  2850. checkLeaderTransferState(t, lead, StateLeader, 1)
  2851. }
  2852. // TestLeaderTransferSecondTransferToAnotherNode verifies leader can transfer to another node
  2853. // when last transfer is pending.
  2854. func TestLeaderTransferSecondTransferToAnotherNode(t *testing.T) {
  2855. nt := newNetwork(nil, nil, nil)
  2856. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2857. nt.isolate(3)
  2858. lead := nt.peers[1].(*raft)
  2859. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2860. if lead.leadTransferee != 3 {
  2861. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2862. }
  2863. // Transfer leadership to another node.
  2864. nt.send(pb.Message{From: 2, To: 1, Type: pb.MsgTransferLeader})
  2865. checkLeaderTransferState(t, lead, StateFollower, 2)
  2866. }
  2867. // TestLeaderTransferSecondTransferToSameNode verifies second transfer leader request
  2868. // to the same node should not extend the timeout while the first one is pending.
  2869. func TestLeaderTransferSecondTransferToSameNode(t *testing.T) {
  2870. nt := newNetwork(nil, nil, nil)
  2871. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2872. nt.isolate(3)
  2873. lead := nt.peers[1].(*raft)
  2874. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2875. if lead.leadTransferee != 3 {
  2876. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2877. }
  2878. for i := 0; i < lead.heartbeatTimeout; i++ {
  2879. lead.tick()
  2880. }
  2881. // Second transfer leadership request to the same node.
  2882. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2883. for i := 0; i < lead.electionTimeout-lead.heartbeatTimeout; i++ {
  2884. lead.tick()
  2885. }
  2886. checkLeaderTransferState(t, lead, StateLeader, 1)
  2887. }
  2888. func checkLeaderTransferState(t *testing.T, r *raft, state StateType, lead uint64) {
  2889. if r.state != state || r.lead != lead {
  2890. t.Fatalf("after transferring, node has state %v lead %v, want state %v lead %v", r.state, r.lead, state, lead)
  2891. }
  2892. if r.leadTransferee != None {
  2893. t.Fatalf("after transferring, node has leadTransferee %v, want leadTransferee %v", r.leadTransferee, None)
  2894. }
  2895. }
  2896. // TestTransferNonMember verifies that when a MsgTimeoutNow arrives at
  2897. // a node that has been removed from the group, nothing happens.
  2898. // (previously, if the node also got votes, it would panic as it
  2899. // transitioned to StateLeader)
  2900. func TestTransferNonMember(t *testing.T) {
  2901. r := newTestRaft(1, []uint64{2, 3, 4}, 5, 1, NewMemoryStorage())
  2902. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgTimeoutNow})
  2903. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgVoteResp})
  2904. r.Step(pb.Message{From: 3, To: 1, Type: pb.MsgVoteResp})
  2905. if r.state != StateFollower {
  2906. t.Fatalf("state is %s, want StateFollower", r.state)
  2907. }
  2908. }
  2909. // TestNodeWithSmallerTermCanCompleteElection tests the scenario where a node
  2910. // that has been partitioned away (and fallen behind) rejoins the cluster at
  2911. // about the same time the leader node gets partitioned away.
  2912. // Previously the cluster would come to a standstill when run with PreVote
  2913. // enabled.
  2914. func TestNodeWithSmallerTermCanCompleteElection(t *testing.T) {
  2915. n1 := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  2916. n2 := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  2917. n3 := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  2918. n1.becomeFollower(1, None)
  2919. n2.becomeFollower(1, None)
  2920. n3.becomeFollower(1, None)
  2921. n1.preVote = true
  2922. n2.preVote = true
  2923. n3.preVote = true
  2924. // cause a network partition to isolate node 3
  2925. nt := newNetwork(n1, n2, n3)
  2926. nt.cut(1, 3)
  2927. nt.cut(2, 3)
  2928. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2929. sm := nt.peers[1].(*raft)
  2930. if sm.state != StateLeader {
  2931. t.Errorf("peer 1 state: %s, want %s", sm.state, StateLeader)
  2932. }
  2933. sm = nt.peers[2].(*raft)
  2934. if sm.state != StateFollower {
  2935. t.Errorf("peer 2 state: %s, want %s", sm.state, StateFollower)
  2936. }
  2937. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  2938. sm = nt.peers[3].(*raft)
  2939. if sm.state != StatePreCandidate {
  2940. t.Errorf("peer 3 state: %s, want %s", sm.state, StatePreCandidate)
  2941. }
  2942. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  2943. // check whether the term values are expected
  2944. // a.Term == 3
  2945. // b.Term == 3
  2946. // c.Term == 1
  2947. sm = nt.peers[1].(*raft)
  2948. if sm.Term != 3 {
  2949. t.Errorf("peer 1 term: %d, want %d", sm.Term, 3)
  2950. }
  2951. sm = nt.peers[2].(*raft)
  2952. if sm.Term != 3 {
  2953. t.Errorf("peer 2 term: %d, want %d", sm.Term, 3)
  2954. }
  2955. sm = nt.peers[3].(*raft)
  2956. if sm.Term != 1 {
  2957. t.Errorf("peer 3 term: %d, want %d", sm.Term, 1)
  2958. }
  2959. // check state
  2960. // a == follower
  2961. // b == leader
  2962. // c == pre-candidate
  2963. sm = nt.peers[1].(*raft)
  2964. if sm.state != StateFollower {
  2965. t.Errorf("peer 1 state: %s, want %s", sm.state, StateFollower)
  2966. }
  2967. sm = nt.peers[2].(*raft)
  2968. if sm.state != StateLeader {
  2969. t.Errorf("peer 2 state: %s, want %s", sm.state, StateLeader)
  2970. }
  2971. sm = nt.peers[3].(*raft)
  2972. if sm.state != StatePreCandidate {
  2973. t.Errorf("peer 3 state: %s, want %s", sm.state, StatePreCandidate)
  2974. }
  2975. sm.logger.Infof("going to bring back peer 3 and kill peer 2")
  2976. // recover the network then immediately isolate b which is currently
  2977. // the leader, this is to emulate the crash of b.
  2978. nt.recover()
  2979. nt.cut(2, 1)
  2980. nt.cut(2, 3)
  2981. // call for election
  2982. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  2983. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2984. // do we have a leader?
  2985. sma := nt.peers[1].(*raft)
  2986. smb := nt.peers[3].(*raft)
  2987. if sma.state != StateLeader && smb.state != StateLeader {
  2988. t.Errorf("no leader")
  2989. }
  2990. }
  2991. // TestPreVoteWithSplitVote verifies that after split vote, cluster can complete
  2992. // election in next round.
  2993. func TestPreVoteWithSplitVote(t *testing.T) {
  2994. n1 := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  2995. n2 := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  2996. n3 := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  2997. n1.becomeFollower(1, None)
  2998. n2.becomeFollower(1, None)
  2999. n3.becomeFollower(1, None)
  3000. n1.preVote = true
  3001. n2.preVote = true
  3002. n3.preVote = true
  3003. nt := newNetwork(n1, n2, n3)
  3004. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  3005. // simulate leader down. followers start split vote.
  3006. nt.isolate(1)
  3007. nt.send([]pb.Message{
  3008. {From: 2, To: 2, Type: pb.MsgHup},
  3009. {From: 3, To: 3, Type: pb.MsgHup},
  3010. }...)
  3011. // check whether the term values are expected
  3012. // n2.Term == 3
  3013. // n3.Term == 3
  3014. sm := nt.peers[2].(*raft)
  3015. if sm.Term != 3 {
  3016. t.Errorf("peer 2 term: %d, want %d", sm.Term, 3)
  3017. }
  3018. sm = nt.peers[3].(*raft)
  3019. if sm.Term != 3 {
  3020. t.Errorf("peer 3 term: %d, want %d", sm.Term, 3)
  3021. }
  3022. // check state
  3023. // n2 == candidate
  3024. // n3 == candidate
  3025. sm = nt.peers[2].(*raft)
  3026. if sm.state != StateCandidate {
  3027. t.Errorf("peer 2 state: %s, want %s", sm.state, StateCandidate)
  3028. }
  3029. sm = nt.peers[3].(*raft)
  3030. if sm.state != StateCandidate {
  3031. t.Errorf("peer 3 state: %s, want %s", sm.state, StateCandidate)
  3032. }
  3033. // node 2 election timeout first
  3034. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  3035. // check whether the term values are expected
  3036. // n2.Term == 4
  3037. // n3.Term == 4
  3038. sm = nt.peers[2].(*raft)
  3039. if sm.Term != 4 {
  3040. t.Errorf("peer 2 term: %d, want %d", sm.Term, 4)
  3041. }
  3042. sm = nt.peers[3].(*raft)
  3043. if sm.Term != 4 {
  3044. t.Errorf("peer 3 term: %d, want %d", sm.Term, 4)
  3045. }
  3046. // check state
  3047. // n2 == leader
  3048. // n3 == follower
  3049. sm = nt.peers[2].(*raft)
  3050. if sm.state != StateLeader {
  3051. t.Errorf("peer 2 state: %s, want %s", sm.state, StateLeader)
  3052. }
  3053. sm = nt.peers[3].(*raft)
  3054. if sm.state != StateFollower {
  3055. t.Errorf("peer 3 state: %s, want %s", sm.state, StateFollower)
  3056. }
  3057. }
  3058. // simulate rolling update a cluster for Pre-Vote. cluster has 3 nodes [n1, n2, n3].
  3059. // n1 is leader with term 2
  3060. // n2 is follower with term 2
  3061. // n3 is partitioned, with term 4 and less log, state is candidate
  3062. func newPreVoteMigrationCluster(t *testing.T) *network {
  3063. n1 := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  3064. n2 := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  3065. n3 := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  3066. n1.becomeFollower(1, None)
  3067. n2.becomeFollower(1, None)
  3068. n3.becomeFollower(1, None)
  3069. n1.preVote = true
  3070. n2.preVote = true
  3071. // We intentionally do not enable PreVote for n3, this is done so in order
  3072. // to simulate a rolling restart process where it's possible to have a mixed
  3073. // version cluster with replicas with PreVote enabled, and replicas without.
  3074. nt := newNetwork(n1, n2, n3)
  3075. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  3076. // Cause a network partition to isolate n3.
  3077. nt.isolate(3)
  3078. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  3079. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  3080. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  3081. // check state
  3082. // n1.state == StateLeader
  3083. // n2.state == StateFollower
  3084. // n3.state == StateCandidate
  3085. if n1.state != StateLeader {
  3086. t.Fatalf("node 1 state: %s, want %s", n1.state, StateLeader)
  3087. }
  3088. if n2.state != StateFollower {
  3089. t.Fatalf("node 2 state: %s, want %s", n2.state, StateFollower)
  3090. }
  3091. if n3.state != StateCandidate {
  3092. t.Fatalf("node 3 state: %s, want %s", n3.state, StateCandidate)
  3093. }
  3094. // check term
  3095. // n1.Term == 2
  3096. // n2.Term == 2
  3097. // n3.Term == 4
  3098. if n1.Term != 2 {
  3099. t.Fatalf("node 1 term: %d, want %d", n1.Term, 2)
  3100. }
  3101. if n2.Term != 2 {
  3102. t.Fatalf("node 2 term: %d, want %d", n2.Term, 2)
  3103. }
  3104. if n3.Term != 4 {
  3105. t.Fatalf("node 3 term: %d, want %d", n3.Term, 4)
  3106. }
  3107. // Enable prevote on n3, then recover the network
  3108. n3.preVote = true
  3109. nt.recover()
  3110. return nt
  3111. }
  3112. func TestPreVoteMigrationCanCompleteElection(t *testing.T) {
  3113. nt := newPreVoteMigrationCluster(t)
  3114. // n1 is leader with term 2
  3115. // n2 is follower with term 2
  3116. // n3 is pre-candidate with term 4, and less log
  3117. n2 := nt.peers[2].(*raft)
  3118. n3 := nt.peers[3].(*raft)
  3119. // simulate leader down
  3120. nt.isolate(1)
  3121. // Call for elections from both n2 and n3.
  3122. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  3123. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  3124. // check state
  3125. // n2.state == Follower
  3126. // n3.state == PreCandidate
  3127. if n2.state != StateFollower {
  3128. t.Errorf("node 2 state: %s, want %s", n2.state, StateFollower)
  3129. }
  3130. if n3.state != StatePreCandidate {
  3131. t.Errorf("node 3 state: %s, want %s", n3.state, StatePreCandidate)
  3132. }
  3133. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  3134. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  3135. // Do we have a leader?
  3136. if n2.state != StateLeader && n3.state != StateFollower {
  3137. t.Errorf("no leader")
  3138. }
  3139. }
  3140. func TestPreVoteMigrationWithFreeStuckPreCandidate(t *testing.T) {
  3141. nt := newPreVoteMigrationCluster(t)
  3142. // n1 is leader with term 2
  3143. // n2 is follower with term 2
  3144. // n3 is pre-candidate with term 4, and less log
  3145. n1 := nt.peers[1].(*raft)
  3146. n2 := nt.peers[2].(*raft)
  3147. n3 := nt.peers[3].(*raft)
  3148. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  3149. if n1.state != StateLeader {
  3150. t.Errorf("node 1 state: %s, want %s", n1.state, StateLeader)
  3151. }
  3152. if n2.state != StateFollower {
  3153. t.Errorf("node 2 state: %s, want %s", n2.state, StateFollower)
  3154. }
  3155. if n3.state != StatePreCandidate {
  3156. t.Errorf("node 3 state: %s, want %s", n3.state, StatePreCandidate)
  3157. }
  3158. // Pre-Vote again for safety
  3159. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  3160. if n1.state != StateLeader {
  3161. t.Errorf("node 1 state: %s, want %s", n1.state, StateLeader)
  3162. }
  3163. if n2.state != StateFollower {
  3164. t.Errorf("node 2 state: %s, want %s", n2.state, StateFollower)
  3165. }
  3166. if n3.state != StatePreCandidate {
  3167. t.Errorf("node 3 state: %s, want %s", n3.state, StatePreCandidate)
  3168. }
  3169. nt.send(pb.Message{From: 1, To: 3, Type: pb.MsgHeartbeat, Term: n1.Term})
  3170. // Disrupt the leader so that the stuck peer is freed
  3171. if n1.state != StateFollower {
  3172. t.Errorf("state = %s, want %s", n1.state, StateFollower)
  3173. }
  3174. if n3.Term != n1.Term {
  3175. t.Errorf("term = %d, want %d", n3.Term, n1.Term)
  3176. }
  3177. }
  3178. func entsWithConfig(configFunc func(*Config), terms ...uint64) *raft {
  3179. storage := NewMemoryStorage()
  3180. for i, term := range terms {
  3181. storage.Append([]pb.Entry{{Index: uint64(i + 1), Term: term}})
  3182. }
  3183. cfg := newTestConfig(1, []uint64{}, 5, 1, storage)
  3184. if configFunc != nil {
  3185. configFunc(cfg)
  3186. }
  3187. sm := newRaft(cfg)
  3188. sm.reset(terms[len(terms)-1])
  3189. return sm
  3190. }
  3191. // votedWithConfig creates a raft state machine with Vote and Term set
  3192. // to the given value but no log entries (indicating that it voted in
  3193. // the given term but has not received any logs).
  3194. func votedWithConfig(configFunc func(*Config), vote, term uint64) *raft {
  3195. storage := NewMemoryStorage()
  3196. storage.SetHardState(pb.HardState{Vote: vote, Term: term})
  3197. cfg := newTestConfig(1, []uint64{}, 5, 1, storage)
  3198. if configFunc != nil {
  3199. configFunc(cfg)
  3200. }
  3201. sm := newRaft(cfg)
  3202. sm.reset(term)
  3203. return sm
  3204. }
  3205. type network struct {
  3206. peers map[uint64]stateMachine
  3207. storage map[uint64]*MemoryStorage
  3208. dropm map[connem]float64
  3209. ignorem map[pb.MessageType]bool
  3210. }
  3211. // newNetwork initializes a network from peers.
  3212. // A nil node will be replaced with a new *stateMachine.
  3213. // A *stateMachine will get its k, id.
  3214. // When using stateMachine, the address list is always [1, n].
  3215. func newNetwork(peers ...stateMachine) *network {
  3216. return newNetworkWithConfig(nil, peers...)
  3217. }
  3218. // newNetworkWithConfig is like newNetwork but calls the given func to
  3219. // modify the configuration of any state machines it creates.
  3220. func newNetworkWithConfig(configFunc func(*Config), peers ...stateMachine) *network {
  3221. size := len(peers)
  3222. peerAddrs := idsBySize(size)
  3223. npeers := make(map[uint64]stateMachine, size)
  3224. nstorage := make(map[uint64]*MemoryStorage, size)
  3225. for j, p := range peers {
  3226. id := peerAddrs[j]
  3227. switch v := p.(type) {
  3228. case nil:
  3229. nstorage[id] = NewMemoryStorage()
  3230. cfg := newTestConfig(id, peerAddrs, 10, 1, nstorage[id])
  3231. if configFunc != nil {
  3232. configFunc(cfg)
  3233. }
  3234. sm := newRaft(cfg)
  3235. npeers[id] = sm
  3236. case *raft:
  3237. learners := make(map[uint64]bool, len(v.learnerPrs))
  3238. for i := range v.learnerPrs {
  3239. learners[i] = true
  3240. }
  3241. v.id = id
  3242. v.prs = make(map[uint64]*Progress)
  3243. v.learnerPrs = make(map[uint64]*Progress)
  3244. for i := 0; i < size; i++ {
  3245. if _, ok := learners[peerAddrs[i]]; ok {
  3246. v.learnerPrs[peerAddrs[i]] = &Progress{IsLearner: true}
  3247. } else {
  3248. v.prs[peerAddrs[i]] = &Progress{}
  3249. }
  3250. }
  3251. v.reset(v.Term)
  3252. npeers[id] = v
  3253. case *blackHole:
  3254. npeers[id] = v
  3255. default:
  3256. panic(fmt.Sprintf("unexpected state machine type: %T", p))
  3257. }
  3258. }
  3259. return &network{
  3260. peers: npeers,
  3261. storage: nstorage,
  3262. dropm: make(map[connem]float64),
  3263. ignorem: make(map[pb.MessageType]bool),
  3264. }
  3265. }
  3266. func preVoteConfig(c *Config) {
  3267. c.PreVote = true
  3268. }
  3269. func (nw *network) send(msgs ...pb.Message) {
  3270. for len(msgs) > 0 {
  3271. m := msgs[0]
  3272. p := nw.peers[m.To]
  3273. p.Step(m)
  3274. msgs = append(msgs[1:], nw.filter(p.readMessages())...)
  3275. }
  3276. }
  3277. func (nw *network) drop(from, to uint64, perc float64) {
  3278. nw.dropm[connem{from, to}] = perc
  3279. }
  3280. func (nw *network) cut(one, other uint64) {
  3281. nw.drop(one, other, 1)
  3282. nw.drop(other, one, 1)
  3283. }
  3284. func (nw *network) isolate(id uint64) {
  3285. for i := 0; i < len(nw.peers); i++ {
  3286. nid := uint64(i) + 1
  3287. if nid != id {
  3288. nw.drop(id, nid, 1.0)
  3289. nw.drop(nid, id, 1.0)
  3290. }
  3291. }
  3292. }
  3293. func (nw *network) ignore(t pb.MessageType) {
  3294. nw.ignorem[t] = true
  3295. }
  3296. func (nw *network) recover() {
  3297. nw.dropm = make(map[connem]float64)
  3298. nw.ignorem = make(map[pb.MessageType]bool)
  3299. }
  3300. func (nw *network) filter(msgs []pb.Message) []pb.Message {
  3301. mm := []pb.Message{}
  3302. for _, m := range msgs {
  3303. if nw.ignorem[m.Type] {
  3304. continue
  3305. }
  3306. switch m.Type {
  3307. case pb.MsgHup:
  3308. // hups never go over the network, so don't drop them but panic
  3309. panic("unexpected msgHup")
  3310. default:
  3311. perc := nw.dropm[connem{m.From, m.To}]
  3312. if n := rand.Float64(); n < perc {
  3313. continue
  3314. }
  3315. }
  3316. mm = append(mm, m)
  3317. }
  3318. return mm
  3319. }
  3320. type connem struct {
  3321. from, to uint64
  3322. }
  3323. type blackHole struct{}
  3324. func (blackHole) Step(pb.Message) error { return nil }
  3325. func (blackHole) readMessages() []pb.Message { return nil }
  3326. var nopStepper = &blackHole{}
  3327. func idsBySize(size int) []uint64 {
  3328. ids := make([]uint64, size)
  3329. for i := 0; i < size; i++ {
  3330. ids[i] = 1 + uint64(i)
  3331. }
  3332. return ids
  3333. }
  3334. // setRandomizedElectionTimeout set up the value by caller instead of choosing
  3335. // by system, in some test scenario we need to fill in some expected value to
  3336. // ensure the certainty
  3337. func setRandomizedElectionTimeout(r *raft, v int) {
  3338. r.randomizedElectionTimeout = v
  3339. }
  3340. func newTestConfig(id uint64, peers []uint64, election, heartbeat int, storage Storage) *Config {
  3341. return &Config{
  3342. ID: id,
  3343. peers: peers,
  3344. ElectionTick: election,
  3345. HeartbeatTick: heartbeat,
  3346. Storage: storage,
  3347. MaxSizePerMsg: noLimit,
  3348. MaxInflightMsgs: 256,
  3349. }
  3350. }
  3351. func newTestRaft(id uint64, peers []uint64, election, heartbeat int, storage Storage) *raft {
  3352. return newRaft(newTestConfig(id, peers, election, heartbeat, storage))
  3353. }
  3354. func newTestLearnerRaft(id uint64, peers []uint64, learners []uint64, election, heartbeat int, storage Storage) *raft {
  3355. cfg := newTestConfig(id, peers, election, heartbeat, storage)
  3356. cfg.learners = learners
  3357. return newRaft(cfg)
  3358. }