raft_test.go 74 KB

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