raft_test.go 113 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962
  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. func TestReadOnlyOptionSafe(t *testing.T) {
  1735. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1736. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1737. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1738. nt := newNetwork(a, b, c)
  1739. setRandomizedElectionTimeout(b, b.electionTimeout+1)
  1740. for i := 0; i < b.electionTimeout; i++ {
  1741. b.tick()
  1742. }
  1743. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1744. if a.state != StateLeader {
  1745. t.Fatalf("state = %s, want %s", a.state, StateLeader)
  1746. }
  1747. tests := []struct {
  1748. sm *raft
  1749. proposals int
  1750. wri uint64
  1751. wctx []byte
  1752. }{
  1753. {a, 10, 11, []byte("ctx1")},
  1754. {b, 10, 21, []byte("ctx2")},
  1755. {c, 10, 31, []byte("ctx3")},
  1756. {a, 10, 41, []byte("ctx4")},
  1757. {b, 10, 51, []byte("ctx5")},
  1758. {c, 10, 61, []byte("ctx6")},
  1759. }
  1760. for i, tt := range tests {
  1761. for j := 0; j < tt.proposals; j++ {
  1762. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  1763. }
  1764. nt.send(pb.Message{From: tt.sm.id, To: tt.sm.id, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: tt.wctx}}})
  1765. r := tt.sm
  1766. if len(r.readStates) == 0 {
  1767. t.Errorf("#%d: len(readStates) = 0, want non-zero", i)
  1768. }
  1769. rs := r.readStates[0]
  1770. if rs.Index != tt.wri {
  1771. t.Errorf("#%d: readIndex = %d, want %d", i, rs.Index, tt.wri)
  1772. }
  1773. if !bytes.Equal(rs.RequestCtx, tt.wctx) {
  1774. t.Errorf("#%d: requestCtx = %v, want %v", i, rs.RequestCtx, tt.wctx)
  1775. }
  1776. r.readStates = nil
  1777. }
  1778. }
  1779. func TestReadOnlyOptionLease(t *testing.T) {
  1780. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1781. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1782. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1783. a.readOnly.option = ReadOnlyLeaseBased
  1784. b.readOnly.option = ReadOnlyLeaseBased
  1785. c.readOnly.option = ReadOnlyLeaseBased
  1786. a.checkQuorum = true
  1787. b.checkQuorum = true
  1788. c.checkQuorum = true
  1789. nt := newNetwork(a, b, c)
  1790. setRandomizedElectionTimeout(b, b.electionTimeout+1)
  1791. for i := 0; i < b.electionTimeout; i++ {
  1792. b.tick()
  1793. }
  1794. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1795. if a.state != StateLeader {
  1796. t.Fatalf("state = %s, want %s", a.state, StateLeader)
  1797. }
  1798. tests := []struct {
  1799. sm *raft
  1800. proposals int
  1801. wri uint64
  1802. wctx []byte
  1803. }{
  1804. {a, 10, 11, []byte("ctx1")},
  1805. {b, 10, 21, []byte("ctx2")},
  1806. {c, 10, 31, []byte("ctx3")},
  1807. {a, 10, 41, []byte("ctx4")},
  1808. {b, 10, 51, []byte("ctx5")},
  1809. {c, 10, 61, []byte("ctx6")},
  1810. }
  1811. for i, tt := range tests {
  1812. for j := 0; j < tt.proposals; j++ {
  1813. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  1814. }
  1815. nt.send(pb.Message{From: tt.sm.id, To: tt.sm.id, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: tt.wctx}}})
  1816. r := tt.sm
  1817. rs := r.readStates[0]
  1818. if rs.Index != tt.wri {
  1819. t.Errorf("#%d: readIndex = %d, want %d", i, rs.Index, tt.wri)
  1820. }
  1821. if !bytes.Equal(rs.RequestCtx, tt.wctx) {
  1822. t.Errorf("#%d: requestCtx = %v, want %v", i, rs.RequestCtx, tt.wctx)
  1823. }
  1824. r.readStates = nil
  1825. }
  1826. }
  1827. // TestReadOnlyForNewLeader ensures that a leader only accepts MsgReadIndex message
  1828. // when it commits at least one log entry at it term.
  1829. func TestReadOnlyForNewLeader(t *testing.T) {
  1830. nodeConfigs := []struct {
  1831. id uint64
  1832. committed uint64
  1833. applied uint64
  1834. compact_index uint64
  1835. }{
  1836. {1, 1, 1, 0},
  1837. {2, 2, 2, 2},
  1838. {3, 2, 2, 2},
  1839. }
  1840. peers := make([]stateMachine, 0)
  1841. for _, c := range nodeConfigs {
  1842. storage := NewMemoryStorage()
  1843. storage.Append([]pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}})
  1844. storage.SetHardState(pb.HardState{Term: 1, Commit: c.committed})
  1845. if c.compact_index != 0 {
  1846. storage.Compact(c.compact_index)
  1847. }
  1848. cfg := newTestConfig(c.id, []uint64{1, 2, 3}, 10, 1, storage)
  1849. cfg.Applied = c.applied
  1850. raft := newRaft(cfg)
  1851. peers = append(peers, raft)
  1852. }
  1853. nt := newNetwork(peers...)
  1854. // Drop MsgApp to forbid peer a to commit any log entry at its term after it becomes leader.
  1855. nt.ignore(pb.MsgApp)
  1856. // Force peer a to become leader.
  1857. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1858. sm := nt.peers[1].(*raft)
  1859. if sm.state != StateLeader {
  1860. t.Fatalf("state = %s, want %s", sm.state, StateLeader)
  1861. }
  1862. // Ensure peer a drops read only request.
  1863. var windex uint64 = 4
  1864. wctx := []byte("ctx")
  1865. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: wctx}}})
  1866. if len(sm.readStates) != 0 {
  1867. t.Fatalf("len(readStates) = %d, want zero", len(sm.readStates))
  1868. }
  1869. nt.recover()
  1870. // Force peer a to commit a log entry at its term
  1871. for i := 0; i < sm.heartbeatTimeout; i++ {
  1872. sm.tick()
  1873. }
  1874. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  1875. if sm.raftLog.committed != 4 {
  1876. t.Fatalf("committed = %d, want 4", sm.raftLog.committed)
  1877. }
  1878. lastLogTerm := sm.raftLog.zeroTermOnErrCompacted(sm.raftLog.term(sm.raftLog.committed))
  1879. if lastLogTerm != sm.Term {
  1880. t.Fatalf("last log term = %d, want %d", lastLogTerm, sm.Term)
  1881. }
  1882. // Ensure peer a accepts read only request after it commits a entry at its term.
  1883. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: wctx}}})
  1884. if len(sm.readStates) != 1 {
  1885. t.Fatalf("len(readStates) = %d, want 1", len(sm.readStates))
  1886. }
  1887. rs := sm.readStates[0]
  1888. if rs.Index != windex {
  1889. t.Fatalf("readIndex = %d, want %d", rs.Index, windex)
  1890. }
  1891. if !bytes.Equal(rs.RequestCtx, wctx) {
  1892. t.Fatalf("requestCtx = %v, want %v", rs.RequestCtx, wctx)
  1893. }
  1894. }
  1895. func TestLeaderAppResp(t *testing.T) {
  1896. // initial progress: match = 0; next = 3
  1897. tests := []struct {
  1898. index uint64
  1899. reject bool
  1900. // progress
  1901. wmatch uint64
  1902. wnext uint64
  1903. // message
  1904. wmsgNum int
  1905. windex uint64
  1906. wcommitted uint64
  1907. }{
  1908. {3, true, 0, 3, 0, 0, 0}, // stale resp; no replies
  1909. {2, true, 0, 2, 1, 1, 0}, // denied resp; leader does not commit; decrease next and send probing msg
  1910. {2, false, 2, 4, 2, 2, 2}, // accept resp; leader commits; broadcast with commit index
  1911. {0, false, 0, 3, 0, 0, 0}, // ignore heartbeat replies
  1912. }
  1913. for i, tt := range tests {
  1914. // sm term is 1 after it becomes the leader.
  1915. // thus the last log term must be 1 to be committed.
  1916. sm := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1917. sm.raftLog = &raftLog{
  1918. storage: &MemoryStorage{ents: []pb.Entry{{}, {Index: 1, Term: 0}, {Index: 2, Term: 1}}},
  1919. unstable: unstable{offset: 3},
  1920. }
  1921. sm.becomeCandidate()
  1922. sm.becomeLeader()
  1923. sm.readMessages()
  1924. sm.Step(pb.Message{From: 2, Type: pb.MsgAppResp, Index: tt.index, Term: sm.Term, Reject: tt.reject, RejectHint: tt.index})
  1925. p := sm.prs[2]
  1926. if p.Match != tt.wmatch {
  1927. t.Errorf("#%d match = %d, want %d", i, p.Match, tt.wmatch)
  1928. }
  1929. if p.Next != tt.wnext {
  1930. t.Errorf("#%d next = %d, want %d", i, p.Next, tt.wnext)
  1931. }
  1932. msgs := sm.readMessages()
  1933. if len(msgs) != tt.wmsgNum {
  1934. t.Errorf("#%d msgNum = %d, want %d", i, len(msgs), tt.wmsgNum)
  1935. }
  1936. for j, msg := range msgs {
  1937. if msg.Index != tt.windex {
  1938. t.Errorf("#%d.%d index = %d, want %d", i, j, msg.Index, tt.windex)
  1939. }
  1940. if msg.Commit != tt.wcommitted {
  1941. t.Errorf("#%d.%d commit = %d, want %d", i, j, msg.Commit, tt.wcommitted)
  1942. }
  1943. }
  1944. }
  1945. }
  1946. // When the leader receives a heartbeat tick, it should
  1947. // send a MsgApp with m.Index = 0, m.LogTerm=0 and empty entries.
  1948. func TestBcastBeat(t *testing.T) {
  1949. offset := uint64(1000)
  1950. // make a state machine with log.offset = 1000
  1951. s := pb.Snapshot{
  1952. Metadata: pb.SnapshotMetadata{
  1953. Index: offset,
  1954. Term: 1,
  1955. ConfState: pb.ConfState{Nodes: []uint64{1, 2, 3}},
  1956. },
  1957. }
  1958. storage := NewMemoryStorage()
  1959. storage.ApplySnapshot(s)
  1960. sm := newTestRaft(1, nil, 10, 1, storage)
  1961. sm.Term = 1
  1962. sm.becomeCandidate()
  1963. sm.becomeLeader()
  1964. for i := 0; i < 10; i++ {
  1965. sm.appendEntry(pb.Entry{Index: uint64(i) + 1})
  1966. }
  1967. // slow follower
  1968. sm.prs[2].Match, sm.prs[2].Next = 5, 6
  1969. // normal follower
  1970. sm.prs[3].Match, sm.prs[3].Next = sm.raftLog.lastIndex(), sm.raftLog.lastIndex()+1
  1971. sm.Step(pb.Message{Type: pb.MsgBeat})
  1972. msgs := sm.readMessages()
  1973. if len(msgs) != 2 {
  1974. t.Fatalf("len(msgs) = %v, want 2", len(msgs))
  1975. }
  1976. wantCommitMap := map[uint64]uint64{
  1977. 2: min(sm.raftLog.committed, sm.prs[2].Match),
  1978. 3: min(sm.raftLog.committed, sm.prs[3].Match),
  1979. }
  1980. for i, m := range msgs {
  1981. if m.Type != pb.MsgHeartbeat {
  1982. t.Fatalf("#%d: type = %v, want = %v", i, m.Type, pb.MsgHeartbeat)
  1983. }
  1984. if m.Index != 0 {
  1985. t.Fatalf("#%d: prevIndex = %d, want %d", i, m.Index, 0)
  1986. }
  1987. if m.LogTerm != 0 {
  1988. t.Fatalf("#%d: prevTerm = %d, want %d", i, m.LogTerm, 0)
  1989. }
  1990. if wantCommitMap[m.To] == 0 {
  1991. t.Fatalf("#%d: unexpected to %d", i, m.To)
  1992. } else {
  1993. if m.Commit != wantCommitMap[m.To] {
  1994. t.Fatalf("#%d: commit = %d, want %d", i, m.Commit, wantCommitMap[m.To])
  1995. }
  1996. delete(wantCommitMap, m.To)
  1997. }
  1998. if len(m.Entries) != 0 {
  1999. t.Fatalf("#%d: len(entries) = %d, want 0", i, len(m.Entries))
  2000. }
  2001. }
  2002. }
  2003. // tests the output of the state machine when receiving MsgBeat
  2004. func TestRecvMsgBeat(t *testing.T) {
  2005. tests := []struct {
  2006. state StateType
  2007. wMsg int
  2008. }{
  2009. {StateLeader, 2},
  2010. // candidate and follower should ignore MsgBeat
  2011. {StateCandidate, 0},
  2012. {StateFollower, 0},
  2013. }
  2014. for i, tt := range tests {
  2015. sm := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  2016. sm.raftLog = &raftLog{storage: &MemoryStorage{ents: []pb.Entry{{}, {Index: 1, Term: 0}, {Index: 2, Term: 1}}}}
  2017. sm.Term = 1
  2018. sm.state = tt.state
  2019. switch tt.state {
  2020. case StateFollower:
  2021. sm.step = stepFollower
  2022. case StateCandidate:
  2023. sm.step = stepCandidate
  2024. case StateLeader:
  2025. sm.step = stepLeader
  2026. }
  2027. sm.Step(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  2028. msgs := sm.readMessages()
  2029. if len(msgs) != tt.wMsg {
  2030. t.Errorf("%d: len(msgs) = %d, want %d", i, len(msgs), tt.wMsg)
  2031. }
  2032. for _, m := range msgs {
  2033. if m.Type != pb.MsgHeartbeat {
  2034. t.Errorf("%d: msg.type = %v, want %v", i, m.Type, pb.MsgHeartbeat)
  2035. }
  2036. }
  2037. }
  2038. }
  2039. func TestLeaderIncreaseNext(t *testing.T) {
  2040. previousEnts := []pb.Entry{{Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3}}
  2041. tests := []struct {
  2042. // progress
  2043. state ProgressStateType
  2044. next uint64
  2045. wnext uint64
  2046. }{
  2047. // state replicate, optimistically increase next
  2048. // previous entries + noop entry + propose + 1
  2049. {ProgressStateReplicate, 2, uint64(len(previousEnts) + 1 + 1 + 1)},
  2050. // state probe, not optimistically increase next
  2051. {ProgressStateProbe, 2, 2},
  2052. }
  2053. for i, tt := range tests {
  2054. sm := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2055. sm.raftLog.append(previousEnts...)
  2056. sm.becomeCandidate()
  2057. sm.becomeLeader()
  2058. sm.prs[2].State = tt.state
  2059. sm.prs[2].Next = tt.next
  2060. sm.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  2061. p := sm.prs[2]
  2062. if p.Next != tt.wnext {
  2063. t.Errorf("#%d next = %d, want %d", i, p.Next, tt.wnext)
  2064. }
  2065. }
  2066. }
  2067. func TestSendAppendForProgressProbe(t *testing.T) {
  2068. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2069. r.becomeCandidate()
  2070. r.becomeLeader()
  2071. r.readMessages()
  2072. r.prs[2].becomeProbe()
  2073. // each round is a heartbeat
  2074. for i := 0; i < 3; i++ {
  2075. if i == 0 {
  2076. // we expect that raft will only send out one msgAPP on the first
  2077. // loop. After that, the follower is paused until a heartbeat response is
  2078. // received.
  2079. r.appendEntry(pb.Entry{Data: []byte("somedata")})
  2080. r.sendAppend(2)
  2081. msg := r.readMessages()
  2082. if len(msg) != 1 {
  2083. t.Errorf("len(msg) = %d, want %d", len(msg), 1)
  2084. }
  2085. if msg[0].Index != 0 {
  2086. t.Errorf("index = %d, want %d", msg[0].Index, 0)
  2087. }
  2088. }
  2089. if !r.prs[2].Paused {
  2090. t.Errorf("paused = %v, want true", r.prs[2].Paused)
  2091. }
  2092. for j := 0; j < 10; j++ {
  2093. r.appendEntry(pb.Entry{Data: []byte("somedata")})
  2094. r.sendAppend(2)
  2095. if l := len(r.readMessages()); l != 0 {
  2096. t.Errorf("len(msg) = %d, want %d", l, 0)
  2097. }
  2098. }
  2099. // do a heartbeat
  2100. for j := 0; j < r.heartbeatTimeout; j++ {
  2101. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  2102. }
  2103. if !r.prs[2].Paused {
  2104. t.Errorf("paused = %v, want true", r.prs[2].Paused)
  2105. }
  2106. // consume the heartbeat
  2107. msg := r.readMessages()
  2108. if len(msg) != 1 {
  2109. t.Errorf("len(msg) = %d, want %d", len(msg), 1)
  2110. }
  2111. if msg[0].Type != pb.MsgHeartbeat {
  2112. t.Errorf("type = %v, want %v", msg[0].Type, pb.MsgHeartbeat)
  2113. }
  2114. }
  2115. // a heartbeat response will allow another message to be sent
  2116. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgHeartbeatResp})
  2117. msg := r.readMessages()
  2118. if len(msg) != 1 {
  2119. t.Errorf("len(msg) = %d, want %d", len(msg), 1)
  2120. }
  2121. if msg[0].Index != 0 {
  2122. t.Errorf("index = %d, want %d", msg[0].Index, 0)
  2123. }
  2124. if !r.prs[2].Paused {
  2125. t.Errorf("paused = %v, want true", r.prs[2].Paused)
  2126. }
  2127. }
  2128. func TestSendAppendForProgressReplicate(t *testing.T) {
  2129. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2130. r.becomeCandidate()
  2131. r.becomeLeader()
  2132. r.readMessages()
  2133. r.prs[2].becomeReplicate()
  2134. for i := 0; i < 10; i++ {
  2135. r.appendEntry(pb.Entry{Data: []byte("somedata")})
  2136. r.sendAppend(2)
  2137. msgs := r.readMessages()
  2138. if len(msgs) != 1 {
  2139. t.Errorf("len(msg) = %d, want %d", len(msgs), 1)
  2140. }
  2141. }
  2142. }
  2143. func TestSendAppendForProgressSnapshot(t *testing.T) {
  2144. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2145. r.becomeCandidate()
  2146. r.becomeLeader()
  2147. r.readMessages()
  2148. r.prs[2].becomeSnapshot(10)
  2149. for i := 0; i < 10; i++ {
  2150. r.appendEntry(pb.Entry{Data: []byte("somedata")})
  2151. r.sendAppend(2)
  2152. msgs := r.readMessages()
  2153. if len(msgs) != 0 {
  2154. t.Errorf("len(msg) = %d, want %d", len(msgs), 0)
  2155. }
  2156. }
  2157. }
  2158. func TestRecvMsgUnreachable(t *testing.T) {
  2159. previousEnts := []pb.Entry{{Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3}}
  2160. s := NewMemoryStorage()
  2161. s.Append(previousEnts)
  2162. r := newTestRaft(1, []uint64{1, 2}, 10, 1, s)
  2163. r.becomeCandidate()
  2164. r.becomeLeader()
  2165. r.readMessages()
  2166. // set node 2 to state replicate
  2167. r.prs[2].Match = 3
  2168. r.prs[2].becomeReplicate()
  2169. r.prs[2].optimisticUpdate(5)
  2170. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgUnreachable})
  2171. if r.prs[2].State != ProgressStateProbe {
  2172. t.Errorf("state = %s, want %s", r.prs[2].State, ProgressStateProbe)
  2173. }
  2174. if wnext := r.prs[2].Match + 1; r.prs[2].Next != wnext {
  2175. t.Errorf("next = %d, want %d", r.prs[2].Next, wnext)
  2176. }
  2177. }
  2178. func TestRestore(t *testing.T) {
  2179. s := pb.Snapshot{
  2180. Metadata: pb.SnapshotMetadata{
  2181. Index: 11, // magic number
  2182. Term: 11, // magic number
  2183. ConfState: pb.ConfState{Nodes: []uint64{1, 2, 3}},
  2184. },
  2185. }
  2186. storage := NewMemoryStorage()
  2187. sm := newTestRaft(1, []uint64{1, 2}, 10, 1, storage)
  2188. if ok := sm.restore(s); !ok {
  2189. t.Fatal("restore fail, want succeed")
  2190. }
  2191. if sm.raftLog.lastIndex() != s.Metadata.Index {
  2192. t.Errorf("log.lastIndex = %d, want %d", sm.raftLog.lastIndex(), s.Metadata.Index)
  2193. }
  2194. if mustTerm(sm.raftLog.term(s.Metadata.Index)) != s.Metadata.Term {
  2195. t.Errorf("log.lastTerm = %d, want %d", mustTerm(sm.raftLog.term(s.Metadata.Index)), s.Metadata.Term)
  2196. }
  2197. sg := sm.nodes()
  2198. if !reflect.DeepEqual(sg, s.Metadata.ConfState.Nodes) {
  2199. t.Errorf("sm.Nodes = %+v, want %+v", sg, s.Metadata.ConfState.Nodes)
  2200. }
  2201. if ok := sm.restore(s); ok {
  2202. t.Fatal("restore succeed, want fail")
  2203. }
  2204. }
  2205. // TestRestoreWithLearner restores a snapshot which contains learners.
  2206. func TestRestoreWithLearner(t *testing.T) {
  2207. s := pb.Snapshot{
  2208. Metadata: pb.SnapshotMetadata{
  2209. Index: 11, // magic number
  2210. Term: 11, // magic number
  2211. ConfState: pb.ConfState{Nodes: []uint64{1, 2}, Learners: []uint64{3}},
  2212. },
  2213. }
  2214. storage := NewMemoryStorage()
  2215. sm := newTestLearnerRaft(3, []uint64{1, 2}, []uint64{3}, 10, 1, storage)
  2216. if ok := sm.restore(s); !ok {
  2217. t.Error("restore fail, want succeed")
  2218. }
  2219. if sm.raftLog.lastIndex() != s.Metadata.Index {
  2220. t.Errorf("log.lastIndex = %d, want %d", sm.raftLog.lastIndex(), s.Metadata.Index)
  2221. }
  2222. if mustTerm(sm.raftLog.term(s.Metadata.Index)) != s.Metadata.Term {
  2223. t.Errorf("log.lastTerm = %d, want %d", mustTerm(sm.raftLog.term(s.Metadata.Index)), s.Metadata.Term)
  2224. }
  2225. sg := sm.nodes()
  2226. if len(sg) != len(s.Metadata.ConfState.Nodes) {
  2227. t.Errorf("sm.Nodes = %+v, length not equal with %+v", sg, s.Metadata.ConfState.Nodes)
  2228. }
  2229. lns := sm.learnerNodes()
  2230. if len(lns) != len(s.Metadata.ConfState.Learners) {
  2231. t.Errorf("sm.LearnerNodes = %+v, length not equal with %+v", sg, s.Metadata.ConfState.Learners)
  2232. }
  2233. for _, n := range s.Metadata.ConfState.Nodes {
  2234. if sm.prs[n].IsLearner {
  2235. t.Errorf("sm.Node %x isLearner = %s, want %t", n, sm.prs[n], false)
  2236. }
  2237. }
  2238. for _, n := range s.Metadata.ConfState.Learners {
  2239. if !sm.learnerPrs[n].IsLearner {
  2240. t.Errorf("sm.Node %x isLearner = %s, want %t", n, sm.prs[n], true)
  2241. }
  2242. }
  2243. if ok := sm.restore(s); ok {
  2244. t.Error("restore succeed, want fail")
  2245. }
  2246. }
  2247. // TestRestoreInvalidLearner verfies that a normal peer can't become learner again
  2248. // when restores snapshot.
  2249. func TestRestoreInvalidLearner(t *testing.T) {
  2250. s := pb.Snapshot{
  2251. Metadata: pb.SnapshotMetadata{
  2252. Index: 11, // magic number
  2253. Term: 11, // magic number
  2254. ConfState: pb.ConfState{Nodes: []uint64{1, 2}, Learners: []uint64{3}},
  2255. },
  2256. }
  2257. storage := NewMemoryStorage()
  2258. sm := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, storage)
  2259. if sm.isLearner {
  2260. t.Errorf("%x is learner, want not", sm.id)
  2261. }
  2262. if ok := sm.restore(s); ok {
  2263. t.Error("restore succeed, want fail")
  2264. }
  2265. }
  2266. // TestRestoreLearnerPromotion checks that a learner can become to a follower after
  2267. // restoring snapshot.
  2268. func TestRestoreLearnerPromotion(t *testing.T) {
  2269. s := pb.Snapshot{
  2270. Metadata: pb.SnapshotMetadata{
  2271. Index: 11, // magic number
  2272. Term: 11, // magic number
  2273. ConfState: pb.ConfState{Nodes: []uint64{1, 2, 3}},
  2274. },
  2275. }
  2276. storage := NewMemoryStorage()
  2277. sm := newTestLearnerRaft(3, []uint64{1, 2}, []uint64{3}, 10, 1, storage)
  2278. if !sm.isLearner {
  2279. t.Errorf("%x is not learner, want yes", sm.id)
  2280. }
  2281. if ok := sm.restore(s); !ok {
  2282. t.Error("restore fail, want succeed")
  2283. }
  2284. if sm.isLearner {
  2285. t.Errorf("%x is learner, want not", sm.id)
  2286. }
  2287. }
  2288. // TestLearnerReceiveSnapshot tests that a learner can receive a snpahost from leader
  2289. func TestLearnerReceiveSnapshot(t *testing.T) {
  2290. // restore the state machine from a snapshot so it has a compacted log and a snapshot
  2291. s := pb.Snapshot{
  2292. Metadata: pb.SnapshotMetadata{
  2293. Index: 11, // magic number
  2294. Term: 11, // magic number
  2295. ConfState: pb.ConfState{Nodes: []uint64{1}, Learners: []uint64{2}},
  2296. },
  2297. }
  2298. n1 := newTestLearnerRaft(1, []uint64{1}, []uint64{2}, 10, 1, NewMemoryStorage())
  2299. n2 := newTestLearnerRaft(2, []uint64{1}, []uint64{2}, 10, 1, NewMemoryStorage())
  2300. n1.restore(s)
  2301. // Force set n1 appplied index.
  2302. n1.raftLog.appliedTo(n1.raftLog.committed)
  2303. nt := newNetwork(n1, n2)
  2304. setRandomizedElectionTimeout(n1, n1.electionTimeout)
  2305. for i := 0; i < n1.electionTimeout; i++ {
  2306. n1.tick()
  2307. }
  2308. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  2309. if n2.raftLog.committed != n1.raftLog.committed {
  2310. t.Errorf("peer 2 must commit to %d, but %d", n1.raftLog.committed, n2.raftLog.committed)
  2311. }
  2312. }
  2313. func TestRestoreIgnoreSnapshot(t *testing.T) {
  2314. previousEnts := []pb.Entry{{Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3}}
  2315. commit := uint64(1)
  2316. storage := NewMemoryStorage()
  2317. sm := newTestRaft(1, []uint64{1, 2}, 10, 1, storage)
  2318. sm.raftLog.append(previousEnts...)
  2319. sm.raftLog.commitTo(commit)
  2320. s := pb.Snapshot{
  2321. Metadata: pb.SnapshotMetadata{
  2322. Index: commit,
  2323. Term: 1,
  2324. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  2325. },
  2326. }
  2327. // ignore snapshot
  2328. if ok := sm.restore(s); ok {
  2329. t.Errorf("restore = %t, want %t", ok, false)
  2330. }
  2331. if sm.raftLog.committed != commit {
  2332. t.Errorf("commit = %d, want %d", sm.raftLog.committed, commit)
  2333. }
  2334. // ignore snapshot and fast forward commit
  2335. s.Metadata.Index = commit + 1
  2336. if ok := sm.restore(s); ok {
  2337. t.Errorf("restore = %t, want %t", ok, false)
  2338. }
  2339. if sm.raftLog.committed != commit+1 {
  2340. t.Errorf("commit = %d, want %d", sm.raftLog.committed, commit+1)
  2341. }
  2342. }
  2343. func TestProvideSnap(t *testing.T) {
  2344. // restore the state machine from a snapshot so it has a compacted log and a snapshot
  2345. s := pb.Snapshot{
  2346. Metadata: pb.SnapshotMetadata{
  2347. Index: 11, // magic number
  2348. Term: 11, // magic number
  2349. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  2350. },
  2351. }
  2352. storage := NewMemoryStorage()
  2353. sm := newTestRaft(1, []uint64{1}, 10, 1, storage)
  2354. sm.restore(s)
  2355. sm.becomeCandidate()
  2356. sm.becomeLeader()
  2357. // force set the next of node 2, so that node 2 needs a snapshot
  2358. sm.prs[2].Next = sm.raftLog.firstIndex()
  2359. sm.Step(pb.Message{From: 2, To: 1, Type: pb.MsgAppResp, Index: sm.prs[2].Next - 1, Reject: true})
  2360. msgs := sm.readMessages()
  2361. if len(msgs) != 1 {
  2362. t.Fatalf("len(msgs) = %d, want 1", len(msgs))
  2363. }
  2364. m := msgs[0]
  2365. if m.Type != pb.MsgSnap {
  2366. t.Errorf("m.Type = %v, want %v", m.Type, pb.MsgSnap)
  2367. }
  2368. }
  2369. func TestIgnoreProvidingSnap(t *testing.T) {
  2370. // restore the state machine from a snapshot so it has a compacted log and a snapshot
  2371. s := pb.Snapshot{
  2372. Metadata: pb.SnapshotMetadata{
  2373. Index: 11, // magic number
  2374. Term: 11, // magic number
  2375. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  2376. },
  2377. }
  2378. storage := NewMemoryStorage()
  2379. sm := newTestRaft(1, []uint64{1}, 10, 1, storage)
  2380. sm.restore(s)
  2381. sm.becomeCandidate()
  2382. sm.becomeLeader()
  2383. // force set the next of node 2, so that node 2 needs a snapshot
  2384. // change node 2 to be inactive, expect node 1 ignore sending snapshot to 2
  2385. sm.prs[2].Next = sm.raftLog.firstIndex() - 1
  2386. sm.prs[2].RecentActive = false
  2387. sm.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  2388. msgs := sm.readMessages()
  2389. if len(msgs) != 0 {
  2390. t.Errorf("len(msgs) = %d, want 0", len(msgs))
  2391. }
  2392. }
  2393. func TestRestoreFromSnapMsg(t *testing.T) {
  2394. s := pb.Snapshot{
  2395. Metadata: pb.SnapshotMetadata{
  2396. Index: 11, // magic number
  2397. Term: 11, // magic number
  2398. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  2399. },
  2400. }
  2401. m := pb.Message{Type: pb.MsgSnap, From: 1, Term: 2, Snapshot: s}
  2402. sm := newTestRaft(2, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2403. sm.Step(m)
  2404. if sm.lead != uint64(1) {
  2405. t.Errorf("sm.lead = %d, want 1", sm.lead)
  2406. }
  2407. // TODO(bdarnell): what should this test?
  2408. }
  2409. func TestSlowNodeRestore(t *testing.T) {
  2410. nt := newNetwork(nil, nil, nil)
  2411. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2412. nt.isolate(3)
  2413. for j := 0; j <= 100; j++ {
  2414. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2415. }
  2416. lead := nt.peers[1].(*raft)
  2417. nextEnts(lead, nt.storage[1])
  2418. nt.storage[1].CreateSnapshot(lead.raftLog.applied, &pb.ConfState{Nodes: lead.nodes()}, nil)
  2419. nt.storage[1].Compact(lead.raftLog.applied)
  2420. nt.recover()
  2421. // send heartbeats so that the leader can learn everyone is active.
  2422. // node 3 will only be considered as active when node 1 receives a reply from it.
  2423. for {
  2424. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  2425. if lead.prs[3].RecentActive {
  2426. break
  2427. }
  2428. }
  2429. // trigger a snapshot
  2430. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2431. follower := nt.peers[3].(*raft)
  2432. // trigger a commit
  2433. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2434. if follower.raftLog.committed != lead.raftLog.committed {
  2435. t.Errorf("follower.committed = %d, want %d", follower.raftLog.committed, lead.raftLog.committed)
  2436. }
  2437. }
  2438. // TestStepConfig tests that when raft step msgProp in EntryConfChange type,
  2439. // it appends the entry to log and sets pendingConf to be true.
  2440. func TestStepConfig(t *testing.T) {
  2441. // a raft that cannot make progress
  2442. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2443. r.becomeCandidate()
  2444. r.becomeLeader()
  2445. index := r.raftLog.lastIndex()
  2446. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange}}})
  2447. if g := r.raftLog.lastIndex(); g != index+1 {
  2448. t.Errorf("index = %d, want %d", g, index+1)
  2449. }
  2450. if r.pendingConfIndex != index+1 {
  2451. t.Errorf("pendingConfIndex = %d, want %d", r.pendingConfIndex, index+1)
  2452. }
  2453. }
  2454. // TestStepIgnoreConfig tests that if raft step the second msgProp in
  2455. // EntryConfChange type when the first one is uncommitted, the node will set
  2456. // the proposal to noop and keep its original state.
  2457. func TestStepIgnoreConfig(t *testing.T) {
  2458. // a raft that cannot make progress
  2459. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2460. r.becomeCandidate()
  2461. r.becomeLeader()
  2462. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange}}})
  2463. index := r.raftLog.lastIndex()
  2464. pendingConfIndex := r.pendingConfIndex
  2465. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange}}})
  2466. wents := []pb.Entry{{Type: pb.EntryNormal, Term: 1, Index: 3, Data: nil}}
  2467. ents, err := r.raftLog.entries(index+1, noLimit)
  2468. if err != nil {
  2469. t.Fatalf("unexpected error %v", err)
  2470. }
  2471. if !reflect.DeepEqual(ents, wents) {
  2472. t.Errorf("ents = %+v, want %+v", ents, wents)
  2473. }
  2474. if r.pendingConfIndex != pendingConfIndex {
  2475. t.Errorf("pendingConfIndex = %d, want %d", r.pendingConfIndex, pendingConfIndex)
  2476. }
  2477. }
  2478. // TestNewLeaderPendingConfig tests that new leader sets its pendingConfigIndex
  2479. // based on uncommitted entries.
  2480. func TestNewLeaderPendingConfig(t *testing.T) {
  2481. tests := []struct {
  2482. addEntry bool
  2483. wpendingIndex uint64
  2484. }{
  2485. {false, 0},
  2486. {true, 1},
  2487. }
  2488. for i, tt := range tests {
  2489. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2490. if tt.addEntry {
  2491. r.appendEntry(pb.Entry{Type: pb.EntryNormal})
  2492. }
  2493. r.becomeCandidate()
  2494. r.becomeLeader()
  2495. if r.pendingConfIndex != tt.wpendingIndex {
  2496. t.Errorf("#%d: pendingConfIndex = %d, want %d",
  2497. i, r.pendingConfIndex, tt.wpendingIndex)
  2498. }
  2499. }
  2500. }
  2501. // TestAddNode tests that addNode could update nodes correctly.
  2502. func TestAddNode(t *testing.T) {
  2503. r := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  2504. r.addNode(2)
  2505. nodes := r.nodes()
  2506. wnodes := []uint64{1, 2}
  2507. if !reflect.DeepEqual(nodes, wnodes) {
  2508. t.Errorf("nodes = %v, want %v", nodes, wnodes)
  2509. }
  2510. }
  2511. // TestAddLearner tests that addLearner could update nodes correctly.
  2512. func TestAddLearner(t *testing.T) {
  2513. r := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  2514. r.addLearner(2)
  2515. nodes := r.learnerNodes()
  2516. wnodes := []uint64{2}
  2517. if !reflect.DeepEqual(nodes, wnodes) {
  2518. t.Errorf("nodes = %v, want %v", nodes, wnodes)
  2519. }
  2520. if !r.learnerPrs[2].IsLearner {
  2521. t.Errorf("node 2 is learner %t, want %t", r.prs[2].IsLearner, true)
  2522. }
  2523. }
  2524. // TestAddNodeCheckQuorum tests that addNode does not trigger a leader election
  2525. // immediately when checkQuorum is set.
  2526. func TestAddNodeCheckQuorum(t *testing.T) {
  2527. r := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  2528. r.checkQuorum = true
  2529. r.becomeCandidate()
  2530. r.becomeLeader()
  2531. for i := 0; i < r.electionTimeout-1; i++ {
  2532. r.tick()
  2533. }
  2534. r.addNode(2)
  2535. // This tick will reach electionTimeout, which triggers a quorum check.
  2536. r.tick()
  2537. // Node 1 should still be the leader after a single tick.
  2538. if r.state != StateLeader {
  2539. t.Errorf("state = %v, want %v", r.state, StateLeader)
  2540. }
  2541. // After another electionTimeout ticks without hearing from node 2,
  2542. // node 1 should step down.
  2543. for i := 0; i < r.electionTimeout; i++ {
  2544. r.tick()
  2545. }
  2546. if r.state != StateFollower {
  2547. t.Errorf("state = %v, want %v", r.state, StateFollower)
  2548. }
  2549. }
  2550. // TestRemoveNode tests that removeNode could update nodes and
  2551. // and removed list correctly.
  2552. func TestRemoveNode(t *testing.T) {
  2553. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2554. r.removeNode(2)
  2555. w := []uint64{1}
  2556. if g := r.nodes(); !reflect.DeepEqual(g, w) {
  2557. t.Errorf("nodes = %v, want %v", g, w)
  2558. }
  2559. // remove all nodes from cluster
  2560. r.removeNode(1)
  2561. w = []uint64{}
  2562. if g := r.nodes(); !reflect.DeepEqual(g, w) {
  2563. t.Errorf("nodes = %v, want %v", g, w)
  2564. }
  2565. }
  2566. // TestRemoveLearner tests that removeNode could update nodes and
  2567. // and removed list correctly.
  2568. func TestRemoveLearner(t *testing.T) {
  2569. r := newTestLearnerRaft(1, []uint64{1}, []uint64{2}, 10, 1, NewMemoryStorage())
  2570. r.removeNode(2)
  2571. w := []uint64{1}
  2572. if g := r.nodes(); !reflect.DeepEqual(g, w) {
  2573. t.Errorf("nodes = %v, want %v", g, w)
  2574. }
  2575. w = []uint64{}
  2576. if g := r.learnerNodes(); !reflect.DeepEqual(g, w) {
  2577. t.Errorf("nodes = %v, want %v", g, w)
  2578. }
  2579. // remove all nodes from cluster
  2580. r.removeNode(1)
  2581. if g := r.nodes(); !reflect.DeepEqual(g, w) {
  2582. t.Errorf("nodes = %v, want %v", g, w)
  2583. }
  2584. }
  2585. func TestPromotable(t *testing.T) {
  2586. id := uint64(1)
  2587. tests := []struct {
  2588. peers []uint64
  2589. wp bool
  2590. }{
  2591. {[]uint64{1}, true},
  2592. {[]uint64{1, 2, 3}, true},
  2593. {[]uint64{}, false},
  2594. {[]uint64{2, 3}, false},
  2595. }
  2596. for i, tt := range tests {
  2597. r := newTestRaft(id, tt.peers, 5, 1, NewMemoryStorage())
  2598. if g := r.promotable(); g != tt.wp {
  2599. t.Errorf("#%d: promotable = %v, want %v", i, g, tt.wp)
  2600. }
  2601. }
  2602. }
  2603. func TestRaftNodes(t *testing.T) {
  2604. tests := []struct {
  2605. ids []uint64
  2606. wids []uint64
  2607. }{
  2608. {
  2609. []uint64{1, 2, 3},
  2610. []uint64{1, 2, 3},
  2611. },
  2612. {
  2613. []uint64{3, 2, 1},
  2614. []uint64{1, 2, 3},
  2615. },
  2616. }
  2617. for i, tt := range tests {
  2618. r := newTestRaft(1, tt.ids, 10, 1, NewMemoryStorage())
  2619. if !reflect.DeepEqual(r.nodes(), tt.wids) {
  2620. t.Errorf("#%d: nodes = %+v, want %+v", i, r.nodes(), tt.wids)
  2621. }
  2622. }
  2623. }
  2624. func TestCampaignWhileLeader(t *testing.T) {
  2625. testCampaignWhileLeader(t, false)
  2626. }
  2627. func TestPreCampaignWhileLeader(t *testing.T) {
  2628. testCampaignWhileLeader(t, true)
  2629. }
  2630. func testCampaignWhileLeader(t *testing.T, preVote bool) {
  2631. cfg := newTestConfig(1, []uint64{1}, 5, 1, NewMemoryStorage())
  2632. cfg.PreVote = preVote
  2633. r := newRaft(cfg)
  2634. if r.state != StateFollower {
  2635. t.Errorf("expected new node to be follower but got %s", r.state)
  2636. }
  2637. // We don't call campaign() directly because it comes after the check
  2638. // for our current state.
  2639. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2640. if r.state != StateLeader {
  2641. t.Errorf("expected single-node election to become leader but got %s", r.state)
  2642. }
  2643. term := r.Term
  2644. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2645. if r.state != StateLeader {
  2646. t.Errorf("expected to remain leader but got %s", r.state)
  2647. }
  2648. if r.Term != term {
  2649. t.Errorf("expected to remain in term %v but got %v", term, r.Term)
  2650. }
  2651. }
  2652. // TestCommitAfterRemoveNode verifies that pending commands can become
  2653. // committed when a config change reduces the quorum requirements.
  2654. func TestCommitAfterRemoveNode(t *testing.T) {
  2655. // Create a cluster with two nodes.
  2656. s := NewMemoryStorage()
  2657. r := newTestRaft(1, []uint64{1, 2}, 5, 1, s)
  2658. r.becomeCandidate()
  2659. r.becomeLeader()
  2660. // Begin to remove the second node.
  2661. cc := pb.ConfChange{
  2662. Type: pb.ConfChangeRemoveNode,
  2663. NodeID: 2,
  2664. }
  2665. ccData, err := cc.Marshal()
  2666. if err != nil {
  2667. t.Fatal(err)
  2668. }
  2669. r.Step(pb.Message{
  2670. Type: pb.MsgProp,
  2671. Entries: []pb.Entry{
  2672. {Type: pb.EntryConfChange, Data: ccData},
  2673. },
  2674. })
  2675. // Stabilize the log and make sure nothing is committed yet.
  2676. if ents := nextEnts(r, s); len(ents) > 0 {
  2677. t.Fatalf("unexpected committed entries: %v", ents)
  2678. }
  2679. ccIndex := r.raftLog.lastIndex()
  2680. // While the config change is pending, make another proposal.
  2681. r.Step(pb.Message{
  2682. Type: pb.MsgProp,
  2683. Entries: []pb.Entry{
  2684. {Type: pb.EntryNormal, Data: []byte("hello")},
  2685. },
  2686. })
  2687. // Node 2 acknowledges the config change, committing it.
  2688. r.Step(pb.Message{
  2689. Type: pb.MsgAppResp,
  2690. From: 2,
  2691. Index: ccIndex,
  2692. })
  2693. ents := nextEnts(r, s)
  2694. if len(ents) != 2 {
  2695. t.Fatalf("expected two committed entries, got %v", ents)
  2696. }
  2697. if ents[0].Type != pb.EntryNormal || ents[0].Data != nil {
  2698. t.Fatalf("expected ents[0] to be empty, but got %v", ents[0])
  2699. }
  2700. if ents[1].Type != pb.EntryConfChange {
  2701. t.Fatalf("expected ents[1] to be EntryConfChange, got %v", ents[1])
  2702. }
  2703. // Apply the config change. This reduces quorum requirements so the
  2704. // pending command can now commit.
  2705. r.removeNode(2)
  2706. ents = nextEnts(r, s)
  2707. if len(ents) != 1 || ents[0].Type != pb.EntryNormal ||
  2708. string(ents[0].Data) != "hello" {
  2709. t.Fatalf("expected one committed EntryNormal, got %v", ents)
  2710. }
  2711. }
  2712. // TestLeaderTransferToUpToDateNode verifies transferring should succeed
  2713. // if the transferee has the most up-to-date log entries when transfer starts.
  2714. func TestLeaderTransferToUpToDateNode(t *testing.T) {
  2715. nt := newNetwork(nil, nil, nil)
  2716. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2717. lead := nt.peers[1].(*raft)
  2718. if lead.lead != 1 {
  2719. t.Fatalf("after election leader is %x, want 1", lead.lead)
  2720. }
  2721. // Transfer leadership to 2.
  2722. nt.send(pb.Message{From: 2, To: 1, Type: pb.MsgTransferLeader})
  2723. checkLeaderTransferState(t, lead, StateFollower, 2)
  2724. // After some log replication, transfer leadership back to 1.
  2725. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2726. nt.send(pb.Message{From: 1, To: 2, Type: pb.MsgTransferLeader})
  2727. checkLeaderTransferState(t, lead, StateLeader, 1)
  2728. }
  2729. // TestLeaderTransferToUpToDateNodeFromFollower verifies transferring should succeed
  2730. // if the transferee has the most up-to-date log entries when transfer starts.
  2731. // Not like TestLeaderTransferToUpToDateNode, where the leader transfer message
  2732. // is sent to the leader, in this test case every leader transfer message is sent
  2733. // to the follower.
  2734. func TestLeaderTransferToUpToDateNodeFromFollower(t *testing.T) {
  2735. nt := newNetwork(nil, nil, nil)
  2736. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2737. lead := nt.peers[1].(*raft)
  2738. if lead.lead != 1 {
  2739. t.Fatalf("after election leader is %x, want 1", lead.lead)
  2740. }
  2741. // Transfer leadership to 2.
  2742. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgTransferLeader})
  2743. checkLeaderTransferState(t, lead, StateFollower, 2)
  2744. // After some log replication, transfer leadership back to 1.
  2745. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2746. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgTransferLeader})
  2747. checkLeaderTransferState(t, lead, StateLeader, 1)
  2748. }
  2749. // TestLeaderTransferWithCheckQuorum ensures transferring leader still works
  2750. // even the current leader is still under its leader lease
  2751. func TestLeaderTransferWithCheckQuorum(t *testing.T) {
  2752. nt := newNetwork(nil, nil, nil)
  2753. for i := 1; i < 4; i++ {
  2754. r := nt.peers[uint64(i)].(*raft)
  2755. r.checkQuorum = true
  2756. setRandomizedElectionTimeout(r, r.electionTimeout+i)
  2757. }
  2758. // Letting peer 2 electionElapsed reach to timeout so that it can vote for peer 1
  2759. f := nt.peers[2].(*raft)
  2760. for i := 0; i < f.electionTimeout; i++ {
  2761. f.tick()
  2762. }
  2763. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2764. lead := nt.peers[1].(*raft)
  2765. if lead.lead != 1 {
  2766. t.Fatalf("after election leader is %x, want 1", lead.lead)
  2767. }
  2768. // Transfer leadership to 2.
  2769. nt.send(pb.Message{From: 2, To: 1, Type: pb.MsgTransferLeader})
  2770. checkLeaderTransferState(t, lead, StateFollower, 2)
  2771. // After some log replication, transfer leadership back to 1.
  2772. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2773. nt.send(pb.Message{From: 1, To: 2, Type: pb.MsgTransferLeader})
  2774. checkLeaderTransferState(t, lead, StateLeader, 1)
  2775. }
  2776. func TestLeaderTransferToSlowFollower(t *testing.T) {
  2777. defaultLogger.EnableDebug()
  2778. nt := newNetwork(nil, nil, nil)
  2779. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2780. nt.isolate(3)
  2781. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2782. nt.recover()
  2783. lead := nt.peers[1].(*raft)
  2784. if lead.prs[3].Match != 1 {
  2785. t.Fatalf("node 1 has match %x for node 3, want %x", lead.prs[3].Match, 1)
  2786. }
  2787. // Transfer leadership to 3 when node 3 is lack of log.
  2788. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2789. checkLeaderTransferState(t, lead, StateFollower, 3)
  2790. }
  2791. func TestLeaderTransferAfterSnapshot(t *testing.T) {
  2792. nt := newNetwork(nil, nil, nil)
  2793. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2794. nt.isolate(3)
  2795. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2796. lead := nt.peers[1].(*raft)
  2797. nextEnts(lead, nt.storage[1])
  2798. nt.storage[1].CreateSnapshot(lead.raftLog.applied, &pb.ConfState{Nodes: lead.nodes()}, nil)
  2799. nt.storage[1].Compact(lead.raftLog.applied)
  2800. nt.recover()
  2801. if lead.prs[3].Match != 1 {
  2802. t.Fatalf("node 1 has match %x for node 3, want %x", lead.prs[3].Match, 1)
  2803. }
  2804. // Transfer leadership to 3 when node 3 is lack of snapshot.
  2805. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2806. // Send pb.MsgHeartbeatResp to leader to trigger a snapshot for node 3.
  2807. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgHeartbeatResp})
  2808. checkLeaderTransferState(t, lead, StateFollower, 3)
  2809. }
  2810. func TestLeaderTransferToSelf(t *testing.T) {
  2811. nt := newNetwork(nil, nil, nil)
  2812. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2813. lead := nt.peers[1].(*raft)
  2814. // Transfer leadership to self, there will be noop.
  2815. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgTransferLeader})
  2816. checkLeaderTransferState(t, lead, StateLeader, 1)
  2817. }
  2818. func TestLeaderTransferToNonExistingNode(t *testing.T) {
  2819. nt := newNetwork(nil, nil, nil)
  2820. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2821. lead := nt.peers[1].(*raft)
  2822. // Transfer leadership to non-existing node, there will be noop.
  2823. nt.send(pb.Message{From: 4, To: 1, Type: pb.MsgTransferLeader})
  2824. checkLeaderTransferState(t, lead, StateLeader, 1)
  2825. }
  2826. func TestLeaderTransferTimeout(t *testing.T) {
  2827. nt := newNetwork(nil, nil, nil)
  2828. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2829. nt.isolate(3)
  2830. lead := nt.peers[1].(*raft)
  2831. // Transfer leadership to isolated node, wait for timeout.
  2832. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2833. if lead.leadTransferee != 3 {
  2834. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2835. }
  2836. for i := 0; i < lead.heartbeatTimeout; i++ {
  2837. lead.tick()
  2838. }
  2839. if lead.leadTransferee != 3 {
  2840. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2841. }
  2842. for i := 0; i < lead.electionTimeout-lead.heartbeatTimeout; i++ {
  2843. lead.tick()
  2844. }
  2845. checkLeaderTransferState(t, lead, StateLeader, 1)
  2846. }
  2847. func TestLeaderTransferIgnoreProposal(t *testing.T) {
  2848. nt := newNetwork(nil, nil, nil)
  2849. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2850. nt.isolate(3)
  2851. lead := nt.peers[1].(*raft)
  2852. // Transfer leadership to isolated node to let transfer pending, then send proposal.
  2853. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2854. if lead.leadTransferee != 3 {
  2855. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2856. }
  2857. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2858. err := lead.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2859. if err != ErrProposalDropped {
  2860. t.Fatalf("should return drop proposal error while transferring")
  2861. }
  2862. if lead.prs[1].Match != 1 {
  2863. t.Fatalf("node 1 has match %x, want %x", lead.prs[1].Match, 1)
  2864. }
  2865. }
  2866. func TestLeaderTransferReceiveHigherTermVote(t *testing.T) {
  2867. nt := newNetwork(nil, nil, nil)
  2868. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2869. nt.isolate(3)
  2870. lead := nt.peers[1].(*raft)
  2871. // Transfer leadership to isolated node to let transfer pending.
  2872. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2873. if lead.leadTransferee != 3 {
  2874. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2875. }
  2876. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup, Index: 1, Term: 2})
  2877. checkLeaderTransferState(t, lead, StateFollower, 2)
  2878. }
  2879. func TestLeaderTransferRemoveNode(t *testing.T) {
  2880. nt := newNetwork(nil, nil, nil)
  2881. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2882. nt.ignore(pb.MsgTimeoutNow)
  2883. lead := nt.peers[1].(*raft)
  2884. // The leadTransferee is removed when leadship transferring.
  2885. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2886. if lead.leadTransferee != 3 {
  2887. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2888. }
  2889. lead.removeNode(3)
  2890. checkLeaderTransferState(t, lead, StateLeader, 1)
  2891. }
  2892. // TestLeaderTransferBack verifies leadership can transfer back to self when last transfer is pending.
  2893. func TestLeaderTransferBack(t *testing.T) {
  2894. nt := newNetwork(nil, nil, nil)
  2895. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2896. nt.isolate(3)
  2897. lead := nt.peers[1].(*raft)
  2898. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2899. if lead.leadTransferee != 3 {
  2900. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2901. }
  2902. // Transfer leadership back to self.
  2903. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgTransferLeader})
  2904. checkLeaderTransferState(t, lead, StateLeader, 1)
  2905. }
  2906. // TestLeaderTransferSecondTransferToAnotherNode verifies leader can transfer to another node
  2907. // when last transfer is pending.
  2908. func TestLeaderTransferSecondTransferToAnotherNode(t *testing.T) {
  2909. nt := newNetwork(nil, nil, nil)
  2910. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2911. nt.isolate(3)
  2912. lead := nt.peers[1].(*raft)
  2913. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2914. if lead.leadTransferee != 3 {
  2915. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2916. }
  2917. // Transfer leadership to another node.
  2918. nt.send(pb.Message{From: 2, To: 1, Type: pb.MsgTransferLeader})
  2919. checkLeaderTransferState(t, lead, StateFollower, 2)
  2920. }
  2921. // TestLeaderTransferSecondTransferToSameNode verifies second transfer leader request
  2922. // to the same node should not extend the timeout while the first one is pending.
  2923. func TestLeaderTransferSecondTransferToSameNode(t *testing.T) {
  2924. nt := newNetwork(nil, nil, nil)
  2925. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2926. nt.isolate(3)
  2927. lead := nt.peers[1].(*raft)
  2928. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2929. if lead.leadTransferee != 3 {
  2930. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2931. }
  2932. for i := 0; i < lead.heartbeatTimeout; i++ {
  2933. lead.tick()
  2934. }
  2935. // Second transfer leadership request to the same node.
  2936. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2937. for i := 0; i < lead.electionTimeout-lead.heartbeatTimeout; i++ {
  2938. lead.tick()
  2939. }
  2940. checkLeaderTransferState(t, lead, StateLeader, 1)
  2941. }
  2942. func checkLeaderTransferState(t *testing.T, r *raft, state StateType, lead uint64) {
  2943. if r.state != state || r.lead != lead {
  2944. t.Fatalf("after transferring, node has state %v lead %v, want state %v lead %v", r.state, r.lead, state, lead)
  2945. }
  2946. if r.leadTransferee != None {
  2947. t.Fatalf("after transferring, node has leadTransferee %v, want leadTransferee %v", r.leadTransferee, None)
  2948. }
  2949. }
  2950. // TestTransferNonMember verifies that when a MsgTimeoutNow arrives at
  2951. // a node that has been removed from the group, nothing happens.
  2952. // (previously, if the node also got votes, it would panic as it
  2953. // transitioned to StateLeader)
  2954. func TestTransferNonMember(t *testing.T) {
  2955. r := newTestRaft(1, []uint64{2, 3, 4}, 5, 1, NewMemoryStorage())
  2956. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgTimeoutNow})
  2957. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgVoteResp})
  2958. r.Step(pb.Message{From: 3, To: 1, Type: pb.MsgVoteResp})
  2959. if r.state != StateFollower {
  2960. t.Fatalf("state is %s, want StateFollower", r.state)
  2961. }
  2962. }
  2963. // TestNodeWithSmallerTermCanCompleteElection tests the scenario where a node
  2964. // that has been partitioned away (and fallen behind) rejoins the cluster at
  2965. // about the same time the leader node gets partitioned away.
  2966. // Previously the cluster would come to a standstill when run with PreVote
  2967. // enabled.
  2968. func TestNodeWithSmallerTermCanCompleteElection(t *testing.T) {
  2969. n1 := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  2970. n2 := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  2971. n3 := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  2972. n1.becomeFollower(1, None)
  2973. n2.becomeFollower(1, None)
  2974. n3.becomeFollower(1, None)
  2975. n1.preVote = true
  2976. n2.preVote = true
  2977. n3.preVote = true
  2978. // cause a network partition to isolate node 3
  2979. nt := newNetwork(n1, n2, n3)
  2980. nt.cut(1, 3)
  2981. nt.cut(2, 3)
  2982. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2983. sm := nt.peers[1].(*raft)
  2984. if sm.state != StateLeader {
  2985. t.Errorf("peer 1 state: %s, want %s", sm.state, StateLeader)
  2986. }
  2987. sm = nt.peers[2].(*raft)
  2988. if sm.state != StateFollower {
  2989. t.Errorf("peer 2 state: %s, want %s", sm.state, StateFollower)
  2990. }
  2991. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  2992. sm = nt.peers[3].(*raft)
  2993. if sm.state != StatePreCandidate {
  2994. t.Errorf("peer 3 state: %s, want %s", sm.state, StatePreCandidate)
  2995. }
  2996. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  2997. // check whether the term values are expected
  2998. // a.Term == 3
  2999. // b.Term == 3
  3000. // c.Term == 1
  3001. sm = nt.peers[1].(*raft)
  3002. if sm.Term != 3 {
  3003. t.Errorf("peer 1 term: %d, want %d", sm.Term, 3)
  3004. }
  3005. sm = nt.peers[2].(*raft)
  3006. if sm.Term != 3 {
  3007. t.Errorf("peer 2 term: %d, want %d", sm.Term, 3)
  3008. }
  3009. sm = nt.peers[3].(*raft)
  3010. if sm.Term != 1 {
  3011. t.Errorf("peer 3 term: %d, want %d", sm.Term, 1)
  3012. }
  3013. // check state
  3014. // a == follower
  3015. // b == leader
  3016. // c == pre-candidate
  3017. sm = nt.peers[1].(*raft)
  3018. if sm.state != StateFollower {
  3019. t.Errorf("peer 1 state: %s, want %s", sm.state, StateFollower)
  3020. }
  3021. sm = nt.peers[2].(*raft)
  3022. if sm.state != StateLeader {
  3023. t.Errorf("peer 2 state: %s, want %s", sm.state, StateLeader)
  3024. }
  3025. sm = nt.peers[3].(*raft)
  3026. if sm.state != StatePreCandidate {
  3027. t.Errorf("peer 3 state: %s, want %s", sm.state, StatePreCandidate)
  3028. }
  3029. sm.logger.Infof("going to bring back peer 3 and kill peer 2")
  3030. // recover the network then immediately isolate b which is currently
  3031. // the leader, this is to emulate the crash of b.
  3032. nt.recover()
  3033. nt.cut(2, 1)
  3034. nt.cut(2, 3)
  3035. // call for election
  3036. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  3037. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  3038. // do we have a leader?
  3039. sma := nt.peers[1].(*raft)
  3040. smb := nt.peers[3].(*raft)
  3041. if sma.state != StateLeader && smb.state != StateLeader {
  3042. t.Errorf("no leader")
  3043. }
  3044. }
  3045. // TestPreVoteWithSplitVote verifies that after split vote, cluster can complete
  3046. // election in next round.
  3047. func TestPreVoteWithSplitVote(t *testing.T) {
  3048. n1 := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  3049. n2 := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  3050. n3 := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  3051. n1.becomeFollower(1, None)
  3052. n2.becomeFollower(1, None)
  3053. n3.becomeFollower(1, None)
  3054. n1.preVote = true
  3055. n2.preVote = true
  3056. n3.preVote = true
  3057. nt := newNetwork(n1, n2, n3)
  3058. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  3059. // simulate leader down. followers start split vote.
  3060. nt.isolate(1)
  3061. nt.send([]pb.Message{
  3062. {From: 2, To: 2, Type: pb.MsgHup},
  3063. {From: 3, To: 3, Type: pb.MsgHup},
  3064. }...)
  3065. // check whether the term values are expected
  3066. // n2.Term == 3
  3067. // n3.Term == 3
  3068. sm := nt.peers[2].(*raft)
  3069. if sm.Term != 3 {
  3070. t.Errorf("peer 2 term: %d, want %d", sm.Term, 3)
  3071. }
  3072. sm = nt.peers[3].(*raft)
  3073. if sm.Term != 3 {
  3074. t.Errorf("peer 3 term: %d, want %d", sm.Term, 3)
  3075. }
  3076. // check state
  3077. // n2 == candidate
  3078. // n3 == candidate
  3079. sm = nt.peers[2].(*raft)
  3080. if sm.state != StateCandidate {
  3081. t.Errorf("peer 2 state: %s, want %s", sm.state, StateCandidate)
  3082. }
  3083. sm = nt.peers[3].(*raft)
  3084. if sm.state != StateCandidate {
  3085. t.Errorf("peer 3 state: %s, want %s", sm.state, StateCandidate)
  3086. }
  3087. // node 2 election timeout first
  3088. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  3089. // check whether the term values are expected
  3090. // n2.Term == 4
  3091. // n3.Term == 4
  3092. sm = nt.peers[2].(*raft)
  3093. if sm.Term != 4 {
  3094. t.Errorf("peer 2 term: %d, want %d", sm.Term, 4)
  3095. }
  3096. sm = nt.peers[3].(*raft)
  3097. if sm.Term != 4 {
  3098. t.Errorf("peer 3 term: %d, want %d", sm.Term, 4)
  3099. }
  3100. // check state
  3101. // n2 == leader
  3102. // n3 == follower
  3103. sm = nt.peers[2].(*raft)
  3104. if sm.state != StateLeader {
  3105. t.Errorf("peer 2 state: %s, want %s", sm.state, StateLeader)
  3106. }
  3107. sm = nt.peers[3].(*raft)
  3108. if sm.state != StateFollower {
  3109. t.Errorf("peer 3 state: %s, want %s", sm.state, StateFollower)
  3110. }
  3111. }
  3112. // simulate rolling update a cluster for Pre-Vote. cluster has 3 nodes [n1, n2, n3].
  3113. // n1 is leader with term 2
  3114. // n2 is follower with term 2
  3115. // n3 is partitioned, with term 4 and less log, state is candidate
  3116. func newPreVoteMigrationCluster(t *testing.T) *network {
  3117. n1 := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  3118. n2 := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  3119. n3 := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  3120. n1.becomeFollower(1, None)
  3121. n2.becomeFollower(1, None)
  3122. n3.becomeFollower(1, None)
  3123. n1.preVote = true
  3124. n2.preVote = true
  3125. // We intentionally do not enable PreVote for n3, this is done so in order
  3126. // to simulate a rolling restart process where it's possible to have a mixed
  3127. // version cluster with replicas with PreVote enabled, and replicas without.
  3128. nt := newNetwork(n1, n2, n3)
  3129. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  3130. // Cause a network partition to isolate n3.
  3131. nt.isolate(3)
  3132. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  3133. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  3134. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  3135. // check state
  3136. // n1.state == StateLeader
  3137. // n2.state == StateFollower
  3138. // n3.state == StateCandidate
  3139. if n1.state != StateLeader {
  3140. t.Fatalf("node 1 state: %s, want %s", n1.state, StateLeader)
  3141. }
  3142. if n2.state != StateFollower {
  3143. t.Fatalf("node 2 state: %s, want %s", n2.state, StateFollower)
  3144. }
  3145. if n3.state != StateCandidate {
  3146. t.Fatalf("node 3 state: %s, want %s", n3.state, StateCandidate)
  3147. }
  3148. // check term
  3149. // n1.Term == 2
  3150. // n2.Term == 2
  3151. // n3.Term == 4
  3152. if n1.Term != 2 {
  3153. t.Fatalf("node 1 term: %d, want %d", n1.Term, 2)
  3154. }
  3155. if n2.Term != 2 {
  3156. t.Fatalf("node 2 term: %d, want %d", n2.Term, 2)
  3157. }
  3158. if n3.Term != 4 {
  3159. t.Fatalf("node 3 term: %d, want %d", n3.Term, 4)
  3160. }
  3161. // Enable prevote on n3, then recover the network
  3162. n3.preVote = true
  3163. nt.recover()
  3164. return nt
  3165. }
  3166. func TestPreVoteMigrationCanCompleteElection(t *testing.T) {
  3167. nt := newPreVoteMigrationCluster(t)
  3168. // n1 is leader with term 2
  3169. // n2 is follower with term 2
  3170. // n3 is pre-candidate with term 4, and less log
  3171. n2 := nt.peers[2].(*raft)
  3172. n3 := nt.peers[3].(*raft)
  3173. // simulate leader down
  3174. nt.isolate(1)
  3175. // Call for elections from both n2 and n3.
  3176. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  3177. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  3178. // check state
  3179. // n2.state == Follower
  3180. // n3.state == PreCandidate
  3181. if n2.state != StateFollower {
  3182. t.Errorf("node 2 state: %s, want %s", n2.state, StateFollower)
  3183. }
  3184. if n3.state != StatePreCandidate {
  3185. t.Errorf("node 3 state: %s, want %s", n3.state, StatePreCandidate)
  3186. }
  3187. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  3188. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  3189. // Do we have a leader?
  3190. if n2.state != StateLeader && n3.state != StateFollower {
  3191. t.Errorf("no leader")
  3192. }
  3193. }
  3194. func TestPreVoteMigrationWithFreeStuckPreCandidate(t *testing.T) {
  3195. nt := newPreVoteMigrationCluster(t)
  3196. // n1 is leader with term 2
  3197. // n2 is follower with term 2
  3198. // n3 is pre-candidate with term 4, and less log
  3199. n1 := nt.peers[1].(*raft)
  3200. n2 := nt.peers[2].(*raft)
  3201. n3 := nt.peers[3].(*raft)
  3202. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  3203. if n1.state != StateLeader {
  3204. t.Errorf("node 1 state: %s, want %s", n1.state, StateLeader)
  3205. }
  3206. if n2.state != StateFollower {
  3207. t.Errorf("node 2 state: %s, want %s", n2.state, StateFollower)
  3208. }
  3209. if n3.state != StatePreCandidate {
  3210. t.Errorf("node 3 state: %s, want %s", n3.state, StatePreCandidate)
  3211. }
  3212. // Pre-Vote again for safety
  3213. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  3214. if n1.state != StateLeader {
  3215. t.Errorf("node 1 state: %s, want %s", n1.state, StateLeader)
  3216. }
  3217. if n2.state != StateFollower {
  3218. t.Errorf("node 2 state: %s, want %s", n2.state, StateFollower)
  3219. }
  3220. if n3.state != StatePreCandidate {
  3221. t.Errorf("node 3 state: %s, want %s", n3.state, StatePreCandidate)
  3222. }
  3223. nt.send(pb.Message{From: 1, To: 3, Type: pb.MsgHeartbeat, Term: n1.Term})
  3224. // Disrupt the leader so that the stuck peer is freed
  3225. if n1.state != StateFollower {
  3226. t.Errorf("state = %s, want %s", n1.state, StateFollower)
  3227. }
  3228. if n3.Term != n1.Term {
  3229. t.Errorf("term = %d, want %d", n3.Term, n1.Term)
  3230. }
  3231. }
  3232. func entsWithConfig(configFunc func(*Config), terms ...uint64) *raft {
  3233. storage := NewMemoryStorage()
  3234. for i, term := range terms {
  3235. storage.Append([]pb.Entry{{Index: uint64(i + 1), Term: term}})
  3236. }
  3237. cfg := newTestConfig(1, []uint64{}, 5, 1, storage)
  3238. if configFunc != nil {
  3239. configFunc(cfg)
  3240. }
  3241. sm := newRaft(cfg)
  3242. sm.reset(terms[len(terms)-1])
  3243. return sm
  3244. }
  3245. // votedWithConfig creates a raft state machine with Vote and Term set
  3246. // to the given value but no log entries (indicating that it voted in
  3247. // the given term but has not received any logs).
  3248. func votedWithConfig(configFunc func(*Config), vote, term uint64) *raft {
  3249. storage := NewMemoryStorage()
  3250. storage.SetHardState(pb.HardState{Vote: vote, Term: term})
  3251. cfg := newTestConfig(1, []uint64{}, 5, 1, storage)
  3252. if configFunc != nil {
  3253. configFunc(cfg)
  3254. }
  3255. sm := newRaft(cfg)
  3256. sm.reset(term)
  3257. return sm
  3258. }
  3259. type network struct {
  3260. peers map[uint64]stateMachine
  3261. storage map[uint64]*MemoryStorage
  3262. dropm map[connem]float64
  3263. ignorem map[pb.MessageType]bool
  3264. }
  3265. // newNetwork initializes a network from peers.
  3266. // A nil node will be replaced with a new *stateMachine.
  3267. // A *stateMachine will get its k, id.
  3268. // When using stateMachine, the address list is always [1, n].
  3269. func newNetwork(peers ...stateMachine) *network {
  3270. return newNetworkWithConfig(nil, peers...)
  3271. }
  3272. // newNetworkWithConfig is like newNetwork but calls the given func to
  3273. // modify the configuration of any state machines it creates.
  3274. func newNetworkWithConfig(configFunc func(*Config), peers ...stateMachine) *network {
  3275. size := len(peers)
  3276. peerAddrs := idsBySize(size)
  3277. npeers := make(map[uint64]stateMachine, size)
  3278. nstorage := make(map[uint64]*MemoryStorage, size)
  3279. for j, p := range peers {
  3280. id := peerAddrs[j]
  3281. switch v := p.(type) {
  3282. case nil:
  3283. nstorage[id] = NewMemoryStorage()
  3284. cfg := newTestConfig(id, peerAddrs, 10, 1, nstorage[id])
  3285. if configFunc != nil {
  3286. configFunc(cfg)
  3287. }
  3288. sm := newRaft(cfg)
  3289. npeers[id] = sm
  3290. case *raft:
  3291. learners := make(map[uint64]bool, len(v.learnerPrs))
  3292. for i := range v.learnerPrs {
  3293. learners[i] = true
  3294. }
  3295. v.id = id
  3296. v.prs = make(map[uint64]*Progress)
  3297. v.learnerPrs = make(map[uint64]*Progress)
  3298. for i := 0; i < size; i++ {
  3299. if _, ok := learners[peerAddrs[i]]; ok {
  3300. v.learnerPrs[peerAddrs[i]] = &Progress{IsLearner: true}
  3301. } else {
  3302. v.prs[peerAddrs[i]] = &Progress{}
  3303. }
  3304. }
  3305. v.reset(v.Term)
  3306. npeers[id] = v
  3307. case *blackHole:
  3308. npeers[id] = v
  3309. default:
  3310. panic(fmt.Sprintf("unexpected state machine type: %T", p))
  3311. }
  3312. }
  3313. return &network{
  3314. peers: npeers,
  3315. storage: nstorage,
  3316. dropm: make(map[connem]float64),
  3317. ignorem: make(map[pb.MessageType]bool),
  3318. }
  3319. }
  3320. func preVoteConfig(c *Config) {
  3321. c.PreVote = true
  3322. }
  3323. func (nw *network) send(msgs ...pb.Message) {
  3324. for len(msgs) > 0 {
  3325. m := msgs[0]
  3326. p := nw.peers[m.To]
  3327. p.Step(m)
  3328. msgs = append(msgs[1:], nw.filter(p.readMessages())...)
  3329. }
  3330. }
  3331. func (nw *network) drop(from, to uint64, perc float64) {
  3332. nw.dropm[connem{from, to}] = perc
  3333. }
  3334. func (nw *network) cut(one, other uint64) {
  3335. nw.drop(one, other, 1)
  3336. nw.drop(other, one, 1)
  3337. }
  3338. func (nw *network) isolate(id uint64) {
  3339. for i := 0; i < len(nw.peers); i++ {
  3340. nid := uint64(i) + 1
  3341. if nid != id {
  3342. nw.drop(id, nid, 1.0)
  3343. nw.drop(nid, id, 1.0)
  3344. }
  3345. }
  3346. }
  3347. func (nw *network) ignore(t pb.MessageType) {
  3348. nw.ignorem[t] = true
  3349. }
  3350. func (nw *network) recover() {
  3351. nw.dropm = make(map[connem]float64)
  3352. nw.ignorem = make(map[pb.MessageType]bool)
  3353. }
  3354. func (nw *network) filter(msgs []pb.Message) []pb.Message {
  3355. mm := []pb.Message{}
  3356. for _, m := range msgs {
  3357. if nw.ignorem[m.Type] {
  3358. continue
  3359. }
  3360. switch m.Type {
  3361. case pb.MsgHup:
  3362. // hups never go over the network, so don't drop them but panic
  3363. panic("unexpected msgHup")
  3364. default:
  3365. perc := nw.dropm[connem{m.From, m.To}]
  3366. if n := rand.Float64(); n < perc {
  3367. continue
  3368. }
  3369. }
  3370. mm = append(mm, m)
  3371. }
  3372. return mm
  3373. }
  3374. type connem struct {
  3375. from, to uint64
  3376. }
  3377. type blackHole struct{}
  3378. func (blackHole) Step(pb.Message) error { return nil }
  3379. func (blackHole) readMessages() []pb.Message { return nil }
  3380. var nopStepper = &blackHole{}
  3381. func idsBySize(size int) []uint64 {
  3382. ids := make([]uint64, size)
  3383. for i := 0; i < size; i++ {
  3384. ids[i] = 1 + uint64(i)
  3385. }
  3386. return ids
  3387. }
  3388. // setRandomizedElectionTimeout set up the value by caller instead of choosing
  3389. // by system, in some test scenario we need to fill in some expected value to
  3390. // ensure the certainty
  3391. func setRandomizedElectionTimeout(r *raft, v int) {
  3392. r.randomizedElectionTimeout = v
  3393. }
  3394. func newTestConfig(id uint64, peers []uint64, election, heartbeat int, storage Storage) *Config {
  3395. return &Config{
  3396. ID: id,
  3397. peers: peers,
  3398. ElectionTick: election,
  3399. HeartbeatTick: heartbeat,
  3400. Storage: storage,
  3401. MaxSizePerMsg: noLimit,
  3402. MaxInflightMsgs: 256,
  3403. }
  3404. }
  3405. func newTestRaft(id uint64, peers []uint64, election, heartbeat int, storage Storage) *raft {
  3406. return newRaft(newTestConfig(id, peers, election, heartbeat, storage))
  3407. }
  3408. func newTestLearnerRaft(id uint64, peers []uint64, learners []uint64, election, heartbeat int, storage Storage) *raft {
  3409. cfg := newTestConfig(id, peers, election, heartbeat, storage)
  3410. cfg.learners = learners
  3411. return newRaft(cfg)
  3412. }