raft_test.go 128 KB

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