raft_test.go 128 KB

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