raft_test.go 127 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389
  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 TestReadOnlyOptionLease(t *testing.T) {
  2108. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  2109. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  2110. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  2111. a.readOnly.option = ReadOnlyLeaseBased
  2112. b.readOnly.option = ReadOnlyLeaseBased
  2113. c.readOnly.option = ReadOnlyLeaseBased
  2114. a.checkQuorum = true
  2115. b.checkQuorum = true
  2116. c.checkQuorum = true
  2117. nt := newNetwork(a, b, c)
  2118. setRandomizedElectionTimeout(b, b.electionTimeout+1)
  2119. for i := 0; i < b.electionTimeout; i++ {
  2120. b.tick()
  2121. }
  2122. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2123. if a.state != StateLeader {
  2124. t.Fatalf("state = %s, want %s", a.state, StateLeader)
  2125. }
  2126. tests := []struct {
  2127. sm *raft
  2128. proposals int
  2129. wri uint64
  2130. wctx []byte
  2131. }{
  2132. {a, 10, 11, []byte("ctx1")},
  2133. {b, 10, 21, []byte("ctx2")},
  2134. {c, 10, 31, []byte("ctx3")},
  2135. {a, 10, 41, []byte("ctx4")},
  2136. {b, 10, 51, []byte("ctx5")},
  2137. {c, 10, 61, []byte("ctx6")},
  2138. }
  2139. for i, tt := range tests {
  2140. for j := 0; j < tt.proposals; j++ {
  2141. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2142. }
  2143. nt.send(pb.Message{From: tt.sm.id, To: tt.sm.id, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: tt.wctx}}})
  2144. r := tt.sm
  2145. rs := r.readStates[0]
  2146. if rs.Index != tt.wri {
  2147. t.Errorf("#%d: readIndex = %d, want %d", i, rs.Index, tt.wri)
  2148. }
  2149. if !bytes.Equal(rs.RequestCtx, tt.wctx) {
  2150. t.Errorf("#%d: requestCtx = %v, want %v", i, rs.RequestCtx, tt.wctx)
  2151. }
  2152. r.readStates = nil
  2153. }
  2154. }
  2155. // TestReadOnlyForNewLeader ensures that a leader only accepts MsgReadIndex message
  2156. // when it commits at least one log entry at it term.
  2157. func TestReadOnlyForNewLeader(t *testing.T) {
  2158. nodeConfigs := []struct {
  2159. id uint64
  2160. committed uint64
  2161. applied uint64
  2162. compactIndex uint64
  2163. }{
  2164. {1, 1, 1, 0},
  2165. {2, 2, 2, 2},
  2166. {3, 2, 2, 2},
  2167. }
  2168. peers := make([]stateMachine, 0)
  2169. for _, c := range nodeConfigs {
  2170. storage := NewMemoryStorage()
  2171. storage.Append([]pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}})
  2172. storage.SetHardState(pb.HardState{Term: 1, Commit: c.committed})
  2173. if c.compactIndex != 0 {
  2174. storage.Compact(c.compactIndex)
  2175. }
  2176. cfg := newTestConfig(c.id, []uint64{1, 2, 3}, 10, 1, storage)
  2177. cfg.Applied = c.applied
  2178. raft := newRaft(cfg)
  2179. peers = append(peers, raft)
  2180. }
  2181. nt := newNetwork(peers...)
  2182. // Drop MsgApp to forbid peer a to commit any log entry at its term after it becomes leader.
  2183. nt.ignore(pb.MsgApp)
  2184. // Force peer a to become leader.
  2185. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2186. sm := nt.peers[1].(*raft)
  2187. if sm.state != StateLeader {
  2188. t.Fatalf("state = %s, want %s", sm.state, StateLeader)
  2189. }
  2190. // Ensure peer a drops read only request.
  2191. var windex uint64 = 4
  2192. wctx := []byte("ctx")
  2193. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: wctx}}})
  2194. if len(sm.readStates) != 0 {
  2195. t.Fatalf("len(readStates) = %d, want zero", len(sm.readStates))
  2196. }
  2197. nt.recover()
  2198. // Force peer a to commit a log entry at its term
  2199. for i := 0; i < sm.heartbeatTimeout; i++ {
  2200. sm.tick()
  2201. }
  2202. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2203. if sm.raftLog.committed != 4 {
  2204. t.Fatalf("committed = %d, want 4", sm.raftLog.committed)
  2205. }
  2206. lastLogTerm := sm.raftLog.zeroTermOnErrCompacted(sm.raftLog.term(sm.raftLog.committed))
  2207. if lastLogTerm != sm.Term {
  2208. t.Fatalf("last log term = %d, want %d", lastLogTerm, sm.Term)
  2209. }
  2210. // Ensure peer a accepts read only request after it commits a entry at its term.
  2211. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: wctx}}})
  2212. if len(sm.readStates) != 1 {
  2213. t.Fatalf("len(readStates) = %d, want 1", len(sm.readStates))
  2214. }
  2215. rs := sm.readStates[0]
  2216. if rs.Index != windex {
  2217. t.Fatalf("readIndex = %d, want %d", rs.Index, windex)
  2218. }
  2219. if !bytes.Equal(rs.RequestCtx, wctx) {
  2220. t.Fatalf("requestCtx = %v, want %v", rs.RequestCtx, wctx)
  2221. }
  2222. }
  2223. func TestLeaderAppResp(t *testing.T) {
  2224. // initial progress: match = 0; next = 3
  2225. tests := []struct {
  2226. index uint64
  2227. reject bool
  2228. // progress
  2229. wmatch uint64
  2230. wnext uint64
  2231. // message
  2232. wmsgNum int
  2233. windex uint64
  2234. wcommitted uint64
  2235. }{
  2236. {3, true, 0, 3, 0, 0, 0}, // stale resp; no replies
  2237. {2, true, 0, 2, 1, 1, 0}, // denied resp; leader does not commit; decrease next and send probing msg
  2238. {2, false, 2, 4, 2, 2, 2}, // accept resp; leader commits; broadcast with commit index
  2239. {0, false, 0, 3, 0, 0, 0}, // ignore heartbeat replies
  2240. }
  2241. for i, tt := range tests {
  2242. // sm term is 1 after it becomes the leader.
  2243. // thus the last log term must be 1 to be committed.
  2244. sm := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  2245. sm.raftLog = &raftLog{
  2246. storage: &MemoryStorage{ents: []pb.Entry{{}, {Index: 1, Term: 0}, {Index: 2, Term: 1}}},
  2247. unstable: unstable{offset: 3},
  2248. }
  2249. sm.becomeCandidate()
  2250. sm.becomeLeader()
  2251. sm.readMessages()
  2252. sm.Step(pb.Message{From: 2, Type: pb.MsgAppResp, Index: tt.index, Term: sm.Term, Reject: tt.reject, RejectHint: tt.index})
  2253. p := sm.prs[2]
  2254. if p.Match != tt.wmatch {
  2255. t.Errorf("#%d match = %d, want %d", i, p.Match, tt.wmatch)
  2256. }
  2257. if p.Next != tt.wnext {
  2258. t.Errorf("#%d next = %d, want %d", i, p.Next, tt.wnext)
  2259. }
  2260. msgs := sm.readMessages()
  2261. if len(msgs) != tt.wmsgNum {
  2262. t.Errorf("#%d msgNum = %d, want %d", i, len(msgs), tt.wmsgNum)
  2263. }
  2264. for j, msg := range msgs {
  2265. if msg.Index != tt.windex {
  2266. t.Errorf("#%d.%d index = %d, want %d", i, j, msg.Index, tt.windex)
  2267. }
  2268. if msg.Commit != tt.wcommitted {
  2269. t.Errorf("#%d.%d commit = %d, want %d", i, j, msg.Commit, tt.wcommitted)
  2270. }
  2271. }
  2272. }
  2273. }
  2274. // When the leader receives a heartbeat tick, it should
  2275. // send a MsgHeartbeat with m.Index = 0, m.LogTerm=0 and empty entries.
  2276. func TestBcastBeat(t *testing.T) {
  2277. offset := uint64(1000)
  2278. // make a state machine with log.offset = 1000
  2279. s := pb.Snapshot{
  2280. Metadata: pb.SnapshotMetadata{
  2281. Index: offset,
  2282. Term: 1,
  2283. ConfState: pb.ConfState{Nodes: []uint64{1, 2, 3}},
  2284. },
  2285. }
  2286. storage := NewMemoryStorage()
  2287. storage.ApplySnapshot(s)
  2288. sm := newTestRaft(1, nil, 10, 1, storage)
  2289. sm.Term = 1
  2290. sm.becomeCandidate()
  2291. sm.becomeLeader()
  2292. for i := 0; i < 10; i++ {
  2293. mustAppendEntry(sm, pb.Entry{Index: uint64(i) + 1})
  2294. }
  2295. // slow follower
  2296. sm.prs[2].Match, sm.prs[2].Next = 5, 6
  2297. // normal follower
  2298. sm.prs[3].Match, sm.prs[3].Next = sm.raftLog.lastIndex(), sm.raftLog.lastIndex()+1
  2299. sm.Step(pb.Message{Type: pb.MsgBeat})
  2300. msgs := sm.readMessages()
  2301. if len(msgs) != 2 {
  2302. t.Fatalf("len(msgs) = %v, want 2", len(msgs))
  2303. }
  2304. wantCommitMap := map[uint64]uint64{
  2305. 2: min(sm.raftLog.committed, sm.prs[2].Match),
  2306. 3: min(sm.raftLog.committed, sm.prs[3].Match),
  2307. }
  2308. for i, m := range msgs {
  2309. if m.Type != pb.MsgHeartbeat {
  2310. t.Fatalf("#%d: type = %v, want = %v", i, m.Type, pb.MsgHeartbeat)
  2311. }
  2312. if m.Index != 0 {
  2313. t.Fatalf("#%d: prevIndex = %d, want %d", i, m.Index, 0)
  2314. }
  2315. if m.LogTerm != 0 {
  2316. t.Fatalf("#%d: prevTerm = %d, want %d", i, m.LogTerm, 0)
  2317. }
  2318. if wantCommitMap[m.To] == 0 {
  2319. t.Fatalf("#%d: unexpected to %d", i, m.To)
  2320. } else {
  2321. if m.Commit != wantCommitMap[m.To] {
  2322. t.Fatalf("#%d: commit = %d, want %d", i, m.Commit, wantCommitMap[m.To])
  2323. }
  2324. delete(wantCommitMap, m.To)
  2325. }
  2326. if len(m.Entries) != 0 {
  2327. t.Fatalf("#%d: len(entries) = %d, want 0", i, len(m.Entries))
  2328. }
  2329. }
  2330. }
  2331. // tests the output of the state machine when receiving MsgBeat
  2332. func TestRecvMsgBeat(t *testing.T) {
  2333. tests := []struct {
  2334. state StateType
  2335. wMsg int
  2336. }{
  2337. {StateLeader, 2},
  2338. // candidate and follower should ignore MsgBeat
  2339. {StateCandidate, 0},
  2340. {StateFollower, 0},
  2341. }
  2342. for i, tt := range tests {
  2343. sm := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  2344. sm.raftLog = &raftLog{storage: &MemoryStorage{ents: []pb.Entry{{}, {Index: 1, Term: 0}, {Index: 2, Term: 1}}}}
  2345. sm.Term = 1
  2346. sm.state = tt.state
  2347. switch tt.state {
  2348. case StateFollower:
  2349. sm.step = stepFollower
  2350. case StateCandidate:
  2351. sm.step = stepCandidate
  2352. case StateLeader:
  2353. sm.step = stepLeader
  2354. }
  2355. sm.Step(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  2356. msgs := sm.readMessages()
  2357. if len(msgs) != tt.wMsg {
  2358. t.Errorf("%d: len(msgs) = %d, want %d", i, len(msgs), tt.wMsg)
  2359. }
  2360. for _, m := range msgs {
  2361. if m.Type != pb.MsgHeartbeat {
  2362. t.Errorf("%d: msg.type = %v, want %v", i, m.Type, pb.MsgHeartbeat)
  2363. }
  2364. }
  2365. }
  2366. }
  2367. func TestLeaderIncreaseNext(t *testing.T) {
  2368. previousEnts := []pb.Entry{{Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3}}
  2369. tests := []struct {
  2370. // progress
  2371. state ProgressStateType
  2372. next uint64
  2373. wnext uint64
  2374. }{
  2375. // state replicate, optimistically increase next
  2376. // previous entries + noop entry + propose + 1
  2377. {ProgressStateReplicate, 2, uint64(len(previousEnts) + 1 + 1 + 1)},
  2378. // state probe, not optimistically increase next
  2379. {ProgressStateProbe, 2, 2},
  2380. }
  2381. for i, tt := range tests {
  2382. sm := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2383. sm.raftLog.append(previousEnts...)
  2384. sm.becomeCandidate()
  2385. sm.becomeLeader()
  2386. sm.prs[2].State = tt.state
  2387. sm.prs[2].Next = tt.next
  2388. sm.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  2389. p := sm.prs[2]
  2390. if p.Next != tt.wnext {
  2391. t.Errorf("#%d next = %d, want %d", i, p.Next, tt.wnext)
  2392. }
  2393. }
  2394. }
  2395. func TestSendAppendForProgressProbe(t *testing.T) {
  2396. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2397. r.becomeCandidate()
  2398. r.becomeLeader()
  2399. r.readMessages()
  2400. r.prs[2].becomeProbe()
  2401. // each round is a heartbeat
  2402. for i := 0; i < 3; i++ {
  2403. if i == 0 {
  2404. // we expect that raft will only send out one msgAPP on the first
  2405. // loop. After that, the follower is paused until a heartbeat response is
  2406. // received.
  2407. mustAppendEntry(r, pb.Entry{Data: []byte("somedata")})
  2408. r.sendAppend(2)
  2409. msg := r.readMessages()
  2410. if len(msg) != 1 {
  2411. t.Errorf("len(msg) = %d, want %d", len(msg), 1)
  2412. }
  2413. if msg[0].Index != 0 {
  2414. t.Errorf("index = %d, want %d", msg[0].Index, 0)
  2415. }
  2416. }
  2417. if !r.prs[2].Paused {
  2418. t.Errorf("paused = %v, want true", r.prs[2].Paused)
  2419. }
  2420. for j := 0; j < 10; j++ {
  2421. mustAppendEntry(r, pb.Entry{Data: []byte("somedata")})
  2422. r.sendAppend(2)
  2423. if l := len(r.readMessages()); l != 0 {
  2424. t.Errorf("len(msg) = %d, want %d", l, 0)
  2425. }
  2426. }
  2427. // do a heartbeat
  2428. for j := 0; j < r.heartbeatTimeout; j++ {
  2429. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  2430. }
  2431. if !r.prs[2].Paused {
  2432. t.Errorf("paused = %v, want true", r.prs[2].Paused)
  2433. }
  2434. // consume the heartbeat
  2435. msg := r.readMessages()
  2436. if len(msg) != 1 {
  2437. t.Errorf("len(msg) = %d, want %d", len(msg), 1)
  2438. }
  2439. if msg[0].Type != pb.MsgHeartbeat {
  2440. t.Errorf("type = %v, want %v", msg[0].Type, pb.MsgHeartbeat)
  2441. }
  2442. }
  2443. // a heartbeat response will allow another message to be sent
  2444. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgHeartbeatResp})
  2445. msg := r.readMessages()
  2446. if len(msg) != 1 {
  2447. t.Errorf("len(msg) = %d, want %d", len(msg), 1)
  2448. }
  2449. if msg[0].Index != 0 {
  2450. t.Errorf("index = %d, want %d", msg[0].Index, 0)
  2451. }
  2452. if !r.prs[2].Paused {
  2453. t.Errorf("paused = %v, want true", r.prs[2].Paused)
  2454. }
  2455. }
  2456. func TestSendAppendForProgressReplicate(t *testing.T) {
  2457. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2458. r.becomeCandidate()
  2459. r.becomeLeader()
  2460. r.readMessages()
  2461. r.prs[2].becomeReplicate()
  2462. for i := 0; i < 10; i++ {
  2463. mustAppendEntry(r, pb.Entry{Data: []byte("somedata")})
  2464. r.sendAppend(2)
  2465. msgs := r.readMessages()
  2466. if len(msgs) != 1 {
  2467. t.Errorf("len(msg) = %d, want %d", len(msgs), 1)
  2468. }
  2469. }
  2470. }
  2471. func TestSendAppendForProgressSnapshot(t *testing.T) {
  2472. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2473. r.becomeCandidate()
  2474. r.becomeLeader()
  2475. r.readMessages()
  2476. r.prs[2].becomeSnapshot(10)
  2477. for i := 0; i < 10; i++ {
  2478. mustAppendEntry(r, pb.Entry{Data: []byte("somedata")})
  2479. r.sendAppend(2)
  2480. msgs := r.readMessages()
  2481. if len(msgs) != 0 {
  2482. t.Errorf("len(msg) = %d, want %d", len(msgs), 0)
  2483. }
  2484. }
  2485. }
  2486. func TestRecvMsgUnreachable(t *testing.T) {
  2487. previousEnts := []pb.Entry{{Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3}}
  2488. s := NewMemoryStorage()
  2489. s.Append(previousEnts)
  2490. r := newTestRaft(1, []uint64{1, 2}, 10, 1, s)
  2491. r.becomeCandidate()
  2492. r.becomeLeader()
  2493. r.readMessages()
  2494. // set node 2 to state replicate
  2495. r.prs[2].Match = 3
  2496. r.prs[2].becomeReplicate()
  2497. r.prs[2].optimisticUpdate(5)
  2498. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgUnreachable})
  2499. if r.prs[2].State != ProgressStateProbe {
  2500. t.Errorf("state = %s, want %s", r.prs[2].State, ProgressStateProbe)
  2501. }
  2502. if wnext := r.prs[2].Match + 1; r.prs[2].Next != wnext {
  2503. t.Errorf("next = %d, want %d", r.prs[2].Next, wnext)
  2504. }
  2505. }
  2506. func TestRestore(t *testing.T) {
  2507. s := pb.Snapshot{
  2508. Metadata: pb.SnapshotMetadata{
  2509. Index: 11, // magic number
  2510. Term: 11, // magic number
  2511. ConfState: pb.ConfState{Nodes: []uint64{1, 2, 3}},
  2512. },
  2513. }
  2514. storage := NewMemoryStorage()
  2515. sm := newTestRaft(1, []uint64{1, 2}, 10, 1, storage)
  2516. if ok := sm.restore(s); !ok {
  2517. t.Fatal("restore fail, want succeed")
  2518. }
  2519. if sm.raftLog.lastIndex() != s.Metadata.Index {
  2520. t.Errorf("log.lastIndex = %d, want %d", sm.raftLog.lastIndex(), s.Metadata.Index)
  2521. }
  2522. if mustTerm(sm.raftLog.term(s.Metadata.Index)) != s.Metadata.Term {
  2523. t.Errorf("log.lastTerm = %d, want %d", mustTerm(sm.raftLog.term(s.Metadata.Index)), s.Metadata.Term)
  2524. }
  2525. sg := sm.nodes()
  2526. if !reflect.DeepEqual(sg, s.Metadata.ConfState.Nodes) {
  2527. t.Errorf("sm.Nodes = %+v, want %+v", sg, s.Metadata.ConfState.Nodes)
  2528. }
  2529. if ok := sm.restore(s); ok {
  2530. t.Fatal("restore succeed, want fail")
  2531. }
  2532. }
  2533. // TestRestoreWithLearner restores a snapshot which contains learners.
  2534. func TestRestoreWithLearner(t *testing.T) {
  2535. s := pb.Snapshot{
  2536. Metadata: pb.SnapshotMetadata{
  2537. Index: 11, // magic number
  2538. Term: 11, // magic number
  2539. ConfState: pb.ConfState{Nodes: []uint64{1, 2}, Learners: []uint64{3}},
  2540. },
  2541. }
  2542. storage := NewMemoryStorage()
  2543. sm := newTestLearnerRaft(3, []uint64{1, 2}, []uint64{3}, 8, 2, storage)
  2544. if ok := sm.restore(s); !ok {
  2545. t.Error("restore fail, want succeed")
  2546. }
  2547. if sm.raftLog.lastIndex() != s.Metadata.Index {
  2548. t.Errorf("log.lastIndex = %d, want %d", sm.raftLog.lastIndex(), s.Metadata.Index)
  2549. }
  2550. if mustTerm(sm.raftLog.term(s.Metadata.Index)) != s.Metadata.Term {
  2551. t.Errorf("log.lastTerm = %d, want %d", mustTerm(sm.raftLog.term(s.Metadata.Index)), s.Metadata.Term)
  2552. }
  2553. sg := sm.nodes()
  2554. if len(sg) != len(s.Metadata.ConfState.Nodes) {
  2555. t.Errorf("sm.Nodes = %+v, length not equal with %+v", sg, s.Metadata.ConfState.Nodes)
  2556. }
  2557. lns := sm.learnerNodes()
  2558. if len(lns) != len(s.Metadata.ConfState.Learners) {
  2559. t.Errorf("sm.LearnerNodes = %+v, length not equal with %+v", sg, s.Metadata.ConfState.Learners)
  2560. }
  2561. for _, n := range s.Metadata.ConfState.Nodes {
  2562. if sm.prs[n].IsLearner {
  2563. t.Errorf("sm.Node %x isLearner = %s, want %t", n, sm.prs[n], false)
  2564. }
  2565. }
  2566. for _, n := range s.Metadata.ConfState.Learners {
  2567. if !sm.learnerPrs[n].IsLearner {
  2568. t.Errorf("sm.Node %x isLearner = %s, want %t", n, sm.prs[n], true)
  2569. }
  2570. }
  2571. if ok := sm.restore(s); ok {
  2572. t.Error("restore succeed, want fail")
  2573. }
  2574. }
  2575. // TestRestoreInvalidLearner verfies that a normal peer can't become learner again
  2576. // when restores snapshot.
  2577. func TestRestoreInvalidLearner(t *testing.T) {
  2578. s := pb.Snapshot{
  2579. Metadata: pb.SnapshotMetadata{
  2580. Index: 11, // magic number
  2581. Term: 11, // magic number
  2582. ConfState: pb.ConfState{Nodes: []uint64{1, 2}, Learners: []uint64{3}},
  2583. },
  2584. }
  2585. storage := NewMemoryStorage()
  2586. sm := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, storage)
  2587. if sm.isLearner {
  2588. t.Errorf("%x is learner, want not", sm.id)
  2589. }
  2590. if ok := sm.restore(s); ok {
  2591. t.Error("restore succeed, want fail")
  2592. }
  2593. }
  2594. // TestRestoreLearnerPromotion checks that a learner can become to a follower after
  2595. // restoring snapshot.
  2596. func TestRestoreLearnerPromotion(t *testing.T) {
  2597. s := pb.Snapshot{
  2598. Metadata: pb.SnapshotMetadata{
  2599. Index: 11, // magic number
  2600. Term: 11, // magic number
  2601. ConfState: pb.ConfState{Nodes: []uint64{1, 2, 3}},
  2602. },
  2603. }
  2604. storage := NewMemoryStorage()
  2605. sm := newTestLearnerRaft(3, []uint64{1, 2}, []uint64{3}, 10, 1, storage)
  2606. if !sm.isLearner {
  2607. t.Errorf("%x is not learner, want yes", sm.id)
  2608. }
  2609. if ok := sm.restore(s); !ok {
  2610. t.Error("restore fail, want succeed")
  2611. }
  2612. if sm.isLearner {
  2613. t.Errorf("%x is learner, want not", sm.id)
  2614. }
  2615. }
  2616. // TestLearnerReceiveSnapshot tests that a learner can receive a snpahost from leader
  2617. func TestLearnerReceiveSnapshot(t *testing.T) {
  2618. // restore the state machine from a snapshot so it has a compacted log and a snapshot
  2619. s := pb.Snapshot{
  2620. Metadata: pb.SnapshotMetadata{
  2621. Index: 11, // magic number
  2622. Term: 11, // magic number
  2623. ConfState: pb.ConfState{Nodes: []uint64{1}, Learners: []uint64{2}},
  2624. },
  2625. }
  2626. n1 := newTestLearnerRaft(1, []uint64{1}, []uint64{2}, 10, 1, NewMemoryStorage())
  2627. n2 := newTestLearnerRaft(2, []uint64{1}, []uint64{2}, 10, 1, NewMemoryStorage())
  2628. n1.restore(s)
  2629. // Force set n1 appplied index.
  2630. n1.raftLog.appliedTo(n1.raftLog.committed)
  2631. nt := newNetwork(n1, n2)
  2632. setRandomizedElectionTimeout(n1, n1.electionTimeout)
  2633. for i := 0; i < n1.electionTimeout; i++ {
  2634. n1.tick()
  2635. }
  2636. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  2637. if n2.raftLog.committed != n1.raftLog.committed {
  2638. t.Errorf("peer 2 must commit to %d, but %d", n1.raftLog.committed, n2.raftLog.committed)
  2639. }
  2640. }
  2641. func TestRestoreIgnoreSnapshot(t *testing.T) {
  2642. previousEnts := []pb.Entry{{Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3}}
  2643. commit := uint64(1)
  2644. storage := NewMemoryStorage()
  2645. sm := newTestRaft(1, []uint64{1, 2}, 10, 1, storage)
  2646. sm.raftLog.append(previousEnts...)
  2647. sm.raftLog.commitTo(commit)
  2648. s := pb.Snapshot{
  2649. Metadata: pb.SnapshotMetadata{
  2650. Index: commit,
  2651. Term: 1,
  2652. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  2653. },
  2654. }
  2655. // ignore snapshot
  2656. if ok := sm.restore(s); ok {
  2657. t.Errorf("restore = %t, want %t", ok, false)
  2658. }
  2659. if sm.raftLog.committed != commit {
  2660. t.Errorf("commit = %d, want %d", sm.raftLog.committed, commit)
  2661. }
  2662. // ignore snapshot and fast forward commit
  2663. s.Metadata.Index = commit + 1
  2664. if ok := sm.restore(s); ok {
  2665. t.Errorf("restore = %t, want %t", ok, false)
  2666. }
  2667. if sm.raftLog.committed != commit+1 {
  2668. t.Errorf("commit = %d, want %d", sm.raftLog.committed, commit+1)
  2669. }
  2670. }
  2671. func TestProvideSnap(t *testing.T) {
  2672. // restore the state machine from a snapshot so it has a compacted log and a snapshot
  2673. s := pb.Snapshot{
  2674. Metadata: pb.SnapshotMetadata{
  2675. Index: 11, // magic number
  2676. Term: 11, // magic number
  2677. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  2678. },
  2679. }
  2680. storage := NewMemoryStorage()
  2681. sm := newTestRaft(1, []uint64{1}, 10, 1, storage)
  2682. sm.restore(s)
  2683. sm.becomeCandidate()
  2684. sm.becomeLeader()
  2685. // force set the next of node 2, so that node 2 needs a snapshot
  2686. sm.prs[2].Next = sm.raftLog.firstIndex()
  2687. sm.Step(pb.Message{From: 2, To: 1, Type: pb.MsgAppResp, Index: sm.prs[2].Next - 1, Reject: true})
  2688. msgs := sm.readMessages()
  2689. if len(msgs) != 1 {
  2690. t.Fatalf("len(msgs) = %d, want 1", len(msgs))
  2691. }
  2692. m := msgs[0]
  2693. if m.Type != pb.MsgSnap {
  2694. t.Errorf("m.Type = %v, want %v", m.Type, pb.MsgSnap)
  2695. }
  2696. }
  2697. func TestIgnoreProvidingSnap(t *testing.T) {
  2698. // restore the state machine from a snapshot so it has a compacted log and a snapshot
  2699. s := pb.Snapshot{
  2700. Metadata: pb.SnapshotMetadata{
  2701. Index: 11, // magic number
  2702. Term: 11, // magic number
  2703. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  2704. },
  2705. }
  2706. storage := NewMemoryStorage()
  2707. sm := newTestRaft(1, []uint64{1}, 10, 1, storage)
  2708. sm.restore(s)
  2709. sm.becomeCandidate()
  2710. sm.becomeLeader()
  2711. // force set the next of node 2, so that node 2 needs a snapshot
  2712. // change node 2 to be inactive, expect node 1 ignore sending snapshot to 2
  2713. sm.prs[2].Next = sm.raftLog.firstIndex() - 1
  2714. sm.prs[2].RecentActive = false
  2715. sm.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  2716. msgs := sm.readMessages()
  2717. if len(msgs) != 0 {
  2718. t.Errorf("len(msgs) = %d, want 0", len(msgs))
  2719. }
  2720. }
  2721. func TestRestoreFromSnapMsg(t *testing.T) {
  2722. s := pb.Snapshot{
  2723. Metadata: pb.SnapshotMetadata{
  2724. Index: 11, // magic number
  2725. Term: 11, // magic number
  2726. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  2727. },
  2728. }
  2729. m := pb.Message{Type: pb.MsgSnap, From: 1, Term: 2, Snapshot: s}
  2730. sm := newTestRaft(2, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2731. sm.Step(m)
  2732. if sm.lead != uint64(1) {
  2733. t.Errorf("sm.lead = %d, want 1", sm.lead)
  2734. }
  2735. // TODO(bdarnell): what should this test?
  2736. }
  2737. func TestSlowNodeRestore(t *testing.T) {
  2738. nt := newNetwork(nil, nil, nil)
  2739. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2740. nt.isolate(3)
  2741. for j := 0; j <= 100; j++ {
  2742. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2743. }
  2744. lead := nt.peers[1].(*raft)
  2745. nextEnts(lead, nt.storage[1])
  2746. nt.storage[1].CreateSnapshot(lead.raftLog.applied, &pb.ConfState{Nodes: lead.nodes()}, nil)
  2747. nt.storage[1].Compact(lead.raftLog.applied)
  2748. nt.recover()
  2749. // send heartbeats so that the leader can learn everyone is active.
  2750. // node 3 will only be considered as active when node 1 receives a reply from it.
  2751. for {
  2752. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  2753. if lead.prs[3].RecentActive {
  2754. break
  2755. }
  2756. }
  2757. // trigger a snapshot
  2758. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2759. follower := nt.peers[3].(*raft)
  2760. // trigger a commit
  2761. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2762. if follower.raftLog.committed != lead.raftLog.committed {
  2763. t.Errorf("follower.committed = %d, want %d", follower.raftLog.committed, lead.raftLog.committed)
  2764. }
  2765. }
  2766. // TestStepConfig tests that when raft step msgProp in EntryConfChange type,
  2767. // it appends the entry to log and sets pendingConf to be true.
  2768. func TestStepConfig(t *testing.T) {
  2769. // a raft that cannot make progress
  2770. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2771. r.becomeCandidate()
  2772. r.becomeLeader()
  2773. index := r.raftLog.lastIndex()
  2774. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange}}})
  2775. if g := r.raftLog.lastIndex(); g != index+1 {
  2776. t.Errorf("index = %d, want %d", g, index+1)
  2777. }
  2778. if r.pendingConfIndex != index+1 {
  2779. t.Errorf("pendingConfIndex = %d, want %d", r.pendingConfIndex, index+1)
  2780. }
  2781. }
  2782. // TestStepIgnoreConfig tests that if raft step the second msgProp in
  2783. // EntryConfChange type when the first one is uncommitted, the node will set
  2784. // the proposal to noop and keep its original state.
  2785. func TestStepIgnoreConfig(t *testing.T) {
  2786. // a raft that cannot make progress
  2787. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2788. r.becomeCandidate()
  2789. r.becomeLeader()
  2790. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange}}})
  2791. index := r.raftLog.lastIndex()
  2792. pendingConfIndex := r.pendingConfIndex
  2793. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange}}})
  2794. wents := []pb.Entry{{Type: pb.EntryNormal, Term: 1, Index: 3, Data: nil}}
  2795. ents, err := r.raftLog.entries(index+1, noLimit)
  2796. if err != nil {
  2797. t.Fatalf("unexpected error %v", err)
  2798. }
  2799. if !reflect.DeepEqual(ents, wents) {
  2800. t.Errorf("ents = %+v, want %+v", ents, wents)
  2801. }
  2802. if r.pendingConfIndex != pendingConfIndex {
  2803. t.Errorf("pendingConfIndex = %d, want %d", r.pendingConfIndex, pendingConfIndex)
  2804. }
  2805. }
  2806. // TestNewLeaderPendingConfig tests that new leader sets its pendingConfigIndex
  2807. // based on uncommitted entries.
  2808. func TestNewLeaderPendingConfig(t *testing.T) {
  2809. tests := []struct {
  2810. addEntry bool
  2811. wpendingIndex uint64
  2812. }{
  2813. {false, 0},
  2814. {true, 1},
  2815. }
  2816. for i, tt := range tests {
  2817. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2818. if tt.addEntry {
  2819. mustAppendEntry(r, pb.Entry{Type: pb.EntryNormal})
  2820. }
  2821. r.becomeCandidate()
  2822. r.becomeLeader()
  2823. if r.pendingConfIndex != tt.wpendingIndex {
  2824. t.Errorf("#%d: pendingConfIndex = %d, want %d",
  2825. i, r.pendingConfIndex, tt.wpendingIndex)
  2826. }
  2827. }
  2828. }
  2829. // TestAddNode tests that addNode could update nodes correctly.
  2830. func TestAddNode(t *testing.T) {
  2831. r := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  2832. r.addNode(2)
  2833. nodes := r.nodes()
  2834. wnodes := []uint64{1, 2}
  2835. if !reflect.DeepEqual(nodes, wnodes) {
  2836. t.Errorf("nodes = %v, want %v", nodes, wnodes)
  2837. }
  2838. }
  2839. // TestAddLearner tests that addLearner could update nodes correctly.
  2840. func TestAddLearner(t *testing.T) {
  2841. r := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  2842. r.addLearner(2)
  2843. nodes := r.learnerNodes()
  2844. wnodes := []uint64{2}
  2845. if !reflect.DeepEqual(nodes, wnodes) {
  2846. t.Errorf("nodes = %v, want %v", nodes, wnodes)
  2847. }
  2848. if !r.learnerPrs[2].IsLearner {
  2849. t.Errorf("node 2 is learner %t, want %t", r.prs[2].IsLearner, true)
  2850. }
  2851. }
  2852. // TestAddNodeCheckQuorum tests that addNode does not trigger a leader election
  2853. // immediately when checkQuorum is set.
  2854. func TestAddNodeCheckQuorum(t *testing.T) {
  2855. r := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  2856. r.checkQuorum = true
  2857. r.becomeCandidate()
  2858. r.becomeLeader()
  2859. for i := 0; i < r.electionTimeout-1; i++ {
  2860. r.tick()
  2861. }
  2862. r.addNode(2)
  2863. // This tick will reach electionTimeout, which triggers a quorum check.
  2864. r.tick()
  2865. // Node 1 should still be the leader after a single tick.
  2866. if r.state != StateLeader {
  2867. t.Errorf("state = %v, want %v", r.state, StateLeader)
  2868. }
  2869. // After another electionTimeout ticks without hearing from node 2,
  2870. // node 1 should step down.
  2871. for i := 0; i < r.electionTimeout; i++ {
  2872. r.tick()
  2873. }
  2874. if r.state != StateFollower {
  2875. t.Errorf("state = %v, want %v", r.state, StateFollower)
  2876. }
  2877. }
  2878. // TestRemoveNode tests that removeNode could update nodes and
  2879. // and removed list correctly.
  2880. func TestRemoveNode(t *testing.T) {
  2881. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2882. r.removeNode(2)
  2883. w := []uint64{1}
  2884. if g := r.nodes(); !reflect.DeepEqual(g, w) {
  2885. t.Errorf("nodes = %v, want %v", g, w)
  2886. }
  2887. // remove all nodes from cluster
  2888. r.removeNode(1)
  2889. w = []uint64{}
  2890. if g := r.nodes(); !reflect.DeepEqual(g, w) {
  2891. t.Errorf("nodes = %v, want %v", g, w)
  2892. }
  2893. }
  2894. // TestRemoveLearner tests that removeNode could update nodes and
  2895. // and removed list correctly.
  2896. func TestRemoveLearner(t *testing.T) {
  2897. r := newTestLearnerRaft(1, []uint64{1}, []uint64{2}, 10, 1, NewMemoryStorage())
  2898. r.removeNode(2)
  2899. w := []uint64{1}
  2900. if g := r.nodes(); !reflect.DeepEqual(g, w) {
  2901. t.Errorf("nodes = %v, want %v", g, w)
  2902. }
  2903. w = []uint64{}
  2904. if g := r.learnerNodes(); !reflect.DeepEqual(g, w) {
  2905. t.Errorf("nodes = %v, want %v", g, w)
  2906. }
  2907. // remove all nodes from cluster
  2908. r.removeNode(1)
  2909. if g := r.nodes(); !reflect.DeepEqual(g, w) {
  2910. t.Errorf("nodes = %v, want %v", g, w)
  2911. }
  2912. }
  2913. func TestPromotable(t *testing.T) {
  2914. id := uint64(1)
  2915. tests := []struct {
  2916. peers []uint64
  2917. wp bool
  2918. }{
  2919. {[]uint64{1}, true},
  2920. {[]uint64{1, 2, 3}, true},
  2921. {[]uint64{}, false},
  2922. {[]uint64{2, 3}, false},
  2923. }
  2924. for i, tt := range tests {
  2925. r := newTestRaft(id, tt.peers, 5, 1, NewMemoryStorage())
  2926. if g := r.promotable(); g != tt.wp {
  2927. t.Errorf("#%d: promotable = %v, want %v", i, g, tt.wp)
  2928. }
  2929. }
  2930. }
  2931. func TestRaftNodes(t *testing.T) {
  2932. tests := []struct {
  2933. ids []uint64
  2934. wids []uint64
  2935. }{
  2936. {
  2937. []uint64{1, 2, 3},
  2938. []uint64{1, 2, 3},
  2939. },
  2940. {
  2941. []uint64{3, 2, 1},
  2942. []uint64{1, 2, 3},
  2943. },
  2944. }
  2945. for i, tt := range tests {
  2946. r := newTestRaft(1, tt.ids, 10, 1, NewMemoryStorage())
  2947. if !reflect.DeepEqual(r.nodes(), tt.wids) {
  2948. t.Errorf("#%d: nodes = %+v, want %+v", i, r.nodes(), tt.wids)
  2949. }
  2950. }
  2951. }
  2952. func TestCampaignWhileLeader(t *testing.T) {
  2953. testCampaignWhileLeader(t, false)
  2954. }
  2955. func TestPreCampaignWhileLeader(t *testing.T) {
  2956. testCampaignWhileLeader(t, true)
  2957. }
  2958. func testCampaignWhileLeader(t *testing.T, preVote bool) {
  2959. cfg := newTestConfig(1, []uint64{1}, 5, 1, NewMemoryStorage())
  2960. cfg.PreVote = preVote
  2961. r := newRaft(cfg)
  2962. if r.state != StateFollower {
  2963. t.Errorf("expected new node to be follower but got %s", r.state)
  2964. }
  2965. // We don't call campaign() directly because it comes after the check
  2966. // for our current state.
  2967. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2968. if r.state != StateLeader {
  2969. t.Errorf("expected single-node election to become leader but got %s", r.state)
  2970. }
  2971. term := r.Term
  2972. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2973. if r.state != StateLeader {
  2974. t.Errorf("expected to remain leader but got %s", r.state)
  2975. }
  2976. if r.Term != term {
  2977. t.Errorf("expected to remain in term %v but got %v", term, r.Term)
  2978. }
  2979. }
  2980. // TestCommitAfterRemoveNode verifies that pending commands can become
  2981. // committed when a config change reduces the quorum requirements.
  2982. func TestCommitAfterRemoveNode(t *testing.T) {
  2983. // Create a cluster with two nodes.
  2984. s := NewMemoryStorage()
  2985. r := newTestRaft(1, []uint64{1, 2}, 5, 1, s)
  2986. r.becomeCandidate()
  2987. r.becomeLeader()
  2988. // Begin to remove the second node.
  2989. cc := pb.ConfChange{
  2990. Type: pb.ConfChangeRemoveNode,
  2991. NodeID: 2,
  2992. }
  2993. ccData, err := cc.Marshal()
  2994. if err != nil {
  2995. t.Fatal(err)
  2996. }
  2997. r.Step(pb.Message{
  2998. Type: pb.MsgProp,
  2999. Entries: []pb.Entry{
  3000. {Type: pb.EntryConfChange, Data: ccData},
  3001. },
  3002. })
  3003. // Stabilize the log and make sure nothing is committed yet.
  3004. if ents := nextEnts(r, s); len(ents) > 0 {
  3005. t.Fatalf("unexpected committed entries: %v", ents)
  3006. }
  3007. ccIndex := r.raftLog.lastIndex()
  3008. // While the config change is pending, make another proposal.
  3009. r.Step(pb.Message{
  3010. Type: pb.MsgProp,
  3011. Entries: []pb.Entry{
  3012. {Type: pb.EntryNormal, Data: []byte("hello")},
  3013. },
  3014. })
  3015. // Node 2 acknowledges the config change, committing it.
  3016. r.Step(pb.Message{
  3017. Type: pb.MsgAppResp,
  3018. From: 2,
  3019. Index: ccIndex,
  3020. })
  3021. ents := nextEnts(r, s)
  3022. if len(ents) != 2 {
  3023. t.Fatalf("expected two committed entries, got %v", ents)
  3024. }
  3025. if ents[0].Type != pb.EntryNormal || ents[0].Data != nil {
  3026. t.Fatalf("expected ents[0] to be empty, but got %v", ents[0])
  3027. }
  3028. if ents[1].Type != pb.EntryConfChange {
  3029. t.Fatalf("expected ents[1] to be EntryConfChange, got %v", ents[1])
  3030. }
  3031. // Apply the config change. This reduces quorum requirements so the
  3032. // pending command can now commit.
  3033. r.removeNode(2)
  3034. ents = nextEnts(r, s)
  3035. if len(ents) != 1 || ents[0].Type != pb.EntryNormal ||
  3036. string(ents[0].Data) != "hello" {
  3037. t.Fatalf("expected one committed EntryNormal, got %v", ents)
  3038. }
  3039. }
  3040. // TestLeaderTransferToUpToDateNode verifies transferring should succeed
  3041. // if the transferee has the most up-to-date log entries when transfer starts.
  3042. func TestLeaderTransferToUpToDateNode(t *testing.T) {
  3043. nt := newNetwork(nil, nil, nil)
  3044. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  3045. lead := nt.peers[1].(*raft)
  3046. if lead.lead != 1 {
  3047. t.Fatalf("after election leader is %x, want 1", lead.lead)
  3048. }
  3049. // Transfer leadership to 2.
  3050. nt.send(pb.Message{From: 2, To: 1, Type: pb.MsgTransferLeader})
  3051. checkLeaderTransferState(t, lead, StateFollower, 2)
  3052. // After some log replication, transfer leadership back to 1.
  3053. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  3054. nt.send(pb.Message{From: 1, To: 2, Type: pb.MsgTransferLeader})
  3055. checkLeaderTransferState(t, lead, StateLeader, 1)
  3056. }
  3057. // TestLeaderTransferToUpToDateNodeFromFollower verifies transferring should succeed
  3058. // if the transferee has the most up-to-date log entries when transfer starts.
  3059. // Not like TestLeaderTransferToUpToDateNode, where the leader transfer message
  3060. // is sent to the leader, in this test case every leader transfer message is sent
  3061. // to the follower.
  3062. func TestLeaderTransferToUpToDateNodeFromFollower(t *testing.T) {
  3063. nt := newNetwork(nil, nil, nil)
  3064. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  3065. lead := nt.peers[1].(*raft)
  3066. if lead.lead != 1 {
  3067. t.Fatalf("after election leader is %x, want 1", lead.lead)
  3068. }
  3069. // Transfer leadership to 2.
  3070. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgTransferLeader})
  3071. checkLeaderTransferState(t, lead, StateFollower, 2)
  3072. // After some log replication, transfer leadership back to 1.
  3073. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  3074. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgTransferLeader})
  3075. checkLeaderTransferState(t, lead, StateLeader, 1)
  3076. }
  3077. // TestLeaderTransferWithCheckQuorum ensures transferring leader still works
  3078. // even the current leader is still under its leader lease
  3079. func TestLeaderTransferWithCheckQuorum(t *testing.T) {
  3080. nt := newNetwork(nil, nil, nil)
  3081. for i := 1; i < 4; i++ {
  3082. r := nt.peers[uint64(i)].(*raft)
  3083. r.checkQuorum = true
  3084. setRandomizedElectionTimeout(r, r.electionTimeout+i)
  3085. }
  3086. // Letting peer 2 electionElapsed reach to timeout so that it can vote for peer 1
  3087. f := nt.peers[2].(*raft)
  3088. for i := 0; i < f.electionTimeout; i++ {
  3089. f.tick()
  3090. }
  3091. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  3092. lead := nt.peers[1].(*raft)
  3093. if lead.lead != 1 {
  3094. t.Fatalf("after election leader is %x, want 1", lead.lead)
  3095. }
  3096. // Transfer leadership to 2.
  3097. nt.send(pb.Message{From: 2, To: 1, Type: pb.MsgTransferLeader})
  3098. checkLeaderTransferState(t, lead, StateFollower, 2)
  3099. // After some log replication, transfer leadership back to 1.
  3100. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  3101. nt.send(pb.Message{From: 1, To: 2, Type: pb.MsgTransferLeader})
  3102. checkLeaderTransferState(t, lead, StateLeader, 1)
  3103. }
  3104. func TestLeaderTransferToSlowFollower(t *testing.T) {
  3105. defaultLogger.EnableDebug()
  3106. nt := newNetwork(nil, nil, nil)
  3107. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  3108. nt.isolate(3)
  3109. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  3110. nt.recover()
  3111. lead := nt.peers[1].(*raft)
  3112. if lead.prs[3].Match != 1 {
  3113. t.Fatalf("node 1 has match %x for node 3, want %x", lead.prs[3].Match, 1)
  3114. }
  3115. // Transfer leadership to 3 when node 3 is lack of log.
  3116. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  3117. checkLeaderTransferState(t, lead, StateFollower, 3)
  3118. }
  3119. func TestLeaderTransferAfterSnapshot(t *testing.T) {
  3120. nt := newNetwork(nil, nil, nil)
  3121. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  3122. nt.isolate(3)
  3123. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  3124. lead := nt.peers[1].(*raft)
  3125. nextEnts(lead, nt.storage[1])
  3126. nt.storage[1].CreateSnapshot(lead.raftLog.applied, &pb.ConfState{Nodes: lead.nodes()}, nil)
  3127. nt.storage[1].Compact(lead.raftLog.applied)
  3128. nt.recover()
  3129. if lead.prs[3].Match != 1 {
  3130. t.Fatalf("node 1 has match %x for node 3, want %x", lead.prs[3].Match, 1)
  3131. }
  3132. // Transfer leadership to 3 when node 3 is lack of snapshot.
  3133. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  3134. // Send pb.MsgHeartbeatResp to leader to trigger a snapshot for node 3.
  3135. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgHeartbeatResp})
  3136. checkLeaderTransferState(t, lead, StateFollower, 3)
  3137. }
  3138. func TestLeaderTransferToSelf(t *testing.T) {
  3139. nt := newNetwork(nil, nil, nil)
  3140. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  3141. lead := nt.peers[1].(*raft)
  3142. // Transfer leadership to self, there will be noop.
  3143. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgTransferLeader})
  3144. checkLeaderTransferState(t, lead, StateLeader, 1)
  3145. }
  3146. func TestLeaderTransferToNonExistingNode(t *testing.T) {
  3147. nt := newNetwork(nil, nil, nil)
  3148. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  3149. lead := nt.peers[1].(*raft)
  3150. // Transfer leadership to non-existing node, there will be noop.
  3151. nt.send(pb.Message{From: 4, To: 1, Type: pb.MsgTransferLeader})
  3152. checkLeaderTransferState(t, lead, StateLeader, 1)
  3153. }
  3154. func TestLeaderTransferTimeout(t *testing.T) {
  3155. nt := newNetwork(nil, nil, nil)
  3156. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  3157. nt.isolate(3)
  3158. lead := nt.peers[1].(*raft)
  3159. // Transfer leadership to isolated node, wait for timeout.
  3160. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  3161. if lead.leadTransferee != 3 {
  3162. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  3163. }
  3164. for i := 0; i < lead.heartbeatTimeout; i++ {
  3165. lead.tick()
  3166. }
  3167. if lead.leadTransferee != 3 {
  3168. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  3169. }
  3170. for i := 0; i < lead.electionTimeout-lead.heartbeatTimeout; i++ {
  3171. lead.tick()
  3172. }
  3173. checkLeaderTransferState(t, lead, StateLeader, 1)
  3174. }
  3175. func TestLeaderTransferIgnoreProposal(t *testing.T) {
  3176. nt := newNetwork(nil, nil, nil)
  3177. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  3178. nt.isolate(3)
  3179. lead := nt.peers[1].(*raft)
  3180. // Transfer leadership to isolated node to let transfer pending, then send proposal.
  3181. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  3182. if lead.leadTransferee != 3 {
  3183. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  3184. }
  3185. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  3186. err := lead.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  3187. if err != ErrProposalDropped {
  3188. t.Fatalf("should return drop proposal error while transferring")
  3189. }
  3190. if lead.prs[1].Match != 1 {
  3191. t.Fatalf("node 1 has match %x, want %x", lead.prs[1].Match, 1)
  3192. }
  3193. }
  3194. func TestLeaderTransferReceiveHigherTermVote(t *testing.T) {
  3195. nt := newNetwork(nil, nil, nil)
  3196. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  3197. nt.isolate(3)
  3198. lead := nt.peers[1].(*raft)
  3199. // Transfer leadership to isolated node to let transfer pending.
  3200. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  3201. if lead.leadTransferee != 3 {
  3202. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  3203. }
  3204. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup, Index: 1, Term: 2})
  3205. checkLeaderTransferState(t, lead, StateFollower, 2)
  3206. }
  3207. func TestLeaderTransferRemoveNode(t *testing.T) {
  3208. nt := newNetwork(nil, nil, nil)
  3209. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  3210. nt.ignore(pb.MsgTimeoutNow)
  3211. lead := nt.peers[1].(*raft)
  3212. // The leadTransferee is removed when leadship transferring.
  3213. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  3214. if lead.leadTransferee != 3 {
  3215. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  3216. }
  3217. lead.removeNode(3)
  3218. checkLeaderTransferState(t, lead, StateLeader, 1)
  3219. }
  3220. // TestLeaderTransferBack verifies leadership can transfer back to self when last transfer is pending.
  3221. func TestLeaderTransferBack(t *testing.T) {
  3222. nt := newNetwork(nil, nil, nil)
  3223. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  3224. nt.isolate(3)
  3225. lead := nt.peers[1].(*raft)
  3226. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  3227. if lead.leadTransferee != 3 {
  3228. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  3229. }
  3230. // Transfer leadership back to self.
  3231. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgTransferLeader})
  3232. checkLeaderTransferState(t, lead, StateLeader, 1)
  3233. }
  3234. // TestLeaderTransferSecondTransferToAnotherNode verifies leader can transfer to another node
  3235. // when last transfer is pending.
  3236. func TestLeaderTransferSecondTransferToAnotherNode(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. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  3242. if lead.leadTransferee != 3 {
  3243. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  3244. }
  3245. // Transfer leadership to another node.
  3246. nt.send(pb.Message{From: 2, To: 1, Type: pb.MsgTransferLeader})
  3247. checkLeaderTransferState(t, lead, StateFollower, 2)
  3248. }
  3249. // TestLeaderTransferSecondTransferToSameNode verifies second transfer leader request
  3250. // to the same node should not extend the timeout while the first one is pending.
  3251. func TestLeaderTransferSecondTransferToSameNode(t *testing.T) {
  3252. nt := newNetwork(nil, nil, nil)
  3253. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  3254. nt.isolate(3)
  3255. lead := nt.peers[1].(*raft)
  3256. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  3257. if lead.leadTransferee != 3 {
  3258. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  3259. }
  3260. for i := 0; i < lead.heartbeatTimeout; i++ {
  3261. lead.tick()
  3262. }
  3263. // Second transfer leadership request to the same node.
  3264. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  3265. for i := 0; i < lead.electionTimeout-lead.heartbeatTimeout; i++ {
  3266. lead.tick()
  3267. }
  3268. checkLeaderTransferState(t, lead, StateLeader, 1)
  3269. }
  3270. func checkLeaderTransferState(t *testing.T, r *raft, state StateType, lead uint64) {
  3271. if r.state != state || r.lead != lead {
  3272. t.Fatalf("after transferring, node has state %v lead %v, want state %v lead %v", r.state, r.lead, state, lead)
  3273. }
  3274. if r.leadTransferee != None {
  3275. t.Fatalf("after transferring, node has leadTransferee %v, want leadTransferee %v", r.leadTransferee, None)
  3276. }
  3277. }
  3278. // TestTransferNonMember verifies that when a MsgTimeoutNow arrives at
  3279. // a node that has been removed from the group, nothing happens.
  3280. // (previously, if the node also got votes, it would panic as it
  3281. // transitioned to StateLeader)
  3282. func TestTransferNonMember(t *testing.T) {
  3283. r := newTestRaft(1, []uint64{2, 3, 4}, 5, 1, NewMemoryStorage())
  3284. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgTimeoutNow})
  3285. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgVoteResp})
  3286. r.Step(pb.Message{From: 3, To: 1, Type: pb.MsgVoteResp})
  3287. if r.state != StateFollower {
  3288. t.Fatalf("state is %s, want StateFollower", r.state)
  3289. }
  3290. }
  3291. // TestNodeWithSmallerTermCanCompleteElection tests the scenario where a node
  3292. // that has been partitioned away (and fallen behind) rejoins the cluster at
  3293. // about the same time the leader node gets partitioned away.
  3294. // Previously the cluster would come to a standstill when run with PreVote
  3295. // enabled.
  3296. func TestNodeWithSmallerTermCanCompleteElection(t *testing.T) {
  3297. n1 := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  3298. n2 := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  3299. n3 := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  3300. n1.becomeFollower(1, None)
  3301. n2.becomeFollower(1, None)
  3302. n3.becomeFollower(1, None)
  3303. n1.preVote = true
  3304. n2.preVote = true
  3305. n3.preVote = true
  3306. // cause a network partition to isolate node 3
  3307. nt := newNetwork(n1, n2, n3)
  3308. nt.cut(1, 3)
  3309. nt.cut(2, 3)
  3310. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  3311. sm := nt.peers[1].(*raft)
  3312. if sm.state != StateLeader {
  3313. t.Errorf("peer 1 state: %s, want %s", sm.state, StateLeader)
  3314. }
  3315. sm = nt.peers[2].(*raft)
  3316. if sm.state != StateFollower {
  3317. t.Errorf("peer 2 state: %s, want %s", sm.state, StateFollower)
  3318. }
  3319. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  3320. sm = nt.peers[3].(*raft)
  3321. if sm.state != StatePreCandidate {
  3322. t.Errorf("peer 3 state: %s, want %s", sm.state, StatePreCandidate)
  3323. }
  3324. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  3325. // check whether the term values are expected
  3326. // a.Term == 3
  3327. // b.Term == 3
  3328. // c.Term == 1
  3329. sm = nt.peers[1].(*raft)
  3330. if sm.Term != 3 {
  3331. t.Errorf("peer 1 term: %d, want %d", sm.Term, 3)
  3332. }
  3333. sm = nt.peers[2].(*raft)
  3334. if sm.Term != 3 {
  3335. t.Errorf("peer 2 term: %d, want %d", sm.Term, 3)
  3336. }
  3337. sm = nt.peers[3].(*raft)
  3338. if sm.Term != 1 {
  3339. t.Errorf("peer 3 term: %d, want %d", sm.Term, 1)
  3340. }
  3341. // check state
  3342. // a == follower
  3343. // b == leader
  3344. // c == pre-candidate
  3345. sm = nt.peers[1].(*raft)
  3346. if sm.state != StateFollower {
  3347. t.Errorf("peer 1 state: %s, want %s", sm.state, StateFollower)
  3348. }
  3349. sm = nt.peers[2].(*raft)
  3350. if sm.state != StateLeader {
  3351. t.Errorf("peer 2 state: %s, want %s", sm.state, StateLeader)
  3352. }
  3353. sm = nt.peers[3].(*raft)
  3354. if sm.state != StatePreCandidate {
  3355. t.Errorf("peer 3 state: %s, want %s", sm.state, StatePreCandidate)
  3356. }
  3357. sm.logger.Infof("going to bring back peer 3 and kill peer 2")
  3358. // recover the network then immediately isolate b which is currently
  3359. // the leader, this is to emulate the crash of b.
  3360. nt.recover()
  3361. nt.cut(2, 1)
  3362. nt.cut(2, 3)
  3363. // call for election
  3364. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  3365. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  3366. // do we have a leader?
  3367. sma := nt.peers[1].(*raft)
  3368. smb := nt.peers[3].(*raft)
  3369. if sma.state != StateLeader && smb.state != StateLeader {
  3370. t.Errorf("no leader")
  3371. }
  3372. }
  3373. // TestPreVoteWithSplitVote verifies that after split vote, cluster can complete
  3374. // election in next round.
  3375. func TestPreVoteWithSplitVote(t *testing.T) {
  3376. n1 := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  3377. n2 := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  3378. n3 := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  3379. n1.becomeFollower(1, None)
  3380. n2.becomeFollower(1, None)
  3381. n3.becomeFollower(1, None)
  3382. n1.preVote = true
  3383. n2.preVote = true
  3384. n3.preVote = true
  3385. nt := newNetwork(n1, n2, n3)
  3386. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  3387. // simulate leader down. followers start split vote.
  3388. nt.isolate(1)
  3389. nt.send([]pb.Message{
  3390. {From: 2, To: 2, Type: pb.MsgHup},
  3391. {From: 3, To: 3, Type: pb.MsgHup},
  3392. }...)
  3393. // check whether the term values are expected
  3394. // n2.Term == 3
  3395. // n3.Term == 3
  3396. sm := nt.peers[2].(*raft)
  3397. if sm.Term != 3 {
  3398. t.Errorf("peer 2 term: %d, want %d", sm.Term, 3)
  3399. }
  3400. sm = nt.peers[3].(*raft)
  3401. if sm.Term != 3 {
  3402. t.Errorf("peer 3 term: %d, want %d", sm.Term, 3)
  3403. }
  3404. // check state
  3405. // n2 == candidate
  3406. // n3 == candidate
  3407. sm = nt.peers[2].(*raft)
  3408. if sm.state != StateCandidate {
  3409. t.Errorf("peer 2 state: %s, want %s", sm.state, StateCandidate)
  3410. }
  3411. sm = nt.peers[3].(*raft)
  3412. if sm.state != StateCandidate {
  3413. t.Errorf("peer 3 state: %s, want %s", sm.state, StateCandidate)
  3414. }
  3415. // node 2 election timeout first
  3416. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  3417. // check whether the term values are expected
  3418. // n2.Term == 4
  3419. // n3.Term == 4
  3420. sm = nt.peers[2].(*raft)
  3421. if sm.Term != 4 {
  3422. t.Errorf("peer 2 term: %d, want %d", sm.Term, 4)
  3423. }
  3424. sm = nt.peers[3].(*raft)
  3425. if sm.Term != 4 {
  3426. t.Errorf("peer 3 term: %d, want %d", sm.Term, 4)
  3427. }
  3428. // check state
  3429. // n2 == leader
  3430. // n3 == follower
  3431. sm = nt.peers[2].(*raft)
  3432. if sm.state != StateLeader {
  3433. t.Errorf("peer 2 state: %s, want %s", sm.state, StateLeader)
  3434. }
  3435. sm = nt.peers[3].(*raft)
  3436. if sm.state != StateFollower {
  3437. t.Errorf("peer 3 state: %s, want %s", sm.state, StateFollower)
  3438. }
  3439. }
  3440. // TestPreVoteWithCheckQuorum ensures that after a node become pre-candidate,
  3441. // it will checkQuorum correctly.
  3442. func TestPreVoteWithCheckQuorum(t *testing.T) {
  3443. n1 := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  3444. n2 := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  3445. n3 := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  3446. n1.becomeFollower(1, None)
  3447. n2.becomeFollower(1, None)
  3448. n3.becomeFollower(1, None)
  3449. n1.preVote = true
  3450. n2.preVote = true
  3451. n3.preVote = true
  3452. n1.checkQuorum = true
  3453. n2.checkQuorum = true
  3454. n3.checkQuorum = true
  3455. nt := newNetwork(n1, n2, n3)
  3456. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  3457. // isolate node 1. node 2 and node 3 have leader info
  3458. nt.isolate(1)
  3459. // check state
  3460. sm := nt.peers[1].(*raft)
  3461. if sm.state != StateLeader {
  3462. t.Fatalf("peer 1 state: %s, want %s", sm.state, StateLeader)
  3463. }
  3464. sm = nt.peers[2].(*raft)
  3465. if sm.state != StateFollower {
  3466. t.Fatalf("peer 2 state: %s, want %s", sm.state, StateFollower)
  3467. }
  3468. sm = nt.peers[3].(*raft)
  3469. if sm.state != StateFollower {
  3470. t.Fatalf("peer 3 state: %s, want %s", sm.state, StateFollower)
  3471. }
  3472. // node 2 will ignore node 3's PreVote
  3473. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  3474. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  3475. // Do we have a leader?
  3476. if n2.state != StateLeader && n3.state != StateFollower {
  3477. t.Errorf("no leader")
  3478. }
  3479. }
  3480. // simulate rolling update a cluster for Pre-Vote. cluster has 3 nodes [n1, n2, n3].
  3481. // n1 is leader with term 2
  3482. // n2 is follower with term 2
  3483. // n3 is partitioned, with term 4 and less log, state is candidate
  3484. func newPreVoteMigrationCluster(t *testing.T) *network {
  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. // We intentionally do not enable PreVote for n3, this is done so in order
  3494. // to simulate a rolling restart process where it's possible to have a mixed
  3495. // version cluster with replicas with PreVote enabled, and replicas without.
  3496. nt := newNetwork(n1, n2, n3)
  3497. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  3498. // Cause a network partition to isolate n3.
  3499. nt.isolate(3)
  3500. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  3501. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  3502. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  3503. // check state
  3504. // n1.state == StateLeader
  3505. // n2.state == StateFollower
  3506. // n3.state == StateCandidate
  3507. if n1.state != StateLeader {
  3508. t.Fatalf("node 1 state: %s, want %s", n1.state, StateLeader)
  3509. }
  3510. if n2.state != StateFollower {
  3511. t.Fatalf("node 2 state: %s, want %s", n2.state, StateFollower)
  3512. }
  3513. if n3.state != StateCandidate {
  3514. t.Fatalf("node 3 state: %s, want %s", n3.state, StateCandidate)
  3515. }
  3516. // check term
  3517. // n1.Term == 2
  3518. // n2.Term == 2
  3519. // n3.Term == 4
  3520. if n1.Term != 2 {
  3521. t.Fatalf("node 1 term: %d, want %d", n1.Term, 2)
  3522. }
  3523. if n2.Term != 2 {
  3524. t.Fatalf("node 2 term: %d, want %d", n2.Term, 2)
  3525. }
  3526. if n3.Term != 4 {
  3527. t.Fatalf("node 3 term: %d, want %d", n3.Term, 4)
  3528. }
  3529. // Enable prevote on n3, then recover the network
  3530. n3.preVote = true
  3531. nt.recover()
  3532. return nt
  3533. }
  3534. func TestPreVoteMigrationCanCompleteElection(t *testing.T) {
  3535. nt := newPreVoteMigrationCluster(t)
  3536. // n1 is leader with term 2
  3537. // n2 is follower with term 2
  3538. // n3 is pre-candidate with term 4, and less log
  3539. n2 := nt.peers[2].(*raft)
  3540. n3 := nt.peers[3].(*raft)
  3541. // simulate leader down
  3542. nt.isolate(1)
  3543. // Call for elections from both n2 and n3.
  3544. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  3545. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  3546. // check state
  3547. // n2.state == Follower
  3548. // n3.state == PreCandidate
  3549. if n2.state != StateFollower {
  3550. t.Errorf("node 2 state: %s, want %s", n2.state, StateFollower)
  3551. }
  3552. if n3.state != StatePreCandidate {
  3553. t.Errorf("node 3 state: %s, want %s", n3.state, StatePreCandidate)
  3554. }
  3555. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  3556. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  3557. // Do we have a leader?
  3558. if n2.state != StateLeader && n3.state != StateFollower {
  3559. t.Errorf("no leader")
  3560. }
  3561. }
  3562. func TestPreVoteMigrationWithFreeStuckPreCandidate(t *testing.T) {
  3563. nt := newPreVoteMigrationCluster(t)
  3564. // n1 is leader with term 2
  3565. // n2 is follower with term 2
  3566. // n3 is pre-candidate with term 4, and less log
  3567. n1 := nt.peers[1].(*raft)
  3568. n2 := nt.peers[2].(*raft)
  3569. n3 := nt.peers[3].(*raft)
  3570. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  3571. if n1.state != StateLeader {
  3572. t.Errorf("node 1 state: %s, want %s", n1.state, StateLeader)
  3573. }
  3574. if n2.state != StateFollower {
  3575. t.Errorf("node 2 state: %s, want %s", n2.state, StateFollower)
  3576. }
  3577. if n3.state != StatePreCandidate {
  3578. t.Errorf("node 3 state: %s, want %s", n3.state, StatePreCandidate)
  3579. }
  3580. // Pre-Vote again for safety
  3581. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  3582. if n1.state != StateLeader {
  3583. t.Errorf("node 1 state: %s, want %s", n1.state, StateLeader)
  3584. }
  3585. if n2.state != StateFollower {
  3586. t.Errorf("node 2 state: %s, want %s", n2.state, StateFollower)
  3587. }
  3588. if n3.state != StatePreCandidate {
  3589. t.Errorf("node 3 state: %s, want %s", n3.state, StatePreCandidate)
  3590. }
  3591. nt.send(pb.Message{From: 1, To: 3, Type: pb.MsgHeartbeat, Term: n1.Term})
  3592. // Disrupt the leader so that the stuck peer is freed
  3593. if n1.state != StateFollower {
  3594. t.Errorf("state = %s, want %s", n1.state, StateFollower)
  3595. }
  3596. if n3.Term != n1.Term {
  3597. t.Errorf("term = %d, want %d", n3.Term, n1.Term)
  3598. }
  3599. }
  3600. func entsWithConfig(configFunc func(*Config), terms ...uint64) *raft {
  3601. storage := NewMemoryStorage()
  3602. for i, term := range terms {
  3603. storage.Append([]pb.Entry{{Index: uint64(i + 1), Term: term}})
  3604. }
  3605. cfg := newTestConfig(1, []uint64{}, 5, 1, storage)
  3606. if configFunc != nil {
  3607. configFunc(cfg)
  3608. }
  3609. sm := newRaft(cfg)
  3610. sm.reset(terms[len(terms)-1])
  3611. return sm
  3612. }
  3613. // votedWithConfig creates a raft state machine with Vote and Term set
  3614. // to the given value but no log entries (indicating that it voted in
  3615. // the given term but has not received any logs).
  3616. func votedWithConfig(configFunc func(*Config), vote, term uint64) *raft {
  3617. storage := NewMemoryStorage()
  3618. storage.SetHardState(pb.HardState{Vote: vote, Term: term})
  3619. cfg := newTestConfig(1, []uint64{}, 5, 1, storage)
  3620. if configFunc != nil {
  3621. configFunc(cfg)
  3622. }
  3623. sm := newRaft(cfg)
  3624. sm.reset(term)
  3625. return sm
  3626. }
  3627. type network struct {
  3628. peers map[uint64]stateMachine
  3629. storage map[uint64]*MemoryStorage
  3630. dropm map[connem]float64
  3631. ignorem map[pb.MessageType]bool
  3632. // msgHook is called for each message sent. It may inspect the
  3633. // message and return true to send it or false to drop it.
  3634. msgHook func(pb.Message) bool
  3635. }
  3636. // newNetwork initializes a network from peers.
  3637. // A nil node will be replaced with a new *stateMachine.
  3638. // A *stateMachine will get its k, id.
  3639. // When using stateMachine, the address list is always [1, n].
  3640. func newNetwork(peers ...stateMachine) *network {
  3641. return newNetworkWithConfig(nil, peers...)
  3642. }
  3643. // newNetworkWithConfig is like newNetwork but calls the given func to
  3644. // modify the configuration of any state machines it creates.
  3645. func newNetworkWithConfig(configFunc func(*Config), peers ...stateMachine) *network {
  3646. size := len(peers)
  3647. peerAddrs := idsBySize(size)
  3648. npeers := make(map[uint64]stateMachine, size)
  3649. nstorage := make(map[uint64]*MemoryStorage, size)
  3650. for j, p := range peers {
  3651. id := peerAddrs[j]
  3652. switch v := p.(type) {
  3653. case nil:
  3654. nstorage[id] = NewMemoryStorage()
  3655. cfg := newTestConfig(id, peerAddrs, 10, 1, nstorage[id])
  3656. if configFunc != nil {
  3657. configFunc(cfg)
  3658. }
  3659. sm := newRaft(cfg)
  3660. npeers[id] = sm
  3661. case *raft:
  3662. learners := make(map[uint64]bool, len(v.learnerPrs))
  3663. for i := range v.learnerPrs {
  3664. learners[i] = true
  3665. }
  3666. v.id = id
  3667. v.prs = make(map[uint64]*Progress)
  3668. v.learnerPrs = make(map[uint64]*Progress)
  3669. for i := 0; i < size; i++ {
  3670. if _, ok := learners[peerAddrs[i]]; ok {
  3671. v.learnerPrs[peerAddrs[i]] = &Progress{IsLearner: true}
  3672. } else {
  3673. v.prs[peerAddrs[i]] = &Progress{}
  3674. }
  3675. }
  3676. v.reset(v.Term)
  3677. npeers[id] = v
  3678. case *blackHole:
  3679. npeers[id] = v
  3680. default:
  3681. panic(fmt.Sprintf("unexpected state machine type: %T", p))
  3682. }
  3683. }
  3684. return &network{
  3685. peers: npeers,
  3686. storage: nstorage,
  3687. dropm: make(map[connem]float64),
  3688. ignorem: make(map[pb.MessageType]bool),
  3689. }
  3690. }
  3691. func preVoteConfig(c *Config) {
  3692. c.PreVote = true
  3693. }
  3694. func (nw *network) send(msgs ...pb.Message) {
  3695. for len(msgs) > 0 {
  3696. m := msgs[0]
  3697. p := nw.peers[m.To]
  3698. p.Step(m)
  3699. msgs = append(msgs[1:], nw.filter(p.readMessages())...)
  3700. }
  3701. }
  3702. func (nw *network) drop(from, to uint64, perc float64) {
  3703. nw.dropm[connem{from, to}] = perc
  3704. }
  3705. func (nw *network) cut(one, other uint64) {
  3706. nw.drop(one, other, 2.0) // always drop
  3707. nw.drop(other, one, 2.0) // always drop
  3708. }
  3709. func (nw *network) isolate(id uint64) {
  3710. for i := 0; i < len(nw.peers); i++ {
  3711. nid := uint64(i) + 1
  3712. if nid != id {
  3713. nw.drop(id, nid, 1.0) // always drop
  3714. nw.drop(nid, id, 1.0) // always drop
  3715. }
  3716. }
  3717. }
  3718. func (nw *network) ignore(t pb.MessageType) {
  3719. nw.ignorem[t] = true
  3720. }
  3721. func (nw *network) recover() {
  3722. nw.dropm = make(map[connem]float64)
  3723. nw.ignorem = make(map[pb.MessageType]bool)
  3724. }
  3725. func (nw *network) filter(msgs []pb.Message) []pb.Message {
  3726. mm := []pb.Message{}
  3727. for _, m := range msgs {
  3728. if nw.ignorem[m.Type] {
  3729. continue
  3730. }
  3731. switch m.Type {
  3732. case pb.MsgHup:
  3733. // hups never go over the network, so don't drop them but panic
  3734. panic("unexpected msgHup")
  3735. default:
  3736. perc := nw.dropm[connem{m.From, m.To}]
  3737. if n := rand.Float64(); n < perc {
  3738. continue
  3739. }
  3740. }
  3741. if nw.msgHook != nil {
  3742. if !nw.msgHook(m) {
  3743. continue
  3744. }
  3745. }
  3746. mm = append(mm, m)
  3747. }
  3748. return mm
  3749. }
  3750. type connem struct {
  3751. from, to uint64
  3752. }
  3753. type blackHole struct{}
  3754. func (blackHole) Step(pb.Message) error { return nil }
  3755. func (blackHole) readMessages() []pb.Message { return nil }
  3756. var nopStepper = &blackHole{}
  3757. func idsBySize(size int) []uint64 {
  3758. ids := make([]uint64, size)
  3759. for i := 0; i < size; i++ {
  3760. ids[i] = 1 + uint64(i)
  3761. }
  3762. return ids
  3763. }
  3764. // setRandomizedElectionTimeout set up the value by caller instead of choosing
  3765. // by system, in some test scenario we need to fill in some expected value to
  3766. // ensure the certainty
  3767. func setRandomizedElectionTimeout(r *raft, v int) {
  3768. r.randomizedElectionTimeout = v
  3769. }
  3770. func newTestConfig(id uint64, peers []uint64, election, heartbeat int, storage Storage) *Config {
  3771. return &Config{
  3772. ID: id,
  3773. peers: peers,
  3774. ElectionTick: election,
  3775. HeartbeatTick: heartbeat,
  3776. Storage: storage,
  3777. MaxSizePerMsg: noLimit,
  3778. MaxInflightMsgs: 256,
  3779. }
  3780. }
  3781. func newTestRaft(id uint64, peers []uint64, election, heartbeat int, storage Storage) *raft {
  3782. return newRaft(newTestConfig(id, peers, election, heartbeat, storage))
  3783. }
  3784. func newTestLearnerRaft(id uint64, peers []uint64, learners []uint64, election, heartbeat int, storage Storage) *raft {
  3785. cfg := newTestConfig(id, peers, election, heartbeat, storage)
  3786. cfg.learners = learners
  3787. return newRaft(cfg)
  3788. }