raft_test.go 65 KB

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