raft_test.go 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324
  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. 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. // remove all nodes from cluster
  1593. r.removeNode(1)
  1594. w = []uint64{}
  1595. if g := r.nodes(); !reflect.DeepEqual(g, w) {
  1596. t.Errorf("nodes = %v, want %v", g, w)
  1597. }
  1598. }
  1599. func TestPromotable(t *testing.T) {
  1600. id := uint64(1)
  1601. tests := []struct {
  1602. peers []uint64
  1603. wp bool
  1604. }{
  1605. {[]uint64{1}, true},
  1606. {[]uint64{1, 2, 3}, true},
  1607. {[]uint64{}, false},
  1608. {[]uint64{2, 3}, false},
  1609. }
  1610. for i, tt := range tests {
  1611. r := newTestRaft(id, tt.peers, 5, 1, NewMemoryStorage())
  1612. if g := r.promotable(); g != tt.wp {
  1613. t.Errorf("#%d: promotable = %v, want %v", i, g, tt.wp)
  1614. }
  1615. }
  1616. }
  1617. func TestRaftNodes(t *testing.T) {
  1618. tests := []struct {
  1619. ids []uint64
  1620. wids []uint64
  1621. }{
  1622. {
  1623. []uint64{1, 2, 3},
  1624. []uint64{1, 2, 3},
  1625. },
  1626. {
  1627. []uint64{3, 2, 1},
  1628. []uint64{1, 2, 3},
  1629. },
  1630. }
  1631. for i, tt := range tests {
  1632. r := newTestRaft(1, tt.ids, 10, 1, NewMemoryStorage())
  1633. if !reflect.DeepEqual(r.nodes(), tt.wids) {
  1634. t.Errorf("#%d: nodes = %+v, want %+v", i, r.nodes(), tt.wids)
  1635. }
  1636. }
  1637. }
  1638. func TestCampaignWhileLeader(t *testing.T) {
  1639. r := newTestRaft(1, []uint64{1}, 5, 1, NewMemoryStorage())
  1640. if r.state != StateFollower {
  1641. t.Errorf("expected new node to be follower but got %s", r.state)
  1642. }
  1643. // We don't call campaign() directly because it comes after the check
  1644. // for our current state.
  1645. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1646. if r.state != StateLeader {
  1647. t.Errorf("expected single-node election to become leader but got %s", r.state)
  1648. }
  1649. term := r.Term
  1650. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1651. if r.state != StateLeader {
  1652. t.Errorf("expected to remain leader but got %s", r.state)
  1653. }
  1654. if r.Term != term {
  1655. t.Errorf("expected to remain in term %v but got %v", term, r.Term)
  1656. }
  1657. }
  1658. // TestCommitAfterRemoveNode verifies that pending commands can become
  1659. // committed when a config change reduces the quorum requirements.
  1660. func TestCommitAfterRemoveNode(t *testing.T) {
  1661. // Create a cluster with two nodes.
  1662. s := NewMemoryStorage()
  1663. r := newTestRaft(1, []uint64{1, 2}, 5, 1, s)
  1664. r.becomeCandidate()
  1665. r.becomeLeader()
  1666. // Begin to remove the second node.
  1667. cc := pb.ConfChange{
  1668. Type: pb.ConfChangeRemoveNode,
  1669. NodeID: 2,
  1670. }
  1671. ccData, err := cc.Marshal()
  1672. if err != nil {
  1673. t.Fatal(err)
  1674. }
  1675. r.Step(pb.Message{
  1676. Type: pb.MsgProp,
  1677. Entries: []pb.Entry{
  1678. {Type: pb.EntryConfChange, Data: ccData},
  1679. },
  1680. })
  1681. // Stabilize the log and make sure nothing is committed yet.
  1682. if ents := nextEnts(r, s); len(ents) > 0 {
  1683. t.Fatalf("unexpected committed entries: %v", ents)
  1684. }
  1685. ccIndex := r.raftLog.lastIndex()
  1686. // While the config change is pending, make another proposal.
  1687. r.Step(pb.Message{
  1688. Type: pb.MsgProp,
  1689. Entries: []pb.Entry{
  1690. {Type: pb.EntryNormal, Data: []byte("hello")},
  1691. },
  1692. })
  1693. // Node 2 acknowledges the config change, committing it.
  1694. r.Step(pb.Message{
  1695. Type: pb.MsgAppResp,
  1696. From: 2,
  1697. Index: ccIndex,
  1698. })
  1699. ents := nextEnts(r, s)
  1700. if len(ents) != 2 {
  1701. t.Fatalf("expected two committed entries, got %v", ents)
  1702. }
  1703. if ents[0].Type != pb.EntryNormal || ents[0].Data != nil {
  1704. t.Fatalf("expected ents[0] to be empty, but got %v", ents[0])
  1705. }
  1706. if ents[1].Type != pb.EntryConfChange {
  1707. t.Fatalf("expected ents[1] to be EntryConfChange, got %v", ents[1])
  1708. }
  1709. // Apply the config change. This reduces quorum requirements so the
  1710. // pending command can now commit.
  1711. r.removeNode(2)
  1712. ents = nextEnts(r, s)
  1713. if len(ents) != 1 || ents[0].Type != pb.EntryNormal ||
  1714. string(ents[0].Data) != "hello" {
  1715. t.Fatalf("expected one committed EntryNormal, got %v", ents)
  1716. }
  1717. }
  1718. // TestLeaderTransferToUpToDateNode verifies transferring should succeed
  1719. // if the transferee has the most up-to-date log entires when transfer starts.
  1720. func TestLeaderTransferToUpToDateNode(t *testing.T) {
  1721. nt := newNetwork(nil, nil, nil)
  1722. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1723. lead := nt.peers[1].(*raft)
  1724. if lead.lead != 1 {
  1725. t.Fatalf("after election leader is %x, want 1", lead.lead)
  1726. }
  1727. // Transfer leadership to 2.
  1728. nt.send(pb.Message{From: 2, To: 1, Type: pb.MsgTransferLeader})
  1729. checkLeaderTransferState(t, lead, StateFollower, 2)
  1730. // After some log replication, transfer leadership back to 1.
  1731. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  1732. nt.send(pb.Message{From: 1, To: 2, Type: pb.MsgTransferLeader})
  1733. checkLeaderTransferState(t, lead, StateLeader, 1)
  1734. }
  1735. func TestLeaderTransferToSlowFollower(t *testing.T) {
  1736. defaultLogger.EnableDebug()
  1737. nt := newNetwork(nil, nil, nil)
  1738. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1739. nt.isolate(3)
  1740. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  1741. nt.recover()
  1742. lead := nt.peers[1].(*raft)
  1743. if lead.prs[3].Match != 1 {
  1744. t.Fatalf("node 1 has match %x for node 3, want %x", lead.prs[3].Match, 1)
  1745. }
  1746. // Transfer leadership to 3 when node 3 is lack of log.
  1747. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  1748. checkLeaderTransferState(t, lead, StateFollower, 3)
  1749. }
  1750. func TestLeaderTransferAfterSnapshot(t *testing.T) {
  1751. nt := newNetwork(nil, nil, nil)
  1752. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1753. nt.isolate(3)
  1754. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  1755. lead := nt.peers[1].(*raft)
  1756. nextEnts(lead, nt.storage[1])
  1757. nt.storage[1].CreateSnapshot(lead.raftLog.applied, &pb.ConfState{Nodes: lead.nodes()}, nil)
  1758. nt.storage[1].Compact(lead.raftLog.applied)
  1759. nt.recover()
  1760. if lead.prs[3].Match != 1 {
  1761. t.Fatalf("node 1 has match %x for node 3, want %x", lead.prs[3].Match, 1)
  1762. }
  1763. // Transfer leadership to 3 when node 3 is lack of snapshot.
  1764. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  1765. // Send pb.MsgHeartbeatResp to leader to trigger a snapshot for node 3.
  1766. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgHeartbeatResp})
  1767. checkLeaderTransferState(t, lead, StateFollower, 3)
  1768. }
  1769. func TestLeaderTransferToSelf(t *testing.T) {
  1770. nt := newNetwork(nil, nil, nil)
  1771. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1772. lead := nt.peers[1].(*raft)
  1773. // Transfer leadership to self, there will be noop.
  1774. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgTransferLeader})
  1775. checkLeaderTransferState(t, lead, StateLeader, 1)
  1776. }
  1777. func TestLeaderTransferToNonExistingNode(t *testing.T) {
  1778. nt := newNetwork(nil, nil, nil)
  1779. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1780. lead := nt.peers[1].(*raft)
  1781. // Transfer leadership to non-existing node, there will be noop.
  1782. nt.send(pb.Message{From: 4, To: 1, Type: pb.MsgTransferLeader})
  1783. checkLeaderTransferState(t, lead, StateLeader, 1)
  1784. }
  1785. func TestLeaderTransferTimeout(t *testing.T) {
  1786. nt := newNetwork(nil, nil, nil)
  1787. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1788. nt.isolate(3)
  1789. lead := nt.peers[1].(*raft)
  1790. // Transfer leadership to isolated node, wait for timeout.
  1791. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  1792. if lead.leadTransferee != 3 {
  1793. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  1794. }
  1795. for i := 0; i < lead.heartbeatTimeout; i++ {
  1796. lead.tick()
  1797. }
  1798. if lead.leadTransferee != 3 {
  1799. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  1800. }
  1801. for i := 0; i < lead.electionTimeout-lead.heartbeatTimeout; i++ {
  1802. lead.tick()
  1803. }
  1804. checkLeaderTransferState(t, lead, StateLeader, 1)
  1805. }
  1806. func TestLeaderTransferIgnoreProposal(t *testing.T) {
  1807. nt := newNetwork(nil, nil, nil)
  1808. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1809. nt.isolate(3)
  1810. lead := nt.peers[1].(*raft)
  1811. // Transfer leadership to isolated node to let transfer pending, then send proposal.
  1812. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  1813. if lead.leadTransferee != 3 {
  1814. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  1815. }
  1816. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  1817. if lead.prs[1].Match != 1 {
  1818. t.Fatalf("node 1 has match %x, want %x", lead.prs[1].Match, 1)
  1819. }
  1820. }
  1821. func TestLeaderTransferReceiveHigherTermVote(t *testing.T) {
  1822. nt := newNetwork(nil, nil, nil)
  1823. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1824. nt.isolate(3)
  1825. lead := nt.peers[1].(*raft)
  1826. // Transfer leadership to isolated node to let transfer pending.
  1827. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  1828. if lead.leadTransferee != 3 {
  1829. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  1830. }
  1831. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup, Index: 1, Term: 2})
  1832. checkLeaderTransferState(t, lead, StateFollower, 2)
  1833. }
  1834. func TestLeaderTransferRemoveNode(t *testing.T) {
  1835. nt := newNetwork(nil, nil, nil)
  1836. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1837. nt.ignore(pb.MsgTimeoutNow)
  1838. lead := nt.peers[1].(*raft)
  1839. // The leadTransferee is removed when leadship transferring.
  1840. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  1841. if lead.leadTransferee != 3 {
  1842. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  1843. }
  1844. lead.removeNode(3)
  1845. checkLeaderTransferState(t, lead, StateLeader, 1)
  1846. }
  1847. // TestLeaderTransferBack verifies leadership can transfer back to self when last transfer is pending.
  1848. func TestLeaderTransferBack(t *testing.T) {
  1849. nt := newNetwork(nil, nil, nil)
  1850. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1851. nt.isolate(3)
  1852. lead := nt.peers[1].(*raft)
  1853. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  1854. if lead.leadTransferee != 3 {
  1855. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  1856. }
  1857. // Transfer leadership back to self.
  1858. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgTransferLeader})
  1859. checkLeaderTransferState(t, lead, StateLeader, 1)
  1860. }
  1861. // TestLeaderTransferSecondTransferToAnotherNode verifies leader can transfer to another node
  1862. // when last transfer is pending.
  1863. func TestLeaderTransferSecondTransferToAnotherNode(t *testing.T) {
  1864. nt := newNetwork(nil, nil, nil)
  1865. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1866. nt.isolate(3)
  1867. lead := nt.peers[1].(*raft)
  1868. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  1869. if lead.leadTransferee != 3 {
  1870. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  1871. }
  1872. // Transfer leadership to another node.
  1873. nt.send(pb.Message{From: 2, To: 1, Type: pb.MsgTransferLeader})
  1874. checkLeaderTransferState(t, lead, StateFollower, 2)
  1875. }
  1876. // TestLeaderTransferSecondTransferToSameNode verifies second transfer leader request
  1877. // to the same node should not extend the timeout while the first one is pending.
  1878. func TestLeaderTransferSecondTransferToSameNode(t *testing.T) {
  1879. nt := newNetwork(nil, nil, nil)
  1880. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1881. nt.isolate(3)
  1882. lead := nt.peers[1].(*raft)
  1883. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  1884. if lead.leadTransferee != 3 {
  1885. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  1886. }
  1887. for i := 0; i < lead.heartbeatTimeout; i++ {
  1888. lead.tick()
  1889. }
  1890. // Second transfer leadership request to the same node.
  1891. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  1892. for i := 0; i < lead.electionTimeout-lead.heartbeatTimeout; i++ {
  1893. lead.tick()
  1894. }
  1895. checkLeaderTransferState(t, lead, StateLeader, 1)
  1896. }
  1897. func checkLeaderTransferState(t *testing.T, r *raft, state StateType, lead uint64) {
  1898. if r.state != state || r.lead != lead {
  1899. t.Fatalf("after transferring, node has state %v lead %v, want state %v lead %v", r.state, r.lead, state, lead)
  1900. }
  1901. if r.leadTransferee != None {
  1902. t.Fatalf("after transferring, node has leadTransferee %v, want leadTransferee %v", r.leadTransferee, None)
  1903. }
  1904. }
  1905. func ents(terms ...uint64) *raft {
  1906. storage := NewMemoryStorage()
  1907. for i, term := range terms {
  1908. storage.Append([]pb.Entry{{Index: uint64(i + 1), Term: term}})
  1909. }
  1910. sm := newTestRaft(1, []uint64{}, 5, 1, storage)
  1911. sm.reset(0)
  1912. return sm
  1913. }
  1914. type network struct {
  1915. peers map[uint64]stateMachine
  1916. storage map[uint64]*MemoryStorage
  1917. dropm map[connem]float64
  1918. ignorem map[pb.MessageType]bool
  1919. }
  1920. // newNetwork initializes a network from peers.
  1921. // A nil node will be replaced with a new *stateMachine.
  1922. // A *stateMachine will get its k, id.
  1923. // When using stateMachine, the address list is always [1, n].
  1924. func newNetwork(peers ...stateMachine) *network {
  1925. size := len(peers)
  1926. peerAddrs := idsBySize(size)
  1927. npeers := make(map[uint64]stateMachine, size)
  1928. nstorage := make(map[uint64]*MemoryStorage, size)
  1929. for j, p := range peers {
  1930. id := peerAddrs[j]
  1931. switch v := p.(type) {
  1932. case nil:
  1933. nstorage[id] = NewMemoryStorage()
  1934. sm := newTestRaft(id, peerAddrs, 10, 1, nstorage[id])
  1935. npeers[id] = sm
  1936. case *raft:
  1937. v.id = id
  1938. v.prs = make(map[uint64]*Progress)
  1939. for i := 0; i < size; i++ {
  1940. v.prs[peerAddrs[i]] = &Progress{}
  1941. }
  1942. v.reset(0)
  1943. npeers[id] = v
  1944. case *blackHole:
  1945. npeers[id] = v
  1946. default:
  1947. panic(fmt.Sprintf("unexpected state machine type: %T", p))
  1948. }
  1949. }
  1950. return &network{
  1951. peers: npeers,
  1952. storage: nstorage,
  1953. dropm: make(map[connem]float64),
  1954. ignorem: make(map[pb.MessageType]bool),
  1955. }
  1956. }
  1957. func (nw *network) send(msgs ...pb.Message) {
  1958. for len(msgs) > 0 {
  1959. m := msgs[0]
  1960. p := nw.peers[m.To]
  1961. p.Step(m)
  1962. msgs = append(msgs[1:], nw.filter(p.readMessages())...)
  1963. }
  1964. }
  1965. func (nw *network) drop(from, to uint64, perc float64) {
  1966. nw.dropm[connem{from, to}] = perc
  1967. }
  1968. func (nw *network) cut(one, other uint64) {
  1969. nw.drop(one, other, 1)
  1970. nw.drop(other, one, 1)
  1971. }
  1972. func (nw *network) isolate(id uint64) {
  1973. for i := 0; i < len(nw.peers); i++ {
  1974. nid := uint64(i) + 1
  1975. if nid != id {
  1976. nw.drop(id, nid, 1.0)
  1977. nw.drop(nid, id, 1.0)
  1978. }
  1979. }
  1980. }
  1981. func (nw *network) ignore(t pb.MessageType) {
  1982. nw.ignorem[t] = true
  1983. }
  1984. func (nw *network) recover() {
  1985. nw.dropm = make(map[connem]float64)
  1986. nw.ignorem = make(map[pb.MessageType]bool)
  1987. }
  1988. func (nw *network) filter(msgs []pb.Message) []pb.Message {
  1989. mm := []pb.Message{}
  1990. for _, m := range msgs {
  1991. if nw.ignorem[m.Type] {
  1992. continue
  1993. }
  1994. switch m.Type {
  1995. case pb.MsgHup:
  1996. // hups never go over the network, so don't drop them but panic
  1997. panic("unexpected msgHup")
  1998. default:
  1999. perc := nw.dropm[connem{m.From, m.To}]
  2000. if n := rand.Float64(); n < perc {
  2001. continue
  2002. }
  2003. }
  2004. mm = append(mm, m)
  2005. }
  2006. return mm
  2007. }
  2008. type connem struct {
  2009. from, to uint64
  2010. }
  2011. type blackHole struct{}
  2012. func (blackHole) Step(pb.Message) error { return nil }
  2013. func (blackHole) readMessages() []pb.Message { return nil }
  2014. var nopStepper = &blackHole{}
  2015. func idsBySize(size int) []uint64 {
  2016. ids := make([]uint64, size)
  2017. for i := 0; i < size; i++ {
  2018. ids[i] = 1 + uint64(i)
  2019. }
  2020. return ids
  2021. }
  2022. func newTestConfig(id uint64, peers []uint64, election, heartbeat int, storage Storage) *Config {
  2023. return &Config{
  2024. ID: id,
  2025. peers: peers,
  2026. ElectionTick: election,
  2027. HeartbeatTick: heartbeat,
  2028. Storage: storage,
  2029. MaxSizePerMsg: noLimit,
  2030. MaxInflightMsgs: 256,
  2031. }
  2032. }
  2033. func newTestRaft(id uint64, peers []uint64, election, heartbeat int, storage Storage) *raft {
  2034. return newRaft(newTestConfig(id, peers, election, heartbeat, storage))
  2035. }