raft_test.go 119 KB

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