raft_test.go 84 KB

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