raft_test.go 130 KB

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