raft_test.go 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201
  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. // TestProgressResumeByHeartbeatResp ensures raft.heartbeat reset progress.paused by heartbeat response.
  243. func TestProgressResumeByHeartbeatResp(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 true", r.prs[2].Paused)
  251. }
  252. r.prs[2].becomeReplicate()
  253. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgHeartbeatResp})
  254. if r.prs[2].Paused {
  255. t.Errorf("paused = %v, want false", r.prs[2].Paused)
  256. }
  257. }
  258. func TestProgressPaused(t *testing.T) {
  259. r := newTestRaft(1, []uint64{1, 2}, 5, 1, NewMemoryStorage())
  260. r.becomeCandidate()
  261. r.becomeLeader()
  262. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  263. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  264. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  265. ms := r.readMessages()
  266. if len(ms) != 1 {
  267. t.Errorf("len(ms) = %d, want 1", len(ms))
  268. }
  269. }
  270. func TestLeaderElection(t *testing.T) {
  271. testLeaderElection(t, false)
  272. }
  273. func TestLeaderElectionPreVote(t *testing.T) {
  274. testLeaderElection(t, true)
  275. }
  276. func testLeaderElection(t *testing.T, preVote bool) {
  277. var cfg func(*Config)
  278. if preVote {
  279. cfg = preVoteConfig
  280. }
  281. tests := []struct {
  282. *network
  283. state StateType
  284. expTerm uint64
  285. }{
  286. {newNetworkWithConfig(cfg, nil, nil, nil), StateLeader, 1},
  287. {newNetworkWithConfig(cfg, nil, nil, nopStepper), StateLeader, 1},
  288. {newNetworkWithConfig(cfg, nil, nopStepper, nopStepper), StateCandidate, 1},
  289. {newNetworkWithConfig(cfg, nil, nopStepper, nopStepper, nil), StateCandidate, 1},
  290. {newNetworkWithConfig(cfg, nil, nopStepper, nopStepper, nil, nil), StateLeader, 1},
  291. // three logs further along than 0, but in the same term so rejections
  292. // are returned instead of the votes being ignored.
  293. {newNetworkWithConfig(cfg,
  294. nil, entsWithConfig(cfg, 1), entsWithConfig(cfg, 1), entsWithConfig(cfg, 1, 1), nil),
  295. StateFollower, 1},
  296. }
  297. for i, tt := range tests {
  298. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  299. sm := tt.network.peers[1].(*raft)
  300. var expState StateType
  301. var expTerm uint64
  302. if tt.state == StateCandidate && preVote {
  303. // In pre-vote mode, an election that fails to complete
  304. // leaves the node in pre-candidate state without advancing
  305. // the term.
  306. expState = StatePreCandidate
  307. expTerm = 0
  308. } else {
  309. expState = tt.state
  310. expTerm = tt.expTerm
  311. }
  312. if sm.state != expState {
  313. t.Errorf("#%d: state = %s, want %s", i, sm.state, expState)
  314. }
  315. if g := sm.Term; g != expTerm {
  316. t.Errorf("#%d: term = %d, want %d", i, g, expTerm)
  317. }
  318. }
  319. }
  320. func TestLeaderCycle(t *testing.T) {
  321. testLeaderCycle(t, false)
  322. }
  323. func TestLeaderCyclePreVote(t *testing.T) {
  324. testLeaderCycle(t, true)
  325. }
  326. // testLeaderCycle verifies that each node in a cluster can campaign
  327. // and be elected in turn. This ensures that elections (including
  328. // pre-vote) work when not starting from a clean slate (as they do in
  329. // TestLeaderElection)
  330. func testLeaderCycle(t *testing.T, preVote bool) {
  331. var cfg func(*Config)
  332. if preVote {
  333. cfg = preVoteConfig
  334. }
  335. n := newNetworkWithConfig(cfg, nil, nil, nil)
  336. for campaignerID := uint64(1); campaignerID <= 3; campaignerID++ {
  337. n.send(pb.Message{From: campaignerID, To: campaignerID, Type: pb.MsgHup})
  338. for _, peer := range n.peers {
  339. sm := peer.(*raft)
  340. if sm.id == campaignerID && sm.state != StateLeader {
  341. t.Errorf("preVote=%v: campaigning node %d state = %v, want StateLeader",
  342. preVote, sm.id, sm.state)
  343. } else if sm.id != campaignerID && sm.state != StateFollower {
  344. t.Errorf("preVote=%v: after campaign of node %d, "+
  345. "node %d had state = %v, want StateFollower",
  346. preVote, campaignerID, sm.id, sm.state)
  347. }
  348. }
  349. }
  350. }
  351. // TestLeaderElectionOverwriteNewerLogs tests a scenario in which a
  352. // newly-elected leader does *not* have the newest (i.e. highest term)
  353. // log entries, and must overwrite higher-term log entries with
  354. // lower-term ones.
  355. func TestLeaderElectionOverwriteNewerLogs(t *testing.T) {
  356. testLeaderElectionOverwriteNewerLogs(t, false)
  357. }
  358. func TestLeaderElectionOverwriteNewerLogsPreVote(t *testing.T) {
  359. testLeaderElectionOverwriteNewerLogs(t, true)
  360. }
  361. func testLeaderElectionOverwriteNewerLogs(t *testing.T, preVote bool) {
  362. var cfg func(*Config)
  363. if preVote {
  364. cfg = preVoteConfig
  365. }
  366. // This network represents the results of the following sequence of
  367. // events:
  368. // - Node 1 won the election in term 1.
  369. // - Node 1 replicated a log entry to node 2 but died before sending
  370. // it to other nodes.
  371. // - Node 3 won the second election in term 2.
  372. // - Node 3 wrote an entry to its logs but died without sending it
  373. // to any other nodes.
  374. //
  375. // At this point, nodes 1, 2, and 3 all have uncommitted entries in
  376. // their logs and could win an election at term 3. The winner's log
  377. // entry overwrites the losers'. (TestLeaderSyncFollowerLog tests
  378. // the case where older log entries are overwritten, so this test
  379. // focuses on the case where the newer entries are lost).
  380. n := newNetworkWithConfig(cfg,
  381. entsWithConfig(cfg, 1), // Node 1: Won first election
  382. entsWithConfig(cfg, 1), // Node 2: Got logs from node 1
  383. entsWithConfig(cfg, 2), // Node 3: Won second election
  384. votedWithConfig(cfg, 3, 2), // Node 4: Voted but didn't get logs
  385. votedWithConfig(cfg, 3, 2)) // Node 5: Voted but didn't get logs
  386. // Node 1 campaigns. The election fails because a quorum of nodes
  387. // know about the election that already happened at term 2. Node 1's
  388. // term is pushed ahead to 2.
  389. n.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  390. sm1 := n.peers[1].(*raft)
  391. if sm1.state != StateFollower {
  392. t.Errorf("state = %s, want StateFollower", sm1.state)
  393. }
  394. if sm1.Term != 2 {
  395. t.Errorf("term = %d, want 2", sm1.Term)
  396. }
  397. // Node 1 campaigns again with a higher term. This time it succeeds.
  398. n.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  399. if sm1.state != StateLeader {
  400. t.Errorf("state = %s, want StateLeader", sm1.state)
  401. }
  402. if sm1.Term != 3 {
  403. t.Errorf("term = %d, want 3", sm1.Term)
  404. }
  405. // Now all nodes agree on a log entry with term 1 at index 1 (and
  406. // term 3 at index 2).
  407. for i := range n.peers {
  408. sm := n.peers[i].(*raft)
  409. entries := sm.raftLog.allEntries()
  410. if len(entries) != 2 {
  411. t.Fatalf("node %d: len(entries) == %d, want 2", i, len(entries))
  412. }
  413. if entries[0].Term != 1 {
  414. t.Errorf("node %d: term at index 1 == %d, want 1", i, entries[0].Term)
  415. }
  416. if entries[1].Term != 3 {
  417. t.Errorf("node %d: term at index 2 == %d, want 3", i, entries[1].Term)
  418. }
  419. }
  420. }
  421. func TestVoteFromAnyState(t *testing.T) {
  422. testVoteFromAnyState(t, pb.MsgVote)
  423. }
  424. func TestPreVoteFromAnyState(t *testing.T) {
  425. testVoteFromAnyState(t, pb.MsgPreVote)
  426. }
  427. func testVoteFromAnyState(t *testing.T, vt pb.MessageType) {
  428. for st := StateType(0); st < numStates; st++ {
  429. r := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  430. r.Term = 1
  431. switch st {
  432. case StateFollower:
  433. r.becomeFollower(r.Term, 3)
  434. case StatePreCandidate:
  435. r.becomePreCandidate()
  436. case StateCandidate:
  437. r.becomeCandidate()
  438. case StateLeader:
  439. r.becomeCandidate()
  440. r.becomeLeader()
  441. }
  442. // Note that setting our state above may have advanced r.Term
  443. // past its initial value.
  444. origTerm := r.Term
  445. newTerm := r.Term + 1
  446. msg := pb.Message{
  447. From: 2,
  448. To: 1,
  449. Type: vt,
  450. Term: newTerm,
  451. LogTerm: newTerm,
  452. Index: 42,
  453. }
  454. if err := r.Step(msg); err != nil {
  455. t.Errorf("%s,%s: Step failed: %s", vt, st, err)
  456. }
  457. if len(r.msgs) != 1 {
  458. t.Errorf("%s,%s: %d response messages, want 1: %+v", vt, st, len(r.msgs), r.msgs)
  459. } else {
  460. resp := r.msgs[0]
  461. if resp.Type != voteRespMsgType(vt) {
  462. t.Errorf("%s,%s: response message is %s, want %s",
  463. vt, st, resp.Type, voteRespMsgType(vt))
  464. }
  465. if resp.Reject {
  466. t.Errorf("%s,%s: unexpected rejection", vt, st)
  467. }
  468. }
  469. // If this was a real vote, we reset our state and term.
  470. if vt == pb.MsgVote {
  471. if r.state != StateFollower {
  472. t.Errorf("%s,%s: state %s, want %s", vt, st, r.state, StateFollower)
  473. }
  474. if r.Term != newTerm {
  475. t.Errorf("%s,%s: term %d, want %d", vt, st, r.Term, newTerm)
  476. }
  477. if r.Vote != 2 {
  478. t.Errorf("%s,%s: vote %d, want 2", vt, st, r.Vote)
  479. }
  480. } else {
  481. // In a prevote, nothing changes.
  482. if r.state != st {
  483. t.Errorf("%s,%s: state %s, want %s", vt, st, r.state, st)
  484. }
  485. if r.Term != origTerm {
  486. t.Errorf("%s,%s: term %d, want %d", vt, st, r.Term, origTerm)
  487. }
  488. // if st == StateFollower or StatePreCandidate, r hasn't voted yet.
  489. // In StateCandidate or StateLeader, it's voted for itself.
  490. if r.Vote != None && r.Vote != 1 {
  491. t.Errorf("%s,%s: vote %d, want %d or 1", vt, st, r.Vote, None)
  492. }
  493. }
  494. }
  495. }
  496. func TestLogReplication(t *testing.T) {
  497. tests := []struct {
  498. *network
  499. msgs []pb.Message
  500. wcommitted uint64
  501. }{
  502. {
  503. newNetwork(nil, nil, nil),
  504. []pb.Message{
  505. {From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}},
  506. },
  507. 2,
  508. },
  509. {
  510. newNetwork(nil, nil, nil),
  511. []pb.Message{
  512. {From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}},
  513. {From: 1, To: 2, Type: pb.MsgHup},
  514. {From: 1, To: 2, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}},
  515. },
  516. 4,
  517. },
  518. }
  519. for i, tt := range tests {
  520. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  521. for _, m := range tt.msgs {
  522. tt.send(m)
  523. }
  524. for j, x := range tt.network.peers {
  525. sm := x.(*raft)
  526. if sm.raftLog.committed != tt.wcommitted {
  527. t.Errorf("#%d.%d: committed = %d, want %d", i, j, sm.raftLog.committed, tt.wcommitted)
  528. }
  529. ents := []pb.Entry{}
  530. for _, e := range nextEnts(sm, tt.network.storage[j]) {
  531. if e.Data != nil {
  532. ents = append(ents, e)
  533. }
  534. }
  535. props := []pb.Message{}
  536. for _, m := range tt.msgs {
  537. if m.Type == pb.MsgProp {
  538. props = append(props, m)
  539. }
  540. }
  541. for k, m := range props {
  542. if !bytes.Equal(ents[k].Data, m.Entries[0].Data) {
  543. t.Errorf("#%d.%d: data = %d, want %d", i, j, ents[k].Data, m.Entries[0].Data)
  544. }
  545. }
  546. }
  547. }
  548. }
  549. func TestSingleNodeCommit(t *testing.T) {
  550. tt := newNetwork(nil)
  551. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  552. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  553. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  554. sm := tt.peers[1].(*raft)
  555. if sm.raftLog.committed != 3 {
  556. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 3)
  557. }
  558. }
  559. // TestCannotCommitWithoutNewTermEntry tests the entries cannot be committed
  560. // when leader changes, no new proposal comes in and ChangeTerm proposal is
  561. // filtered.
  562. func TestCannotCommitWithoutNewTermEntry(t *testing.T) {
  563. tt := newNetwork(nil, nil, nil, nil, nil)
  564. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  565. // 0 cannot reach 2,3,4
  566. tt.cut(1, 3)
  567. tt.cut(1, 4)
  568. tt.cut(1, 5)
  569. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  570. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  571. sm := tt.peers[1].(*raft)
  572. if sm.raftLog.committed != 1 {
  573. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 1)
  574. }
  575. // network recovery
  576. tt.recover()
  577. // avoid committing ChangeTerm proposal
  578. tt.ignore(pb.MsgApp)
  579. // elect 2 as the new leader with term 2
  580. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  581. // no log entries from previous term should be committed
  582. sm = tt.peers[2].(*raft)
  583. if sm.raftLog.committed != 1 {
  584. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 1)
  585. }
  586. tt.recover()
  587. // send heartbeat; reset wait
  588. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgBeat})
  589. // append an entry at current term
  590. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  591. // expect the committed to be advanced
  592. if sm.raftLog.committed != 5 {
  593. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 5)
  594. }
  595. }
  596. // TestCommitWithoutNewTermEntry tests the entries could be committed
  597. // when leader changes, no new proposal comes in.
  598. func TestCommitWithoutNewTermEntry(t *testing.T) {
  599. tt := newNetwork(nil, nil, nil, nil, nil)
  600. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  601. // 0 cannot reach 2,3,4
  602. tt.cut(1, 3)
  603. tt.cut(1, 4)
  604. tt.cut(1, 5)
  605. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  606. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  607. sm := tt.peers[1].(*raft)
  608. if sm.raftLog.committed != 1 {
  609. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 1)
  610. }
  611. // network recovery
  612. tt.recover()
  613. // elect 1 as the new leader with term 2
  614. // after append a ChangeTerm entry from the current term, all entries
  615. // should be committed
  616. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  617. if sm.raftLog.committed != 4 {
  618. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 4)
  619. }
  620. }
  621. func TestDuelingCandidates(t *testing.T) {
  622. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  623. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  624. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  625. nt := newNetwork(a, b, c)
  626. nt.cut(1, 3)
  627. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  628. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  629. // 1 becomes leader since it receives votes from 1 and 2
  630. sm := nt.peers[1].(*raft)
  631. if sm.state != StateLeader {
  632. t.Errorf("state = %s, want %s", sm.state, StateLeader)
  633. }
  634. // 3 stays as candidate since it receives a vote from 3 and a rejection from 2
  635. sm = nt.peers[3].(*raft)
  636. if sm.state != StateCandidate {
  637. t.Errorf("state = %s, want %s", sm.state, StateCandidate)
  638. }
  639. nt.recover()
  640. // candidate 3 now increases its term and tries to vote again
  641. // we expect it to disrupt the leader 1 since it has a higher term
  642. // 3 will be follower again since both 1 and 2 rejects its vote request since 3 does not have a long enough log
  643. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  644. wlog := &raftLog{
  645. storage: &MemoryStorage{ents: []pb.Entry{{}, {Data: nil, Term: 1, Index: 1}}},
  646. committed: 1,
  647. unstable: unstable{offset: 2},
  648. }
  649. tests := []struct {
  650. sm *raft
  651. state StateType
  652. term uint64
  653. raftLog *raftLog
  654. }{
  655. {a, StateFollower, 2, wlog},
  656. {b, StateFollower, 2, wlog},
  657. {c, StateFollower, 2, newLog(NewMemoryStorage(), raftLogger)},
  658. }
  659. for i, tt := range tests {
  660. if g := tt.sm.state; g != tt.state {
  661. t.Errorf("#%d: state = %s, want %s", i, g, tt.state)
  662. }
  663. if g := tt.sm.Term; g != tt.term {
  664. t.Errorf("#%d: term = %d, want %d", i, g, tt.term)
  665. }
  666. base := ltoa(tt.raftLog)
  667. if sm, ok := nt.peers[1+uint64(i)].(*raft); ok {
  668. l := ltoa(sm.raftLog)
  669. if g := diffu(base, l); g != "" {
  670. t.Errorf("#%d: diff:\n%s", i, g)
  671. }
  672. } else {
  673. t.Logf("#%d: empty log", i)
  674. }
  675. }
  676. }
  677. func TestDuelingPreCandidates(t *testing.T) {
  678. cfgA := newTestConfig(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  679. cfgB := newTestConfig(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  680. cfgC := newTestConfig(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  681. cfgA.PreVote = true
  682. cfgB.PreVote = true
  683. cfgC.PreVote = true
  684. a := newRaft(cfgA)
  685. b := newRaft(cfgB)
  686. c := newRaft(cfgC)
  687. nt := newNetwork(a, b, c)
  688. nt.cut(1, 3)
  689. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  690. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  691. // 1 becomes leader since it receives votes from 1 and 2
  692. sm := nt.peers[1].(*raft)
  693. if sm.state != StateLeader {
  694. t.Errorf("state = %s, want %s", sm.state, StateLeader)
  695. }
  696. // 3 campaigns then reverts to follower when its PreVote is rejected
  697. sm = nt.peers[3].(*raft)
  698. if sm.state != StateFollower {
  699. t.Errorf("state = %s, want %s", sm.state, StateFollower)
  700. }
  701. nt.recover()
  702. // Candidate 3 now increases its term and tries to vote again.
  703. // With PreVote, it does not disrupt the leader.
  704. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  705. wlog := &raftLog{
  706. storage: &MemoryStorage{ents: []pb.Entry{{}, {Data: nil, Term: 1, Index: 1}}},
  707. committed: 1,
  708. unstable: unstable{offset: 2},
  709. }
  710. tests := []struct {
  711. sm *raft
  712. state StateType
  713. term uint64
  714. raftLog *raftLog
  715. }{
  716. {a, StateLeader, 1, wlog},
  717. {b, StateFollower, 1, wlog},
  718. {c, StateFollower, 1, newLog(NewMemoryStorage(), raftLogger)},
  719. }
  720. for i, tt := range tests {
  721. if g := tt.sm.state; g != tt.state {
  722. t.Errorf("#%d: state = %s, want %s", i, g, tt.state)
  723. }
  724. if g := tt.sm.Term; g != tt.term {
  725. t.Errorf("#%d: term = %d, want %d", i, g, tt.term)
  726. }
  727. base := ltoa(tt.raftLog)
  728. if sm, ok := nt.peers[1+uint64(i)].(*raft); ok {
  729. l := ltoa(sm.raftLog)
  730. if g := diffu(base, l); g != "" {
  731. t.Errorf("#%d: diff:\n%s", i, g)
  732. }
  733. } else {
  734. t.Logf("#%d: empty log", i)
  735. }
  736. }
  737. }
  738. func TestCandidateConcede(t *testing.T) {
  739. tt := newNetwork(nil, nil, nil)
  740. tt.isolate(1)
  741. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  742. tt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  743. // heal the partition
  744. tt.recover()
  745. // send heartbeat; reset wait
  746. tt.send(pb.Message{From: 3, To: 3, Type: pb.MsgBeat})
  747. data := []byte("force follower")
  748. // send a proposal to 3 to flush out a MsgApp to 1
  749. tt.send(pb.Message{From: 3, To: 3, Type: pb.MsgProp, Entries: []pb.Entry{{Data: data}}})
  750. // send heartbeat; flush out commit
  751. tt.send(pb.Message{From: 3, To: 3, Type: pb.MsgBeat})
  752. a := tt.peers[1].(*raft)
  753. if g := a.state; g != StateFollower {
  754. t.Errorf("state = %s, want %s", g, StateFollower)
  755. }
  756. if g := a.Term; g != 1 {
  757. t.Errorf("term = %d, want %d", g, 1)
  758. }
  759. wantLog := ltoa(&raftLog{
  760. storage: &MemoryStorage{
  761. ents: []pb.Entry{{}, {Data: nil, Term: 1, Index: 1}, {Term: 1, Index: 2, Data: data}},
  762. },
  763. unstable: unstable{offset: 3},
  764. committed: 2,
  765. })
  766. for i, p := range tt.peers {
  767. if sm, ok := p.(*raft); ok {
  768. l := ltoa(sm.raftLog)
  769. if g := diffu(wantLog, l); g != "" {
  770. t.Errorf("#%d: diff:\n%s", i, g)
  771. }
  772. } else {
  773. t.Logf("#%d: empty log", i)
  774. }
  775. }
  776. }
  777. func TestSingleNodeCandidate(t *testing.T) {
  778. tt := newNetwork(nil)
  779. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  780. sm := tt.peers[1].(*raft)
  781. if sm.state != StateLeader {
  782. t.Errorf("state = %d, want %d", sm.state, StateLeader)
  783. }
  784. }
  785. func TestSingleNodePreCandidate(t *testing.T) {
  786. tt := newNetworkWithConfig(preVoteConfig, nil)
  787. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  788. sm := tt.peers[1].(*raft)
  789. if sm.state != StateLeader {
  790. t.Errorf("state = %d, want %d", sm.state, StateLeader)
  791. }
  792. }
  793. func TestOldMessages(t *testing.T) {
  794. tt := newNetwork(nil, nil, nil)
  795. // make 0 leader @ term 3
  796. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  797. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  798. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  799. // pretend we're an old leader trying to make progress; this entry is expected to be ignored.
  800. tt.send(pb.Message{From: 2, To: 1, Type: pb.MsgApp, Term: 2, Entries: []pb.Entry{{Index: 3, Term: 2}}})
  801. // commit a new entry
  802. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  803. ilog := &raftLog{
  804. storage: &MemoryStorage{
  805. ents: []pb.Entry{
  806. {}, {Data: nil, Term: 1, Index: 1},
  807. {Data: nil, Term: 2, Index: 2}, {Data: nil, Term: 3, Index: 3},
  808. {Data: []byte("somedata"), Term: 3, Index: 4},
  809. },
  810. },
  811. unstable: unstable{offset: 5},
  812. committed: 4,
  813. }
  814. base := ltoa(ilog)
  815. for i, p := range tt.peers {
  816. if sm, ok := p.(*raft); ok {
  817. l := ltoa(sm.raftLog)
  818. if g := diffu(base, l); g != "" {
  819. t.Errorf("#%d: diff:\n%s", i, g)
  820. }
  821. } else {
  822. t.Logf("#%d: empty log", i)
  823. }
  824. }
  825. }
  826. // TestOldMessagesReply - optimization - reply with new term.
  827. func TestProposal(t *testing.T) {
  828. tests := []struct {
  829. *network
  830. success bool
  831. }{
  832. {newNetwork(nil, nil, nil), true},
  833. {newNetwork(nil, nil, nopStepper), true},
  834. {newNetwork(nil, nopStepper, nopStepper), false},
  835. {newNetwork(nil, nopStepper, nopStepper, nil), false},
  836. {newNetwork(nil, nopStepper, nopStepper, nil, nil), true},
  837. }
  838. for j, tt := range tests {
  839. send := func(m pb.Message) {
  840. defer func() {
  841. // only recover is we expect it to panic so
  842. // panics we don't expect go up.
  843. if !tt.success {
  844. e := recover()
  845. if e != nil {
  846. t.Logf("#%d: err: %s", j, e)
  847. }
  848. }
  849. }()
  850. tt.send(m)
  851. }
  852. data := []byte("somedata")
  853. // promote 0 the leader
  854. send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  855. send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: data}}})
  856. wantLog := newLog(NewMemoryStorage(), raftLogger)
  857. if tt.success {
  858. wantLog = &raftLog{
  859. storage: &MemoryStorage{
  860. ents: []pb.Entry{{}, {Data: nil, Term: 1, Index: 1}, {Term: 1, Index: 2, Data: data}},
  861. },
  862. unstable: unstable{offset: 3},
  863. committed: 2}
  864. }
  865. base := ltoa(wantLog)
  866. for i, p := range tt.peers {
  867. if sm, ok := p.(*raft); ok {
  868. l := ltoa(sm.raftLog)
  869. if g := diffu(base, l); g != "" {
  870. t.Errorf("#%d: diff:\n%s", i, g)
  871. }
  872. } else {
  873. t.Logf("#%d: empty log", i)
  874. }
  875. }
  876. sm := tt.network.peers[1].(*raft)
  877. if g := sm.Term; g != 1 {
  878. t.Errorf("#%d: term = %d, want %d", j, g, 1)
  879. }
  880. }
  881. }
  882. func TestProposalByProxy(t *testing.T) {
  883. data := []byte("somedata")
  884. tests := []*network{
  885. newNetwork(nil, nil, nil),
  886. newNetwork(nil, nil, nopStepper),
  887. }
  888. for j, tt := range tests {
  889. // promote 0 the leader
  890. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  891. // propose via follower
  892. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  893. wantLog := &raftLog{
  894. storage: &MemoryStorage{
  895. ents: []pb.Entry{{}, {Data: nil, Term: 1, Index: 1}, {Term: 1, Data: data, Index: 2}},
  896. },
  897. unstable: unstable{offset: 3},
  898. committed: 2}
  899. base := ltoa(wantLog)
  900. for i, p := range tt.peers {
  901. if sm, ok := p.(*raft); ok {
  902. l := ltoa(sm.raftLog)
  903. if g := diffu(base, l); g != "" {
  904. t.Errorf("#%d: diff:\n%s", i, g)
  905. }
  906. } else {
  907. t.Logf("#%d: empty log", i)
  908. }
  909. }
  910. sm := tt.peers[1].(*raft)
  911. if g := sm.Term; g != 1 {
  912. t.Errorf("#%d: term = %d, want %d", j, g, 1)
  913. }
  914. }
  915. }
  916. func TestCommit(t *testing.T) {
  917. tests := []struct {
  918. matches []uint64
  919. logs []pb.Entry
  920. smTerm uint64
  921. w uint64
  922. }{
  923. // single
  924. {[]uint64{1}, []pb.Entry{{Index: 1, Term: 1}}, 1, 1},
  925. {[]uint64{1}, []pb.Entry{{Index: 1, Term: 1}}, 2, 0},
  926. {[]uint64{2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 2, 2},
  927. {[]uint64{1}, []pb.Entry{{Index: 1, Term: 2}}, 2, 1},
  928. // odd
  929. {[]uint64{2, 1, 1}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 1, 1},
  930. {[]uint64{2, 1, 1}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}}, 2, 0},
  931. {[]uint64{2, 1, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 2, 2},
  932. {[]uint64{2, 1, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}}, 2, 0},
  933. // even
  934. {[]uint64{2, 1, 1, 1}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 1, 1},
  935. {[]uint64{2, 1, 1, 1}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}}, 2, 0},
  936. {[]uint64{2, 1, 1, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 1, 1},
  937. {[]uint64{2, 1, 1, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}}, 2, 0},
  938. {[]uint64{2, 1, 2, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 2, 2},
  939. {[]uint64{2, 1, 2, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}}, 2, 0},
  940. }
  941. for i, tt := range tests {
  942. storage := NewMemoryStorage()
  943. storage.Append(tt.logs)
  944. storage.hardState = pb.HardState{Term: tt.smTerm}
  945. sm := newTestRaft(1, []uint64{1}, 5, 1, storage)
  946. for j := 0; j < len(tt.matches); j++ {
  947. sm.setProgress(uint64(j)+1, tt.matches[j], tt.matches[j]+1)
  948. }
  949. sm.maybeCommit()
  950. if g := sm.raftLog.committed; g != tt.w {
  951. t.Errorf("#%d: committed = %d, want %d", i, g, tt.w)
  952. }
  953. }
  954. }
  955. func TestPastElectionTimeout(t *testing.T) {
  956. tests := []struct {
  957. elapse int
  958. wprobability float64
  959. round bool
  960. }{
  961. {5, 0, false},
  962. {10, 0.1, true},
  963. {13, 0.4, true},
  964. {15, 0.6, true},
  965. {18, 0.9, true},
  966. {20, 1, false},
  967. }
  968. for i, tt := range tests {
  969. sm := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  970. sm.electionElapsed = tt.elapse
  971. c := 0
  972. for j := 0; j < 10000; j++ {
  973. sm.resetRandomizedElectionTimeout()
  974. if sm.pastElectionTimeout() {
  975. c++
  976. }
  977. }
  978. got := float64(c) / 10000.0
  979. if tt.round {
  980. got = math.Floor(got*10+0.5) / 10.0
  981. }
  982. if got != tt.wprobability {
  983. t.Errorf("#%d: probability = %v, want %v", i, got, tt.wprobability)
  984. }
  985. }
  986. }
  987. // ensure that the Step function ignores the message from old term and does not pass it to the
  988. // actual stepX function.
  989. func TestStepIgnoreOldTermMsg(t *testing.T) {
  990. called := false
  991. fakeStep := func(r *raft, m pb.Message) {
  992. called = true
  993. }
  994. sm := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  995. sm.step = fakeStep
  996. sm.Term = 2
  997. sm.Step(pb.Message{Type: pb.MsgApp, Term: sm.Term - 1})
  998. if called {
  999. t.Errorf("stepFunc called = %v , want %v", called, false)
  1000. }
  1001. }
  1002. // TestHandleMsgApp ensures:
  1003. // 1. Reply false if log doesn’t contain an entry at prevLogIndex whose term matches prevLogTerm.
  1004. // 2. If an existing entry conflicts with a new one (same index but different terms),
  1005. // delete the existing entry and all that follow it; append any new entries not already in the log.
  1006. // 3. If leaderCommit > commitIndex, set commitIndex = min(leaderCommit, index of last new entry).
  1007. func TestHandleMsgApp(t *testing.T) {
  1008. tests := []struct {
  1009. m pb.Message
  1010. wIndex uint64
  1011. wCommit uint64
  1012. wReject bool
  1013. }{
  1014. // Ensure 1
  1015. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 3, Index: 2, Commit: 3}, 2, 0, true}, // previous log mismatch
  1016. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 3, Index: 3, Commit: 3}, 2, 0, true}, // previous log non-exist
  1017. // Ensure 2
  1018. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 1, Index: 1, Commit: 1}, 2, 1, false},
  1019. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 0, Index: 0, Commit: 1, Entries: []pb.Entry{{Index: 1, Term: 2}}}, 1, 1, false},
  1020. {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},
  1021. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 2, Index: 2, Commit: 4, Entries: []pb.Entry{{Index: 3, Term: 2}}}, 3, 3, false},
  1022. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 1, Index: 1, Commit: 4, Entries: []pb.Entry{{Index: 2, Term: 2}}}, 2, 2, false},
  1023. // Ensure 3
  1024. {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
  1025. {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
  1026. {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
  1027. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 2, Index: 2, Commit: 4}, 2, 2, false}, // commit up to log.last()
  1028. }
  1029. for i, tt := range tests {
  1030. storage := NewMemoryStorage()
  1031. storage.Append([]pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}})
  1032. sm := newTestRaft(1, []uint64{1}, 10, 1, storage)
  1033. sm.becomeFollower(2, None)
  1034. sm.handleAppendEntries(tt.m)
  1035. if sm.raftLog.lastIndex() != tt.wIndex {
  1036. t.Errorf("#%d: lastIndex = %d, want %d", i, sm.raftLog.lastIndex(), tt.wIndex)
  1037. }
  1038. if sm.raftLog.committed != tt.wCommit {
  1039. t.Errorf("#%d: committed = %d, want %d", i, sm.raftLog.committed, tt.wCommit)
  1040. }
  1041. m := sm.readMessages()
  1042. if len(m) != 1 {
  1043. t.Fatalf("#%d: msg = nil, want 1", i)
  1044. }
  1045. if m[0].Reject != tt.wReject {
  1046. t.Errorf("#%d: reject = %v, want %v", i, m[0].Reject, tt.wReject)
  1047. }
  1048. }
  1049. }
  1050. // TestHandleHeartbeat ensures that the follower commits to the commit in the message.
  1051. func TestHandleHeartbeat(t *testing.T) {
  1052. commit := uint64(2)
  1053. tests := []struct {
  1054. m pb.Message
  1055. wCommit uint64
  1056. }{
  1057. {pb.Message{From: 2, To: 1, Type: pb.MsgHeartbeat, Term: 2, Commit: commit + 1}, commit + 1},
  1058. {pb.Message{From: 2, To: 1, Type: pb.MsgHeartbeat, Term: 2, Commit: commit - 1}, commit}, // do not decrease commit
  1059. }
  1060. for i, tt := range tests {
  1061. storage := NewMemoryStorage()
  1062. storage.Append([]pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}, {Index: 3, Term: 3}})
  1063. sm := newTestRaft(1, []uint64{1, 2}, 5, 1, storage)
  1064. sm.becomeFollower(2, 2)
  1065. sm.raftLog.commitTo(commit)
  1066. sm.handleHeartbeat(tt.m)
  1067. if sm.raftLog.committed != tt.wCommit {
  1068. t.Errorf("#%d: committed = %d, want %d", i, sm.raftLog.committed, tt.wCommit)
  1069. }
  1070. m := sm.readMessages()
  1071. if len(m) != 1 {
  1072. t.Fatalf("#%d: msg = nil, want 1", i)
  1073. }
  1074. if m[0].Type != pb.MsgHeartbeatResp {
  1075. t.Errorf("#%d: type = %v, want MsgHeartbeatResp", i, m[0].Type)
  1076. }
  1077. }
  1078. }
  1079. // TestHandleHeartbeatResp ensures that we re-send log entries when we get a heartbeat response.
  1080. func TestHandleHeartbeatResp(t *testing.T) {
  1081. storage := NewMemoryStorage()
  1082. storage.Append([]pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}, {Index: 3, Term: 3}})
  1083. sm := newTestRaft(1, []uint64{1, 2}, 5, 1, storage)
  1084. sm.becomeCandidate()
  1085. sm.becomeLeader()
  1086. sm.raftLog.commitTo(sm.raftLog.lastIndex())
  1087. // A heartbeat response from a node that is behind; re-send MsgApp
  1088. sm.Step(pb.Message{From: 2, Type: pb.MsgHeartbeatResp})
  1089. msgs := sm.readMessages()
  1090. if len(msgs) != 1 {
  1091. t.Fatalf("len(msgs) = %d, want 1", len(msgs))
  1092. }
  1093. if msgs[0].Type != pb.MsgApp {
  1094. t.Errorf("type = %v, want MsgApp", msgs[0].Type)
  1095. }
  1096. // A second heartbeat response generates another MsgApp re-send
  1097. sm.Step(pb.Message{From: 2, Type: pb.MsgHeartbeatResp})
  1098. msgs = sm.readMessages()
  1099. if len(msgs) != 1 {
  1100. t.Fatalf("len(msgs) = %d, want 1", len(msgs))
  1101. }
  1102. if msgs[0].Type != pb.MsgApp {
  1103. t.Errorf("type = %v, want MsgApp", msgs[0].Type)
  1104. }
  1105. // Once we have an MsgAppResp, heartbeats no longer send MsgApp.
  1106. sm.Step(pb.Message{
  1107. From: 2,
  1108. Type: pb.MsgAppResp,
  1109. Index: msgs[0].Index + uint64(len(msgs[0].Entries)),
  1110. })
  1111. // Consume the message sent in response to MsgAppResp
  1112. sm.readMessages()
  1113. sm.Step(pb.Message{From: 2, Type: pb.MsgHeartbeatResp})
  1114. msgs = sm.readMessages()
  1115. if len(msgs) != 0 {
  1116. t.Fatalf("len(msgs) = %d, want 0: %+v", len(msgs), msgs)
  1117. }
  1118. }
  1119. // TestMsgAppRespWaitReset verifies the resume behavior of a leader
  1120. // MsgAppResp.
  1121. func TestMsgAppRespWaitReset(t *testing.T) {
  1122. sm := newTestRaft(1, []uint64{1, 2, 3}, 5, 1, NewMemoryStorage())
  1123. sm.becomeCandidate()
  1124. sm.becomeLeader()
  1125. // The new leader has just emitted a new Term 4 entry; consume those messages
  1126. // from the outgoing queue.
  1127. sm.bcastAppend()
  1128. sm.readMessages()
  1129. // Node 2 acks the first entry, making it committed.
  1130. sm.Step(pb.Message{
  1131. From: 2,
  1132. Type: pb.MsgAppResp,
  1133. Index: 1,
  1134. })
  1135. if sm.raftLog.committed != 1 {
  1136. t.Fatalf("expected committed to be 1, got %d", sm.raftLog.committed)
  1137. }
  1138. // Also consume the MsgApp messages that update Commit on the followers.
  1139. sm.readMessages()
  1140. // A new command is now proposed on node 1.
  1141. sm.Step(pb.Message{
  1142. From: 1,
  1143. Type: pb.MsgProp,
  1144. Entries: []pb.Entry{{}},
  1145. })
  1146. // The command is broadcast to all nodes not in the wait state.
  1147. // Node 2 left the wait state due to its MsgAppResp, but node 3 is still waiting.
  1148. msgs := sm.readMessages()
  1149. if len(msgs) != 1 {
  1150. t.Fatalf("expected 1 message, got %d: %+v", len(msgs), msgs)
  1151. }
  1152. if msgs[0].Type != pb.MsgApp || msgs[0].To != 2 {
  1153. t.Errorf("expected MsgApp to node 2, got %v to %d", msgs[0].Type, msgs[0].To)
  1154. }
  1155. if len(msgs[0].Entries) != 1 || msgs[0].Entries[0].Index != 2 {
  1156. t.Errorf("expected to send entry 2, but got %v", msgs[0].Entries)
  1157. }
  1158. // Now Node 3 acks the first entry. This releases the wait and entry 2 is sent.
  1159. sm.Step(pb.Message{
  1160. From: 3,
  1161. Type: pb.MsgAppResp,
  1162. Index: 1,
  1163. })
  1164. msgs = sm.readMessages()
  1165. if len(msgs) != 1 {
  1166. t.Fatalf("expected 1 message, got %d: %+v", len(msgs), msgs)
  1167. }
  1168. if msgs[0].Type != pb.MsgApp || msgs[0].To != 3 {
  1169. t.Errorf("expected MsgApp to node 3, got %v to %d", msgs[0].Type, msgs[0].To)
  1170. }
  1171. if len(msgs[0].Entries) != 1 || msgs[0].Entries[0].Index != 2 {
  1172. t.Errorf("expected to send entry 2, but got %v", msgs[0].Entries)
  1173. }
  1174. }
  1175. func TestRecvMsgVote(t *testing.T) {
  1176. testRecvMsgVote(t, pb.MsgVote)
  1177. }
  1178. func testRecvMsgVote(t *testing.T, msgType pb.MessageType) {
  1179. tests := []struct {
  1180. state StateType
  1181. i, term uint64
  1182. voteFor uint64
  1183. wreject bool
  1184. }{
  1185. {StateFollower, 0, 0, None, true},
  1186. {StateFollower, 0, 1, None, true},
  1187. {StateFollower, 0, 2, None, true},
  1188. {StateFollower, 0, 3, None, false},
  1189. {StateFollower, 1, 0, None, true},
  1190. {StateFollower, 1, 1, None, true},
  1191. {StateFollower, 1, 2, None, true},
  1192. {StateFollower, 1, 3, None, false},
  1193. {StateFollower, 2, 0, None, true},
  1194. {StateFollower, 2, 1, None, true},
  1195. {StateFollower, 2, 2, None, false},
  1196. {StateFollower, 2, 3, None, false},
  1197. {StateFollower, 3, 0, None, true},
  1198. {StateFollower, 3, 1, None, true},
  1199. {StateFollower, 3, 2, None, false},
  1200. {StateFollower, 3, 3, None, false},
  1201. {StateFollower, 3, 2, 2, false},
  1202. {StateFollower, 3, 2, 1, true},
  1203. {StateLeader, 3, 3, 1, true},
  1204. {StatePreCandidate, 3, 3, 1, true},
  1205. {StateCandidate, 3, 3, 1, true},
  1206. }
  1207. for i, tt := range tests {
  1208. sm := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  1209. sm.state = tt.state
  1210. switch tt.state {
  1211. case StateFollower:
  1212. sm.step = stepFollower
  1213. case StateCandidate, StatePreCandidate:
  1214. sm.step = stepCandidate
  1215. case StateLeader:
  1216. sm.step = stepLeader
  1217. }
  1218. sm.Vote = tt.voteFor
  1219. sm.raftLog = &raftLog{
  1220. storage: &MemoryStorage{ents: []pb.Entry{{}, {Index: 1, Term: 2}, {Index: 2, Term: 2}}},
  1221. unstable: unstable{offset: 3},
  1222. }
  1223. sm.Step(pb.Message{Type: msgType, From: 2, Index: tt.i, LogTerm: tt.term})
  1224. msgs := sm.readMessages()
  1225. if g := len(msgs); g != 1 {
  1226. t.Fatalf("#%d: len(msgs) = %d, want 1", i, g)
  1227. continue
  1228. }
  1229. if g := msgs[0].Type; g != voteRespMsgType(msgType) {
  1230. t.Errorf("#%d, m.Type = %v, want %v", i, g, voteRespMsgType(msgType))
  1231. }
  1232. if g := msgs[0].Reject; g != tt.wreject {
  1233. t.Errorf("#%d, m.Reject = %v, want %v", i, g, tt.wreject)
  1234. }
  1235. }
  1236. }
  1237. func TestStateTransition(t *testing.T) {
  1238. tests := []struct {
  1239. from StateType
  1240. to StateType
  1241. wallow bool
  1242. wterm uint64
  1243. wlead uint64
  1244. }{
  1245. {StateFollower, StateFollower, true, 1, None},
  1246. {StateFollower, StatePreCandidate, true, 0, None},
  1247. {StateFollower, StateCandidate, true, 1, None},
  1248. {StateFollower, StateLeader, false, 0, None},
  1249. {StatePreCandidate, StateFollower, true, 0, None},
  1250. {StatePreCandidate, StatePreCandidate, true, 0, None},
  1251. {StatePreCandidate, StateCandidate, true, 1, None},
  1252. {StatePreCandidate, StateLeader, true, 0, 1},
  1253. {StateCandidate, StateFollower, true, 0, None},
  1254. {StateCandidate, StatePreCandidate, true, 0, None},
  1255. {StateCandidate, StateCandidate, true, 1, None},
  1256. {StateCandidate, StateLeader, true, 0, 1},
  1257. {StateLeader, StateFollower, true, 1, None},
  1258. {StateLeader, StatePreCandidate, false, 0, None},
  1259. {StateLeader, StateCandidate, false, 1, None},
  1260. {StateLeader, StateLeader, true, 0, 1},
  1261. }
  1262. for i, tt := range tests {
  1263. func() {
  1264. defer func() {
  1265. if r := recover(); r != nil {
  1266. if tt.wallow {
  1267. t.Errorf("%d: allow = %v, want %v", i, false, true)
  1268. }
  1269. }
  1270. }()
  1271. sm := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  1272. sm.state = tt.from
  1273. switch tt.to {
  1274. case StateFollower:
  1275. sm.becomeFollower(tt.wterm, tt.wlead)
  1276. case StatePreCandidate:
  1277. sm.becomePreCandidate()
  1278. case StateCandidate:
  1279. sm.becomeCandidate()
  1280. case StateLeader:
  1281. sm.becomeLeader()
  1282. }
  1283. if sm.Term != tt.wterm {
  1284. t.Errorf("%d: term = %d, want %d", i, sm.Term, tt.wterm)
  1285. }
  1286. if sm.lead != tt.wlead {
  1287. t.Errorf("%d: lead = %d, want %d", i, sm.lead, tt.wlead)
  1288. }
  1289. }()
  1290. }
  1291. }
  1292. func TestAllServerStepdown(t *testing.T) {
  1293. tests := []struct {
  1294. state StateType
  1295. wstate StateType
  1296. wterm uint64
  1297. windex uint64
  1298. }{
  1299. {StateFollower, StateFollower, 3, 0},
  1300. {StatePreCandidate, StateFollower, 3, 0},
  1301. {StateCandidate, StateFollower, 3, 0},
  1302. {StateLeader, StateFollower, 3, 1},
  1303. }
  1304. tmsgTypes := [...]pb.MessageType{pb.MsgVote, pb.MsgApp}
  1305. tterm := uint64(3)
  1306. for i, tt := range tests {
  1307. sm := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1308. switch tt.state {
  1309. case StateFollower:
  1310. sm.becomeFollower(1, None)
  1311. case StatePreCandidate:
  1312. sm.becomePreCandidate()
  1313. case StateCandidate:
  1314. sm.becomeCandidate()
  1315. case StateLeader:
  1316. sm.becomeCandidate()
  1317. sm.becomeLeader()
  1318. }
  1319. for j, msgType := range tmsgTypes {
  1320. sm.Step(pb.Message{From: 2, Type: msgType, Term: tterm, LogTerm: tterm})
  1321. if sm.state != tt.wstate {
  1322. t.Errorf("#%d.%d state = %v , want %v", i, j, sm.state, tt.wstate)
  1323. }
  1324. if sm.Term != tt.wterm {
  1325. t.Errorf("#%d.%d term = %v , want %v", i, j, sm.Term, tt.wterm)
  1326. }
  1327. if uint64(sm.raftLog.lastIndex()) != tt.windex {
  1328. t.Errorf("#%d.%d index = %v , want %v", i, j, sm.raftLog.lastIndex(), tt.windex)
  1329. }
  1330. if uint64(len(sm.raftLog.allEntries())) != tt.windex {
  1331. t.Errorf("#%d.%d len(ents) = %v , want %v", i, j, len(sm.raftLog.allEntries()), tt.windex)
  1332. }
  1333. wlead := uint64(2)
  1334. if msgType == pb.MsgVote {
  1335. wlead = None
  1336. }
  1337. if sm.lead != wlead {
  1338. t.Errorf("#%d, sm.lead = %d, want %d", i, sm.lead, None)
  1339. }
  1340. }
  1341. }
  1342. }
  1343. func TestLeaderStepdownWhenQuorumActive(t *testing.T) {
  1344. sm := newTestRaft(1, []uint64{1, 2, 3}, 5, 1, NewMemoryStorage())
  1345. sm.checkQuorum = true
  1346. sm.becomeCandidate()
  1347. sm.becomeLeader()
  1348. for i := 0; i < sm.electionTimeout+1; i++ {
  1349. sm.Step(pb.Message{From: 2, Type: pb.MsgHeartbeatResp, Term: sm.Term})
  1350. sm.tick()
  1351. }
  1352. if sm.state != StateLeader {
  1353. t.Errorf("state = %v, want %v", sm.state, StateLeader)
  1354. }
  1355. }
  1356. func TestLeaderStepdownWhenQuorumLost(t *testing.T) {
  1357. sm := newTestRaft(1, []uint64{1, 2, 3}, 5, 1, NewMemoryStorage())
  1358. sm.checkQuorum = true
  1359. sm.becomeCandidate()
  1360. sm.becomeLeader()
  1361. for i := 0; i < sm.electionTimeout+1; i++ {
  1362. sm.tick()
  1363. }
  1364. if sm.state != StateFollower {
  1365. t.Errorf("state = %v, want %v", sm.state, StateFollower)
  1366. }
  1367. }
  1368. func TestLeaderSupersedingWithCheckQuorum(t *testing.T) {
  1369. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1370. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1371. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1372. a.checkQuorum = true
  1373. b.checkQuorum = true
  1374. c.checkQuorum = true
  1375. nt := newNetwork(a, b, c)
  1376. setRandomizedElectionTimeout(b, b.electionTimeout+1)
  1377. for i := 0; i < b.electionTimeout; i++ {
  1378. b.tick()
  1379. }
  1380. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1381. if a.state != StateLeader {
  1382. t.Errorf("state = %s, want %s", a.state, StateLeader)
  1383. }
  1384. if c.state != StateFollower {
  1385. t.Errorf("state = %s, want %s", c.state, StateFollower)
  1386. }
  1387. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  1388. // Peer b rejected c's vote since its electionElapsed had not reached to electionTimeout
  1389. if c.state != StateCandidate {
  1390. t.Errorf("state = %s, want %s", c.state, StateCandidate)
  1391. }
  1392. // Letting b's electionElapsed reach to electionTimeout
  1393. for i := 0; i < b.electionTimeout; i++ {
  1394. b.tick()
  1395. }
  1396. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  1397. if c.state != StateLeader {
  1398. t.Errorf("state = %s, want %s", c.state, StateLeader)
  1399. }
  1400. }
  1401. func TestLeaderElectionWithCheckQuorum(t *testing.T) {
  1402. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1403. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1404. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1405. a.checkQuorum = true
  1406. b.checkQuorum = true
  1407. c.checkQuorum = true
  1408. nt := newNetwork(a, b, c)
  1409. setRandomizedElectionTimeout(a, a.electionTimeout+1)
  1410. setRandomizedElectionTimeout(b, b.electionTimeout+2)
  1411. // Immediately after creation, votes are cast regardless of the
  1412. // election timeout.
  1413. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1414. if a.state != StateLeader {
  1415. t.Errorf("state = %s, want %s", a.state, StateLeader)
  1416. }
  1417. if c.state != StateFollower {
  1418. t.Errorf("state = %s, want %s", c.state, StateFollower)
  1419. }
  1420. // need to reset randomizedElectionTimeout larger than electionTimeout again,
  1421. // because the value might be reset to electionTimeout since the last state changes
  1422. setRandomizedElectionTimeout(a, a.electionTimeout+1)
  1423. setRandomizedElectionTimeout(b, b.electionTimeout+2)
  1424. for i := 0; i < a.electionTimeout; i++ {
  1425. a.tick()
  1426. }
  1427. for i := 0; i < b.electionTimeout; i++ {
  1428. b.tick()
  1429. }
  1430. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  1431. if a.state != StateFollower {
  1432. t.Errorf("state = %s, want %s", a.state, StateFollower)
  1433. }
  1434. if c.state != StateLeader {
  1435. t.Errorf("state = %s, want %s", c.state, StateLeader)
  1436. }
  1437. }
  1438. // TestFreeStuckCandidateWithCheckQuorum ensures that a candidate with a higher term
  1439. // can disrupt the leader even if the leader still "officially" holds the lease, The
  1440. // leader is expected to step down and adopt the candidate's term
  1441. func TestFreeStuckCandidateWithCheckQuorum(t *testing.T) {
  1442. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1443. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1444. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1445. a.checkQuorum = true
  1446. b.checkQuorum = true
  1447. c.checkQuorum = true
  1448. nt := newNetwork(a, b, c)
  1449. setRandomizedElectionTimeout(b, b.electionTimeout+1)
  1450. for i := 0; i < b.electionTimeout; i++ {
  1451. b.tick()
  1452. }
  1453. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1454. nt.isolate(1)
  1455. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  1456. if b.state != StateFollower {
  1457. t.Errorf("state = %s, want %s", b.state, StateFollower)
  1458. }
  1459. if c.state != StateCandidate {
  1460. t.Errorf("state = %s, want %s", c.state, StateCandidate)
  1461. }
  1462. if c.Term != b.Term+1 {
  1463. t.Errorf("term = %d, want %d", c.Term, b.Term+1)
  1464. }
  1465. // Vote again for safety
  1466. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  1467. if b.state != StateFollower {
  1468. t.Errorf("state = %s, want %s", b.state, StateFollower)
  1469. }
  1470. if c.state != StateCandidate {
  1471. t.Errorf("state = %s, want %s", c.state, StateCandidate)
  1472. }
  1473. if c.Term != b.Term+2 {
  1474. t.Errorf("term = %d, want %d", c.Term, b.Term+2)
  1475. }
  1476. nt.recover()
  1477. nt.send(pb.Message{From: 1, To: 3, Type: pb.MsgHeartbeat, Term: a.Term})
  1478. // Disrupt the leader so that the stuck peer is freed
  1479. if a.state != StateFollower {
  1480. t.Errorf("state = %s, want %s", a.state, StateFollower)
  1481. }
  1482. if c.Term != a.Term {
  1483. t.Errorf("term = %d, want %d", c.Term, a.Term)
  1484. }
  1485. }
  1486. func TestNonPromotableVoterWithCheckQuorum(t *testing.T) {
  1487. a := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  1488. b := newTestRaft(2, []uint64{1}, 10, 1, NewMemoryStorage())
  1489. a.checkQuorum = true
  1490. b.checkQuorum = true
  1491. nt := newNetwork(a, b)
  1492. setRandomizedElectionTimeout(b, b.electionTimeout+1)
  1493. // Need to remove 2 again to make it a non-promotable node since newNetwork overwritten some internal states
  1494. b.delProgress(2)
  1495. if b.promotable() {
  1496. t.Fatalf("promotable = %v, want false", b.promotable())
  1497. }
  1498. for i := 0; i < b.electionTimeout; i++ {
  1499. b.tick()
  1500. }
  1501. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1502. if a.state != StateLeader {
  1503. t.Errorf("state = %s, want %s", a.state, StateLeader)
  1504. }
  1505. if b.state != StateFollower {
  1506. t.Errorf("state = %s, want %s", b.state, StateFollower)
  1507. }
  1508. if b.lead != 1 {
  1509. t.Errorf("lead = %d, want 1", b.lead)
  1510. }
  1511. }
  1512. func TestReadOnlyOptionSafe(t *testing.T) {
  1513. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1514. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1515. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1516. nt := newNetwork(a, b, c)
  1517. setRandomizedElectionTimeout(b, b.electionTimeout+1)
  1518. for i := 0; i < b.electionTimeout; i++ {
  1519. b.tick()
  1520. }
  1521. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1522. if a.state != StateLeader {
  1523. t.Fatalf("state = %s, want %s", a.state, StateLeader)
  1524. }
  1525. tests := []struct {
  1526. sm *raft
  1527. proposals int
  1528. wri uint64
  1529. wctx []byte
  1530. }{
  1531. {a, 10, 11, []byte("ctx1")},
  1532. {b, 10, 21, []byte("ctx2")},
  1533. {c, 10, 31, []byte("ctx3")},
  1534. {a, 10, 41, []byte("ctx4")},
  1535. {b, 10, 51, []byte("ctx5")},
  1536. {c, 10, 61, []byte("ctx6")},
  1537. }
  1538. for i, tt := range tests {
  1539. for j := 0; j < tt.proposals; j++ {
  1540. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  1541. }
  1542. nt.send(pb.Message{From: tt.sm.id, To: tt.sm.id, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: tt.wctx}}})
  1543. r := tt.sm
  1544. if len(r.readStates) == 0 {
  1545. t.Errorf("#%d: len(readStates) = 0, want non-zero", i)
  1546. }
  1547. rs := r.readStates[0]
  1548. if rs.Index != tt.wri {
  1549. t.Errorf("#%d: readIndex = %d, want %d", i, rs.Index, tt.wri)
  1550. }
  1551. if !bytes.Equal(rs.RequestCtx, tt.wctx) {
  1552. t.Errorf("#%d: requestCtx = %v, want %v", i, rs.RequestCtx, tt.wctx)
  1553. }
  1554. r.readStates = nil
  1555. }
  1556. }
  1557. func TestReadOnlyOptionLease(t *testing.T) {
  1558. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1559. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1560. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1561. a.readOnly.option = ReadOnlyLeaseBased
  1562. b.readOnly.option = ReadOnlyLeaseBased
  1563. c.readOnly.option = ReadOnlyLeaseBased
  1564. a.checkQuorum = true
  1565. b.checkQuorum = true
  1566. c.checkQuorum = true
  1567. nt := newNetwork(a, b, c)
  1568. setRandomizedElectionTimeout(b, b.electionTimeout+1)
  1569. for i := 0; i < b.electionTimeout; i++ {
  1570. b.tick()
  1571. }
  1572. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1573. if a.state != StateLeader {
  1574. t.Fatalf("state = %s, want %s", a.state, StateLeader)
  1575. }
  1576. tests := []struct {
  1577. sm *raft
  1578. proposals int
  1579. wri uint64
  1580. wctx []byte
  1581. }{
  1582. {a, 10, 11, []byte("ctx1")},
  1583. {b, 10, 21, []byte("ctx2")},
  1584. {c, 10, 31, []byte("ctx3")},
  1585. {a, 10, 41, []byte("ctx4")},
  1586. {b, 10, 51, []byte("ctx5")},
  1587. {c, 10, 61, []byte("ctx6")},
  1588. }
  1589. for i, tt := range tests {
  1590. for j := 0; j < tt.proposals; j++ {
  1591. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  1592. }
  1593. nt.send(pb.Message{From: tt.sm.id, To: tt.sm.id, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: tt.wctx}}})
  1594. r := tt.sm
  1595. rs := r.readStates[0]
  1596. if rs.Index != tt.wri {
  1597. t.Errorf("#%d: readIndex = %d, want %d", i, rs.Index, tt.wri)
  1598. }
  1599. if !bytes.Equal(rs.RequestCtx, tt.wctx) {
  1600. t.Errorf("#%d: requestCtx = %v, want %v", i, rs.RequestCtx, tt.wctx)
  1601. }
  1602. r.readStates = nil
  1603. }
  1604. }
  1605. func TestReadOnlyOptionLeaseWithoutCheckQuorum(t *testing.T) {
  1606. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1607. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1608. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1609. a.readOnly.option = ReadOnlyLeaseBased
  1610. b.readOnly.option = ReadOnlyLeaseBased
  1611. c.readOnly.option = ReadOnlyLeaseBased
  1612. nt := newNetwork(a, b, c)
  1613. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1614. ctx := []byte("ctx1")
  1615. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: ctx}}})
  1616. rs := b.readStates[0]
  1617. if rs.Index != None {
  1618. t.Errorf("readIndex = %d, want %d", rs.Index, None)
  1619. }
  1620. if !bytes.Equal(rs.RequestCtx, ctx) {
  1621. t.Errorf("requestCtx = %v, want %v", rs.RequestCtx, ctx)
  1622. }
  1623. }
  1624. // TestReadOnlyForNewLeader ensures that a leader only accepts MsgReadIndex message
  1625. // when it commits at least one log entry at it term.
  1626. func TestReadOnlyForNewLeader(t *testing.T) {
  1627. nodeConfigs := []struct {
  1628. id uint64
  1629. committed uint64
  1630. applied uint64
  1631. compact_index uint64
  1632. }{
  1633. {1, 1, 1, 0},
  1634. {2, 2, 2, 2},
  1635. {3, 2, 2, 2},
  1636. }
  1637. peers := make([]stateMachine, 0)
  1638. for _, c := range nodeConfigs {
  1639. storage := NewMemoryStorage()
  1640. storage.Append([]pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}})
  1641. storage.SetHardState(pb.HardState{Term: 1, Commit: c.committed})
  1642. if c.compact_index != 0 {
  1643. storage.Compact(c.compact_index)
  1644. }
  1645. cfg := newTestConfig(c.id, []uint64{1, 2, 3}, 10, 1, storage)
  1646. cfg.Applied = c.applied
  1647. raft := newRaft(cfg)
  1648. peers = append(peers, raft)
  1649. }
  1650. nt := newNetwork(peers...)
  1651. // Drop MsgApp to forbid peer a to commit any log entry at its term after it becomes leader.
  1652. nt.ignore(pb.MsgApp)
  1653. // Force peer a to become leader.
  1654. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1655. sm := nt.peers[1].(*raft)
  1656. if sm.state != StateLeader {
  1657. t.Fatalf("state = %s, want %s", sm.state, StateLeader)
  1658. }
  1659. // Ensure peer a drops read only request.
  1660. var windex uint64 = 4
  1661. wctx := []byte("ctx")
  1662. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: wctx}}})
  1663. if len(sm.readStates) != 0 {
  1664. t.Fatalf("len(readStates) = %d, want zero", len(sm.readStates))
  1665. }
  1666. nt.recover()
  1667. // Force peer a to commit a log entry at its term
  1668. for i := 0; i < sm.heartbeatTimeout; i++ {
  1669. sm.tick()
  1670. }
  1671. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  1672. if sm.raftLog.committed != 4 {
  1673. t.Fatalf("committed = %d, want 4", sm.raftLog.committed)
  1674. }
  1675. lastLogTerm := sm.raftLog.zeroTermOnErrCompacted(sm.raftLog.term(sm.raftLog.committed))
  1676. if lastLogTerm != sm.Term {
  1677. t.Fatalf("last log term = %d, want %d", lastLogTerm, sm.Term)
  1678. }
  1679. // Ensure peer a accepts read only request after it commits a entry at its term.
  1680. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: wctx}}})
  1681. if len(sm.readStates) != 1 {
  1682. t.Fatalf("len(readStates) = %d, want 1", len(sm.readStates))
  1683. }
  1684. rs := sm.readStates[0]
  1685. if rs.Index != windex {
  1686. t.Fatalf("readIndex = %d, want %d", rs.Index, windex)
  1687. }
  1688. if !bytes.Equal(rs.RequestCtx, wctx) {
  1689. t.Fatalf("requestCtx = %v, want %v", rs.RequestCtx, wctx)
  1690. }
  1691. }
  1692. func TestLeaderAppResp(t *testing.T) {
  1693. // initial progress: match = 0; next = 3
  1694. tests := []struct {
  1695. index uint64
  1696. reject bool
  1697. // progress
  1698. wmatch uint64
  1699. wnext uint64
  1700. // message
  1701. wmsgNum int
  1702. windex uint64
  1703. wcommitted uint64
  1704. }{
  1705. {3, true, 0, 3, 0, 0, 0}, // stale resp; no replies
  1706. {2, true, 0, 2, 1, 1, 0}, // denied resp; leader does not commit; decrease next and send probing msg
  1707. {2, false, 2, 4, 2, 2, 2}, // accept resp; leader commits; broadcast with commit index
  1708. {0, false, 0, 3, 0, 0, 0}, // ignore heartbeat replies
  1709. }
  1710. for i, tt := range tests {
  1711. // sm term is 1 after it becomes the leader.
  1712. // thus the last log term must be 1 to be committed.
  1713. sm := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1714. sm.raftLog = &raftLog{
  1715. storage: &MemoryStorage{ents: []pb.Entry{{}, {Index: 1, Term: 0}, {Index: 2, Term: 1}}},
  1716. unstable: unstable{offset: 3},
  1717. }
  1718. sm.becomeCandidate()
  1719. sm.becomeLeader()
  1720. sm.readMessages()
  1721. sm.Step(pb.Message{From: 2, Type: pb.MsgAppResp, Index: tt.index, Term: sm.Term, Reject: tt.reject, RejectHint: tt.index})
  1722. p := sm.prs[2]
  1723. if p.Match != tt.wmatch {
  1724. t.Errorf("#%d match = %d, want %d", i, p.Match, tt.wmatch)
  1725. }
  1726. if p.Next != tt.wnext {
  1727. t.Errorf("#%d next = %d, want %d", i, p.Next, tt.wnext)
  1728. }
  1729. msgs := sm.readMessages()
  1730. if len(msgs) != tt.wmsgNum {
  1731. t.Errorf("#%d msgNum = %d, want %d", i, len(msgs), tt.wmsgNum)
  1732. }
  1733. for j, msg := range msgs {
  1734. if msg.Index != tt.windex {
  1735. t.Errorf("#%d.%d index = %d, want %d", i, j, msg.Index, tt.windex)
  1736. }
  1737. if msg.Commit != tt.wcommitted {
  1738. t.Errorf("#%d.%d commit = %d, want %d", i, j, msg.Commit, tt.wcommitted)
  1739. }
  1740. }
  1741. }
  1742. }
  1743. // When the leader receives a heartbeat tick, it should
  1744. // send a MsgApp with m.Index = 0, m.LogTerm=0 and empty entries.
  1745. func TestBcastBeat(t *testing.T) {
  1746. offset := uint64(1000)
  1747. // make a state machine with log.offset = 1000
  1748. s := pb.Snapshot{
  1749. Metadata: pb.SnapshotMetadata{
  1750. Index: offset,
  1751. Term: 1,
  1752. ConfState: pb.ConfState{Nodes: []uint64{1, 2, 3}},
  1753. },
  1754. }
  1755. storage := NewMemoryStorage()
  1756. storage.ApplySnapshot(s)
  1757. sm := newTestRaft(1, nil, 10, 1, storage)
  1758. sm.Term = 1
  1759. sm.becomeCandidate()
  1760. sm.becomeLeader()
  1761. for i := 0; i < 10; i++ {
  1762. sm.appendEntry(pb.Entry{Index: uint64(i) + 1})
  1763. }
  1764. // slow follower
  1765. sm.prs[2].Match, sm.prs[2].Next = 5, 6
  1766. // normal follower
  1767. sm.prs[3].Match, sm.prs[3].Next = sm.raftLog.lastIndex(), sm.raftLog.lastIndex()+1
  1768. sm.Step(pb.Message{Type: pb.MsgBeat})
  1769. msgs := sm.readMessages()
  1770. if len(msgs) != 2 {
  1771. t.Fatalf("len(msgs) = %v, want 2", len(msgs))
  1772. }
  1773. wantCommitMap := map[uint64]uint64{
  1774. 2: min(sm.raftLog.committed, sm.prs[2].Match),
  1775. 3: min(sm.raftLog.committed, sm.prs[3].Match),
  1776. }
  1777. for i, m := range msgs {
  1778. if m.Type != pb.MsgHeartbeat {
  1779. t.Fatalf("#%d: type = %v, want = %v", i, m.Type, pb.MsgHeartbeat)
  1780. }
  1781. if m.Index != 0 {
  1782. t.Fatalf("#%d: prevIndex = %d, want %d", i, m.Index, 0)
  1783. }
  1784. if m.LogTerm != 0 {
  1785. t.Fatalf("#%d: prevTerm = %d, want %d", i, m.LogTerm, 0)
  1786. }
  1787. if wantCommitMap[m.To] == 0 {
  1788. t.Fatalf("#%d: unexpected to %d", i, m.To)
  1789. } else {
  1790. if m.Commit != wantCommitMap[m.To] {
  1791. t.Fatalf("#%d: commit = %d, want %d", i, m.Commit, wantCommitMap[m.To])
  1792. }
  1793. delete(wantCommitMap, m.To)
  1794. }
  1795. if len(m.Entries) != 0 {
  1796. t.Fatalf("#%d: len(entries) = %d, want 0", i, len(m.Entries))
  1797. }
  1798. }
  1799. }
  1800. // tests the output of the state machine when receiving MsgBeat
  1801. func TestRecvMsgBeat(t *testing.T) {
  1802. tests := []struct {
  1803. state StateType
  1804. wMsg int
  1805. }{
  1806. {StateLeader, 2},
  1807. // candidate and follower should ignore MsgBeat
  1808. {StateCandidate, 0},
  1809. {StateFollower, 0},
  1810. }
  1811. for i, tt := range tests {
  1812. sm := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1813. sm.raftLog = &raftLog{storage: &MemoryStorage{ents: []pb.Entry{{}, {Index: 1, Term: 0}, {Index: 2, Term: 1}}}}
  1814. sm.Term = 1
  1815. sm.state = tt.state
  1816. switch tt.state {
  1817. case StateFollower:
  1818. sm.step = stepFollower
  1819. case StateCandidate:
  1820. sm.step = stepCandidate
  1821. case StateLeader:
  1822. sm.step = stepLeader
  1823. }
  1824. sm.Step(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  1825. msgs := sm.readMessages()
  1826. if len(msgs) != tt.wMsg {
  1827. t.Errorf("%d: len(msgs) = %d, want %d", i, len(msgs), tt.wMsg)
  1828. }
  1829. for _, m := range msgs {
  1830. if m.Type != pb.MsgHeartbeat {
  1831. t.Errorf("%d: msg.type = %v, want %v", i, m.Type, pb.MsgHeartbeat)
  1832. }
  1833. }
  1834. }
  1835. }
  1836. func TestLeaderIncreaseNext(t *testing.T) {
  1837. previousEnts := []pb.Entry{{Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3}}
  1838. tests := []struct {
  1839. // progress
  1840. state ProgressStateType
  1841. next uint64
  1842. wnext uint64
  1843. }{
  1844. // state replicate, optimistically increase next
  1845. // previous entries + noop entry + propose + 1
  1846. {ProgressStateReplicate, 2, uint64(len(previousEnts) + 1 + 1 + 1)},
  1847. // state probe, not optimistically increase next
  1848. {ProgressStateProbe, 2, 2},
  1849. }
  1850. for i, tt := range tests {
  1851. sm := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  1852. sm.raftLog.append(previousEnts...)
  1853. sm.becomeCandidate()
  1854. sm.becomeLeader()
  1855. sm.prs[2].State = tt.state
  1856. sm.prs[2].Next = tt.next
  1857. sm.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  1858. p := sm.prs[2]
  1859. if p.Next != tt.wnext {
  1860. t.Errorf("#%d next = %d, want %d", i, p.Next, tt.wnext)
  1861. }
  1862. }
  1863. }
  1864. func TestSendAppendForProgressProbe(t *testing.T) {
  1865. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  1866. r.becomeCandidate()
  1867. r.becomeLeader()
  1868. r.readMessages()
  1869. r.prs[2].becomeProbe()
  1870. // each round is a heartbeat
  1871. for i := 0; i < 3; i++ {
  1872. if i == 0 {
  1873. // we expect that raft will only send out one msgAPP on the first
  1874. // loop. After that, the follower is paused until a heartbeat response is
  1875. // received.
  1876. r.appendEntry(pb.Entry{Data: []byte("somedata")})
  1877. r.sendAppend(2)
  1878. msg := r.readMessages()
  1879. if len(msg) != 1 {
  1880. t.Errorf("len(msg) = %d, want %d", len(msg), 1)
  1881. }
  1882. if msg[0].Index != 0 {
  1883. t.Errorf("index = %d, want %d", msg[0].Index, 0)
  1884. }
  1885. }
  1886. if !r.prs[2].Paused {
  1887. t.Errorf("paused = %v, want true", r.prs[2].Paused)
  1888. }
  1889. for j := 0; j < 10; j++ {
  1890. r.appendEntry(pb.Entry{Data: []byte("somedata")})
  1891. r.sendAppend(2)
  1892. if l := len(r.readMessages()); l != 0 {
  1893. t.Errorf("len(msg) = %d, want %d", l, 0)
  1894. }
  1895. }
  1896. // do a heartbeat
  1897. for j := 0; j < r.heartbeatTimeout; j++ {
  1898. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  1899. }
  1900. if !r.prs[2].Paused {
  1901. t.Errorf("paused = %v, want true", r.prs[2].Paused)
  1902. }
  1903. // consume the heartbeat
  1904. msg := r.readMessages()
  1905. if len(msg) != 1 {
  1906. t.Errorf("len(msg) = %d, want %d", len(msg), 1)
  1907. }
  1908. if msg[0].Type != pb.MsgHeartbeat {
  1909. t.Errorf("type = %v, want %v", msg[0].Type, pb.MsgHeartbeat)
  1910. }
  1911. }
  1912. // a heartbeat response will allow another message to be sent
  1913. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgHeartbeatResp})
  1914. msg := r.readMessages()
  1915. if len(msg) != 1 {
  1916. t.Errorf("len(msg) = %d, want %d", len(msg), 1)
  1917. }
  1918. if msg[0].Index != 0 {
  1919. t.Errorf("index = %d, want %d", msg[0].Index, 0)
  1920. }
  1921. if !r.prs[2].Paused {
  1922. t.Errorf("paused = %v, want true", r.prs[2].Paused)
  1923. }
  1924. }
  1925. func TestSendAppendForProgressReplicate(t *testing.T) {
  1926. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  1927. r.becomeCandidate()
  1928. r.becomeLeader()
  1929. r.readMessages()
  1930. r.prs[2].becomeReplicate()
  1931. for i := 0; i < 10; i++ {
  1932. r.appendEntry(pb.Entry{Data: []byte("somedata")})
  1933. r.sendAppend(2)
  1934. msgs := r.readMessages()
  1935. if len(msgs) != 1 {
  1936. t.Errorf("len(msg) = %d, want %d", len(msgs), 1)
  1937. }
  1938. }
  1939. }
  1940. func TestSendAppendForProgressSnapshot(t *testing.T) {
  1941. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  1942. r.becomeCandidate()
  1943. r.becomeLeader()
  1944. r.readMessages()
  1945. r.prs[2].becomeSnapshot(10)
  1946. for i := 0; i < 10; i++ {
  1947. r.appendEntry(pb.Entry{Data: []byte("somedata")})
  1948. r.sendAppend(2)
  1949. msgs := r.readMessages()
  1950. if len(msgs) != 0 {
  1951. t.Errorf("len(msg) = %d, want %d", len(msgs), 0)
  1952. }
  1953. }
  1954. }
  1955. func TestRecvMsgUnreachable(t *testing.T) {
  1956. previousEnts := []pb.Entry{{Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3}}
  1957. s := NewMemoryStorage()
  1958. s.Append(previousEnts)
  1959. r := newTestRaft(1, []uint64{1, 2}, 10, 1, s)
  1960. r.becomeCandidate()
  1961. r.becomeLeader()
  1962. r.readMessages()
  1963. // set node 2 to state replicate
  1964. r.prs[2].Match = 3
  1965. r.prs[2].becomeReplicate()
  1966. r.prs[2].optimisticUpdate(5)
  1967. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgUnreachable})
  1968. if r.prs[2].State != ProgressStateProbe {
  1969. t.Errorf("state = %s, want %s", r.prs[2].State, ProgressStateProbe)
  1970. }
  1971. if wnext := r.prs[2].Match + 1; r.prs[2].Next != wnext {
  1972. t.Errorf("next = %d, want %d", r.prs[2].Next, wnext)
  1973. }
  1974. }
  1975. func TestRestore(t *testing.T) {
  1976. s := pb.Snapshot{
  1977. Metadata: pb.SnapshotMetadata{
  1978. Index: 11, // magic number
  1979. Term: 11, // magic number
  1980. ConfState: pb.ConfState{Nodes: []uint64{1, 2, 3}},
  1981. },
  1982. }
  1983. storage := NewMemoryStorage()
  1984. sm := newTestRaft(1, []uint64{1, 2}, 10, 1, storage)
  1985. if ok := sm.restore(s); !ok {
  1986. t.Fatal("restore fail, want succeed")
  1987. }
  1988. if sm.raftLog.lastIndex() != s.Metadata.Index {
  1989. t.Errorf("log.lastIndex = %d, want %d", sm.raftLog.lastIndex(), s.Metadata.Index)
  1990. }
  1991. if mustTerm(sm.raftLog.term(s.Metadata.Index)) != s.Metadata.Term {
  1992. t.Errorf("log.lastTerm = %d, want %d", mustTerm(sm.raftLog.term(s.Metadata.Index)), s.Metadata.Term)
  1993. }
  1994. sg := sm.nodes()
  1995. if !reflect.DeepEqual(sg, s.Metadata.ConfState.Nodes) {
  1996. t.Errorf("sm.Nodes = %+v, want %+v", sg, s.Metadata.ConfState.Nodes)
  1997. }
  1998. if ok := sm.restore(s); ok {
  1999. t.Fatal("restore succeed, want fail")
  2000. }
  2001. }
  2002. func TestRestoreIgnoreSnapshot(t *testing.T) {
  2003. previousEnts := []pb.Entry{{Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3}}
  2004. commit := uint64(1)
  2005. storage := NewMemoryStorage()
  2006. sm := newTestRaft(1, []uint64{1, 2}, 10, 1, storage)
  2007. sm.raftLog.append(previousEnts...)
  2008. sm.raftLog.commitTo(commit)
  2009. s := pb.Snapshot{
  2010. Metadata: pb.SnapshotMetadata{
  2011. Index: commit,
  2012. Term: 1,
  2013. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  2014. },
  2015. }
  2016. // ignore snapshot
  2017. if ok := sm.restore(s); ok {
  2018. t.Errorf("restore = %t, want %t", ok, false)
  2019. }
  2020. if sm.raftLog.committed != commit {
  2021. t.Errorf("commit = %d, want %d", sm.raftLog.committed, commit)
  2022. }
  2023. // ignore snapshot and fast forward commit
  2024. s.Metadata.Index = commit + 1
  2025. if ok := sm.restore(s); ok {
  2026. t.Errorf("restore = %t, want %t", ok, false)
  2027. }
  2028. if sm.raftLog.committed != commit+1 {
  2029. t.Errorf("commit = %d, want %d", sm.raftLog.committed, commit+1)
  2030. }
  2031. }
  2032. func TestProvideSnap(t *testing.T) {
  2033. // restore the state machine from a snapshot so it has a compacted log and a snapshot
  2034. s := pb.Snapshot{
  2035. Metadata: pb.SnapshotMetadata{
  2036. Index: 11, // magic number
  2037. Term: 11, // magic number
  2038. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  2039. },
  2040. }
  2041. storage := NewMemoryStorage()
  2042. sm := newTestRaft(1, []uint64{1}, 10, 1, storage)
  2043. sm.restore(s)
  2044. sm.becomeCandidate()
  2045. sm.becomeLeader()
  2046. // force set the next of node 2, so that node 2 needs a snapshot
  2047. sm.prs[2].Next = sm.raftLog.firstIndex()
  2048. sm.Step(pb.Message{From: 2, To: 1, Type: pb.MsgAppResp, Index: sm.prs[2].Next - 1, Reject: true})
  2049. msgs := sm.readMessages()
  2050. if len(msgs) != 1 {
  2051. t.Fatalf("len(msgs) = %d, want 1", len(msgs))
  2052. }
  2053. m := msgs[0]
  2054. if m.Type != pb.MsgSnap {
  2055. t.Errorf("m.Type = %v, want %v", m.Type, pb.MsgSnap)
  2056. }
  2057. }
  2058. func TestIgnoreProvidingSnap(t *testing.T) {
  2059. // restore the state machine from a snapshot so it has a compacted log and a snapshot
  2060. s := pb.Snapshot{
  2061. Metadata: pb.SnapshotMetadata{
  2062. Index: 11, // magic number
  2063. Term: 11, // magic number
  2064. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  2065. },
  2066. }
  2067. storage := NewMemoryStorage()
  2068. sm := newTestRaft(1, []uint64{1}, 10, 1, storage)
  2069. sm.restore(s)
  2070. sm.becomeCandidate()
  2071. sm.becomeLeader()
  2072. // force set the next of node 2, so that node 2 needs a snapshot
  2073. // change node 2 to be inactive, expect node 1 ignore sending snapshot to 2
  2074. sm.prs[2].Next = sm.raftLog.firstIndex() - 1
  2075. sm.prs[2].RecentActive = false
  2076. sm.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  2077. msgs := sm.readMessages()
  2078. if len(msgs) != 0 {
  2079. t.Errorf("len(msgs) = %d, want 0", len(msgs))
  2080. }
  2081. }
  2082. func TestRestoreFromSnapMsg(t *testing.T) {
  2083. s := pb.Snapshot{
  2084. Metadata: pb.SnapshotMetadata{
  2085. Index: 11, // magic number
  2086. Term: 11, // magic number
  2087. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  2088. },
  2089. }
  2090. m := pb.Message{Type: pb.MsgSnap, From: 1, Term: 2, Snapshot: s}
  2091. sm := newTestRaft(2, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2092. sm.Step(m)
  2093. if sm.lead != uint64(1) {
  2094. t.Errorf("sm.lead = %d, want 1", sm.lead)
  2095. }
  2096. // TODO(bdarnell): what should this test?
  2097. }
  2098. func TestSlowNodeRestore(t *testing.T) {
  2099. nt := newNetwork(nil, nil, nil)
  2100. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2101. nt.isolate(3)
  2102. for j := 0; j <= 100; j++ {
  2103. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2104. }
  2105. lead := nt.peers[1].(*raft)
  2106. nextEnts(lead, nt.storage[1])
  2107. nt.storage[1].CreateSnapshot(lead.raftLog.applied, &pb.ConfState{Nodes: lead.nodes()}, nil)
  2108. nt.storage[1].Compact(lead.raftLog.applied)
  2109. nt.recover()
  2110. // send heartbeats so that the leader can learn everyone is active.
  2111. // node 3 will only be considered as active when node 1 receives a reply from it.
  2112. for {
  2113. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  2114. if lead.prs[3].RecentActive {
  2115. break
  2116. }
  2117. }
  2118. // trigger a snapshot
  2119. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2120. follower := nt.peers[3].(*raft)
  2121. // trigger a commit
  2122. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2123. if follower.raftLog.committed != lead.raftLog.committed {
  2124. t.Errorf("follower.committed = %d, want %d", follower.raftLog.committed, lead.raftLog.committed)
  2125. }
  2126. }
  2127. // TestStepConfig tests that when raft step msgProp in EntryConfChange type,
  2128. // it appends the entry to log and sets pendingConf to be true.
  2129. func TestStepConfig(t *testing.T) {
  2130. // a raft that cannot make progress
  2131. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2132. r.becomeCandidate()
  2133. r.becomeLeader()
  2134. index := r.raftLog.lastIndex()
  2135. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange}}})
  2136. if g := r.raftLog.lastIndex(); g != index+1 {
  2137. t.Errorf("index = %d, want %d", g, index+1)
  2138. }
  2139. if !r.pendingConf {
  2140. t.Errorf("pendingConf = %v, want true", r.pendingConf)
  2141. }
  2142. }
  2143. // TestStepIgnoreConfig tests that if raft step the second msgProp in
  2144. // EntryConfChange type when the first one is uncommitted, the node will set
  2145. // the proposal to noop and keep its original state.
  2146. func TestStepIgnoreConfig(t *testing.T) {
  2147. // a raft that cannot make progress
  2148. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2149. r.becomeCandidate()
  2150. r.becomeLeader()
  2151. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange}}})
  2152. index := r.raftLog.lastIndex()
  2153. pendingConf := r.pendingConf
  2154. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange}}})
  2155. wents := []pb.Entry{{Type: pb.EntryNormal, Term: 1, Index: 3, Data: nil}}
  2156. ents, err := r.raftLog.entries(index+1, noLimit)
  2157. if err != nil {
  2158. t.Fatalf("unexpected error %v", err)
  2159. }
  2160. if !reflect.DeepEqual(ents, wents) {
  2161. t.Errorf("ents = %+v, want %+v", ents, wents)
  2162. }
  2163. if r.pendingConf != pendingConf {
  2164. t.Errorf("pendingConf = %v, want %v", r.pendingConf, pendingConf)
  2165. }
  2166. }
  2167. // TestRecoverPendingConfig tests that new leader recovers its pendingConf flag
  2168. // based on uncommitted entries.
  2169. func TestRecoverPendingConfig(t *testing.T) {
  2170. tests := []struct {
  2171. entType pb.EntryType
  2172. wpending bool
  2173. }{
  2174. {pb.EntryNormal, false},
  2175. {pb.EntryConfChange, true},
  2176. }
  2177. for i, tt := range tests {
  2178. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2179. r.appendEntry(pb.Entry{Type: tt.entType})
  2180. r.becomeCandidate()
  2181. r.becomeLeader()
  2182. if r.pendingConf != tt.wpending {
  2183. t.Errorf("#%d: pendingConf = %v, want %v", i, r.pendingConf, tt.wpending)
  2184. }
  2185. }
  2186. }
  2187. // TestRecoverDoublePendingConfig tests that new leader will panic if
  2188. // there exist two uncommitted config entries.
  2189. func TestRecoverDoublePendingConfig(t *testing.T) {
  2190. func() {
  2191. defer func() {
  2192. if err := recover(); err == nil {
  2193. t.Errorf("expect panic, but nothing happens")
  2194. }
  2195. }()
  2196. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2197. r.appendEntry(pb.Entry{Type: pb.EntryConfChange})
  2198. r.appendEntry(pb.Entry{Type: pb.EntryConfChange})
  2199. r.becomeCandidate()
  2200. r.becomeLeader()
  2201. }()
  2202. }
  2203. // TestAddNode tests that addNode could update pendingConf and nodes correctly.
  2204. func TestAddNode(t *testing.T) {
  2205. r := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  2206. r.pendingConf = true
  2207. r.addNode(2)
  2208. if r.pendingConf {
  2209. t.Errorf("pendingConf = %v, want false", r.pendingConf)
  2210. }
  2211. nodes := r.nodes()
  2212. wnodes := []uint64{1, 2}
  2213. if !reflect.DeepEqual(nodes, wnodes) {
  2214. t.Errorf("nodes = %v, want %v", nodes, wnodes)
  2215. }
  2216. }
  2217. // TestRemoveNode tests that removeNode could update pendingConf, nodes and
  2218. // and removed list correctly.
  2219. func TestRemoveNode(t *testing.T) {
  2220. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2221. r.pendingConf = true
  2222. r.removeNode(2)
  2223. if r.pendingConf {
  2224. t.Errorf("pendingConf = %v, want false", r.pendingConf)
  2225. }
  2226. w := []uint64{1}
  2227. if g := r.nodes(); !reflect.DeepEqual(g, w) {
  2228. t.Errorf("nodes = %v, want %v", g, w)
  2229. }
  2230. // remove all nodes from cluster
  2231. r.removeNode(1)
  2232. w = []uint64{}
  2233. if g := r.nodes(); !reflect.DeepEqual(g, w) {
  2234. t.Errorf("nodes = %v, want %v", g, w)
  2235. }
  2236. }
  2237. func TestPromotable(t *testing.T) {
  2238. id := uint64(1)
  2239. tests := []struct {
  2240. peers []uint64
  2241. wp bool
  2242. }{
  2243. {[]uint64{1}, true},
  2244. {[]uint64{1, 2, 3}, true},
  2245. {[]uint64{}, false},
  2246. {[]uint64{2, 3}, false},
  2247. }
  2248. for i, tt := range tests {
  2249. r := newTestRaft(id, tt.peers, 5, 1, NewMemoryStorage())
  2250. if g := r.promotable(); g != tt.wp {
  2251. t.Errorf("#%d: promotable = %v, want %v", i, g, tt.wp)
  2252. }
  2253. }
  2254. }
  2255. func TestRaftNodes(t *testing.T) {
  2256. tests := []struct {
  2257. ids []uint64
  2258. wids []uint64
  2259. }{
  2260. {
  2261. []uint64{1, 2, 3},
  2262. []uint64{1, 2, 3},
  2263. },
  2264. {
  2265. []uint64{3, 2, 1},
  2266. []uint64{1, 2, 3},
  2267. },
  2268. }
  2269. for i, tt := range tests {
  2270. r := newTestRaft(1, tt.ids, 10, 1, NewMemoryStorage())
  2271. if !reflect.DeepEqual(r.nodes(), tt.wids) {
  2272. t.Errorf("#%d: nodes = %+v, want %+v", i, r.nodes(), tt.wids)
  2273. }
  2274. }
  2275. }
  2276. func TestCampaignWhileLeader(t *testing.T) {
  2277. testCampaignWhileLeader(t, false)
  2278. }
  2279. func TestPreCampaignWhileLeader(t *testing.T) {
  2280. testCampaignWhileLeader(t, true)
  2281. }
  2282. func testCampaignWhileLeader(t *testing.T, preVote bool) {
  2283. cfg := newTestConfig(1, []uint64{1}, 5, 1, NewMemoryStorage())
  2284. cfg.PreVote = preVote
  2285. r := newRaft(cfg)
  2286. if r.state != StateFollower {
  2287. t.Errorf("expected new node to be follower but got %s", r.state)
  2288. }
  2289. // We don't call campaign() directly because it comes after the check
  2290. // for our current state.
  2291. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2292. if r.state != StateLeader {
  2293. t.Errorf("expected single-node election to become leader but got %s", r.state)
  2294. }
  2295. term := r.Term
  2296. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2297. if r.state != StateLeader {
  2298. t.Errorf("expected to remain leader but got %s", r.state)
  2299. }
  2300. if r.Term != term {
  2301. t.Errorf("expected to remain in term %v but got %v", term, r.Term)
  2302. }
  2303. }
  2304. // TestCommitAfterRemoveNode verifies that pending commands can become
  2305. // committed when a config change reduces the quorum requirements.
  2306. func TestCommitAfterRemoveNode(t *testing.T) {
  2307. // Create a cluster with two nodes.
  2308. s := NewMemoryStorage()
  2309. r := newTestRaft(1, []uint64{1, 2}, 5, 1, s)
  2310. r.becomeCandidate()
  2311. r.becomeLeader()
  2312. // Begin to remove the second node.
  2313. cc := pb.ConfChange{
  2314. Type: pb.ConfChangeRemoveNode,
  2315. NodeID: 2,
  2316. }
  2317. ccData, err := cc.Marshal()
  2318. if err != nil {
  2319. t.Fatal(err)
  2320. }
  2321. r.Step(pb.Message{
  2322. Type: pb.MsgProp,
  2323. Entries: []pb.Entry{
  2324. {Type: pb.EntryConfChange, Data: ccData},
  2325. },
  2326. })
  2327. // Stabilize the log and make sure nothing is committed yet.
  2328. if ents := nextEnts(r, s); len(ents) > 0 {
  2329. t.Fatalf("unexpected committed entries: %v", ents)
  2330. }
  2331. ccIndex := r.raftLog.lastIndex()
  2332. // While the config change is pending, make another proposal.
  2333. r.Step(pb.Message{
  2334. Type: pb.MsgProp,
  2335. Entries: []pb.Entry{
  2336. {Type: pb.EntryNormal, Data: []byte("hello")},
  2337. },
  2338. })
  2339. // Node 2 acknowledges the config change, committing it.
  2340. r.Step(pb.Message{
  2341. Type: pb.MsgAppResp,
  2342. From: 2,
  2343. Index: ccIndex,
  2344. })
  2345. ents := nextEnts(r, s)
  2346. if len(ents) != 2 {
  2347. t.Fatalf("expected two committed entries, got %v", ents)
  2348. }
  2349. if ents[0].Type != pb.EntryNormal || ents[0].Data != nil {
  2350. t.Fatalf("expected ents[0] to be empty, but got %v", ents[0])
  2351. }
  2352. if ents[1].Type != pb.EntryConfChange {
  2353. t.Fatalf("expected ents[1] to be EntryConfChange, got %v", ents[1])
  2354. }
  2355. // Apply the config change. This reduces quorum requirements so the
  2356. // pending command can now commit.
  2357. r.removeNode(2)
  2358. ents = nextEnts(r, s)
  2359. if len(ents) != 1 || ents[0].Type != pb.EntryNormal ||
  2360. string(ents[0].Data) != "hello" {
  2361. t.Fatalf("expected one committed EntryNormal, got %v", ents)
  2362. }
  2363. }
  2364. // TestLeaderTransferToUpToDateNode verifies transferring should succeed
  2365. // if the transferee has the most up-to-date log entries when transfer starts.
  2366. func TestLeaderTransferToUpToDateNode(t *testing.T) {
  2367. nt := newNetwork(nil, nil, nil)
  2368. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2369. lead := nt.peers[1].(*raft)
  2370. if lead.lead != 1 {
  2371. t.Fatalf("after election leader is %x, want 1", lead.lead)
  2372. }
  2373. // Transfer leadership to 2.
  2374. nt.send(pb.Message{From: 2, To: 1, Type: pb.MsgTransferLeader})
  2375. checkLeaderTransferState(t, lead, StateFollower, 2)
  2376. // After some log replication, transfer leadership back to 1.
  2377. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2378. nt.send(pb.Message{From: 1, To: 2, Type: pb.MsgTransferLeader})
  2379. checkLeaderTransferState(t, lead, StateLeader, 1)
  2380. }
  2381. // TestLeaderTransferToUpToDateNodeFromFollower verifies transferring should succeed
  2382. // if the transferee has the most up-to-date log entries when transfer starts.
  2383. // Not like TestLeaderTransferToUpToDateNode, where the leader transfer message
  2384. // is sent to the leader, in this test case every leader transfer message is sent
  2385. // to the follower.
  2386. func TestLeaderTransferToUpToDateNodeFromFollower(t *testing.T) {
  2387. nt := newNetwork(nil, nil, nil)
  2388. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2389. lead := nt.peers[1].(*raft)
  2390. if lead.lead != 1 {
  2391. t.Fatalf("after election leader is %x, want 1", lead.lead)
  2392. }
  2393. // Transfer leadership to 2.
  2394. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgTransferLeader})
  2395. checkLeaderTransferState(t, lead, StateFollower, 2)
  2396. // After some log replication, transfer leadership back to 1.
  2397. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2398. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgTransferLeader})
  2399. checkLeaderTransferState(t, lead, StateLeader, 1)
  2400. }
  2401. // TestLeaderTransferWithCheckQuorum ensures transferring leader still works
  2402. // even the current leader is still under its leader lease
  2403. func TestLeaderTransferWithCheckQuorum(t *testing.T) {
  2404. nt := newNetwork(nil, nil, nil)
  2405. for i := 1; i < 4; i++ {
  2406. r := nt.peers[uint64(i)].(*raft)
  2407. r.checkQuorum = true
  2408. setRandomizedElectionTimeout(r, r.electionTimeout+i)
  2409. }
  2410. // Letting peer 2 electionElapsed reach to timeout so that it can vote for peer 1
  2411. f := nt.peers[2].(*raft)
  2412. for i := 0; i < f.electionTimeout; i++ {
  2413. f.tick()
  2414. }
  2415. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2416. lead := nt.peers[1].(*raft)
  2417. if lead.lead != 1 {
  2418. t.Fatalf("after election leader is %x, want 1", lead.lead)
  2419. }
  2420. // Transfer leadership to 2.
  2421. nt.send(pb.Message{From: 2, To: 1, Type: pb.MsgTransferLeader})
  2422. checkLeaderTransferState(t, lead, StateFollower, 2)
  2423. // After some log replication, transfer leadership back to 1.
  2424. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2425. nt.send(pb.Message{From: 1, To: 2, Type: pb.MsgTransferLeader})
  2426. checkLeaderTransferState(t, lead, StateLeader, 1)
  2427. }
  2428. func TestLeaderTransferToSlowFollower(t *testing.T) {
  2429. defaultLogger.EnableDebug()
  2430. nt := newNetwork(nil, nil, nil)
  2431. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2432. nt.isolate(3)
  2433. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2434. nt.recover()
  2435. lead := nt.peers[1].(*raft)
  2436. if lead.prs[3].Match != 1 {
  2437. t.Fatalf("node 1 has match %x for node 3, want %x", lead.prs[3].Match, 1)
  2438. }
  2439. // Transfer leadership to 3 when node 3 is lack of log.
  2440. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2441. checkLeaderTransferState(t, lead, StateFollower, 3)
  2442. }
  2443. func TestLeaderTransferAfterSnapshot(t *testing.T) {
  2444. nt := newNetwork(nil, nil, nil)
  2445. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2446. nt.isolate(3)
  2447. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2448. lead := nt.peers[1].(*raft)
  2449. nextEnts(lead, nt.storage[1])
  2450. nt.storage[1].CreateSnapshot(lead.raftLog.applied, &pb.ConfState{Nodes: lead.nodes()}, nil)
  2451. nt.storage[1].Compact(lead.raftLog.applied)
  2452. nt.recover()
  2453. if lead.prs[3].Match != 1 {
  2454. t.Fatalf("node 1 has match %x for node 3, want %x", lead.prs[3].Match, 1)
  2455. }
  2456. // Transfer leadership to 3 when node 3 is lack of snapshot.
  2457. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2458. // Send pb.MsgHeartbeatResp to leader to trigger a snapshot for node 3.
  2459. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgHeartbeatResp})
  2460. checkLeaderTransferState(t, lead, StateFollower, 3)
  2461. }
  2462. func TestLeaderTransferToSelf(t *testing.T) {
  2463. nt := newNetwork(nil, nil, nil)
  2464. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2465. lead := nt.peers[1].(*raft)
  2466. // Transfer leadership to self, there will be noop.
  2467. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgTransferLeader})
  2468. checkLeaderTransferState(t, lead, StateLeader, 1)
  2469. }
  2470. func TestLeaderTransferToNonExistingNode(t *testing.T) {
  2471. nt := newNetwork(nil, nil, nil)
  2472. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2473. lead := nt.peers[1].(*raft)
  2474. // Transfer leadership to non-existing node, there will be noop.
  2475. nt.send(pb.Message{From: 4, To: 1, Type: pb.MsgTransferLeader})
  2476. checkLeaderTransferState(t, lead, StateLeader, 1)
  2477. }
  2478. func TestLeaderTransferTimeout(t *testing.T) {
  2479. nt := newNetwork(nil, nil, nil)
  2480. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2481. nt.isolate(3)
  2482. lead := nt.peers[1].(*raft)
  2483. // Transfer leadership to isolated node, wait for timeout.
  2484. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2485. if lead.leadTransferee != 3 {
  2486. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2487. }
  2488. for i := 0; i < lead.heartbeatTimeout; i++ {
  2489. lead.tick()
  2490. }
  2491. if lead.leadTransferee != 3 {
  2492. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2493. }
  2494. for i := 0; i < lead.electionTimeout-lead.heartbeatTimeout; i++ {
  2495. lead.tick()
  2496. }
  2497. checkLeaderTransferState(t, lead, StateLeader, 1)
  2498. }
  2499. func TestLeaderTransferIgnoreProposal(t *testing.T) {
  2500. nt := newNetwork(nil, nil, nil)
  2501. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2502. nt.isolate(3)
  2503. lead := nt.peers[1].(*raft)
  2504. // Transfer leadership to isolated node to let transfer pending, then send proposal.
  2505. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2506. if lead.leadTransferee != 3 {
  2507. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2508. }
  2509. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2510. if lead.prs[1].Match != 1 {
  2511. t.Fatalf("node 1 has match %x, want %x", lead.prs[1].Match, 1)
  2512. }
  2513. }
  2514. func TestLeaderTransferReceiveHigherTermVote(t *testing.T) {
  2515. nt := newNetwork(nil, nil, nil)
  2516. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2517. nt.isolate(3)
  2518. lead := nt.peers[1].(*raft)
  2519. // Transfer leadership to isolated node to let transfer pending.
  2520. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2521. if lead.leadTransferee != 3 {
  2522. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2523. }
  2524. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup, Index: 1, Term: 2})
  2525. checkLeaderTransferState(t, lead, StateFollower, 2)
  2526. }
  2527. func TestLeaderTransferRemoveNode(t *testing.T) {
  2528. nt := newNetwork(nil, nil, nil)
  2529. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2530. nt.ignore(pb.MsgTimeoutNow)
  2531. lead := nt.peers[1].(*raft)
  2532. // The leadTransferee is removed when leadship transferring.
  2533. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2534. if lead.leadTransferee != 3 {
  2535. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2536. }
  2537. lead.removeNode(3)
  2538. checkLeaderTransferState(t, lead, StateLeader, 1)
  2539. }
  2540. // TestLeaderTransferBack verifies leadership can transfer back to self when last transfer is pending.
  2541. func TestLeaderTransferBack(t *testing.T) {
  2542. nt := newNetwork(nil, nil, nil)
  2543. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2544. nt.isolate(3)
  2545. lead := nt.peers[1].(*raft)
  2546. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2547. if lead.leadTransferee != 3 {
  2548. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2549. }
  2550. // Transfer leadership back to self.
  2551. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgTransferLeader})
  2552. checkLeaderTransferState(t, lead, StateLeader, 1)
  2553. }
  2554. // TestLeaderTransferSecondTransferToAnotherNode verifies leader can transfer to another node
  2555. // when last transfer is pending.
  2556. func TestLeaderTransferSecondTransferToAnotherNode(t *testing.T) {
  2557. nt := newNetwork(nil, nil, nil)
  2558. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2559. nt.isolate(3)
  2560. lead := nt.peers[1].(*raft)
  2561. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2562. if lead.leadTransferee != 3 {
  2563. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2564. }
  2565. // Transfer leadership to another node.
  2566. nt.send(pb.Message{From: 2, To: 1, Type: pb.MsgTransferLeader})
  2567. checkLeaderTransferState(t, lead, StateFollower, 2)
  2568. }
  2569. // TestLeaderTransferSecondTransferToSameNode verifies second transfer leader request
  2570. // to the same node should not extend the timeout while the first one is pending.
  2571. func TestLeaderTransferSecondTransferToSameNode(t *testing.T) {
  2572. nt := newNetwork(nil, nil, nil)
  2573. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2574. nt.isolate(3)
  2575. lead := nt.peers[1].(*raft)
  2576. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2577. if lead.leadTransferee != 3 {
  2578. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2579. }
  2580. for i := 0; i < lead.heartbeatTimeout; i++ {
  2581. lead.tick()
  2582. }
  2583. // Second transfer leadership request to the same node.
  2584. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2585. for i := 0; i < lead.electionTimeout-lead.heartbeatTimeout; i++ {
  2586. lead.tick()
  2587. }
  2588. checkLeaderTransferState(t, lead, StateLeader, 1)
  2589. }
  2590. func checkLeaderTransferState(t *testing.T, r *raft, state StateType, lead uint64) {
  2591. if r.state != state || r.lead != lead {
  2592. t.Fatalf("after transferring, node has state %v lead %v, want state %v lead %v", r.state, r.lead, state, lead)
  2593. }
  2594. if r.leadTransferee != None {
  2595. t.Fatalf("after transferring, node has leadTransferee %v, want leadTransferee %v", r.leadTransferee, None)
  2596. }
  2597. }
  2598. // TestTransferNonMember verifies that when a MsgTimeoutNow arrives at
  2599. // a node that has been removed from the group, nothing happens.
  2600. // (previously, if the node also got votes, it would panic as it
  2601. // transitioned to StateLeader)
  2602. func TestTransferNonMember(t *testing.T) {
  2603. r := newTestRaft(1, []uint64{2, 3, 4}, 5, 1, NewMemoryStorage())
  2604. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgTimeoutNow})
  2605. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgVoteResp})
  2606. r.Step(pb.Message{From: 3, To: 1, Type: pb.MsgVoteResp})
  2607. if r.state != StateFollower {
  2608. t.Fatalf("state is %s, want StateFollower", r.state)
  2609. }
  2610. }
  2611. func entsWithConfig(configFunc func(*Config), terms ...uint64) *raft {
  2612. storage := NewMemoryStorage()
  2613. for i, term := range terms {
  2614. storage.Append([]pb.Entry{{Index: uint64(i + 1), Term: term}})
  2615. }
  2616. cfg := newTestConfig(1, []uint64{}, 5, 1, storage)
  2617. if configFunc != nil {
  2618. configFunc(cfg)
  2619. }
  2620. sm := newRaft(cfg)
  2621. sm.reset(terms[len(terms)-1])
  2622. return sm
  2623. }
  2624. // votedWithConfig creates a raft state machine with Vote and Term set
  2625. // to the given value but no log entries (indicating that it voted in
  2626. // the given term but has not received any logs).
  2627. func votedWithConfig(configFunc func(*Config), vote, term uint64) *raft {
  2628. storage := NewMemoryStorage()
  2629. storage.SetHardState(pb.HardState{Vote: vote, Term: term})
  2630. cfg := newTestConfig(1, []uint64{}, 5, 1, storage)
  2631. if configFunc != nil {
  2632. configFunc(cfg)
  2633. }
  2634. sm := newRaft(cfg)
  2635. sm.reset(term)
  2636. return sm
  2637. }
  2638. type network struct {
  2639. peers map[uint64]stateMachine
  2640. storage map[uint64]*MemoryStorage
  2641. dropm map[connem]float64
  2642. ignorem map[pb.MessageType]bool
  2643. }
  2644. // newNetwork initializes a network from peers.
  2645. // A nil node will be replaced with a new *stateMachine.
  2646. // A *stateMachine will get its k, id.
  2647. // When using stateMachine, the address list is always [1, n].
  2648. func newNetwork(peers ...stateMachine) *network {
  2649. return newNetworkWithConfig(nil, peers...)
  2650. }
  2651. // newNetworkWithConfig is like newNetwork but calls the given func to
  2652. // modify the configuration of any state machines it creates.
  2653. func newNetworkWithConfig(configFunc func(*Config), peers ...stateMachine) *network {
  2654. size := len(peers)
  2655. peerAddrs := idsBySize(size)
  2656. npeers := make(map[uint64]stateMachine, size)
  2657. nstorage := make(map[uint64]*MemoryStorage, size)
  2658. for j, p := range peers {
  2659. id := peerAddrs[j]
  2660. switch v := p.(type) {
  2661. case nil:
  2662. nstorage[id] = NewMemoryStorage()
  2663. cfg := newTestConfig(id, peerAddrs, 10, 1, nstorage[id])
  2664. if configFunc != nil {
  2665. configFunc(cfg)
  2666. }
  2667. sm := newRaft(cfg)
  2668. npeers[id] = sm
  2669. case *raft:
  2670. v.id = id
  2671. v.prs = make(map[uint64]*Progress)
  2672. for i := 0; i < size; i++ {
  2673. v.prs[peerAddrs[i]] = &Progress{}
  2674. }
  2675. v.reset(v.Term)
  2676. npeers[id] = v
  2677. case *blackHole:
  2678. npeers[id] = v
  2679. default:
  2680. panic(fmt.Sprintf("unexpected state machine type: %T", p))
  2681. }
  2682. }
  2683. return &network{
  2684. peers: npeers,
  2685. storage: nstorage,
  2686. dropm: make(map[connem]float64),
  2687. ignorem: make(map[pb.MessageType]bool),
  2688. }
  2689. }
  2690. func preVoteConfig(c *Config) {
  2691. c.PreVote = true
  2692. }
  2693. func (nw *network) send(msgs ...pb.Message) {
  2694. for len(msgs) > 0 {
  2695. m := msgs[0]
  2696. p := nw.peers[m.To]
  2697. p.Step(m)
  2698. msgs = append(msgs[1:], nw.filter(p.readMessages())...)
  2699. }
  2700. }
  2701. func (nw *network) drop(from, to uint64, perc float64) {
  2702. nw.dropm[connem{from, to}] = perc
  2703. }
  2704. func (nw *network) cut(one, other uint64) {
  2705. nw.drop(one, other, 1)
  2706. nw.drop(other, one, 1)
  2707. }
  2708. func (nw *network) isolate(id uint64) {
  2709. for i := 0; i < len(nw.peers); i++ {
  2710. nid := uint64(i) + 1
  2711. if nid != id {
  2712. nw.drop(id, nid, 1.0)
  2713. nw.drop(nid, id, 1.0)
  2714. }
  2715. }
  2716. }
  2717. func (nw *network) ignore(t pb.MessageType) {
  2718. nw.ignorem[t] = true
  2719. }
  2720. func (nw *network) recover() {
  2721. nw.dropm = make(map[connem]float64)
  2722. nw.ignorem = make(map[pb.MessageType]bool)
  2723. }
  2724. func (nw *network) filter(msgs []pb.Message) []pb.Message {
  2725. mm := []pb.Message{}
  2726. for _, m := range msgs {
  2727. if nw.ignorem[m.Type] {
  2728. continue
  2729. }
  2730. switch m.Type {
  2731. case pb.MsgHup:
  2732. // hups never go over the network, so don't drop them but panic
  2733. panic("unexpected msgHup")
  2734. default:
  2735. perc := nw.dropm[connem{m.From, m.To}]
  2736. if n := rand.Float64(); n < perc {
  2737. continue
  2738. }
  2739. }
  2740. mm = append(mm, m)
  2741. }
  2742. return mm
  2743. }
  2744. type connem struct {
  2745. from, to uint64
  2746. }
  2747. type blackHole struct{}
  2748. func (blackHole) Step(pb.Message) error { return nil }
  2749. func (blackHole) readMessages() []pb.Message { return nil }
  2750. var nopStepper = &blackHole{}
  2751. func idsBySize(size int) []uint64 {
  2752. ids := make([]uint64, size)
  2753. for i := 0; i < size; i++ {
  2754. ids[i] = 1 + uint64(i)
  2755. }
  2756. return ids
  2757. }
  2758. // setRandomizedElectionTimeout set up the value by caller instead of choosing
  2759. // by system, in some test scenario we need to fill in some expected value to
  2760. // ensure the certainty
  2761. func setRandomizedElectionTimeout(r *raft, v int) {
  2762. r.randomizedElectionTimeout = v
  2763. }
  2764. func newTestConfig(id uint64, peers []uint64, election, heartbeat int, storage Storage) *Config {
  2765. return &Config{
  2766. ID: id,
  2767. peers: peers,
  2768. ElectionTick: election,
  2769. HeartbeatTick: heartbeat,
  2770. Storage: storage,
  2771. MaxSizePerMsg: noLimit,
  2772. MaxInflightMsgs: 256,
  2773. }
  2774. }
  2775. func newTestRaft(id uint64, peers []uint64, election, heartbeat int, storage Storage) *raft {
  2776. return newRaft(newTestConfig(id, peers, election, heartbeat, storage))
  2777. }