raft_test.go 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034
  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.
  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 false", 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, nil, ents(1), ents(1), ents(1, 1), nil), StateFollower, 1},
  294. // logs converge
  295. {newNetworkWithConfig(cfg, ents(1), nil, ents(2), ents(1), nil), StateLeader, 2},
  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. func TestLeaderCycle(t *testing.T) {
  321. testLeaderCycle(t, false)
  322. }
  323. func TestLeaderCyclePreVote(t *testing.T) {
  324. testLeaderCycle(t, true)
  325. }
  326. // testLeaderCycle verifies that each node in a cluster can campaign
  327. // and be elected in turn. This ensures that elections (including
  328. // pre-vote) work when not starting from a clean slate (as they do in
  329. // TestLeaderElection)
  330. func testLeaderCycle(t *testing.T, preVote bool) {
  331. var cfg func(*Config)
  332. if preVote {
  333. cfg = preVoteConfig
  334. }
  335. n := newNetworkWithConfig(cfg, nil, nil, nil)
  336. for campaignerID := uint64(1); campaignerID <= 3; campaignerID++ {
  337. n.send(pb.Message{From: campaignerID, To: campaignerID, Type: pb.MsgHup})
  338. for _, peer := range n.peers {
  339. sm := peer.(*raft)
  340. if sm.id == campaignerID && sm.state != StateLeader {
  341. t.Errorf("preVote=%v: campaigning node %d state = %v, want StateLeader",
  342. preVote, sm.id, sm.state)
  343. } else if sm.id != campaignerID && sm.state != StateFollower {
  344. t.Errorf("preVote=%v: after campaign of node %d, "+
  345. "node %d had state = %v, want StateFollower",
  346. preVote, campaignerID, sm.id, sm.state)
  347. }
  348. }
  349. }
  350. }
  351. func TestVoteFromAnyState(t *testing.T) {
  352. testVoteFromAnyState(t, pb.MsgVote)
  353. }
  354. func TestPreVoteFromAnyState(t *testing.T) {
  355. testVoteFromAnyState(t, pb.MsgPreVote)
  356. }
  357. func testVoteFromAnyState(t *testing.T, vt pb.MessageType) {
  358. for st := StateType(0); st < numStates; st++ {
  359. r := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  360. r.Term = 1
  361. switch st {
  362. case StateFollower:
  363. r.becomeFollower(r.Term, 3)
  364. case StatePreCandidate:
  365. r.becomePreCandidate()
  366. case StateCandidate:
  367. r.becomeCandidate()
  368. case StateLeader:
  369. r.becomeCandidate()
  370. r.becomeLeader()
  371. }
  372. // Note that setting our state above may have advanced r.Term
  373. // past its initial value.
  374. origTerm := r.Term
  375. newTerm := r.Term + 1
  376. msg := pb.Message{
  377. From: 2,
  378. To: 1,
  379. Type: vt,
  380. Term: newTerm,
  381. LogTerm: newTerm,
  382. Index: 42,
  383. }
  384. if err := r.Step(msg); err != nil {
  385. t.Errorf("%s,%s: Step failed: %s", vt, st, err)
  386. }
  387. if len(r.msgs) != 1 {
  388. t.Errorf("%s,%s: %d response messages, want 1: %+v", vt, st, len(r.msgs), r.msgs)
  389. } else {
  390. resp := r.msgs[0]
  391. if resp.Type != voteRespMsgType(vt) {
  392. t.Errorf("%s,%s: response message is %s, want %s",
  393. vt, st, resp.Type, voteRespMsgType(vt))
  394. }
  395. if resp.Reject {
  396. t.Errorf("%s,%s: unexpected rejection", vt, st)
  397. }
  398. }
  399. // If this was a real vote, we reset our state and term.
  400. if vt == pb.MsgVote {
  401. if r.state != StateFollower {
  402. t.Errorf("%s,%s: state %s, want %s", vt, StateFollower, r.state, st)
  403. }
  404. if r.Term != newTerm {
  405. t.Errorf("%s,%s: term %d, want %d", vt, st, r.Term, newTerm)
  406. }
  407. if r.Vote != 2 {
  408. t.Errorf("%s,%s: vote %d, want 2", vt, st, r.Vote)
  409. }
  410. } else {
  411. // In a prevote, nothing changes.
  412. if r.state != st {
  413. t.Errorf("%s,%s: state %s, want %s", vt, st, r.state, st)
  414. }
  415. if r.Term != origTerm {
  416. t.Errorf("%s,%s: term %d, want %d", vt, st, r.Term, origTerm)
  417. }
  418. // if st == StateFollower or StatePreCandidate, r hasn't voted yet.
  419. // In StateCandidate or StateLeader, it's voted for itself.
  420. if r.Vote != None && r.Vote != 1 {
  421. t.Errorf("%s,%s: vote %d, want %d or 1", vt, st, r.Vote, None)
  422. }
  423. }
  424. }
  425. }
  426. func TestLogReplication(t *testing.T) {
  427. tests := []struct {
  428. *network
  429. msgs []pb.Message
  430. wcommitted uint64
  431. }{
  432. {
  433. newNetwork(nil, nil, nil),
  434. []pb.Message{
  435. {From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}},
  436. },
  437. 2,
  438. },
  439. {
  440. newNetwork(nil, nil, nil),
  441. []pb.Message{
  442. {From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}},
  443. {From: 1, To: 2, Type: pb.MsgHup},
  444. {From: 1, To: 2, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}},
  445. },
  446. 4,
  447. },
  448. }
  449. for i, tt := range tests {
  450. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  451. for _, m := range tt.msgs {
  452. tt.send(m)
  453. }
  454. for j, x := range tt.network.peers {
  455. sm := x.(*raft)
  456. if sm.raftLog.committed != tt.wcommitted {
  457. t.Errorf("#%d.%d: committed = %d, want %d", i, j, sm.raftLog.committed, tt.wcommitted)
  458. }
  459. ents := []pb.Entry{}
  460. for _, e := range nextEnts(sm, tt.network.storage[j]) {
  461. if e.Data != nil {
  462. ents = append(ents, e)
  463. }
  464. }
  465. props := []pb.Message{}
  466. for _, m := range tt.msgs {
  467. if m.Type == pb.MsgProp {
  468. props = append(props, m)
  469. }
  470. }
  471. for k, m := range props {
  472. if !bytes.Equal(ents[k].Data, m.Entries[0].Data) {
  473. t.Errorf("#%d.%d: data = %d, want %d", i, j, ents[k].Data, m.Entries[0].Data)
  474. }
  475. }
  476. }
  477. }
  478. }
  479. func TestSingleNodeCommit(t *testing.T) {
  480. tt := newNetwork(nil)
  481. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  482. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  483. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  484. sm := tt.peers[1].(*raft)
  485. if sm.raftLog.committed != 3 {
  486. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 3)
  487. }
  488. }
  489. // TestCannotCommitWithoutNewTermEntry tests the entries cannot be committed
  490. // when leader changes, no new proposal comes in and ChangeTerm proposal is
  491. // filtered.
  492. func TestCannotCommitWithoutNewTermEntry(t *testing.T) {
  493. tt := newNetwork(nil, nil, nil, nil, nil)
  494. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  495. // 0 cannot reach 2,3,4
  496. tt.cut(1, 3)
  497. tt.cut(1, 4)
  498. tt.cut(1, 5)
  499. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  500. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  501. sm := tt.peers[1].(*raft)
  502. if sm.raftLog.committed != 1 {
  503. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 1)
  504. }
  505. // network recovery
  506. tt.recover()
  507. // avoid committing ChangeTerm proposal
  508. tt.ignore(pb.MsgApp)
  509. // elect 2 as the new leader with term 2
  510. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  511. // no log entries from previous term should be committed
  512. sm = tt.peers[2].(*raft)
  513. if sm.raftLog.committed != 1 {
  514. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 1)
  515. }
  516. tt.recover()
  517. // send heartbeat; reset wait
  518. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgBeat})
  519. // append an entry at current term
  520. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  521. // expect the committed to be advanced
  522. if sm.raftLog.committed != 5 {
  523. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 5)
  524. }
  525. }
  526. // TestCommitWithoutNewTermEntry tests the entries could be committed
  527. // when leader changes, no new proposal comes in.
  528. func TestCommitWithoutNewTermEntry(t *testing.T) {
  529. tt := newNetwork(nil, nil, nil, nil, nil)
  530. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  531. // 0 cannot reach 2,3,4
  532. tt.cut(1, 3)
  533. tt.cut(1, 4)
  534. tt.cut(1, 5)
  535. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  536. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  537. sm := tt.peers[1].(*raft)
  538. if sm.raftLog.committed != 1 {
  539. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 1)
  540. }
  541. // network recovery
  542. tt.recover()
  543. // elect 1 as the new leader with term 2
  544. // after append a ChangeTerm entry from the current term, all entries
  545. // should be committed
  546. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  547. if sm.raftLog.committed != 4 {
  548. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 4)
  549. }
  550. }
  551. func TestDuelingCandidates(t *testing.T) {
  552. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  553. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  554. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  555. nt := newNetwork(a, b, c)
  556. nt.cut(1, 3)
  557. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  558. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  559. // 1 becomes leader since it receives votes from 1 and 2
  560. sm := nt.peers[1].(*raft)
  561. if sm.state != StateLeader {
  562. t.Errorf("state = %s, want %s", sm.state, StateLeader)
  563. }
  564. // 3 stays as candidate since it receives a vote from 3 and a rejection from 2
  565. sm = nt.peers[3].(*raft)
  566. if sm.state != StateCandidate {
  567. t.Errorf("state = %s, want %s", sm.state, StateCandidate)
  568. }
  569. nt.recover()
  570. // candidate 3 now increases its term and tries to vote again
  571. // we expect it to disrupt the leader 1 since it has a higher term
  572. // 3 will be follower again since both 1 and 2 rejects its vote request since 3 does not have a long enough log
  573. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  574. wlog := &raftLog{
  575. storage: &MemoryStorage{ents: []pb.Entry{{}, {Data: nil, Term: 1, Index: 1}}},
  576. committed: 1,
  577. unstable: unstable{offset: 2},
  578. }
  579. tests := []struct {
  580. sm *raft
  581. state StateType
  582. term uint64
  583. raftLog *raftLog
  584. }{
  585. {a, StateFollower, 2, wlog},
  586. {b, StateFollower, 2, wlog},
  587. {c, StateFollower, 2, newLog(NewMemoryStorage(), raftLogger)},
  588. }
  589. for i, tt := range tests {
  590. if g := tt.sm.state; g != tt.state {
  591. t.Errorf("#%d: state = %s, want %s", i, g, tt.state)
  592. }
  593. if g := tt.sm.Term; g != tt.term {
  594. t.Errorf("#%d: term = %d, want %d", i, g, tt.term)
  595. }
  596. base := ltoa(tt.raftLog)
  597. if sm, ok := nt.peers[1+uint64(i)].(*raft); ok {
  598. l := ltoa(sm.raftLog)
  599. if g := diffu(base, l); g != "" {
  600. t.Errorf("#%d: diff:\n%s", i, g)
  601. }
  602. } else {
  603. t.Logf("#%d: empty log", i)
  604. }
  605. }
  606. }
  607. func TestDuelingPreCandidates(t *testing.T) {
  608. cfgA := newTestConfig(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  609. cfgB := newTestConfig(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  610. cfgC := newTestConfig(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  611. cfgA.PreVote = true
  612. cfgB.PreVote = true
  613. cfgC.PreVote = true
  614. a := newRaft(cfgA)
  615. b := newRaft(cfgB)
  616. c := newRaft(cfgC)
  617. nt := newNetwork(a, b, c)
  618. nt.cut(1, 3)
  619. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  620. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  621. // 1 becomes leader since it receives votes from 1 and 2
  622. sm := nt.peers[1].(*raft)
  623. if sm.state != StateLeader {
  624. t.Errorf("state = %s, want %s", sm.state, StateLeader)
  625. }
  626. // 3 campaigns then reverts to follower when its PreVote is rejected
  627. sm = nt.peers[3].(*raft)
  628. if sm.state != StateFollower {
  629. t.Errorf("state = %s, want %s", sm.state, StateFollower)
  630. }
  631. nt.recover()
  632. // Candidate 3 now increases its term and tries to vote again.
  633. // With PreVote, it does not disrupt the leader.
  634. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  635. wlog := &raftLog{
  636. storage: &MemoryStorage{ents: []pb.Entry{{}, {Data: nil, Term: 1, Index: 1}}},
  637. committed: 1,
  638. unstable: unstable{offset: 2},
  639. }
  640. tests := []struct {
  641. sm *raft
  642. state StateType
  643. term uint64
  644. raftLog *raftLog
  645. }{
  646. {a, StateLeader, 1, wlog},
  647. {b, StateFollower, 1, wlog},
  648. {c, StateFollower, 1, newLog(NewMemoryStorage(), raftLogger)},
  649. }
  650. for i, tt := range tests {
  651. if g := tt.sm.state; g != tt.state {
  652. t.Errorf("#%d: state = %s, want %s", i, g, tt.state)
  653. }
  654. if g := tt.sm.Term; g != tt.term {
  655. t.Errorf("#%d: term = %d, want %d", i, g, tt.term)
  656. }
  657. base := ltoa(tt.raftLog)
  658. if sm, ok := nt.peers[1+uint64(i)].(*raft); ok {
  659. l := ltoa(sm.raftLog)
  660. if g := diffu(base, l); g != "" {
  661. t.Errorf("#%d: diff:\n%s", i, g)
  662. }
  663. } else {
  664. t.Logf("#%d: empty log", i)
  665. }
  666. }
  667. }
  668. func TestCandidateConcede(t *testing.T) {
  669. tt := newNetwork(nil, nil, nil)
  670. tt.isolate(1)
  671. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  672. tt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  673. // heal the partition
  674. tt.recover()
  675. // send heartbeat; reset wait
  676. tt.send(pb.Message{From: 3, To: 3, Type: pb.MsgBeat})
  677. data := []byte("force follower")
  678. // send a proposal to 3 to flush out a MsgApp to 1
  679. tt.send(pb.Message{From: 3, To: 3, Type: pb.MsgProp, Entries: []pb.Entry{{Data: data}}})
  680. // send heartbeat; flush out commit
  681. tt.send(pb.Message{From: 3, To: 3, Type: pb.MsgBeat})
  682. a := tt.peers[1].(*raft)
  683. if g := a.state; g != StateFollower {
  684. t.Errorf("state = %s, want %s", g, StateFollower)
  685. }
  686. if g := a.Term; g != 1 {
  687. t.Errorf("term = %d, want %d", g, 1)
  688. }
  689. wantLog := ltoa(&raftLog{
  690. storage: &MemoryStorage{
  691. ents: []pb.Entry{{}, {Data: nil, Term: 1, Index: 1}, {Term: 1, Index: 2, Data: data}},
  692. },
  693. unstable: unstable{offset: 3},
  694. committed: 2,
  695. })
  696. for i, p := range tt.peers {
  697. if sm, ok := p.(*raft); ok {
  698. l := ltoa(sm.raftLog)
  699. if g := diffu(wantLog, l); g != "" {
  700. t.Errorf("#%d: diff:\n%s", i, g)
  701. }
  702. } else {
  703. t.Logf("#%d: empty log", i)
  704. }
  705. }
  706. }
  707. func TestSingleNodeCandidate(t *testing.T) {
  708. tt := newNetwork(nil)
  709. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  710. sm := tt.peers[1].(*raft)
  711. if sm.state != StateLeader {
  712. t.Errorf("state = %d, want %d", sm.state, StateLeader)
  713. }
  714. }
  715. func TestSingleNodePreCandidate(t *testing.T) {
  716. tt := newNetworkWithConfig(preVoteConfig, nil)
  717. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  718. sm := tt.peers[1].(*raft)
  719. if sm.state != StateLeader {
  720. t.Errorf("state = %d, want %d", sm.state, StateLeader)
  721. }
  722. }
  723. func TestOldMessages(t *testing.T) {
  724. tt := newNetwork(nil, nil, nil)
  725. // make 0 leader @ term 3
  726. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  727. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  728. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  729. // pretend we're an old leader trying to make progress; this entry is expected to be ignored.
  730. tt.send(pb.Message{From: 2, To: 1, Type: pb.MsgApp, Term: 2, Entries: []pb.Entry{{Index: 3, Term: 2}}})
  731. // commit a new entry
  732. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  733. ilog := &raftLog{
  734. storage: &MemoryStorage{
  735. ents: []pb.Entry{
  736. {}, {Data: nil, Term: 1, Index: 1},
  737. {Data: nil, Term: 2, Index: 2}, {Data: nil, Term: 3, Index: 3},
  738. {Data: []byte("somedata"), Term: 3, Index: 4},
  739. },
  740. },
  741. unstable: unstable{offset: 5},
  742. committed: 4,
  743. }
  744. base := ltoa(ilog)
  745. for i, p := range tt.peers {
  746. if sm, ok := p.(*raft); ok {
  747. l := ltoa(sm.raftLog)
  748. if g := diffu(base, l); g != "" {
  749. t.Errorf("#%d: diff:\n%s", i, g)
  750. }
  751. } else {
  752. t.Logf("#%d: empty log", i)
  753. }
  754. }
  755. }
  756. // TestOldMessagesReply - optimization - reply with new term.
  757. func TestProposal(t *testing.T) {
  758. tests := []struct {
  759. *network
  760. success bool
  761. }{
  762. {newNetwork(nil, nil, nil), true},
  763. {newNetwork(nil, nil, nopStepper), true},
  764. {newNetwork(nil, nopStepper, nopStepper), false},
  765. {newNetwork(nil, nopStepper, nopStepper, nil), false},
  766. {newNetwork(nil, nopStepper, nopStepper, nil, nil), true},
  767. }
  768. for j, tt := range tests {
  769. send := func(m pb.Message) {
  770. defer func() {
  771. // only recover is we expect it to panic so
  772. // panics we don't expect go up.
  773. if !tt.success {
  774. e := recover()
  775. if e != nil {
  776. t.Logf("#%d: err: %s", j, e)
  777. }
  778. }
  779. }()
  780. tt.send(m)
  781. }
  782. data := []byte("somedata")
  783. // promote 0 the leader
  784. send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  785. send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: data}}})
  786. wantLog := newLog(NewMemoryStorage(), raftLogger)
  787. if tt.success {
  788. wantLog = &raftLog{
  789. storage: &MemoryStorage{
  790. ents: []pb.Entry{{}, {Data: nil, Term: 1, Index: 1}, {Term: 1, Index: 2, Data: data}},
  791. },
  792. unstable: unstable{offset: 3},
  793. committed: 2}
  794. }
  795. base := ltoa(wantLog)
  796. for i, p := range tt.peers {
  797. if sm, ok := p.(*raft); ok {
  798. l := ltoa(sm.raftLog)
  799. if g := diffu(base, l); g != "" {
  800. t.Errorf("#%d: diff:\n%s", i, g)
  801. }
  802. } else {
  803. t.Logf("#%d: empty log", i)
  804. }
  805. }
  806. sm := tt.network.peers[1].(*raft)
  807. if g := sm.Term; g != 1 {
  808. t.Errorf("#%d: term = %d, want %d", j, g, 1)
  809. }
  810. }
  811. }
  812. func TestProposalByProxy(t *testing.T) {
  813. data := []byte("somedata")
  814. tests := []*network{
  815. newNetwork(nil, nil, nil),
  816. newNetwork(nil, nil, nopStepper),
  817. }
  818. for j, tt := range tests {
  819. // promote 0 the leader
  820. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  821. // propose via follower
  822. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  823. wantLog := &raftLog{
  824. storage: &MemoryStorage{
  825. ents: []pb.Entry{{}, {Data: nil, Term: 1, Index: 1}, {Term: 1, Data: data, Index: 2}},
  826. },
  827. unstable: unstable{offset: 3},
  828. committed: 2}
  829. base := ltoa(wantLog)
  830. for i, p := range tt.peers {
  831. if sm, ok := p.(*raft); ok {
  832. l := ltoa(sm.raftLog)
  833. if g := diffu(base, l); g != "" {
  834. t.Errorf("#%d: diff:\n%s", i, g)
  835. }
  836. } else {
  837. t.Logf("#%d: empty log", i)
  838. }
  839. }
  840. sm := tt.peers[1].(*raft)
  841. if g := sm.Term; g != 1 {
  842. t.Errorf("#%d: term = %d, want %d", j, g, 1)
  843. }
  844. }
  845. }
  846. func TestCommit(t *testing.T) {
  847. tests := []struct {
  848. matches []uint64
  849. logs []pb.Entry
  850. smTerm uint64
  851. w uint64
  852. }{
  853. // single
  854. {[]uint64{1}, []pb.Entry{{Index: 1, Term: 1}}, 1, 1},
  855. {[]uint64{1}, []pb.Entry{{Index: 1, Term: 1}}, 2, 0},
  856. {[]uint64{2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 2, 2},
  857. {[]uint64{1}, []pb.Entry{{Index: 1, Term: 2}}, 2, 1},
  858. // odd
  859. {[]uint64{2, 1, 1}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 1, 1},
  860. {[]uint64{2, 1, 1}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}}, 2, 0},
  861. {[]uint64{2, 1, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 2, 2},
  862. {[]uint64{2, 1, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}}, 2, 0},
  863. // even
  864. {[]uint64{2, 1, 1, 1}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 1, 1},
  865. {[]uint64{2, 1, 1, 1}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}}, 2, 0},
  866. {[]uint64{2, 1, 1, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 1, 1},
  867. {[]uint64{2, 1, 1, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}}, 2, 0},
  868. {[]uint64{2, 1, 2, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 2, 2},
  869. {[]uint64{2, 1, 2, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}}, 2, 0},
  870. }
  871. for i, tt := range tests {
  872. storage := NewMemoryStorage()
  873. storage.Append(tt.logs)
  874. storage.hardState = pb.HardState{Term: tt.smTerm}
  875. sm := newTestRaft(1, []uint64{1}, 5, 1, storage)
  876. for j := 0; j < len(tt.matches); j++ {
  877. sm.setProgress(uint64(j)+1, tt.matches[j], tt.matches[j]+1)
  878. }
  879. sm.maybeCommit()
  880. if g := sm.raftLog.committed; g != tt.w {
  881. t.Errorf("#%d: committed = %d, want %d", i, g, tt.w)
  882. }
  883. }
  884. }
  885. func TestPastElectionTimeout(t *testing.T) {
  886. tests := []struct {
  887. elapse int
  888. wprobability float64
  889. round bool
  890. }{
  891. {5, 0, false},
  892. {10, 0.1, true},
  893. {13, 0.4, true},
  894. {15, 0.6, true},
  895. {18, 0.9, true},
  896. {20, 1, false},
  897. }
  898. for i, tt := range tests {
  899. sm := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  900. sm.electionElapsed = tt.elapse
  901. c := 0
  902. for j := 0; j < 10000; j++ {
  903. sm.resetRandomizedElectionTimeout()
  904. if sm.pastElectionTimeout() {
  905. c++
  906. }
  907. }
  908. got := float64(c) / 10000.0
  909. if tt.round {
  910. got = math.Floor(got*10+0.5) / 10.0
  911. }
  912. if got != tt.wprobability {
  913. t.Errorf("#%d: probability = %v, want %v", i, got, tt.wprobability)
  914. }
  915. }
  916. }
  917. // ensure that the Step function ignores the message from old term and does not pass it to the
  918. // actual stepX function.
  919. func TestStepIgnoreOldTermMsg(t *testing.T) {
  920. called := false
  921. fakeStep := func(r *raft, m pb.Message) {
  922. called = true
  923. }
  924. sm := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  925. sm.step = fakeStep
  926. sm.Term = 2
  927. sm.Step(pb.Message{Type: pb.MsgApp, Term: sm.Term - 1})
  928. if called {
  929. t.Errorf("stepFunc called = %v , want %v", called, false)
  930. }
  931. }
  932. // TestHandleMsgApp ensures:
  933. // 1. Reply false if log doesn’t contain an entry at prevLogIndex whose term matches prevLogTerm.
  934. // 2. If an existing entry conflicts with a new one (same index but different terms),
  935. // delete the existing entry and all that follow it; append any new entries not already in the log.
  936. // 3. If leaderCommit > commitIndex, set commitIndex = min(leaderCommit, index of last new entry).
  937. func TestHandleMsgApp(t *testing.T) {
  938. tests := []struct {
  939. m pb.Message
  940. wIndex uint64
  941. wCommit uint64
  942. wReject bool
  943. }{
  944. // Ensure 1
  945. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 3, Index: 2, Commit: 3}, 2, 0, true}, // previous log mismatch
  946. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 3, Index: 3, Commit: 3}, 2, 0, true}, // previous log non-exist
  947. // Ensure 2
  948. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 1, Index: 1, Commit: 1}, 2, 1, false},
  949. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 0, Index: 0, Commit: 1, Entries: []pb.Entry{{Index: 1, Term: 2}}}, 1, 1, false},
  950. {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},
  951. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 2, Index: 2, Commit: 4, Entries: []pb.Entry{{Index: 3, Term: 2}}}, 3, 3, false},
  952. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 1, Index: 1, Commit: 4, Entries: []pb.Entry{{Index: 2, Term: 2}}}, 2, 2, false},
  953. // Ensure 3
  954. {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
  955. {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
  956. {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
  957. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 2, Index: 2, Commit: 4}, 2, 2, false}, // commit up to log.last()
  958. }
  959. for i, tt := range tests {
  960. storage := NewMemoryStorage()
  961. storage.Append([]pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}})
  962. sm := newTestRaft(1, []uint64{1}, 10, 1, storage)
  963. sm.becomeFollower(2, None)
  964. sm.handleAppendEntries(tt.m)
  965. if sm.raftLog.lastIndex() != tt.wIndex {
  966. t.Errorf("#%d: lastIndex = %d, want %d", i, sm.raftLog.lastIndex(), tt.wIndex)
  967. }
  968. if sm.raftLog.committed != tt.wCommit {
  969. t.Errorf("#%d: committed = %d, want %d", i, sm.raftLog.committed, tt.wCommit)
  970. }
  971. m := sm.readMessages()
  972. if len(m) != 1 {
  973. t.Fatalf("#%d: msg = nil, want 1", i)
  974. }
  975. if m[0].Reject != tt.wReject {
  976. t.Errorf("#%d: reject = %v, want %v", i, m[0].Reject, tt.wReject)
  977. }
  978. }
  979. }
  980. // TestHandleHeartbeat ensures that the follower commits to the commit in the message.
  981. func TestHandleHeartbeat(t *testing.T) {
  982. commit := uint64(2)
  983. tests := []struct {
  984. m pb.Message
  985. wCommit uint64
  986. }{
  987. {pb.Message{From: 2, To: 1, Type: pb.MsgHeartbeat, Term: 2, Commit: commit + 1}, commit + 1},
  988. {pb.Message{From: 2, To: 1, Type: pb.MsgHeartbeat, Term: 2, Commit: commit - 1}, commit}, // do not decrease commit
  989. }
  990. for i, tt := range tests {
  991. storage := NewMemoryStorage()
  992. storage.Append([]pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}, {Index: 3, Term: 3}})
  993. sm := newTestRaft(1, []uint64{1, 2}, 5, 1, storage)
  994. sm.becomeFollower(2, 2)
  995. sm.raftLog.commitTo(commit)
  996. sm.handleHeartbeat(tt.m)
  997. if sm.raftLog.committed != tt.wCommit {
  998. t.Errorf("#%d: committed = %d, want %d", i, sm.raftLog.committed, tt.wCommit)
  999. }
  1000. m := sm.readMessages()
  1001. if len(m) != 1 {
  1002. t.Fatalf("#%d: msg = nil, want 1", i)
  1003. }
  1004. if m[0].Type != pb.MsgHeartbeatResp {
  1005. t.Errorf("#%d: type = %v, want MsgHeartbeatResp", i, m[0].Type)
  1006. }
  1007. }
  1008. }
  1009. // TestHandleHeartbeatResp ensures that we re-send log entries when we get a heartbeat response.
  1010. func TestHandleHeartbeatResp(t *testing.T) {
  1011. storage := NewMemoryStorage()
  1012. storage.Append([]pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}, {Index: 3, Term: 3}})
  1013. sm := newTestRaft(1, []uint64{1, 2}, 5, 1, storage)
  1014. sm.becomeCandidate()
  1015. sm.becomeLeader()
  1016. sm.raftLog.commitTo(sm.raftLog.lastIndex())
  1017. // A heartbeat response from a node that is behind; re-send MsgApp
  1018. sm.Step(pb.Message{From: 2, Type: pb.MsgHeartbeatResp})
  1019. msgs := sm.readMessages()
  1020. if len(msgs) != 1 {
  1021. t.Fatalf("len(msgs) = %d, want 1", len(msgs))
  1022. }
  1023. if msgs[0].Type != pb.MsgApp {
  1024. t.Errorf("type = %v, want MsgApp", msgs[0].Type)
  1025. }
  1026. // A second heartbeat response generates another MsgApp re-send
  1027. sm.Step(pb.Message{From: 2, Type: pb.MsgHeartbeatResp})
  1028. msgs = sm.readMessages()
  1029. if len(msgs) != 1 {
  1030. t.Fatalf("len(msgs) = %d, want 1", len(msgs))
  1031. }
  1032. if msgs[0].Type != pb.MsgApp {
  1033. t.Errorf("type = %v, want MsgApp", msgs[0].Type)
  1034. }
  1035. // Once we have an MsgAppResp, heartbeats no longer send MsgApp.
  1036. sm.Step(pb.Message{
  1037. From: 2,
  1038. Type: pb.MsgAppResp,
  1039. Index: msgs[0].Index + uint64(len(msgs[0].Entries)),
  1040. })
  1041. // Consume the message sent in response to MsgAppResp
  1042. sm.readMessages()
  1043. sm.Step(pb.Message{From: 2, Type: pb.MsgHeartbeatResp})
  1044. msgs = sm.readMessages()
  1045. if len(msgs) != 0 {
  1046. t.Fatalf("len(msgs) = %d, want 0: %+v", len(msgs), msgs)
  1047. }
  1048. }
  1049. // TestMsgAppRespWaitReset verifies the resume behavior of a leader
  1050. // MsgAppResp.
  1051. func TestMsgAppRespWaitReset(t *testing.T) {
  1052. sm := newTestRaft(1, []uint64{1, 2, 3}, 5, 1, NewMemoryStorage())
  1053. sm.becomeCandidate()
  1054. sm.becomeLeader()
  1055. // The new leader has just emitted a new Term 4 entry; consume those messages
  1056. // from the outgoing queue.
  1057. sm.bcastAppend()
  1058. sm.readMessages()
  1059. // Node 2 acks the first entry, making it committed.
  1060. sm.Step(pb.Message{
  1061. From: 2,
  1062. Type: pb.MsgAppResp,
  1063. Index: 1,
  1064. })
  1065. if sm.raftLog.committed != 1 {
  1066. t.Fatalf("expected committed to be 1, got %d", sm.raftLog.committed)
  1067. }
  1068. // Also consume the MsgApp messages that update Commit on the followers.
  1069. sm.readMessages()
  1070. // A new command is now proposed on node 1.
  1071. sm.Step(pb.Message{
  1072. From: 1,
  1073. Type: pb.MsgProp,
  1074. Entries: []pb.Entry{{}},
  1075. })
  1076. // The command is broadcast to all nodes not in the wait state.
  1077. // Node 2 left the wait state due to its MsgAppResp, but node 3 is still waiting.
  1078. msgs := sm.readMessages()
  1079. if len(msgs) != 1 {
  1080. t.Fatalf("expected 1 message, got %d: %+v", len(msgs), msgs)
  1081. }
  1082. if msgs[0].Type != pb.MsgApp || msgs[0].To != 2 {
  1083. t.Errorf("expected MsgApp to node 2, got %v to %d", msgs[0].Type, msgs[0].To)
  1084. }
  1085. if len(msgs[0].Entries) != 1 || msgs[0].Entries[0].Index != 2 {
  1086. t.Errorf("expected to send entry 2, but got %v", msgs[0].Entries)
  1087. }
  1088. // Now Node 3 acks the first entry. This releases the wait and entry 2 is sent.
  1089. sm.Step(pb.Message{
  1090. From: 3,
  1091. Type: pb.MsgAppResp,
  1092. Index: 1,
  1093. })
  1094. msgs = sm.readMessages()
  1095. if len(msgs) != 1 {
  1096. t.Fatalf("expected 1 message, got %d: %+v", len(msgs), msgs)
  1097. }
  1098. if msgs[0].Type != pb.MsgApp || msgs[0].To != 3 {
  1099. t.Errorf("expected MsgApp to node 3, got %v to %d", msgs[0].Type, msgs[0].To)
  1100. }
  1101. if len(msgs[0].Entries) != 1 || msgs[0].Entries[0].Index != 2 {
  1102. t.Errorf("expected to send entry 2, but got %v", msgs[0].Entries)
  1103. }
  1104. }
  1105. func TestRecvMsgVote(t *testing.T) {
  1106. testRecvMsgVote(t, pb.MsgVote)
  1107. }
  1108. func testRecvMsgPreVote(t *testing.T) {
  1109. testRecvMsgVote(t, pb.MsgPreVote)
  1110. }
  1111. func testRecvMsgVote(t *testing.T, msgType pb.MessageType) {
  1112. tests := []struct {
  1113. state StateType
  1114. i, term uint64
  1115. voteFor uint64
  1116. wreject bool
  1117. }{
  1118. {StateFollower, 0, 0, None, true},
  1119. {StateFollower, 0, 1, None, true},
  1120. {StateFollower, 0, 2, None, true},
  1121. {StateFollower, 0, 3, None, false},
  1122. {StateFollower, 1, 0, None, true},
  1123. {StateFollower, 1, 1, None, true},
  1124. {StateFollower, 1, 2, None, true},
  1125. {StateFollower, 1, 3, None, false},
  1126. {StateFollower, 2, 0, None, true},
  1127. {StateFollower, 2, 1, None, true},
  1128. {StateFollower, 2, 2, None, false},
  1129. {StateFollower, 2, 3, None, false},
  1130. {StateFollower, 3, 0, None, true},
  1131. {StateFollower, 3, 1, None, true},
  1132. {StateFollower, 3, 2, None, false},
  1133. {StateFollower, 3, 3, None, false},
  1134. {StateFollower, 3, 2, 2, false},
  1135. {StateFollower, 3, 2, 1, true},
  1136. {StateLeader, 3, 3, 1, true},
  1137. {StatePreCandidate, 3, 3, 1, true},
  1138. {StateCandidate, 3, 3, 1, true},
  1139. }
  1140. for i, tt := range tests {
  1141. sm := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  1142. sm.state = tt.state
  1143. switch tt.state {
  1144. case StateFollower:
  1145. sm.step = stepFollower
  1146. case StateCandidate, StatePreCandidate:
  1147. sm.step = stepCandidate
  1148. case StateLeader:
  1149. sm.step = stepLeader
  1150. }
  1151. sm.Vote = tt.voteFor
  1152. sm.raftLog = &raftLog{
  1153. storage: &MemoryStorage{ents: []pb.Entry{{}, {Index: 1, Term: 2}, {Index: 2, Term: 2}}},
  1154. unstable: unstable{offset: 3},
  1155. }
  1156. sm.Step(pb.Message{Type: msgType, From: 2, Index: tt.i, LogTerm: tt.term})
  1157. msgs := sm.readMessages()
  1158. if g := len(msgs); g != 1 {
  1159. t.Fatalf("#%d: len(msgs) = %d, want 1", i, g)
  1160. continue
  1161. }
  1162. if g := msgs[0].Type; g != voteRespMsgType(msgType) {
  1163. t.Errorf("#%d, m.Type = %v, want %v", i, g, voteRespMsgType(msgType))
  1164. }
  1165. if g := msgs[0].Reject; g != tt.wreject {
  1166. t.Errorf("#%d, m.Reject = %v, want %v", i, g, tt.wreject)
  1167. }
  1168. }
  1169. }
  1170. func TestStateTransition(t *testing.T) {
  1171. tests := []struct {
  1172. from StateType
  1173. to StateType
  1174. wallow bool
  1175. wterm uint64
  1176. wlead uint64
  1177. }{
  1178. {StateFollower, StateFollower, true, 1, None},
  1179. {StateFollower, StatePreCandidate, true, 0, None},
  1180. {StateFollower, StateCandidate, true, 1, None},
  1181. {StateFollower, StateLeader, false, 0, None},
  1182. {StatePreCandidate, StateFollower, true, 0, None},
  1183. {StatePreCandidate, StatePreCandidate, true, 0, None},
  1184. {StatePreCandidate, StateCandidate, true, 1, None},
  1185. {StatePreCandidate, StateLeader, true, 0, 1},
  1186. {StateCandidate, StateFollower, true, 0, None},
  1187. {StateCandidate, StatePreCandidate, true, 0, None},
  1188. {StateCandidate, StateCandidate, true, 1, None},
  1189. {StateCandidate, StateLeader, true, 0, 1},
  1190. {StateLeader, StateFollower, true, 1, None},
  1191. {StateLeader, StatePreCandidate, false, 0, None},
  1192. {StateLeader, StateCandidate, false, 1, None},
  1193. {StateLeader, StateLeader, true, 0, 1},
  1194. }
  1195. for i, tt := range tests {
  1196. func() {
  1197. defer func() {
  1198. if r := recover(); r != nil {
  1199. if tt.wallow {
  1200. t.Errorf("%d: allow = %v, want %v", i, false, true)
  1201. }
  1202. }
  1203. }()
  1204. sm := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  1205. sm.state = tt.from
  1206. switch tt.to {
  1207. case StateFollower:
  1208. sm.becomeFollower(tt.wterm, tt.wlead)
  1209. case StatePreCandidate:
  1210. sm.becomePreCandidate()
  1211. case StateCandidate:
  1212. sm.becomeCandidate()
  1213. case StateLeader:
  1214. sm.becomeLeader()
  1215. }
  1216. if sm.Term != tt.wterm {
  1217. t.Errorf("%d: term = %d, want %d", i, sm.Term, tt.wterm)
  1218. }
  1219. if sm.lead != tt.wlead {
  1220. t.Errorf("%d: lead = %d, want %d", i, sm.lead, tt.wlead)
  1221. }
  1222. }()
  1223. }
  1224. }
  1225. func TestAllServerStepdown(t *testing.T) {
  1226. tests := []struct {
  1227. state StateType
  1228. wstate StateType
  1229. wterm uint64
  1230. windex uint64
  1231. }{
  1232. {StateFollower, StateFollower, 3, 0},
  1233. {StatePreCandidate, StateFollower, 3, 0},
  1234. {StateCandidate, StateFollower, 3, 0},
  1235. {StateLeader, StateFollower, 3, 1},
  1236. }
  1237. tmsgTypes := [...]pb.MessageType{pb.MsgVote, pb.MsgApp}
  1238. tterm := uint64(3)
  1239. for i, tt := range tests {
  1240. sm := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1241. switch tt.state {
  1242. case StateFollower:
  1243. sm.becomeFollower(1, None)
  1244. case StateCandidate:
  1245. sm.becomeCandidate()
  1246. case StateLeader:
  1247. sm.becomeCandidate()
  1248. sm.becomeLeader()
  1249. }
  1250. for j, msgType := range tmsgTypes {
  1251. sm.Step(pb.Message{From: 2, Type: msgType, Term: tterm, LogTerm: tterm})
  1252. if sm.state != tt.wstate {
  1253. t.Errorf("#%d.%d state = %v , want %v", i, j, sm.state, tt.wstate)
  1254. }
  1255. if sm.Term != tt.wterm {
  1256. t.Errorf("#%d.%d term = %v , want %v", i, j, sm.Term, tt.wterm)
  1257. }
  1258. if uint64(sm.raftLog.lastIndex()) != tt.windex {
  1259. t.Errorf("#%d.%d index = %v , want %v", i, j, sm.raftLog.lastIndex(), tt.windex)
  1260. }
  1261. if uint64(len(sm.raftLog.allEntries())) != tt.windex {
  1262. t.Errorf("#%d.%d len(ents) = %v , want %v", i, j, len(sm.raftLog.allEntries()), tt.windex)
  1263. }
  1264. wlead := uint64(2)
  1265. if msgType == pb.MsgVote {
  1266. wlead = None
  1267. }
  1268. if sm.lead != wlead {
  1269. t.Errorf("#%d, sm.lead = %d, want %d", i, sm.lead, None)
  1270. }
  1271. }
  1272. }
  1273. }
  1274. func TestLeaderStepdownWhenQuorumActive(t *testing.T) {
  1275. sm := newTestRaft(1, []uint64{1, 2, 3}, 5, 1, NewMemoryStorage())
  1276. sm.checkQuorum = true
  1277. sm.becomeCandidate()
  1278. sm.becomeLeader()
  1279. for i := 0; i < sm.electionTimeout+1; i++ {
  1280. sm.Step(pb.Message{From: 2, Type: pb.MsgHeartbeatResp, Term: sm.Term})
  1281. sm.tick()
  1282. }
  1283. if sm.state != StateLeader {
  1284. t.Errorf("state = %v, want %v", sm.state, StateLeader)
  1285. }
  1286. }
  1287. func TestLeaderStepdownWhenQuorumLost(t *testing.T) {
  1288. sm := newTestRaft(1, []uint64{1, 2, 3}, 5, 1, NewMemoryStorage())
  1289. sm.checkQuorum = true
  1290. sm.becomeCandidate()
  1291. sm.becomeLeader()
  1292. for i := 0; i < sm.electionTimeout+1; i++ {
  1293. sm.tick()
  1294. }
  1295. if sm.state != StateFollower {
  1296. t.Errorf("state = %v, want %v", sm.state, StateFollower)
  1297. }
  1298. }
  1299. func TestLeaderSupersedingWithCheckQuorum(t *testing.T) {
  1300. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1301. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1302. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1303. a.checkQuorum = true
  1304. b.checkQuorum = true
  1305. c.checkQuorum = true
  1306. nt := newNetwork(a, b, c)
  1307. setRandomizedElectionTimeout(b, b.electionTimeout+1)
  1308. for i := 0; i < b.electionTimeout; i++ {
  1309. b.tick()
  1310. }
  1311. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1312. if a.state != StateLeader {
  1313. t.Errorf("state = %s, want %s", a.state, StateLeader)
  1314. }
  1315. if c.state != StateFollower {
  1316. t.Errorf("state = %s, want %s", c.state, StateFollower)
  1317. }
  1318. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  1319. // Peer b rejected c's vote since its electionElapsed had not reached to electionTimeout
  1320. if c.state != StateCandidate {
  1321. t.Errorf("state = %s, want %s", c.state, StateCandidate)
  1322. }
  1323. // Letting b's electionElapsed reach to electionTimeout
  1324. for i := 0; i < b.electionTimeout; i++ {
  1325. b.tick()
  1326. }
  1327. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  1328. if c.state != StateLeader {
  1329. t.Errorf("state = %s, want %s", c.state, StateLeader)
  1330. }
  1331. }
  1332. func TestLeaderElectionWithCheckQuorum(t *testing.T) {
  1333. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1334. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1335. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1336. a.checkQuorum = true
  1337. b.checkQuorum = true
  1338. c.checkQuorum = true
  1339. nt := newNetwork(a, b, c)
  1340. setRandomizedElectionTimeout(a, a.electionTimeout+1)
  1341. setRandomizedElectionTimeout(b, b.electionTimeout+2)
  1342. // Immediately after creation, votes are cast regardless of the
  1343. // election timeout.
  1344. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1345. if a.state != StateLeader {
  1346. t.Errorf("state = %s, want %s", a.state, StateLeader)
  1347. }
  1348. if c.state != StateFollower {
  1349. t.Errorf("state = %s, want %s", c.state, StateFollower)
  1350. }
  1351. // need to reset randomizedElectionTimeout larger than electionTimeout again,
  1352. // because the value might be reset to electionTimeout since the last state changes
  1353. setRandomizedElectionTimeout(a, a.electionTimeout+1)
  1354. setRandomizedElectionTimeout(b, b.electionTimeout+2)
  1355. for i := 0; i < a.electionTimeout; i++ {
  1356. a.tick()
  1357. }
  1358. for i := 0; i < b.electionTimeout; i++ {
  1359. b.tick()
  1360. }
  1361. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  1362. if a.state != StateFollower {
  1363. t.Errorf("state = %s, want %s", a.state, StateFollower)
  1364. }
  1365. if c.state != StateLeader {
  1366. t.Errorf("state = %s, want %s", c.state, StateLeader)
  1367. }
  1368. }
  1369. // TestFreeStuckCandidateWithCheckQuorum ensures that a candidate with a higher term
  1370. // can disrupt the leader even if the leader still "officially" holds the lease, The
  1371. // leader is expected to step down and adopt the candidate's term
  1372. func TestFreeStuckCandidateWithCheckQuorum(t *testing.T) {
  1373. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1374. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1375. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1376. a.checkQuorum = true
  1377. b.checkQuorum = true
  1378. c.checkQuorum = true
  1379. nt := newNetwork(a, b, c)
  1380. setRandomizedElectionTimeout(b, b.electionTimeout+1)
  1381. for i := 0; i < b.electionTimeout; i++ {
  1382. b.tick()
  1383. }
  1384. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1385. nt.isolate(1)
  1386. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  1387. if b.state != StateFollower {
  1388. t.Errorf("state = %s, want %s", b.state, StateFollower)
  1389. }
  1390. if c.state != StateCandidate {
  1391. t.Errorf("state = %s, want %s", c.state, StateCandidate)
  1392. }
  1393. if c.Term != b.Term+1 {
  1394. t.Errorf("term = %d, want %d", c.Term, b.Term+1)
  1395. }
  1396. // Vote again for safety
  1397. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  1398. if b.state != StateFollower {
  1399. t.Errorf("state = %s, want %s", b.state, StateFollower)
  1400. }
  1401. if c.state != StateCandidate {
  1402. t.Errorf("state = %s, want %s", c.state, StateCandidate)
  1403. }
  1404. if c.Term != b.Term+2 {
  1405. t.Errorf("term = %d, want %d", c.Term, b.Term+2)
  1406. }
  1407. nt.recover()
  1408. nt.send(pb.Message{From: 1, To: 3, Type: pb.MsgHeartbeat, Term: a.Term})
  1409. // Disrupt the leader so that the stuck peer is freed
  1410. if a.state != StateFollower {
  1411. t.Errorf("state = %s, want %s", a.state, StateFollower)
  1412. }
  1413. if c.Term != a.Term {
  1414. t.Errorf("term = %d, want %d", c.Term, a.Term)
  1415. }
  1416. }
  1417. func TestNonPromotableVoterWithCheckQuorum(t *testing.T) {
  1418. a := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  1419. b := newTestRaft(2, []uint64{1}, 10, 1, NewMemoryStorage())
  1420. a.checkQuorum = true
  1421. b.checkQuorum = true
  1422. nt := newNetwork(a, b)
  1423. setRandomizedElectionTimeout(b, b.electionTimeout+1)
  1424. // Need to remove 2 again to make it a non-promotable node since newNetwork overwritten some internal states
  1425. b.delProgress(2)
  1426. if b.promotable() {
  1427. t.Fatalf("promotable = %v, want false", b.promotable())
  1428. }
  1429. for i := 0; i < b.electionTimeout; i++ {
  1430. b.tick()
  1431. }
  1432. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1433. if a.state != StateLeader {
  1434. t.Errorf("state = %s, want %s", a.state, StateLeader)
  1435. }
  1436. if b.state != StateFollower {
  1437. t.Errorf("state = %s, want %s", b.state, StateFollower)
  1438. }
  1439. if b.lead != 1 {
  1440. t.Errorf("lead = %d, want 1", b.lead)
  1441. }
  1442. }
  1443. func TestReadOnlyOptionSafe(t *testing.T) {
  1444. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1445. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1446. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1447. nt := newNetwork(a, b, c)
  1448. setRandomizedElectionTimeout(b, b.electionTimeout+1)
  1449. for i := 0; i < b.electionTimeout; i++ {
  1450. b.tick()
  1451. }
  1452. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1453. if a.state != StateLeader {
  1454. t.Fatalf("state = %s, want %s", a.state, StateLeader)
  1455. }
  1456. tests := []struct {
  1457. sm *raft
  1458. proposals int
  1459. wri uint64
  1460. wctx []byte
  1461. }{
  1462. {a, 10, 11, []byte("ctx1")},
  1463. {b, 10, 21, []byte("ctx2")},
  1464. {c, 10, 31, []byte("ctx3")},
  1465. {a, 10, 41, []byte("ctx4")},
  1466. {b, 10, 51, []byte("ctx5")},
  1467. {c, 10, 61, []byte("ctx6")},
  1468. }
  1469. for i, tt := range tests {
  1470. for j := 0; j < tt.proposals; j++ {
  1471. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  1472. }
  1473. nt.send(pb.Message{From: tt.sm.id, To: tt.sm.id, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: tt.wctx}}})
  1474. r := tt.sm
  1475. if len(r.readStates) == 0 {
  1476. t.Errorf("#%d: len(readStates) = 0, want non-zero", i)
  1477. }
  1478. rs := r.readStates[0]
  1479. if rs.Index != tt.wri {
  1480. t.Errorf("#%d: readIndex = %d, want %d", i, rs.Index, tt.wri)
  1481. }
  1482. if !bytes.Equal(rs.RequestCtx, tt.wctx) {
  1483. t.Errorf("#%d: requestCtx = %v, want %v", i, rs.RequestCtx, tt.wctx)
  1484. }
  1485. r.readStates = nil
  1486. }
  1487. }
  1488. func TestReadOnlyOptionLease(t *testing.T) {
  1489. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1490. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1491. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1492. a.readOnly.option = ReadOnlyLeaseBased
  1493. b.readOnly.option = ReadOnlyLeaseBased
  1494. c.readOnly.option = ReadOnlyLeaseBased
  1495. a.checkQuorum = true
  1496. b.checkQuorum = true
  1497. c.checkQuorum = true
  1498. nt := newNetwork(a, b, c)
  1499. setRandomizedElectionTimeout(b, b.electionTimeout+1)
  1500. for i := 0; i < b.electionTimeout; i++ {
  1501. b.tick()
  1502. }
  1503. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1504. if a.state != StateLeader {
  1505. t.Fatalf("state = %s, want %s", a.state, StateLeader)
  1506. }
  1507. tests := []struct {
  1508. sm *raft
  1509. proposals int
  1510. wri uint64
  1511. wctx []byte
  1512. }{
  1513. {a, 10, 11, []byte("ctx1")},
  1514. {b, 10, 21, []byte("ctx2")},
  1515. {c, 10, 31, []byte("ctx3")},
  1516. {a, 10, 41, []byte("ctx4")},
  1517. {b, 10, 51, []byte("ctx5")},
  1518. {c, 10, 61, []byte("ctx6")},
  1519. }
  1520. for i, tt := range tests {
  1521. for j := 0; j < tt.proposals; j++ {
  1522. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  1523. }
  1524. nt.send(pb.Message{From: tt.sm.id, To: tt.sm.id, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: tt.wctx}}})
  1525. r := tt.sm
  1526. rs := r.readStates[0]
  1527. if rs.Index != tt.wri {
  1528. t.Errorf("#%d: readIndex = %d, want %d", i, rs.Index, tt.wri)
  1529. }
  1530. if !bytes.Equal(rs.RequestCtx, tt.wctx) {
  1531. t.Errorf("#%d: requestCtx = %v, want %v", i, rs.RequestCtx, tt.wctx)
  1532. }
  1533. r.readStates = nil
  1534. }
  1535. }
  1536. func TestReadOnlyOptionLeaseWithoutCheckQuorum(t *testing.T) {
  1537. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1538. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1539. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1540. a.readOnly.option = ReadOnlyLeaseBased
  1541. b.readOnly.option = ReadOnlyLeaseBased
  1542. c.readOnly.option = ReadOnlyLeaseBased
  1543. nt := newNetwork(a, b, c)
  1544. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1545. ctx := []byte("ctx1")
  1546. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: ctx}}})
  1547. rs := b.readStates[0]
  1548. if rs.Index != None {
  1549. t.Errorf("readIndex = %d, want %d", rs.Index, None)
  1550. }
  1551. if !bytes.Equal(rs.RequestCtx, ctx) {
  1552. t.Errorf("requestCtx = %v, want %v", rs.RequestCtx, ctx)
  1553. }
  1554. }
  1555. func TestLeaderAppResp(t *testing.T) {
  1556. // initial progress: match = 0; next = 3
  1557. tests := []struct {
  1558. index uint64
  1559. reject bool
  1560. // progress
  1561. wmatch uint64
  1562. wnext uint64
  1563. // message
  1564. wmsgNum int
  1565. windex uint64
  1566. wcommitted uint64
  1567. }{
  1568. {3, true, 0, 3, 0, 0, 0}, // stale resp; no replies
  1569. {2, true, 0, 2, 1, 1, 0}, // denied resp; leader does not commit; decrease next and send probing msg
  1570. {2, false, 2, 4, 2, 2, 2}, // accept resp; leader commits; broadcast with commit index
  1571. {0, false, 0, 3, 0, 0, 0}, // ignore heartbeat replies
  1572. }
  1573. for i, tt := range tests {
  1574. // sm term is 1 after it becomes the leader.
  1575. // thus the last log term must be 1 to be committed.
  1576. sm := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1577. sm.raftLog = &raftLog{
  1578. storage: &MemoryStorage{ents: []pb.Entry{{}, {Index: 1, Term: 0}, {Index: 2, Term: 1}}},
  1579. unstable: unstable{offset: 3},
  1580. }
  1581. sm.becomeCandidate()
  1582. sm.becomeLeader()
  1583. sm.readMessages()
  1584. sm.Step(pb.Message{From: 2, Type: pb.MsgAppResp, Index: tt.index, Term: sm.Term, Reject: tt.reject, RejectHint: tt.index})
  1585. p := sm.prs[2]
  1586. if p.Match != tt.wmatch {
  1587. t.Errorf("#%d match = %d, want %d", i, p.Match, tt.wmatch)
  1588. }
  1589. if p.Next != tt.wnext {
  1590. t.Errorf("#%d next = %d, want %d", i, p.Next, tt.wnext)
  1591. }
  1592. msgs := sm.readMessages()
  1593. if len(msgs) != tt.wmsgNum {
  1594. t.Errorf("#%d msgNum = %d, want %d", i, len(msgs), tt.wmsgNum)
  1595. }
  1596. for j, msg := range msgs {
  1597. if msg.Index != tt.windex {
  1598. t.Errorf("#%d.%d index = %d, want %d", i, j, msg.Index, tt.windex)
  1599. }
  1600. if msg.Commit != tt.wcommitted {
  1601. t.Errorf("#%d.%d commit = %d, want %d", i, j, msg.Commit, tt.wcommitted)
  1602. }
  1603. }
  1604. }
  1605. }
  1606. // When the leader receives a heartbeat tick, it should
  1607. // send a MsgApp with m.Index = 0, m.LogTerm=0 and empty entries.
  1608. func TestBcastBeat(t *testing.T) {
  1609. offset := uint64(1000)
  1610. // make a state machine with log.offset = 1000
  1611. s := pb.Snapshot{
  1612. Metadata: pb.SnapshotMetadata{
  1613. Index: offset,
  1614. Term: 1,
  1615. ConfState: pb.ConfState{Nodes: []uint64{1, 2, 3}},
  1616. },
  1617. }
  1618. storage := NewMemoryStorage()
  1619. storage.ApplySnapshot(s)
  1620. sm := newTestRaft(1, nil, 10, 1, storage)
  1621. sm.Term = 1
  1622. sm.becomeCandidate()
  1623. sm.becomeLeader()
  1624. for i := 0; i < 10; i++ {
  1625. sm.appendEntry(pb.Entry{Index: uint64(i) + 1})
  1626. }
  1627. // slow follower
  1628. sm.prs[2].Match, sm.prs[2].Next = 5, 6
  1629. // normal follower
  1630. sm.prs[3].Match, sm.prs[3].Next = sm.raftLog.lastIndex(), sm.raftLog.lastIndex()+1
  1631. sm.Step(pb.Message{Type: pb.MsgBeat})
  1632. msgs := sm.readMessages()
  1633. if len(msgs) != 2 {
  1634. t.Fatalf("len(msgs) = %v, want 2", len(msgs))
  1635. }
  1636. wantCommitMap := map[uint64]uint64{
  1637. 2: min(sm.raftLog.committed, sm.prs[2].Match),
  1638. 3: min(sm.raftLog.committed, sm.prs[3].Match),
  1639. }
  1640. for i, m := range msgs {
  1641. if m.Type != pb.MsgHeartbeat {
  1642. t.Fatalf("#%d: type = %v, want = %v", i, m.Type, pb.MsgHeartbeat)
  1643. }
  1644. if m.Index != 0 {
  1645. t.Fatalf("#%d: prevIndex = %d, want %d", i, m.Index, 0)
  1646. }
  1647. if m.LogTerm != 0 {
  1648. t.Fatalf("#%d: prevTerm = %d, want %d", i, m.LogTerm, 0)
  1649. }
  1650. if wantCommitMap[m.To] == 0 {
  1651. t.Fatalf("#%d: unexpected to %d", i, m.To)
  1652. } else {
  1653. if m.Commit != wantCommitMap[m.To] {
  1654. t.Fatalf("#%d: commit = %d, want %d", i, m.Commit, wantCommitMap[m.To])
  1655. }
  1656. delete(wantCommitMap, m.To)
  1657. }
  1658. if len(m.Entries) != 0 {
  1659. t.Fatalf("#%d: len(entries) = %d, want 0", i, len(m.Entries))
  1660. }
  1661. }
  1662. }
  1663. // tests the output of the state machine when receiving MsgBeat
  1664. func TestRecvMsgBeat(t *testing.T) {
  1665. tests := []struct {
  1666. state StateType
  1667. wMsg int
  1668. }{
  1669. {StateLeader, 2},
  1670. // candidate and follower should ignore MsgBeat
  1671. {StateCandidate, 0},
  1672. {StateFollower, 0},
  1673. }
  1674. for i, tt := range tests {
  1675. sm := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1676. sm.raftLog = &raftLog{storage: &MemoryStorage{ents: []pb.Entry{{}, {Index: 1, Term: 0}, {Index: 2, Term: 1}}}}
  1677. sm.Term = 1
  1678. sm.state = tt.state
  1679. switch tt.state {
  1680. case StateFollower:
  1681. sm.step = stepFollower
  1682. case StateCandidate:
  1683. sm.step = stepCandidate
  1684. case StateLeader:
  1685. sm.step = stepLeader
  1686. }
  1687. sm.Step(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  1688. msgs := sm.readMessages()
  1689. if len(msgs) != tt.wMsg {
  1690. t.Errorf("%d: len(msgs) = %d, want %d", i, len(msgs), tt.wMsg)
  1691. }
  1692. for _, m := range msgs {
  1693. if m.Type != pb.MsgHeartbeat {
  1694. t.Errorf("%d: msg.type = %v, want %v", i, m.Type, pb.MsgHeartbeat)
  1695. }
  1696. }
  1697. }
  1698. }
  1699. func TestLeaderIncreaseNext(t *testing.T) {
  1700. previousEnts := []pb.Entry{{Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3}}
  1701. tests := []struct {
  1702. // progress
  1703. state ProgressStateType
  1704. next uint64
  1705. wnext uint64
  1706. }{
  1707. // state replicate, optimistically increase next
  1708. // previous entries + noop entry + propose + 1
  1709. {ProgressStateReplicate, 2, uint64(len(previousEnts) + 1 + 1 + 1)},
  1710. // state probe, not optimistically increase next
  1711. {ProgressStateProbe, 2, 2},
  1712. }
  1713. for i, tt := range tests {
  1714. sm := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  1715. sm.raftLog.append(previousEnts...)
  1716. sm.becomeCandidate()
  1717. sm.becomeLeader()
  1718. sm.prs[2].State = tt.state
  1719. sm.prs[2].Next = tt.next
  1720. sm.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  1721. p := sm.prs[2]
  1722. if p.Next != tt.wnext {
  1723. t.Errorf("#%d next = %d, want %d", i, p.Next, tt.wnext)
  1724. }
  1725. }
  1726. }
  1727. func TestSendAppendForProgressProbe(t *testing.T) {
  1728. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  1729. r.becomeCandidate()
  1730. r.becomeLeader()
  1731. r.readMessages()
  1732. r.prs[2].becomeProbe()
  1733. // each round is a heartbeat
  1734. for i := 0; i < 3; i++ {
  1735. if i == 0 {
  1736. // we expect that raft will only send out one msgAPP on the first
  1737. // loop. After that, the follower is paused until a heartbeat response is
  1738. // received.
  1739. r.appendEntry(pb.Entry{Data: []byte("somedata")})
  1740. r.sendAppend(2)
  1741. msg := r.readMessages()
  1742. if len(msg) != 1 {
  1743. t.Errorf("len(msg) = %d, want %d", len(msg), 1)
  1744. }
  1745. if msg[0].Index != 0 {
  1746. t.Errorf("index = %d, want %d", msg[0].Index, 0)
  1747. }
  1748. }
  1749. if !r.prs[2].Paused {
  1750. t.Errorf("paused = %v, want true", r.prs[2].Paused)
  1751. }
  1752. for j := 0; j < 10; j++ {
  1753. r.appendEntry(pb.Entry{Data: []byte("somedata")})
  1754. r.sendAppend(2)
  1755. if l := len(r.readMessages()); l != 0 {
  1756. t.Errorf("len(msg) = %d, want %d", l, 0)
  1757. }
  1758. }
  1759. // do a heartbeat
  1760. for j := 0; j < r.heartbeatTimeout; j++ {
  1761. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  1762. }
  1763. if !r.prs[2].Paused {
  1764. t.Errorf("paused = %v, want true", r.prs[2].Paused)
  1765. }
  1766. // consume the heartbeat
  1767. msg := r.readMessages()
  1768. if len(msg) != 1 {
  1769. t.Errorf("len(msg) = %d, want %d", len(msg), 1)
  1770. }
  1771. if msg[0].Type != pb.MsgHeartbeat {
  1772. t.Errorf("type = %v, want %v", msg[0].Type, pb.MsgHeartbeat)
  1773. }
  1774. }
  1775. // a heartbeat response will allow another message to be sent
  1776. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgHeartbeatResp})
  1777. msg := r.readMessages()
  1778. if len(msg) != 1 {
  1779. t.Errorf("len(msg) = %d, want %d", len(msg), 1)
  1780. }
  1781. if msg[0].Index != 0 {
  1782. t.Errorf("index = %d, want %d", msg[0].Index, 0)
  1783. }
  1784. if !r.prs[2].Paused {
  1785. t.Errorf("paused = %v, want true", r.prs[2].Paused)
  1786. }
  1787. }
  1788. func TestSendAppendForProgressReplicate(t *testing.T) {
  1789. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  1790. r.becomeCandidate()
  1791. r.becomeLeader()
  1792. r.readMessages()
  1793. r.prs[2].becomeReplicate()
  1794. for i := 0; i < 10; i++ {
  1795. r.appendEntry(pb.Entry{Data: []byte("somedata")})
  1796. r.sendAppend(2)
  1797. msgs := r.readMessages()
  1798. if len(msgs) != 1 {
  1799. t.Errorf("len(msg) = %d, want %d", len(msgs), 1)
  1800. }
  1801. }
  1802. }
  1803. func TestSendAppendForProgressSnapshot(t *testing.T) {
  1804. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  1805. r.becomeCandidate()
  1806. r.becomeLeader()
  1807. r.readMessages()
  1808. r.prs[2].becomeSnapshot(10)
  1809. for i := 0; i < 10; i++ {
  1810. r.appendEntry(pb.Entry{Data: []byte("somedata")})
  1811. r.sendAppend(2)
  1812. msgs := r.readMessages()
  1813. if len(msgs) != 0 {
  1814. t.Errorf("len(msg) = %d, want %d", len(msgs), 0)
  1815. }
  1816. }
  1817. }
  1818. func TestRecvMsgUnreachable(t *testing.T) {
  1819. previousEnts := []pb.Entry{{Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3}}
  1820. s := NewMemoryStorage()
  1821. s.Append(previousEnts)
  1822. r := newTestRaft(1, []uint64{1, 2}, 10, 1, s)
  1823. r.becomeCandidate()
  1824. r.becomeLeader()
  1825. r.readMessages()
  1826. // set node 2 to state replicate
  1827. r.prs[2].Match = 3
  1828. r.prs[2].becomeReplicate()
  1829. r.prs[2].optimisticUpdate(5)
  1830. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgUnreachable})
  1831. if r.prs[2].State != ProgressStateProbe {
  1832. t.Errorf("state = %s, want %s", r.prs[2].State, ProgressStateProbe)
  1833. }
  1834. if wnext := r.prs[2].Match + 1; r.prs[2].Next != wnext {
  1835. t.Errorf("next = %d, want %d", r.prs[2].Next, wnext)
  1836. }
  1837. }
  1838. func TestRestore(t *testing.T) {
  1839. s := pb.Snapshot{
  1840. Metadata: pb.SnapshotMetadata{
  1841. Index: 11, // magic number
  1842. Term: 11, // magic number
  1843. ConfState: pb.ConfState{Nodes: []uint64{1, 2, 3}},
  1844. },
  1845. }
  1846. storage := NewMemoryStorage()
  1847. sm := newTestRaft(1, []uint64{1, 2}, 10, 1, storage)
  1848. if ok := sm.restore(s); !ok {
  1849. t.Fatal("restore fail, want succeed")
  1850. }
  1851. if sm.raftLog.lastIndex() != s.Metadata.Index {
  1852. t.Errorf("log.lastIndex = %d, want %d", sm.raftLog.lastIndex(), s.Metadata.Index)
  1853. }
  1854. if mustTerm(sm.raftLog.term(s.Metadata.Index)) != s.Metadata.Term {
  1855. t.Errorf("log.lastTerm = %d, want %d", mustTerm(sm.raftLog.term(s.Metadata.Index)), s.Metadata.Term)
  1856. }
  1857. sg := sm.nodes()
  1858. if !reflect.DeepEqual(sg, s.Metadata.ConfState.Nodes) {
  1859. t.Errorf("sm.Nodes = %+v, want %+v", sg, s.Metadata.ConfState.Nodes)
  1860. }
  1861. if ok := sm.restore(s); ok {
  1862. t.Fatal("restore succeed, want fail")
  1863. }
  1864. }
  1865. func TestRestoreIgnoreSnapshot(t *testing.T) {
  1866. previousEnts := []pb.Entry{{Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3}}
  1867. commit := uint64(1)
  1868. storage := NewMemoryStorage()
  1869. sm := newTestRaft(1, []uint64{1, 2}, 10, 1, storage)
  1870. sm.raftLog.append(previousEnts...)
  1871. sm.raftLog.commitTo(commit)
  1872. s := pb.Snapshot{
  1873. Metadata: pb.SnapshotMetadata{
  1874. Index: commit,
  1875. Term: 1,
  1876. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  1877. },
  1878. }
  1879. // ignore snapshot
  1880. if ok := sm.restore(s); ok {
  1881. t.Errorf("restore = %t, want %t", ok, false)
  1882. }
  1883. if sm.raftLog.committed != commit {
  1884. t.Errorf("commit = %d, want %d", sm.raftLog.committed, commit)
  1885. }
  1886. // ignore snapshot and fast forward commit
  1887. s.Metadata.Index = commit + 1
  1888. if ok := sm.restore(s); ok {
  1889. t.Errorf("restore = %t, want %t", ok, false)
  1890. }
  1891. if sm.raftLog.committed != commit+1 {
  1892. t.Errorf("commit = %d, want %d", sm.raftLog.committed, commit+1)
  1893. }
  1894. }
  1895. func TestProvideSnap(t *testing.T) {
  1896. // restore the state machine from a snapshot so it has a compacted log and a snapshot
  1897. s := pb.Snapshot{
  1898. Metadata: pb.SnapshotMetadata{
  1899. Index: 11, // magic number
  1900. Term: 11, // magic number
  1901. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  1902. },
  1903. }
  1904. storage := NewMemoryStorage()
  1905. sm := newTestRaft(1, []uint64{1}, 10, 1, storage)
  1906. sm.restore(s)
  1907. sm.becomeCandidate()
  1908. sm.becomeLeader()
  1909. // force set the next of node 2, so that node 2 needs a snapshot
  1910. sm.prs[2].Next = sm.raftLog.firstIndex()
  1911. sm.Step(pb.Message{From: 2, To: 1, Type: pb.MsgAppResp, Index: sm.prs[2].Next - 1, Reject: true})
  1912. msgs := sm.readMessages()
  1913. if len(msgs) != 1 {
  1914. t.Fatalf("len(msgs) = %d, want 1", len(msgs))
  1915. }
  1916. m := msgs[0]
  1917. if m.Type != pb.MsgSnap {
  1918. t.Errorf("m.Type = %v, want %v", m.Type, pb.MsgSnap)
  1919. }
  1920. }
  1921. func TestIgnoreProvidingSnap(t *testing.T) {
  1922. // restore the state machine from a snapshot so it has a compacted log and a snapshot
  1923. s := pb.Snapshot{
  1924. Metadata: pb.SnapshotMetadata{
  1925. Index: 11, // magic number
  1926. Term: 11, // magic number
  1927. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  1928. },
  1929. }
  1930. storage := NewMemoryStorage()
  1931. sm := newTestRaft(1, []uint64{1}, 10, 1, storage)
  1932. sm.restore(s)
  1933. sm.becomeCandidate()
  1934. sm.becomeLeader()
  1935. // force set the next of node 2, so that node 2 needs a snapshot
  1936. // change node 2 to be inactive, expect node 1 ignore sending snapshot to 2
  1937. sm.prs[2].Next = sm.raftLog.firstIndex() - 1
  1938. sm.prs[2].RecentActive = false
  1939. sm.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  1940. msgs := sm.readMessages()
  1941. if len(msgs) != 0 {
  1942. t.Errorf("len(msgs) = %d, want 0", len(msgs))
  1943. }
  1944. }
  1945. func TestRestoreFromSnapMsg(t *testing.T) {
  1946. s := pb.Snapshot{
  1947. Metadata: pb.SnapshotMetadata{
  1948. Index: 11, // magic number
  1949. Term: 11, // magic number
  1950. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  1951. },
  1952. }
  1953. m := pb.Message{Type: pb.MsgSnap, From: 1, Term: 2, Snapshot: s}
  1954. sm := newTestRaft(2, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  1955. sm.Step(m)
  1956. if sm.lead != uint64(1) {
  1957. t.Errorf("sm.lead = %d, want 1", sm.lead)
  1958. }
  1959. // TODO(bdarnell): what should this test?
  1960. }
  1961. func TestSlowNodeRestore(t *testing.T) {
  1962. nt := newNetwork(nil, nil, nil)
  1963. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1964. nt.isolate(3)
  1965. for j := 0; j <= 100; j++ {
  1966. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  1967. }
  1968. lead := nt.peers[1].(*raft)
  1969. nextEnts(lead, nt.storage[1])
  1970. nt.storage[1].CreateSnapshot(lead.raftLog.applied, &pb.ConfState{Nodes: lead.nodes()}, nil)
  1971. nt.storage[1].Compact(lead.raftLog.applied)
  1972. nt.recover()
  1973. // send heartbeats so that the leader can learn everyone is active.
  1974. // node 3 will only be considered as active when node 1 receives a reply from it.
  1975. for {
  1976. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  1977. if lead.prs[3].RecentActive {
  1978. break
  1979. }
  1980. }
  1981. // trigger a snapshot
  1982. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  1983. follower := nt.peers[3].(*raft)
  1984. // trigger a commit
  1985. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  1986. if follower.raftLog.committed != lead.raftLog.committed {
  1987. t.Errorf("follower.committed = %d, want %d", follower.raftLog.committed, lead.raftLog.committed)
  1988. }
  1989. }
  1990. // TestStepConfig tests that when raft step msgProp in EntryConfChange type,
  1991. // it appends the entry to log and sets pendingConf to be true.
  1992. func TestStepConfig(t *testing.T) {
  1993. // a raft that cannot make progress
  1994. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  1995. r.becomeCandidate()
  1996. r.becomeLeader()
  1997. index := r.raftLog.lastIndex()
  1998. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange}}})
  1999. if g := r.raftLog.lastIndex(); g != index+1 {
  2000. t.Errorf("index = %d, want %d", g, index+1)
  2001. }
  2002. if !r.pendingConf {
  2003. t.Errorf("pendingConf = %v, want true", r.pendingConf)
  2004. }
  2005. }
  2006. // TestStepIgnoreConfig tests that if raft step the second msgProp in
  2007. // EntryConfChange type when the first one is uncommitted, the node will set
  2008. // the proposal to noop and keep its original state.
  2009. func TestStepIgnoreConfig(t *testing.T) {
  2010. // a raft that cannot make progress
  2011. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2012. r.becomeCandidate()
  2013. r.becomeLeader()
  2014. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange}}})
  2015. index := r.raftLog.lastIndex()
  2016. pendingConf := r.pendingConf
  2017. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange}}})
  2018. wents := []pb.Entry{{Type: pb.EntryNormal, Term: 1, Index: 3, Data: nil}}
  2019. ents, err := r.raftLog.entries(index+1, noLimit)
  2020. if err != nil {
  2021. t.Fatalf("unexpected error %v", err)
  2022. }
  2023. if !reflect.DeepEqual(ents, wents) {
  2024. t.Errorf("ents = %+v, want %+v", ents, wents)
  2025. }
  2026. if r.pendingConf != pendingConf {
  2027. t.Errorf("pendingConf = %v, want %v", r.pendingConf, pendingConf)
  2028. }
  2029. }
  2030. // TestRecoverPendingConfig tests that new leader recovers its pendingConf flag
  2031. // based on uncommitted entries.
  2032. func TestRecoverPendingConfig(t *testing.T) {
  2033. tests := []struct {
  2034. entType pb.EntryType
  2035. wpending bool
  2036. }{
  2037. {pb.EntryNormal, false},
  2038. {pb.EntryConfChange, true},
  2039. }
  2040. for i, tt := range tests {
  2041. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2042. r.appendEntry(pb.Entry{Type: tt.entType})
  2043. r.becomeCandidate()
  2044. r.becomeLeader()
  2045. if r.pendingConf != tt.wpending {
  2046. t.Errorf("#%d: pendingConf = %v, want %v", i, r.pendingConf, tt.wpending)
  2047. }
  2048. }
  2049. }
  2050. // TestRecoverDoublePendingConfig tests that new leader will panic if
  2051. // there exist two uncommitted config entries.
  2052. func TestRecoverDoublePendingConfig(t *testing.T) {
  2053. func() {
  2054. defer func() {
  2055. if err := recover(); err == nil {
  2056. t.Errorf("expect panic, but nothing happens")
  2057. }
  2058. }()
  2059. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2060. r.appendEntry(pb.Entry{Type: pb.EntryConfChange})
  2061. r.appendEntry(pb.Entry{Type: pb.EntryConfChange})
  2062. r.becomeCandidate()
  2063. r.becomeLeader()
  2064. }()
  2065. }
  2066. // TestAddNode tests that addNode could update pendingConf and nodes correctly.
  2067. func TestAddNode(t *testing.T) {
  2068. r := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  2069. r.pendingConf = true
  2070. r.addNode(2)
  2071. if r.pendingConf {
  2072. t.Errorf("pendingConf = %v, want false", r.pendingConf)
  2073. }
  2074. nodes := r.nodes()
  2075. wnodes := []uint64{1, 2}
  2076. if !reflect.DeepEqual(nodes, wnodes) {
  2077. t.Errorf("nodes = %v, want %v", nodes, wnodes)
  2078. }
  2079. }
  2080. // TestRemoveNode tests that removeNode could update pendingConf, nodes and
  2081. // and removed list correctly.
  2082. func TestRemoveNode(t *testing.T) {
  2083. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2084. r.pendingConf = true
  2085. r.removeNode(2)
  2086. if r.pendingConf {
  2087. t.Errorf("pendingConf = %v, want false", r.pendingConf)
  2088. }
  2089. w := []uint64{1}
  2090. if g := r.nodes(); !reflect.DeepEqual(g, w) {
  2091. t.Errorf("nodes = %v, want %v", g, w)
  2092. }
  2093. // remove all nodes from cluster
  2094. r.removeNode(1)
  2095. w = []uint64{}
  2096. if g := r.nodes(); !reflect.DeepEqual(g, w) {
  2097. t.Errorf("nodes = %v, want %v", g, w)
  2098. }
  2099. }
  2100. func TestPromotable(t *testing.T) {
  2101. id := uint64(1)
  2102. tests := []struct {
  2103. peers []uint64
  2104. wp bool
  2105. }{
  2106. {[]uint64{1}, true},
  2107. {[]uint64{1, 2, 3}, true},
  2108. {[]uint64{}, false},
  2109. {[]uint64{2, 3}, false},
  2110. }
  2111. for i, tt := range tests {
  2112. r := newTestRaft(id, tt.peers, 5, 1, NewMemoryStorage())
  2113. if g := r.promotable(); g != tt.wp {
  2114. t.Errorf("#%d: promotable = %v, want %v", i, g, tt.wp)
  2115. }
  2116. }
  2117. }
  2118. func TestRaftNodes(t *testing.T) {
  2119. tests := []struct {
  2120. ids []uint64
  2121. wids []uint64
  2122. }{
  2123. {
  2124. []uint64{1, 2, 3},
  2125. []uint64{1, 2, 3},
  2126. },
  2127. {
  2128. []uint64{3, 2, 1},
  2129. []uint64{1, 2, 3},
  2130. },
  2131. }
  2132. for i, tt := range tests {
  2133. r := newTestRaft(1, tt.ids, 10, 1, NewMemoryStorage())
  2134. if !reflect.DeepEqual(r.nodes(), tt.wids) {
  2135. t.Errorf("#%d: nodes = %+v, want %+v", i, r.nodes(), tt.wids)
  2136. }
  2137. }
  2138. }
  2139. func TestCampaignWhileLeader(t *testing.T) {
  2140. testCampaignWhileLeader(t, false)
  2141. }
  2142. func TestPreCampaignWhileLeader(t *testing.T) {
  2143. testCampaignWhileLeader(t, true)
  2144. }
  2145. func testCampaignWhileLeader(t *testing.T, preVote bool) {
  2146. cfg := newTestConfig(1, []uint64{1}, 5, 1, NewMemoryStorage())
  2147. cfg.PreVote = preVote
  2148. r := newRaft(cfg)
  2149. if r.state != StateFollower {
  2150. t.Errorf("expected new node to be follower but got %s", r.state)
  2151. }
  2152. // We don't call campaign() directly because it comes after the check
  2153. // for our current state.
  2154. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2155. if r.state != StateLeader {
  2156. t.Errorf("expected single-node election to become leader but got %s", r.state)
  2157. }
  2158. term := r.Term
  2159. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2160. if r.state != StateLeader {
  2161. t.Errorf("expected to remain leader but got %s", r.state)
  2162. }
  2163. if r.Term != term {
  2164. t.Errorf("expected to remain in term %v but got %v", term, r.Term)
  2165. }
  2166. }
  2167. // TestCommitAfterRemoveNode verifies that pending commands can become
  2168. // committed when a config change reduces the quorum requirements.
  2169. func TestCommitAfterRemoveNode(t *testing.T) {
  2170. // Create a cluster with two nodes.
  2171. s := NewMemoryStorage()
  2172. r := newTestRaft(1, []uint64{1, 2}, 5, 1, s)
  2173. r.becomeCandidate()
  2174. r.becomeLeader()
  2175. // Begin to remove the second node.
  2176. cc := pb.ConfChange{
  2177. Type: pb.ConfChangeRemoveNode,
  2178. NodeID: 2,
  2179. }
  2180. ccData, err := cc.Marshal()
  2181. if err != nil {
  2182. t.Fatal(err)
  2183. }
  2184. r.Step(pb.Message{
  2185. Type: pb.MsgProp,
  2186. Entries: []pb.Entry{
  2187. {Type: pb.EntryConfChange, Data: ccData},
  2188. },
  2189. })
  2190. // Stabilize the log and make sure nothing is committed yet.
  2191. if ents := nextEnts(r, s); len(ents) > 0 {
  2192. t.Fatalf("unexpected committed entries: %v", ents)
  2193. }
  2194. ccIndex := r.raftLog.lastIndex()
  2195. // While the config change is pending, make another proposal.
  2196. r.Step(pb.Message{
  2197. Type: pb.MsgProp,
  2198. Entries: []pb.Entry{
  2199. {Type: pb.EntryNormal, Data: []byte("hello")},
  2200. },
  2201. })
  2202. // Node 2 acknowledges the config change, committing it.
  2203. r.Step(pb.Message{
  2204. Type: pb.MsgAppResp,
  2205. From: 2,
  2206. Index: ccIndex,
  2207. })
  2208. ents := nextEnts(r, s)
  2209. if len(ents) != 2 {
  2210. t.Fatalf("expected two committed entries, got %v", ents)
  2211. }
  2212. if ents[0].Type != pb.EntryNormal || ents[0].Data != nil {
  2213. t.Fatalf("expected ents[0] to be empty, but got %v", ents[0])
  2214. }
  2215. if ents[1].Type != pb.EntryConfChange {
  2216. t.Fatalf("expected ents[1] to be EntryConfChange, got %v", ents[1])
  2217. }
  2218. // Apply the config change. This reduces quorum requirements so the
  2219. // pending command can now commit.
  2220. r.removeNode(2)
  2221. ents = nextEnts(r, s)
  2222. if len(ents) != 1 || ents[0].Type != pb.EntryNormal ||
  2223. string(ents[0].Data) != "hello" {
  2224. t.Fatalf("expected one committed EntryNormal, got %v", ents)
  2225. }
  2226. }
  2227. // TestLeaderTransferToUpToDateNode verifies transferring should succeed
  2228. // if the transferee has the most up-to-date log entries when transfer starts.
  2229. func TestLeaderTransferToUpToDateNode(t *testing.T) {
  2230. nt := newNetwork(nil, nil, nil)
  2231. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2232. lead := nt.peers[1].(*raft)
  2233. if lead.lead != 1 {
  2234. t.Fatalf("after election leader is %x, want 1", lead.lead)
  2235. }
  2236. // Transfer leadership to 2.
  2237. nt.send(pb.Message{From: 2, To: 1, Type: pb.MsgTransferLeader})
  2238. checkLeaderTransferState(t, lead, StateFollower, 2)
  2239. // After some log replication, transfer leadership back to 1.
  2240. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2241. nt.send(pb.Message{From: 1, To: 2, Type: pb.MsgTransferLeader})
  2242. checkLeaderTransferState(t, lead, StateLeader, 1)
  2243. }
  2244. // TestLeaderTransferToUpToDateNodeFromFollower verifies transferring should succeed
  2245. // if the transferee has the most up-to-date log entries when transfer starts.
  2246. // Not like TestLeaderTransferToUpToDateNode, where the leader transfer message
  2247. // is sent to the leader, in this test case every leader transfer message is sent
  2248. // to the follower.
  2249. func TestLeaderTransferToUpToDateNodeFromFollower(t *testing.T) {
  2250. nt := newNetwork(nil, nil, nil)
  2251. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2252. lead := nt.peers[1].(*raft)
  2253. if lead.lead != 1 {
  2254. t.Fatalf("after election leader is %x, want 1", lead.lead)
  2255. }
  2256. // Transfer leadership to 2.
  2257. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgTransferLeader})
  2258. checkLeaderTransferState(t, lead, StateFollower, 2)
  2259. // After some log replication, transfer leadership back to 1.
  2260. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2261. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgTransferLeader})
  2262. checkLeaderTransferState(t, lead, StateLeader, 1)
  2263. }
  2264. // TestLeaderTransferWithCheckQuorum ensures transferring leader still works
  2265. // even the current leader is still under its leader lease
  2266. func TestLeaderTransferWithCheckQuorum(t *testing.T) {
  2267. nt := newNetwork(nil, nil, nil)
  2268. for i := 1; i < 4; i++ {
  2269. r := nt.peers[uint64(i)].(*raft)
  2270. r.checkQuorum = true
  2271. setRandomizedElectionTimeout(r, r.electionTimeout+i)
  2272. }
  2273. // Letting peer 2 electionElapsed reach to timeout so that it can vote for peer 1
  2274. f := nt.peers[2].(*raft)
  2275. for i := 0; i < f.electionTimeout; i++ {
  2276. f.tick()
  2277. }
  2278. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2279. lead := nt.peers[1].(*raft)
  2280. if lead.lead != 1 {
  2281. t.Fatalf("after election leader is %x, want 1", lead.lead)
  2282. }
  2283. // Transfer leadership to 2.
  2284. nt.send(pb.Message{From: 2, To: 1, Type: pb.MsgTransferLeader})
  2285. checkLeaderTransferState(t, lead, StateFollower, 2)
  2286. // After some log replication, transfer leadership back to 1.
  2287. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2288. nt.send(pb.Message{From: 1, To: 2, Type: pb.MsgTransferLeader})
  2289. checkLeaderTransferState(t, lead, StateLeader, 1)
  2290. }
  2291. func TestLeaderTransferToSlowFollower(t *testing.T) {
  2292. defaultLogger.EnableDebug()
  2293. nt := newNetwork(nil, nil, nil)
  2294. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2295. nt.isolate(3)
  2296. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2297. nt.recover()
  2298. lead := nt.peers[1].(*raft)
  2299. if lead.prs[3].Match != 1 {
  2300. t.Fatalf("node 1 has match %x for node 3, want %x", lead.prs[3].Match, 1)
  2301. }
  2302. // Transfer leadership to 3 when node 3 is lack of log.
  2303. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2304. checkLeaderTransferState(t, lead, StateFollower, 3)
  2305. }
  2306. func TestLeaderTransferAfterSnapshot(t *testing.T) {
  2307. nt := newNetwork(nil, nil, nil)
  2308. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2309. nt.isolate(3)
  2310. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2311. lead := nt.peers[1].(*raft)
  2312. nextEnts(lead, nt.storage[1])
  2313. nt.storage[1].CreateSnapshot(lead.raftLog.applied, &pb.ConfState{Nodes: lead.nodes()}, nil)
  2314. nt.storage[1].Compact(lead.raftLog.applied)
  2315. nt.recover()
  2316. if lead.prs[3].Match != 1 {
  2317. t.Fatalf("node 1 has match %x for node 3, want %x", lead.prs[3].Match, 1)
  2318. }
  2319. // Transfer leadership to 3 when node 3 is lack of snapshot.
  2320. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2321. // Send pb.MsgHeartbeatResp to leader to trigger a snapshot for node 3.
  2322. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgHeartbeatResp})
  2323. checkLeaderTransferState(t, lead, StateFollower, 3)
  2324. }
  2325. func TestLeaderTransferToSelf(t *testing.T) {
  2326. nt := newNetwork(nil, nil, nil)
  2327. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2328. lead := nt.peers[1].(*raft)
  2329. // Transfer leadership to self, there will be noop.
  2330. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgTransferLeader})
  2331. checkLeaderTransferState(t, lead, StateLeader, 1)
  2332. }
  2333. func TestLeaderTransferToNonExistingNode(t *testing.T) {
  2334. nt := newNetwork(nil, nil, nil)
  2335. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2336. lead := nt.peers[1].(*raft)
  2337. // Transfer leadership to non-existing node, there will be noop.
  2338. nt.send(pb.Message{From: 4, To: 1, Type: pb.MsgTransferLeader})
  2339. checkLeaderTransferState(t, lead, StateLeader, 1)
  2340. }
  2341. func TestLeaderTransferTimeout(t *testing.T) {
  2342. nt := newNetwork(nil, nil, nil)
  2343. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2344. nt.isolate(3)
  2345. lead := nt.peers[1].(*raft)
  2346. // Transfer leadership to isolated node, wait for timeout.
  2347. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2348. if lead.leadTransferee != 3 {
  2349. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2350. }
  2351. for i := 0; i < lead.heartbeatTimeout; i++ {
  2352. lead.tick()
  2353. }
  2354. if lead.leadTransferee != 3 {
  2355. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2356. }
  2357. for i := 0; i < lead.electionTimeout-lead.heartbeatTimeout; i++ {
  2358. lead.tick()
  2359. }
  2360. checkLeaderTransferState(t, lead, StateLeader, 1)
  2361. }
  2362. func TestLeaderTransferIgnoreProposal(t *testing.T) {
  2363. nt := newNetwork(nil, nil, nil)
  2364. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2365. nt.isolate(3)
  2366. lead := nt.peers[1].(*raft)
  2367. // Transfer leadership to isolated node to let transfer pending, then send proposal.
  2368. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2369. if lead.leadTransferee != 3 {
  2370. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2371. }
  2372. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2373. if lead.prs[1].Match != 1 {
  2374. t.Fatalf("node 1 has match %x, want %x", lead.prs[1].Match, 1)
  2375. }
  2376. }
  2377. func TestLeaderTransferReceiveHigherTermVote(t *testing.T) {
  2378. nt := newNetwork(nil, nil, nil)
  2379. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2380. nt.isolate(3)
  2381. lead := nt.peers[1].(*raft)
  2382. // Transfer leadership to isolated node to let transfer pending.
  2383. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2384. if lead.leadTransferee != 3 {
  2385. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2386. }
  2387. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup, Index: 1, Term: 2})
  2388. checkLeaderTransferState(t, lead, StateFollower, 2)
  2389. }
  2390. func TestLeaderTransferRemoveNode(t *testing.T) {
  2391. nt := newNetwork(nil, nil, nil)
  2392. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2393. nt.ignore(pb.MsgTimeoutNow)
  2394. lead := nt.peers[1].(*raft)
  2395. // The leadTransferee is removed when leadship transferring.
  2396. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2397. if lead.leadTransferee != 3 {
  2398. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2399. }
  2400. lead.removeNode(3)
  2401. checkLeaderTransferState(t, lead, StateLeader, 1)
  2402. }
  2403. // TestLeaderTransferBack verifies leadership can transfer back to self when last transfer is pending.
  2404. func TestLeaderTransferBack(t *testing.T) {
  2405. nt := newNetwork(nil, nil, nil)
  2406. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2407. nt.isolate(3)
  2408. lead := nt.peers[1].(*raft)
  2409. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2410. if lead.leadTransferee != 3 {
  2411. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2412. }
  2413. // Transfer leadership back to self.
  2414. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgTransferLeader})
  2415. checkLeaderTransferState(t, lead, StateLeader, 1)
  2416. }
  2417. // TestLeaderTransferSecondTransferToAnotherNode verifies leader can transfer to another node
  2418. // when last transfer is pending.
  2419. func TestLeaderTransferSecondTransferToAnotherNode(t *testing.T) {
  2420. nt := newNetwork(nil, nil, nil)
  2421. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2422. nt.isolate(3)
  2423. lead := nt.peers[1].(*raft)
  2424. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2425. if lead.leadTransferee != 3 {
  2426. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2427. }
  2428. // Transfer leadership to another node.
  2429. nt.send(pb.Message{From: 2, To: 1, Type: pb.MsgTransferLeader})
  2430. checkLeaderTransferState(t, lead, StateFollower, 2)
  2431. }
  2432. // TestLeaderTransferSecondTransferToSameNode verifies second transfer leader request
  2433. // to the same node should not extend the timeout while the first one is pending.
  2434. func TestLeaderTransferSecondTransferToSameNode(t *testing.T) {
  2435. nt := newNetwork(nil, nil, nil)
  2436. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2437. nt.isolate(3)
  2438. lead := nt.peers[1].(*raft)
  2439. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2440. if lead.leadTransferee != 3 {
  2441. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2442. }
  2443. for i := 0; i < lead.heartbeatTimeout; i++ {
  2444. lead.tick()
  2445. }
  2446. // Second transfer leadership request to the same node.
  2447. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2448. for i := 0; i < lead.electionTimeout-lead.heartbeatTimeout; i++ {
  2449. lead.tick()
  2450. }
  2451. checkLeaderTransferState(t, lead, StateLeader, 1)
  2452. }
  2453. func checkLeaderTransferState(t *testing.T, r *raft, state StateType, lead uint64) {
  2454. if r.state != state || r.lead != lead {
  2455. t.Fatalf("after transferring, node has state %v lead %v, want state %v lead %v", r.state, r.lead, state, lead)
  2456. }
  2457. if r.leadTransferee != None {
  2458. t.Fatalf("after transferring, node has leadTransferee %v, want leadTransferee %v", r.leadTransferee, None)
  2459. }
  2460. }
  2461. // TestTransferNonMember verifies that when a MsgTimeoutNow arrives at
  2462. // a node that has been removed from the group, nothing happens.
  2463. // (previously, if the node also got votes, it would panic as it
  2464. // transitioned to StateLeader)
  2465. func TestTransferNonMember(t *testing.T) {
  2466. r := newTestRaft(1, []uint64{2, 3, 4}, 5, 1, NewMemoryStorage())
  2467. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgTimeoutNow})
  2468. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgVoteResp})
  2469. r.Step(pb.Message{From: 3, To: 1, Type: pb.MsgVoteResp})
  2470. if r.state != StateFollower {
  2471. t.Fatalf("state is %s, want StateFollower", r.state)
  2472. }
  2473. }
  2474. func ents(terms ...uint64) *raft {
  2475. storage := NewMemoryStorage()
  2476. for i, term := range terms {
  2477. storage.Append([]pb.Entry{{Index: uint64(i + 1), Term: term}})
  2478. }
  2479. sm := newTestRaft(1, []uint64{}, 5, 1, storage)
  2480. sm.reset(terms[len(terms)-1])
  2481. return sm
  2482. }
  2483. type network struct {
  2484. peers map[uint64]stateMachine
  2485. storage map[uint64]*MemoryStorage
  2486. dropm map[connem]float64
  2487. ignorem map[pb.MessageType]bool
  2488. }
  2489. // newNetwork initializes a network from peers.
  2490. // A nil node will be replaced with a new *stateMachine.
  2491. // A *stateMachine will get its k, id.
  2492. // When using stateMachine, the address list is always [1, n].
  2493. func newNetwork(peers ...stateMachine) *network {
  2494. return newNetworkWithConfig(nil, peers...)
  2495. }
  2496. // newNetworkWithConfig is like newNetwork but calls the given func to
  2497. // modify the configuration of any state machines it creates.
  2498. func newNetworkWithConfig(configFunc func(*Config), peers ...stateMachine) *network {
  2499. size := len(peers)
  2500. peerAddrs := idsBySize(size)
  2501. npeers := make(map[uint64]stateMachine, size)
  2502. nstorage := make(map[uint64]*MemoryStorage, size)
  2503. for j, p := range peers {
  2504. id := peerAddrs[j]
  2505. switch v := p.(type) {
  2506. case nil:
  2507. nstorage[id] = NewMemoryStorage()
  2508. cfg := newTestConfig(id, peerAddrs, 10, 1, nstorage[id])
  2509. if configFunc != nil {
  2510. configFunc(cfg)
  2511. }
  2512. sm := newRaft(cfg)
  2513. npeers[id] = sm
  2514. case *raft:
  2515. v.id = id
  2516. v.prs = make(map[uint64]*Progress)
  2517. for i := 0; i < size; i++ {
  2518. v.prs[peerAddrs[i]] = &Progress{}
  2519. }
  2520. v.reset(v.Term)
  2521. npeers[id] = v
  2522. case *blackHole:
  2523. npeers[id] = v
  2524. default:
  2525. panic(fmt.Sprintf("unexpected state machine type: %T", p))
  2526. }
  2527. }
  2528. return &network{
  2529. peers: npeers,
  2530. storage: nstorage,
  2531. dropm: make(map[connem]float64),
  2532. ignorem: make(map[pb.MessageType]bool),
  2533. }
  2534. }
  2535. func preVoteConfig(c *Config) {
  2536. c.PreVote = true
  2537. }
  2538. func (nw *network) send(msgs ...pb.Message) {
  2539. for len(msgs) > 0 {
  2540. m := msgs[0]
  2541. p := nw.peers[m.To]
  2542. p.Step(m)
  2543. msgs = append(msgs[1:], nw.filter(p.readMessages())...)
  2544. }
  2545. }
  2546. func (nw *network) drop(from, to uint64, perc float64) {
  2547. nw.dropm[connem{from, to}] = perc
  2548. }
  2549. func (nw *network) cut(one, other uint64) {
  2550. nw.drop(one, other, 1)
  2551. nw.drop(other, one, 1)
  2552. }
  2553. func (nw *network) isolate(id uint64) {
  2554. for i := 0; i < len(nw.peers); i++ {
  2555. nid := uint64(i) + 1
  2556. if nid != id {
  2557. nw.drop(id, nid, 1.0)
  2558. nw.drop(nid, id, 1.0)
  2559. }
  2560. }
  2561. }
  2562. func (nw *network) ignore(t pb.MessageType) {
  2563. nw.ignorem[t] = true
  2564. }
  2565. func (nw *network) recover() {
  2566. nw.dropm = make(map[connem]float64)
  2567. nw.ignorem = make(map[pb.MessageType]bool)
  2568. }
  2569. func (nw *network) filter(msgs []pb.Message) []pb.Message {
  2570. mm := []pb.Message{}
  2571. for _, m := range msgs {
  2572. if nw.ignorem[m.Type] {
  2573. continue
  2574. }
  2575. switch m.Type {
  2576. case pb.MsgHup:
  2577. // hups never go over the network, so don't drop them but panic
  2578. panic("unexpected msgHup")
  2579. default:
  2580. perc := nw.dropm[connem{m.From, m.To}]
  2581. if n := rand.Float64(); n < perc {
  2582. continue
  2583. }
  2584. }
  2585. mm = append(mm, m)
  2586. }
  2587. return mm
  2588. }
  2589. type connem struct {
  2590. from, to uint64
  2591. }
  2592. type blackHole struct{}
  2593. func (blackHole) Step(pb.Message) error { return nil }
  2594. func (blackHole) readMessages() []pb.Message { return nil }
  2595. var nopStepper = &blackHole{}
  2596. func idsBySize(size int) []uint64 {
  2597. ids := make([]uint64, size)
  2598. for i := 0; i < size; i++ {
  2599. ids[i] = 1 + uint64(i)
  2600. }
  2601. return ids
  2602. }
  2603. // setRandomizedElectionTimeout set up the value by caller instead of choosing
  2604. // by system, in some test scenario we need to fill in some expected value to
  2605. // ensure the certainty
  2606. func setRandomizedElectionTimeout(r *raft, v int) {
  2607. r.randomizedElectionTimeout = v
  2608. }
  2609. func newTestConfig(id uint64, peers []uint64, election, heartbeat int, storage Storage) *Config {
  2610. return &Config{
  2611. ID: id,
  2612. peers: peers,
  2613. ElectionTick: election,
  2614. HeartbeatTick: heartbeat,
  2615. Storage: storage,
  2616. MaxSizePerMsg: noLimit,
  2617. MaxInflightMsgs: 256,
  2618. }
  2619. }
  2620. func newTestRaft(id uint64, peers []uint64, election, heartbeat int, storage Storage) *raft {
  2621. return newRaft(newTestConfig(id, peers, election, heartbeat, storage))
  2622. }