raft_test.go 70 KB

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