raft_test.go 109 KB

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