raft_test.go 125 KB

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