raft_test.go 125 KB

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