raft_test.go 72 KB

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