raft_test.go 119 KB

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