raft_test.go 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285
  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. // TestRaftFreesReadOnlyMem ensures raft will free read request from
  1120. // readOnly readIndexQueue and pendingReadIndex map.
  1121. // related issue: https://github.com/coreos/etcd/issues/7571
  1122. func TestRaftFreesReadOnlyMem(t *testing.T) {
  1123. sm := newTestRaft(1, []uint64{1, 2}, 5, 1, NewMemoryStorage())
  1124. sm.becomeCandidate()
  1125. sm.becomeLeader()
  1126. sm.raftLog.commitTo(sm.raftLog.lastIndex())
  1127. ctx := []byte("ctx")
  1128. // leader starts linearizable read request.
  1129. // more info: raft dissertation 6.4, step 2.
  1130. sm.Step(pb.Message{From: 2, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: ctx}}})
  1131. msgs := sm.readMessages()
  1132. if len(msgs) != 1 {
  1133. t.Fatalf("len(msgs) = %d, want 1", len(msgs))
  1134. }
  1135. if msgs[0].Type != pb.MsgHeartbeat {
  1136. t.Fatalf("type = %v, want MsgHeartbeat", msgs[0].Type)
  1137. }
  1138. if !bytes.Equal(msgs[0].Context, ctx) {
  1139. t.Fatalf("Context = %v, want %v", msgs[0].Context, ctx)
  1140. }
  1141. if len(sm.readOnly.readIndexQueue) != 1 {
  1142. t.Fatalf("len(readIndexQueue) = %v, want 1", len(sm.readOnly.readIndexQueue))
  1143. }
  1144. if len(sm.readOnly.pendingReadIndex) != 1 {
  1145. t.Fatalf("len(pendingReadIndex) = %v, want 1", len(sm.readOnly.pendingReadIndex))
  1146. }
  1147. if _, ok := sm.readOnly.pendingReadIndex[string(ctx)]; !ok {
  1148. t.Fatalf("can't find context %v in pendingReadIndex ", ctx)
  1149. }
  1150. // heartbeat responses from majority of followers (1 in this case)
  1151. // acknowledge the authority of the leader.
  1152. // more info: raft dissertation 6.4, step 3.
  1153. sm.Step(pb.Message{From: 2, Type: pb.MsgHeartbeatResp, Context: ctx})
  1154. if len(sm.readOnly.readIndexQueue) != 0 {
  1155. t.Fatalf("len(readIndexQueue) = %v, want 0", len(sm.readOnly.readIndexQueue))
  1156. }
  1157. if len(sm.readOnly.pendingReadIndex) != 0 {
  1158. t.Fatalf("len(pendingReadIndex) = %v, want 0", len(sm.readOnly.pendingReadIndex))
  1159. }
  1160. if _, ok := sm.readOnly.pendingReadIndex[string(ctx)]; ok {
  1161. t.Fatalf("found context %v in pendingReadIndex, want none", ctx)
  1162. }
  1163. }
  1164. // TestMsgAppRespWaitReset verifies the resume behavior of a leader
  1165. // MsgAppResp.
  1166. func TestMsgAppRespWaitReset(t *testing.T) {
  1167. sm := newTestRaft(1, []uint64{1, 2, 3}, 5, 1, NewMemoryStorage())
  1168. sm.becomeCandidate()
  1169. sm.becomeLeader()
  1170. // The new leader has just emitted a new Term 4 entry; consume those messages
  1171. // from the outgoing queue.
  1172. sm.bcastAppend()
  1173. sm.readMessages()
  1174. // Node 2 acks the first entry, making it committed.
  1175. sm.Step(pb.Message{
  1176. From: 2,
  1177. Type: pb.MsgAppResp,
  1178. Index: 1,
  1179. })
  1180. if sm.raftLog.committed != 1 {
  1181. t.Fatalf("expected committed to be 1, got %d", sm.raftLog.committed)
  1182. }
  1183. // Also consume the MsgApp messages that update Commit on the followers.
  1184. sm.readMessages()
  1185. // A new command is now proposed on node 1.
  1186. sm.Step(pb.Message{
  1187. From: 1,
  1188. Type: pb.MsgProp,
  1189. Entries: []pb.Entry{{}},
  1190. })
  1191. // The command is broadcast to all nodes not in the wait state.
  1192. // Node 2 left the wait state due to its MsgAppResp, but node 3 is still waiting.
  1193. msgs := sm.readMessages()
  1194. if len(msgs) != 1 {
  1195. t.Fatalf("expected 1 message, got %d: %+v", len(msgs), msgs)
  1196. }
  1197. if msgs[0].Type != pb.MsgApp || msgs[0].To != 2 {
  1198. t.Errorf("expected MsgApp to node 2, got %v to %d", msgs[0].Type, msgs[0].To)
  1199. }
  1200. if len(msgs[0].Entries) != 1 || msgs[0].Entries[0].Index != 2 {
  1201. t.Errorf("expected to send entry 2, but got %v", msgs[0].Entries)
  1202. }
  1203. // Now Node 3 acks the first entry. This releases the wait and entry 2 is sent.
  1204. sm.Step(pb.Message{
  1205. From: 3,
  1206. Type: pb.MsgAppResp,
  1207. Index: 1,
  1208. })
  1209. msgs = sm.readMessages()
  1210. if len(msgs) != 1 {
  1211. t.Fatalf("expected 1 message, got %d: %+v", len(msgs), msgs)
  1212. }
  1213. if msgs[0].Type != pb.MsgApp || msgs[0].To != 3 {
  1214. t.Errorf("expected MsgApp to node 3, got %v to %d", msgs[0].Type, msgs[0].To)
  1215. }
  1216. if len(msgs[0].Entries) != 1 || msgs[0].Entries[0].Index != 2 {
  1217. t.Errorf("expected to send entry 2, but got %v", msgs[0].Entries)
  1218. }
  1219. }
  1220. func TestRecvMsgVote(t *testing.T) {
  1221. testRecvMsgVote(t, pb.MsgVote)
  1222. }
  1223. func testRecvMsgVote(t *testing.T, msgType pb.MessageType) {
  1224. tests := []struct {
  1225. state StateType
  1226. i, term uint64
  1227. voteFor uint64
  1228. wreject bool
  1229. }{
  1230. {StateFollower, 0, 0, None, true},
  1231. {StateFollower, 0, 1, None, true},
  1232. {StateFollower, 0, 2, None, true},
  1233. {StateFollower, 0, 3, None, false},
  1234. {StateFollower, 1, 0, None, true},
  1235. {StateFollower, 1, 1, None, true},
  1236. {StateFollower, 1, 2, None, true},
  1237. {StateFollower, 1, 3, None, false},
  1238. {StateFollower, 2, 0, None, true},
  1239. {StateFollower, 2, 1, None, true},
  1240. {StateFollower, 2, 2, None, false},
  1241. {StateFollower, 2, 3, None, false},
  1242. {StateFollower, 3, 0, None, true},
  1243. {StateFollower, 3, 1, None, true},
  1244. {StateFollower, 3, 2, None, false},
  1245. {StateFollower, 3, 3, None, false},
  1246. {StateFollower, 3, 2, 2, false},
  1247. {StateFollower, 3, 2, 1, true},
  1248. {StateLeader, 3, 3, 1, true},
  1249. {StatePreCandidate, 3, 3, 1, true},
  1250. {StateCandidate, 3, 3, 1, true},
  1251. }
  1252. for i, tt := range tests {
  1253. sm := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  1254. sm.state = tt.state
  1255. switch tt.state {
  1256. case StateFollower:
  1257. sm.step = stepFollower
  1258. case StateCandidate, StatePreCandidate:
  1259. sm.step = stepCandidate
  1260. case StateLeader:
  1261. sm.step = stepLeader
  1262. }
  1263. sm.Vote = tt.voteFor
  1264. sm.raftLog = &raftLog{
  1265. storage: &MemoryStorage{ents: []pb.Entry{{}, {Index: 1, Term: 2}, {Index: 2, Term: 2}}},
  1266. unstable: unstable{offset: 3},
  1267. }
  1268. sm.Step(pb.Message{Type: msgType, From: 2, Index: tt.i, LogTerm: tt.term})
  1269. msgs := sm.readMessages()
  1270. if g := len(msgs); g != 1 {
  1271. t.Fatalf("#%d: len(msgs) = %d, want 1", i, g)
  1272. continue
  1273. }
  1274. if g := msgs[0].Type; g != voteRespMsgType(msgType) {
  1275. t.Errorf("#%d, m.Type = %v, want %v", i, g, voteRespMsgType(msgType))
  1276. }
  1277. if g := msgs[0].Reject; g != tt.wreject {
  1278. t.Errorf("#%d, m.Reject = %v, want %v", i, g, tt.wreject)
  1279. }
  1280. }
  1281. }
  1282. func TestStateTransition(t *testing.T) {
  1283. tests := []struct {
  1284. from StateType
  1285. to StateType
  1286. wallow bool
  1287. wterm uint64
  1288. wlead uint64
  1289. }{
  1290. {StateFollower, StateFollower, true, 1, None},
  1291. {StateFollower, StatePreCandidate, true, 0, None},
  1292. {StateFollower, StateCandidate, true, 1, None},
  1293. {StateFollower, StateLeader, false, 0, None},
  1294. {StatePreCandidate, StateFollower, true, 0, None},
  1295. {StatePreCandidate, StatePreCandidate, true, 0, None},
  1296. {StatePreCandidate, StateCandidate, true, 1, None},
  1297. {StatePreCandidate, StateLeader, true, 0, 1},
  1298. {StateCandidate, StateFollower, true, 0, None},
  1299. {StateCandidate, StatePreCandidate, true, 0, None},
  1300. {StateCandidate, StateCandidate, true, 1, None},
  1301. {StateCandidate, StateLeader, true, 0, 1},
  1302. {StateLeader, StateFollower, true, 1, None},
  1303. {StateLeader, StatePreCandidate, false, 0, None},
  1304. {StateLeader, StateCandidate, false, 1, None},
  1305. {StateLeader, StateLeader, true, 0, 1},
  1306. }
  1307. for i, tt := range tests {
  1308. func() {
  1309. defer func() {
  1310. if r := recover(); r != nil {
  1311. if tt.wallow {
  1312. t.Errorf("%d: allow = %v, want %v", i, false, true)
  1313. }
  1314. }
  1315. }()
  1316. sm := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  1317. sm.state = tt.from
  1318. switch tt.to {
  1319. case StateFollower:
  1320. sm.becomeFollower(tt.wterm, tt.wlead)
  1321. case StatePreCandidate:
  1322. sm.becomePreCandidate()
  1323. case StateCandidate:
  1324. sm.becomeCandidate()
  1325. case StateLeader:
  1326. sm.becomeLeader()
  1327. }
  1328. if sm.Term != tt.wterm {
  1329. t.Errorf("%d: term = %d, want %d", i, sm.Term, tt.wterm)
  1330. }
  1331. if sm.lead != tt.wlead {
  1332. t.Errorf("%d: lead = %d, want %d", i, sm.lead, tt.wlead)
  1333. }
  1334. }()
  1335. }
  1336. }
  1337. func TestAllServerStepdown(t *testing.T) {
  1338. tests := []struct {
  1339. state StateType
  1340. wstate StateType
  1341. wterm uint64
  1342. windex uint64
  1343. }{
  1344. {StateFollower, StateFollower, 3, 0},
  1345. {StatePreCandidate, StateFollower, 3, 0},
  1346. {StateCandidate, StateFollower, 3, 0},
  1347. {StateLeader, StateFollower, 3, 1},
  1348. }
  1349. tmsgTypes := [...]pb.MessageType{pb.MsgVote, pb.MsgApp}
  1350. tterm := uint64(3)
  1351. for i, tt := range tests {
  1352. sm := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1353. switch tt.state {
  1354. case StateFollower:
  1355. sm.becomeFollower(1, None)
  1356. case StatePreCandidate:
  1357. sm.becomePreCandidate()
  1358. case StateCandidate:
  1359. sm.becomeCandidate()
  1360. case StateLeader:
  1361. sm.becomeCandidate()
  1362. sm.becomeLeader()
  1363. }
  1364. for j, msgType := range tmsgTypes {
  1365. sm.Step(pb.Message{From: 2, Type: msgType, Term: tterm, LogTerm: tterm})
  1366. if sm.state != tt.wstate {
  1367. t.Errorf("#%d.%d state = %v , want %v", i, j, sm.state, tt.wstate)
  1368. }
  1369. if sm.Term != tt.wterm {
  1370. t.Errorf("#%d.%d term = %v , want %v", i, j, sm.Term, tt.wterm)
  1371. }
  1372. if uint64(sm.raftLog.lastIndex()) != tt.windex {
  1373. t.Errorf("#%d.%d index = %v , want %v", i, j, sm.raftLog.lastIndex(), tt.windex)
  1374. }
  1375. if uint64(len(sm.raftLog.allEntries())) != tt.windex {
  1376. t.Errorf("#%d.%d len(ents) = %v , want %v", i, j, len(sm.raftLog.allEntries()), tt.windex)
  1377. }
  1378. wlead := uint64(2)
  1379. if msgType == pb.MsgVote {
  1380. wlead = None
  1381. }
  1382. if sm.lead != wlead {
  1383. t.Errorf("#%d, sm.lead = %d, want %d", i, sm.lead, None)
  1384. }
  1385. }
  1386. }
  1387. }
  1388. func TestLeaderStepdownWhenQuorumActive(t *testing.T) {
  1389. sm := newTestRaft(1, []uint64{1, 2, 3}, 5, 1, NewMemoryStorage())
  1390. sm.checkQuorum = true
  1391. sm.becomeCandidate()
  1392. sm.becomeLeader()
  1393. for i := 0; i < sm.electionTimeout+1; i++ {
  1394. sm.Step(pb.Message{From: 2, Type: pb.MsgHeartbeatResp, Term: sm.Term})
  1395. sm.tick()
  1396. }
  1397. if sm.state != StateLeader {
  1398. t.Errorf("state = %v, want %v", sm.state, StateLeader)
  1399. }
  1400. }
  1401. func TestLeaderStepdownWhenQuorumLost(t *testing.T) {
  1402. sm := newTestRaft(1, []uint64{1, 2, 3}, 5, 1, NewMemoryStorage())
  1403. sm.checkQuorum = true
  1404. sm.becomeCandidate()
  1405. sm.becomeLeader()
  1406. for i := 0; i < sm.electionTimeout+1; i++ {
  1407. sm.tick()
  1408. }
  1409. if sm.state != StateFollower {
  1410. t.Errorf("state = %v, want %v", sm.state, StateFollower)
  1411. }
  1412. }
  1413. func TestLeaderSupersedingWithCheckQuorum(t *testing.T) {
  1414. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1415. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1416. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1417. a.checkQuorum = true
  1418. b.checkQuorum = true
  1419. c.checkQuorum = true
  1420. nt := newNetwork(a, b, c)
  1421. setRandomizedElectionTimeout(b, b.electionTimeout+1)
  1422. for i := 0; i < b.electionTimeout; i++ {
  1423. b.tick()
  1424. }
  1425. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1426. if a.state != StateLeader {
  1427. t.Errorf("state = %s, want %s", a.state, StateLeader)
  1428. }
  1429. if c.state != StateFollower {
  1430. t.Errorf("state = %s, want %s", c.state, StateFollower)
  1431. }
  1432. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  1433. // Peer b rejected c's vote since its electionElapsed had not reached to electionTimeout
  1434. if c.state != StateCandidate {
  1435. t.Errorf("state = %s, want %s", c.state, StateCandidate)
  1436. }
  1437. // Letting b's electionElapsed reach to electionTimeout
  1438. for i := 0; i < b.electionTimeout; i++ {
  1439. b.tick()
  1440. }
  1441. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  1442. if c.state != StateLeader {
  1443. t.Errorf("state = %s, want %s", c.state, StateLeader)
  1444. }
  1445. }
  1446. func TestLeaderElectionWithCheckQuorum(t *testing.T) {
  1447. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1448. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1449. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1450. a.checkQuorum = true
  1451. b.checkQuorum = true
  1452. c.checkQuorum = true
  1453. nt := newNetwork(a, b, c)
  1454. setRandomizedElectionTimeout(a, a.electionTimeout+1)
  1455. setRandomizedElectionTimeout(b, b.electionTimeout+2)
  1456. // Immediately after creation, votes are cast regardless of the
  1457. // election timeout.
  1458. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1459. if a.state != StateLeader {
  1460. t.Errorf("state = %s, want %s", a.state, StateLeader)
  1461. }
  1462. if c.state != StateFollower {
  1463. t.Errorf("state = %s, want %s", c.state, StateFollower)
  1464. }
  1465. // need to reset randomizedElectionTimeout larger than electionTimeout again,
  1466. // because the value might be reset to electionTimeout since the last state changes
  1467. setRandomizedElectionTimeout(a, a.electionTimeout+1)
  1468. setRandomizedElectionTimeout(b, b.electionTimeout+2)
  1469. for i := 0; i < a.electionTimeout; i++ {
  1470. a.tick()
  1471. }
  1472. for i := 0; i < b.electionTimeout; i++ {
  1473. b.tick()
  1474. }
  1475. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  1476. if a.state != StateFollower {
  1477. t.Errorf("state = %s, want %s", a.state, StateFollower)
  1478. }
  1479. if c.state != StateLeader {
  1480. t.Errorf("state = %s, want %s", c.state, StateLeader)
  1481. }
  1482. }
  1483. // TestFreeStuckCandidateWithCheckQuorum ensures that a candidate with a higher term
  1484. // can disrupt the leader even if the leader still "officially" holds the lease, The
  1485. // leader is expected to step down and adopt the candidate's term
  1486. func TestFreeStuckCandidateWithCheckQuorum(t *testing.T) {
  1487. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1488. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1489. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1490. a.checkQuorum = true
  1491. b.checkQuorum = true
  1492. c.checkQuorum = true
  1493. nt := newNetwork(a, b, c)
  1494. setRandomizedElectionTimeout(b, b.electionTimeout+1)
  1495. for i := 0; i < b.electionTimeout; i++ {
  1496. b.tick()
  1497. }
  1498. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1499. nt.isolate(1)
  1500. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  1501. if b.state != StateFollower {
  1502. t.Errorf("state = %s, want %s", b.state, StateFollower)
  1503. }
  1504. if c.state != StateCandidate {
  1505. t.Errorf("state = %s, want %s", c.state, StateCandidate)
  1506. }
  1507. if c.Term != b.Term+1 {
  1508. t.Errorf("term = %d, want %d", c.Term, b.Term+1)
  1509. }
  1510. // Vote again for safety
  1511. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  1512. if b.state != StateFollower {
  1513. t.Errorf("state = %s, want %s", b.state, StateFollower)
  1514. }
  1515. if c.state != StateCandidate {
  1516. t.Errorf("state = %s, want %s", c.state, StateCandidate)
  1517. }
  1518. if c.Term != b.Term+2 {
  1519. t.Errorf("term = %d, want %d", c.Term, b.Term+2)
  1520. }
  1521. nt.recover()
  1522. nt.send(pb.Message{From: 1, To: 3, Type: pb.MsgHeartbeat, Term: a.Term})
  1523. // Disrupt the leader so that the stuck peer is freed
  1524. if a.state != StateFollower {
  1525. t.Errorf("state = %s, want %s", a.state, StateFollower)
  1526. }
  1527. if c.Term != a.Term {
  1528. t.Errorf("term = %d, want %d", c.Term, a.Term)
  1529. }
  1530. }
  1531. func TestNonPromotableVoterWithCheckQuorum(t *testing.T) {
  1532. a := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  1533. b := newTestRaft(2, []uint64{1}, 10, 1, NewMemoryStorage())
  1534. a.checkQuorum = true
  1535. b.checkQuorum = true
  1536. nt := newNetwork(a, b)
  1537. setRandomizedElectionTimeout(b, b.electionTimeout+1)
  1538. // Need to remove 2 again to make it a non-promotable node since newNetwork overwritten some internal states
  1539. b.delProgress(2)
  1540. if b.promotable() {
  1541. t.Fatalf("promotable = %v, want false", b.promotable())
  1542. }
  1543. for i := 0; i < b.electionTimeout; i++ {
  1544. b.tick()
  1545. }
  1546. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1547. if a.state != StateLeader {
  1548. t.Errorf("state = %s, want %s", a.state, StateLeader)
  1549. }
  1550. if b.state != StateFollower {
  1551. t.Errorf("state = %s, want %s", b.state, StateFollower)
  1552. }
  1553. if b.lead != 1 {
  1554. t.Errorf("lead = %d, want 1", b.lead)
  1555. }
  1556. }
  1557. func TestReadOnlyOptionSafe(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. nt := newNetwork(a, b, c)
  1562. setRandomizedElectionTimeout(b, b.electionTimeout+1)
  1563. for i := 0; i < b.electionTimeout; i++ {
  1564. b.tick()
  1565. }
  1566. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1567. if a.state != StateLeader {
  1568. t.Fatalf("state = %s, want %s", a.state, StateLeader)
  1569. }
  1570. tests := []struct {
  1571. sm *raft
  1572. proposals int
  1573. wri uint64
  1574. wctx []byte
  1575. }{
  1576. {a, 10, 11, []byte("ctx1")},
  1577. {b, 10, 21, []byte("ctx2")},
  1578. {c, 10, 31, []byte("ctx3")},
  1579. {a, 10, 41, []byte("ctx4")},
  1580. {b, 10, 51, []byte("ctx5")},
  1581. {c, 10, 61, []byte("ctx6")},
  1582. }
  1583. for i, tt := range tests {
  1584. for j := 0; j < tt.proposals; j++ {
  1585. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  1586. }
  1587. nt.send(pb.Message{From: tt.sm.id, To: tt.sm.id, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: tt.wctx}}})
  1588. r := tt.sm
  1589. if len(r.readStates) == 0 {
  1590. t.Errorf("#%d: len(readStates) = 0, want non-zero", i)
  1591. }
  1592. rs := r.readStates[0]
  1593. if rs.Index != tt.wri {
  1594. t.Errorf("#%d: readIndex = %d, want %d", i, rs.Index, tt.wri)
  1595. }
  1596. if !bytes.Equal(rs.RequestCtx, tt.wctx) {
  1597. t.Errorf("#%d: requestCtx = %v, want %v", i, rs.RequestCtx, tt.wctx)
  1598. }
  1599. r.readStates = nil
  1600. }
  1601. }
  1602. func TestReadOnlyOptionLease(t *testing.T) {
  1603. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1604. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1605. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1606. a.readOnly.option = ReadOnlyLeaseBased
  1607. b.readOnly.option = ReadOnlyLeaseBased
  1608. c.readOnly.option = ReadOnlyLeaseBased
  1609. a.checkQuorum = true
  1610. b.checkQuorum = true
  1611. c.checkQuorum = true
  1612. nt := newNetwork(a, b, c)
  1613. setRandomizedElectionTimeout(b, b.electionTimeout+1)
  1614. for i := 0; i < b.electionTimeout; i++ {
  1615. b.tick()
  1616. }
  1617. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1618. if a.state != StateLeader {
  1619. t.Fatalf("state = %s, want %s", a.state, StateLeader)
  1620. }
  1621. tests := []struct {
  1622. sm *raft
  1623. proposals int
  1624. wri uint64
  1625. wctx []byte
  1626. }{
  1627. {a, 10, 11, []byte("ctx1")},
  1628. {b, 10, 21, []byte("ctx2")},
  1629. {c, 10, 31, []byte("ctx3")},
  1630. {a, 10, 41, []byte("ctx4")},
  1631. {b, 10, 51, []byte("ctx5")},
  1632. {c, 10, 61, []byte("ctx6")},
  1633. }
  1634. for i, tt := range tests {
  1635. for j := 0; j < tt.proposals; j++ {
  1636. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  1637. }
  1638. nt.send(pb.Message{From: tt.sm.id, To: tt.sm.id, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: tt.wctx}}})
  1639. r := tt.sm
  1640. rs := r.readStates[0]
  1641. if rs.Index != tt.wri {
  1642. t.Errorf("#%d: readIndex = %d, want %d", i, rs.Index, tt.wri)
  1643. }
  1644. if !bytes.Equal(rs.RequestCtx, tt.wctx) {
  1645. t.Errorf("#%d: requestCtx = %v, want %v", i, rs.RequestCtx, tt.wctx)
  1646. }
  1647. r.readStates = nil
  1648. }
  1649. }
  1650. func TestReadOnlyOptionLeaseWithoutCheckQuorum(t *testing.T) {
  1651. a := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1652. b := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1653. c := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1654. a.readOnly.option = ReadOnlyLeaseBased
  1655. b.readOnly.option = ReadOnlyLeaseBased
  1656. c.readOnly.option = ReadOnlyLeaseBased
  1657. nt := newNetwork(a, b, c)
  1658. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1659. ctx := []byte("ctx1")
  1660. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: ctx}}})
  1661. rs := b.readStates[0]
  1662. if rs.Index != None {
  1663. t.Errorf("readIndex = %d, want %d", rs.Index, None)
  1664. }
  1665. if !bytes.Equal(rs.RequestCtx, ctx) {
  1666. t.Errorf("requestCtx = %v, want %v", rs.RequestCtx, ctx)
  1667. }
  1668. }
  1669. // TestReadOnlyForNewLeader ensures that a leader only accepts MsgReadIndex message
  1670. // when it commits at least one log entry at it term.
  1671. func TestReadOnlyForNewLeader(t *testing.T) {
  1672. nodeConfigs := []struct {
  1673. id uint64
  1674. committed uint64
  1675. applied uint64
  1676. compact_index uint64
  1677. }{
  1678. {1, 1, 1, 0},
  1679. {2, 2, 2, 2},
  1680. {3, 2, 2, 2},
  1681. }
  1682. peers := make([]stateMachine, 0)
  1683. for _, c := range nodeConfigs {
  1684. storage := NewMemoryStorage()
  1685. storage.Append([]pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}})
  1686. storage.SetHardState(pb.HardState{Term: 1, Commit: c.committed})
  1687. if c.compact_index != 0 {
  1688. storage.Compact(c.compact_index)
  1689. }
  1690. cfg := newTestConfig(c.id, []uint64{1, 2, 3}, 10, 1, storage)
  1691. cfg.Applied = c.applied
  1692. raft := newRaft(cfg)
  1693. peers = append(peers, raft)
  1694. }
  1695. nt := newNetwork(peers...)
  1696. // Drop MsgApp to forbid peer a to commit any log entry at its term after it becomes leader.
  1697. nt.ignore(pb.MsgApp)
  1698. // Force peer a to become leader.
  1699. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1700. sm := nt.peers[1].(*raft)
  1701. if sm.state != StateLeader {
  1702. t.Fatalf("state = %s, want %s", sm.state, StateLeader)
  1703. }
  1704. // Ensure peer a drops read only request.
  1705. var windex uint64 = 4
  1706. wctx := []byte("ctx")
  1707. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: wctx}}})
  1708. if len(sm.readStates) != 0 {
  1709. t.Fatalf("len(readStates) = %d, want zero", len(sm.readStates))
  1710. }
  1711. nt.recover()
  1712. // Force peer a to commit a log entry at its term
  1713. for i := 0; i < sm.heartbeatTimeout; i++ {
  1714. sm.tick()
  1715. }
  1716. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  1717. if sm.raftLog.committed != 4 {
  1718. t.Fatalf("committed = %d, want 4", sm.raftLog.committed)
  1719. }
  1720. lastLogTerm := sm.raftLog.zeroTermOnErrCompacted(sm.raftLog.term(sm.raftLog.committed))
  1721. if lastLogTerm != sm.Term {
  1722. t.Fatalf("last log term = %d, want %d", lastLogTerm, sm.Term)
  1723. }
  1724. // Ensure peer a accepts read only request after it commits a entry at its term.
  1725. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgReadIndex, Entries: []pb.Entry{{Data: wctx}}})
  1726. if len(sm.readStates) != 1 {
  1727. t.Fatalf("len(readStates) = %d, want 1", len(sm.readStates))
  1728. }
  1729. rs := sm.readStates[0]
  1730. if rs.Index != windex {
  1731. t.Fatalf("readIndex = %d, want %d", rs.Index, windex)
  1732. }
  1733. if !bytes.Equal(rs.RequestCtx, wctx) {
  1734. t.Fatalf("requestCtx = %v, want %v", rs.RequestCtx, wctx)
  1735. }
  1736. }
  1737. func TestLeaderAppResp(t *testing.T) {
  1738. // initial progress: match = 0; next = 3
  1739. tests := []struct {
  1740. index uint64
  1741. reject bool
  1742. // progress
  1743. wmatch uint64
  1744. wnext uint64
  1745. // message
  1746. wmsgNum int
  1747. windex uint64
  1748. wcommitted uint64
  1749. }{
  1750. {3, true, 0, 3, 0, 0, 0}, // stale resp; no replies
  1751. {2, true, 0, 2, 1, 1, 0}, // denied resp; leader does not commit; decrease next and send probing msg
  1752. {2, false, 2, 4, 2, 2, 2}, // accept resp; leader commits; broadcast with commit index
  1753. {0, false, 0, 3, 0, 0, 0}, // ignore heartbeat replies
  1754. }
  1755. for i, tt := range tests {
  1756. // sm term is 1 after it becomes the leader.
  1757. // thus the last log term must be 1 to be committed.
  1758. sm := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1759. sm.raftLog = &raftLog{
  1760. storage: &MemoryStorage{ents: []pb.Entry{{}, {Index: 1, Term: 0}, {Index: 2, Term: 1}}},
  1761. unstable: unstable{offset: 3},
  1762. }
  1763. sm.becomeCandidate()
  1764. sm.becomeLeader()
  1765. sm.readMessages()
  1766. sm.Step(pb.Message{From: 2, Type: pb.MsgAppResp, Index: tt.index, Term: sm.Term, Reject: tt.reject, RejectHint: tt.index})
  1767. p := sm.prs[2]
  1768. if p.Match != tt.wmatch {
  1769. t.Errorf("#%d match = %d, want %d", i, p.Match, tt.wmatch)
  1770. }
  1771. if p.Next != tt.wnext {
  1772. t.Errorf("#%d next = %d, want %d", i, p.Next, tt.wnext)
  1773. }
  1774. msgs := sm.readMessages()
  1775. if len(msgs) != tt.wmsgNum {
  1776. t.Errorf("#%d msgNum = %d, want %d", i, len(msgs), tt.wmsgNum)
  1777. }
  1778. for j, msg := range msgs {
  1779. if msg.Index != tt.windex {
  1780. t.Errorf("#%d.%d index = %d, want %d", i, j, msg.Index, tt.windex)
  1781. }
  1782. if msg.Commit != tt.wcommitted {
  1783. t.Errorf("#%d.%d commit = %d, want %d", i, j, msg.Commit, tt.wcommitted)
  1784. }
  1785. }
  1786. }
  1787. }
  1788. // When the leader receives a heartbeat tick, it should
  1789. // send a MsgApp with m.Index = 0, m.LogTerm=0 and empty entries.
  1790. func TestBcastBeat(t *testing.T) {
  1791. offset := uint64(1000)
  1792. // make a state machine with log.offset = 1000
  1793. s := pb.Snapshot{
  1794. Metadata: pb.SnapshotMetadata{
  1795. Index: offset,
  1796. Term: 1,
  1797. ConfState: pb.ConfState{Nodes: []uint64{1, 2, 3}},
  1798. },
  1799. }
  1800. storage := NewMemoryStorage()
  1801. storage.ApplySnapshot(s)
  1802. sm := newTestRaft(1, nil, 10, 1, storage)
  1803. sm.Term = 1
  1804. sm.becomeCandidate()
  1805. sm.becomeLeader()
  1806. for i := 0; i < 10; i++ {
  1807. sm.appendEntry(pb.Entry{Index: uint64(i) + 1})
  1808. }
  1809. // slow follower
  1810. sm.prs[2].Match, sm.prs[2].Next = 5, 6
  1811. // normal follower
  1812. sm.prs[3].Match, sm.prs[3].Next = sm.raftLog.lastIndex(), sm.raftLog.lastIndex()+1
  1813. sm.Step(pb.Message{Type: pb.MsgBeat})
  1814. msgs := sm.readMessages()
  1815. if len(msgs) != 2 {
  1816. t.Fatalf("len(msgs) = %v, want 2", len(msgs))
  1817. }
  1818. wantCommitMap := map[uint64]uint64{
  1819. 2: min(sm.raftLog.committed, sm.prs[2].Match),
  1820. 3: min(sm.raftLog.committed, sm.prs[3].Match),
  1821. }
  1822. for i, m := range msgs {
  1823. if m.Type != pb.MsgHeartbeat {
  1824. t.Fatalf("#%d: type = %v, want = %v", i, m.Type, pb.MsgHeartbeat)
  1825. }
  1826. if m.Index != 0 {
  1827. t.Fatalf("#%d: prevIndex = %d, want %d", i, m.Index, 0)
  1828. }
  1829. if m.LogTerm != 0 {
  1830. t.Fatalf("#%d: prevTerm = %d, want %d", i, m.LogTerm, 0)
  1831. }
  1832. if wantCommitMap[m.To] == 0 {
  1833. t.Fatalf("#%d: unexpected to %d", i, m.To)
  1834. } else {
  1835. if m.Commit != wantCommitMap[m.To] {
  1836. t.Fatalf("#%d: commit = %d, want %d", i, m.Commit, wantCommitMap[m.To])
  1837. }
  1838. delete(wantCommitMap, m.To)
  1839. }
  1840. if len(m.Entries) != 0 {
  1841. t.Fatalf("#%d: len(entries) = %d, want 0", i, len(m.Entries))
  1842. }
  1843. }
  1844. }
  1845. // tests the output of the state machine when receiving MsgBeat
  1846. func TestRecvMsgBeat(t *testing.T) {
  1847. tests := []struct {
  1848. state StateType
  1849. wMsg int
  1850. }{
  1851. {StateLeader, 2},
  1852. // candidate and follower should ignore MsgBeat
  1853. {StateCandidate, 0},
  1854. {StateFollower, 0},
  1855. }
  1856. for i, tt := range tests {
  1857. sm := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  1858. sm.raftLog = &raftLog{storage: &MemoryStorage{ents: []pb.Entry{{}, {Index: 1, Term: 0}, {Index: 2, Term: 1}}}}
  1859. sm.Term = 1
  1860. sm.state = tt.state
  1861. switch tt.state {
  1862. case StateFollower:
  1863. sm.step = stepFollower
  1864. case StateCandidate:
  1865. sm.step = stepCandidate
  1866. case StateLeader:
  1867. sm.step = stepLeader
  1868. }
  1869. sm.Step(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  1870. msgs := sm.readMessages()
  1871. if len(msgs) != tt.wMsg {
  1872. t.Errorf("%d: len(msgs) = %d, want %d", i, len(msgs), tt.wMsg)
  1873. }
  1874. for _, m := range msgs {
  1875. if m.Type != pb.MsgHeartbeat {
  1876. t.Errorf("%d: msg.type = %v, want %v", i, m.Type, pb.MsgHeartbeat)
  1877. }
  1878. }
  1879. }
  1880. }
  1881. func TestLeaderIncreaseNext(t *testing.T) {
  1882. previousEnts := []pb.Entry{{Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3}}
  1883. tests := []struct {
  1884. // progress
  1885. state ProgressStateType
  1886. next uint64
  1887. wnext uint64
  1888. }{
  1889. // state replicate, optimistically increase next
  1890. // previous entries + noop entry + propose + 1
  1891. {ProgressStateReplicate, 2, uint64(len(previousEnts) + 1 + 1 + 1)},
  1892. // state probe, not optimistically increase next
  1893. {ProgressStateProbe, 2, 2},
  1894. }
  1895. for i, tt := range tests {
  1896. sm := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  1897. sm.raftLog.append(previousEnts...)
  1898. sm.becomeCandidate()
  1899. sm.becomeLeader()
  1900. sm.prs[2].State = tt.state
  1901. sm.prs[2].Next = tt.next
  1902. sm.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  1903. p := sm.prs[2]
  1904. if p.Next != tt.wnext {
  1905. t.Errorf("#%d next = %d, want %d", i, p.Next, tt.wnext)
  1906. }
  1907. }
  1908. }
  1909. func TestSendAppendForProgressProbe(t *testing.T) {
  1910. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  1911. r.becomeCandidate()
  1912. r.becomeLeader()
  1913. r.readMessages()
  1914. r.prs[2].becomeProbe()
  1915. // each round is a heartbeat
  1916. for i := 0; i < 3; i++ {
  1917. if i == 0 {
  1918. // we expect that raft will only send out one msgAPP on the first
  1919. // loop. After that, the follower is paused until a heartbeat response is
  1920. // received.
  1921. r.appendEntry(pb.Entry{Data: []byte("somedata")})
  1922. r.sendAppend(2)
  1923. msg := r.readMessages()
  1924. if len(msg) != 1 {
  1925. t.Errorf("len(msg) = %d, want %d", len(msg), 1)
  1926. }
  1927. if msg[0].Index != 0 {
  1928. t.Errorf("index = %d, want %d", msg[0].Index, 0)
  1929. }
  1930. }
  1931. if !r.prs[2].Paused {
  1932. t.Errorf("paused = %v, want true", r.prs[2].Paused)
  1933. }
  1934. for j := 0; j < 10; j++ {
  1935. r.appendEntry(pb.Entry{Data: []byte("somedata")})
  1936. r.sendAppend(2)
  1937. if l := len(r.readMessages()); l != 0 {
  1938. t.Errorf("len(msg) = %d, want %d", l, 0)
  1939. }
  1940. }
  1941. // do a heartbeat
  1942. for j := 0; j < r.heartbeatTimeout; j++ {
  1943. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  1944. }
  1945. if !r.prs[2].Paused {
  1946. t.Errorf("paused = %v, want true", r.prs[2].Paused)
  1947. }
  1948. // consume the heartbeat
  1949. msg := r.readMessages()
  1950. if len(msg) != 1 {
  1951. t.Errorf("len(msg) = %d, want %d", len(msg), 1)
  1952. }
  1953. if msg[0].Type != pb.MsgHeartbeat {
  1954. t.Errorf("type = %v, want %v", msg[0].Type, pb.MsgHeartbeat)
  1955. }
  1956. }
  1957. // a heartbeat response will allow another message to be sent
  1958. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgHeartbeatResp})
  1959. msg := r.readMessages()
  1960. if len(msg) != 1 {
  1961. t.Errorf("len(msg) = %d, want %d", len(msg), 1)
  1962. }
  1963. if msg[0].Index != 0 {
  1964. t.Errorf("index = %d, want %d", msg[0].Index, 0)
  1965. }
  1966. if !r.prs[2].Paused {
  1967. t.Errorf("paused = %v, want true", r.prs[2].Paused)
  1968. }
  1969. }
  1970. func TestSendAppendForProgressReplicate(t *testing.T) {
  1971. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  1972. r.becomeCandidate()
  1973. r.becomeLeader()
  1974. r.readMessages()
  1975. r.prs[2].becomeReplicate()
  1976. for i := 0; i < 10; i++ {
  1977. r.appendEntry(pb.Entry{Data: []byte("somedata")})
  1978. r.sendAppend(2)
  1979. msgs := r.readMessages()
  1980. if len(msgs) != 1 {
  1981. t.Errorf("len(msg) = %d, want %d", len(msgs), 1)
  1982. }
  1983. }
  1984. }
  1985. func TestSendAppendForProgressSnapshot(t *testing.T) {
  1986. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  1987. r.becomeCandidate()
  1988. r.becomeLeader()
  1989. r.readMessages()
  1990. r.prs[2].becomeSnapshot(10)
  1991. for i := 0; i < 10; i++ {
  1992. r.appendEntry(pb.Entry{Data: []byte("somedata")})
  1993. r.sendAppend(2)
  1994. msgs := r.readMessages()
  1995. if len(msgs) != 0 {
  1996. t.Errorf("len(msg) = %d, want %d", len(msgs), 0)
  1997. }
  1998. }
  1999. }
  2000. func TestRecvMsgUnreachable(t *testing.T) {
  2001. previousEnts := []pb.Entry{{Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3}}
  2002. s := NewMemoryStorage()
  2003. s.Append(previousEnts)
  2004. r := newTestRaft(1, []uint64{1, 2}, 10, 1, s)
  2005. r.becomeCandidate()
  2006. r.becomeLeader()
  2007. r.readMessages()
  2008. // set node 2 to state replicate
  2009. r.prs[2].Match = 3
  2010. r.prs[2].becomeReplicate()
  2011. r.prs[2].optimisticUpdate(5)
  2012. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgUnreachable})
  2013. if r.prs[2].State != ProgressStateProbe {
  2014. t.Errorf("state = %s, want %s", r.prs[2].State, ProgressStateProbe)
  2015. }
  2016. if wnext := r.prs[2].Match + 1; r.prs[2].Next != wnext {
  2017. t.Errorf("next = %d, want %d", r.prs[2].Next, wnext)
  2018. }
  2019. }
  2020. func TestRestore(t *testing.T) {
  2021. s := pb.Snapshot{
  2022. Metadata: pb.SnapshotMetadata{
  2023. Index: 11, // magic number
  2024. Term: 11, // magic number
  2025. ConfState: pb.ConfState{Nodes: []uint64{1, 2, 3}},
  2026. },
  2027. }
  2028. storage := NewMemoryStorage()
  2029. sm := newTestRaft(1, []uint64{1, 2}, 10, 1, storage)
  2030. if ok := sm.restore(s); !ok {
  2031. t.Fatal("restore fail, want succeed")
  2032. }
  2033. if sm.raftLog.lastIndex() != s.Metadata.Index {
  2034. t.Errorf("log.lastIndex = %d, want %d", sm.raftLog.lastIndex(), s.Metadata.Index)
  2035. }
  2036. if mustTerm(sm.raftLog.term(s.Metadata.Index)) != s.Metadata.Term {
  2037. t.Errorf("log.lastTerm = %d, want %d", mustTerm(sm.raftLog.term(s.Metadata.Index)), s.Metadata.Term)
  2038. }
  2039. sg := sm.nodes()
  2040. if !reflect.DeepEqual(sg, s.Metadata.ConfState.Nodes) {
  2041. t.Errorf("sm.Nodes = %+v, want %+v", sg, s.Metadata.ConfState.Nodes)
  2042. }
  2043. if ok := sm.restore(s); ok {
  2044. t.Fatal("restore succeed, want fail")
  2045. }
  2046. }
  2047. func TestRestoreIgnoreSnapshot(t *testing.T) {
  2048. previousEnts := []pb.Entry{{Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3}}
  2049. commit := uint64(1)
  2050. storage := NewMemoryStorage()
  2051. sm := newTestRaft(1, []uint64{1, 2}, 10, 1, storage)
  2052. sm.raftLog.append(previousEnts...)
  2053. sm.raftLog.commitTo(commit)
  2054. s := pb.Snapshot{
  2055. Metadata: pb.SnapshotMetadata{
  2056. Index: commit,
  2057. Term: 1,
  2058. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  2059. },
  2060. }
  2061. // ignore snapshot
  2062. if ok := sm.restore(s); ok {
  2063. t.Errorf("restore = %t, want %t", ok, false)
  2064. }
  2065. if sm.raftLog.committed != commit {
  2066. t.Errorf("commit = %d, want %d", sm.raftLog.committed, commit)
  2067. }
  2068. // ignore snapshot and fast forward commit
  2069. s.Metadata.Index = commit + 1
  2070. if ok := sm.restore(s); ok {
  2071. t.Errorf("restore = %t, want %t", ok, false)
  2072. }
  2073. if sm.raftLog.committed != commit+1 {
  2074. t.Errorf("commit = %d, want %d", sm.raftLog.committed, commit+1)
  2075. }
  2076. }
  2077. func TestProvideSnap(t *testing.T) {
  2078. // restore the state machine from a snapshot so it has a compacted log and a snapshot
  2079. s := pb.Snapshot{
  2080. Metadata: pb.SnapshotMetadata{
  2081. Index: 11, // magic number
  2082. Term: 11, // magic number
  2083. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  2084. },
  2085. }
  2086. storage := NewMemoryStorage()
  2087. sm := newTestRaft(1, []uint64{1}, 10, 1, storage)
  2088. sm.restore(s)
  2089. sm.becomeCandidate()
  2090. sm.becomeLeader()
  2091. // force set the next of node 2, so that node 2 needs a snapshot
  2092. sm.prs[2].Next = sm.raftLog.firstIndex()
  2093. sm.Step(pb.Message{From: 2, To: 1, Type: pb.MsgAppResp, Index: sm.prs[2].Next - 1, Reject: true})
  2094. msgs := sm.readMessages()
  2095. if len(msgs) != 1 {
  2096. t.Fatalf("len(msgs) = %d, want 1", len(msgs))
  2097. }
  2098. m := msgs[0]
  2099. if m.Type != pb.MsgSnap {
  2100. t.Errorf("m.Type = %v, want %v", m.Type, pb.MsgSnap)
  2101. }
  2102. }
  2103. func TestIgnoreProvidingSnap(t *testing.T) {
  2104. // restore the state machine from a snapshot so it has a compacted log and a snapshot
  2105. s := pb.Snapshot{
  2106. Metadata: pb.SnapshotMetadata{
  2107. Index: 11, // magic number
  2108. Term: 11, // magic number
  2109. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  2110. },
  2111. }
  2112. storage := NewMemoryStorage()
  2113. sm := newTestRaft(1, []uint64{1}, 10, 1, storage)
  2114. sm.restore(s)
  2115. sm.becomeCandidate()
  2116. sm.becomeLeader()
  2117. // force set the next of node 2, so that node 2 needs a snapshot
  2118. // change node 2 to be inactive, expect node 1 ignore sending snapshot to 2
  2119. sm.prs[2].Next = sm.raftLog.firstIndex() - 1
  2120. sm.prs[2].RecentActive = false
  2121. sm.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  2122. msgs := sm.readMessages()
  2123. if len(msgs) != 0 {
  2124. t.Errorf("len(msgs) = %d, want 0", len(msgs))
  2125. }
  2126. }
  2127. func TestRestoreFromSnapMsg(t *testing.T) {
  2128. s := pb.Snapshot{
  2129. Metadata: pb.SnapshotMetadata{
  2130. Index: 11, // magic number
  2131. Term: 11, // magic number
  2132. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  2133. },
  2134. }
  2135. m := pb.Message{Type: pb.MsgSnap, From: 1, Term: 2, Snapshot: s}
  2136. sm := newTestRaft(2, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2137. sm.Step(m)
  2138. if sm.lead != uint64(1) {
  2139. t.Errorf("sm.lead = %d, want 1", sm.lead)
  2140. }
  2141. // TODO(bdarnell): what should this test?
  2142. }
  2143. func TestSlowNodeRestore(t *testing.T) {
  2144. nt := newNetwork(nil, nil, nil)
  2145. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2146. nt.isolate(3)
  2147. for j := 0; j <= 100; j++ {
  2148. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2149. }
  2150. lead := nt.peers[1].(*raft)
  2151. nextEnts(lead, nt.storage[1])
  2152. nt.storage[1].CreateSnapshot(lead.raftLog.applied, &pb.ConfState{Nodes: lead.nodes()}, nil)
  2153. nt.storage[1].Compact(lead.raftLog.applied)
  2154. nt.recover()
  2155. // send heartbeats so that the leader can learn everyone is active.
  2156. // node 3 will only be considered as active when node 1 receives a reply from it.
  2157. for {
  2158. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  2159. if lead.prs[3].RecentActive {
  2160. break
  2161. }
  2162. }
  2163. // trigger a snapshot
  2164. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2165. follower := nt.peers[3].(*raft)
  2166. // trigger a commit
  2167. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2168. if follower.raftLog.committed != lead.raftLog.committed {
  2169. t.Errorf("follower.committed = %d, want %d", follower.raftLog.committed, lead.raftLog.committed)
  2170. }
  2171. }
  2172. // TestStepConfig tests that when raft step msgProp in EntryConfChange type,
  2173. // it appends the entry to log and sets pendingConf to be true.
  2174. func TestStepConfig(t *testing.T) {
  2175. // a raft that cannot make progress
  2176. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2177. r.becomeCandidate()
  2178. r.becomeLeader()
  2179. index := r.raftLog.lastIndex()
  2180. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange}}})
  2181. if g := r.raftLog.lastIndex(); g != index+1 {
  2182. t.Errorf("index = %d, want %d", g, index+1)
  2183. }
  2184. if !r.pendingConf {
  2185. t.Errorf("pendingConf = %v, want true", r.pendingConf)
  2186. }
  2187. }
  2188. // TestStepIgnoreConfig tests that if raft step the second msgProp in
  2189. // EntryConfChange type when the first one is uncommitted, the node will set
  2190. // the proposal to noop and keep its original state.
  2191. func TestStepIgnoreConfig(t *testing.T) {
  2192. // a raft that cannot make progress
  2193. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2194. r.becomeCandidate()
  2195. r.becomeLeader()
  2196. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange}}})
  2197. index := r.raftLog.lastIndex()
  2198. pendingConf := r.pendingConf
  2199. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange}}})
  2200. wents := []pb.Entry{{Type: pb.EntryNormal, Term: 1, Index: 3, Data: nil}}
  2201. ents, err := r.raftLog.entries(index+1, noLimit)
  2202. if err != nil {
  2203. t.Fatalf("unexpected error %v", err)
  2204. }
  2205. if !reflect.DeepEqual(ents, wents) {
  2206. t.Errorf("ents = %+v, want %+v", ents, wents)
  2207. }
  2208. if r.pendingConf != pendingConf {
  2209. t.Errorf("pendingConf = %v, want %v", r.pendingConf, pendingConf)
  2210. }
  2211. }
  2212. // TestRecoverPendingConfig tests that new leader recovers its pendingConf flag
  2213. // based on uncommitted entries.
  2214. func TestRecoverPendingConfig(t *testing.T) {
  2215. tests := []struct {
  2216. entType pb.EntryType
  2217. wpending bool
  2218. }{
  2219. {pb.EntryNormal, false},
  2220. {pb.EntryConfChange, true},
  2221. }
  2222. for i, tt := range tests {
  2223. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2224. r.appendEntry(pb.Entry{Type: tt.entType})
  2225. r.becomeCandidate()
  2226. r.becomeLeader()
  2227. if r.pendingConf != tt.wpending {
  2228. t.Errorf("#%d: pendingConf = %v, want %v", i, r.pendingConf, tt.wpending)
  2229. }
  2230. }
  2231. }
  2232. // TestRecoverDoublePendingConfig tests that new leader will panic if
  2233. // there exist two uncommitted config entries.
  2234. func TestRecoverDoublePendingConfig(t *testing.T) {
  2235. func() {
  2236. defer func() {
  2237. if err := recover(); err == nil {
  2238. t.Errorf("expect panic, but nothing happens")
  2239. }
  2240. }()
  2241. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2242. r.appendEntry(pb.Entry{Type: pb.EntryConfChange})
  2243. r.appendEntry(pb.Entry{Type: pb.EntryConfChange})
  2244. r.becomeCandidate()
  2245. r.becomeLeader()
  2246. }()
  2247. }
  2248. // TestAddNode tests that addNode could update pendingConf and nodes correctly.
  2249. func TestAddNode(t *testing.T) {
  2250. r := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  2251. r.pendingConf = true
  2252. r.addNode(2)
  2253. if r.pendingConf {
  2254. t.Errorf("pendingConf = %v, want false", r.pendingConf)
  2255. }
  2256. nodes := r.nodes()
  2257. wnodes := []uint64{1, 2}
  2258. if !reflect.DeepEqual(nodes, wnodes) {
  2259. t.Errorf("nodes = %v, want %v", nodes, wnodes)
  2260. }
  2261. }
  2262. // TestAddNodeCheckQuorum tests that addNode does not trigger a leader election
  2263. // immediately when checkQuorum is set.
  2264. func TestAddNodeCheckQuorum(t *testing.T) {
  2265. r := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  2266. r.pendingConf = true
  2267. r.checkQuorum = true
  2268. r.becomeCandidate()
  2269. r.becomeLeader()
  2270. for i := 0; i < r.electionTimeout-1; i++ {
  2271. r.tick()
  2272. }
  2273. r.addNode(2)
  2274. // This tick will reach electionTimeout, which triggers a quorum check.
  2275. r.tick()
  2276. // Node 1 should still be the leader after a single tick.
  2277. if r.state != StateLeader {
  2278. t.Errorf("state = %v, want %v", r.state, StateLeader)
  2279. }
  2280. // After another electionTimeout ticks without hearing from node 2,
  2281. // node 1 should step down.
  2282. for i := 0; i < r.electionTimeout; i++ {
  2283. r.tick()
  2284. }
  2285. if r.state != StateFollower {
  2286. t.Errorf("state = %v, want %v", r.state, StateFollower)
  2287. }
  2288. }
  2289. // TestRemoveNode tests that removeNode could update pendingConf, nodes and
  2290. // and removed list correctly.
  2291. func TestRemoveNode(t *testing.T) {
  2292. r := newTestRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage())
  2293. r.pendingConf = true
  2294. r.removeNode(2)
  2295. if r.pendingConf {
  2296. t.Errorf("pendingConf = %v, want false", r.pendingConf)
  2297. }
  2298. w := []uint64{1}
  2299. if g := r.nodes(); !reflect.DeepEqual(g, w) {
  2300. t.Errorf("nodes = %v, want %v", g, w)
  2301. }
  2302. // remove all nodes from cluster
  2303. r.removeNode(1)
  2304. w = []uint64{}
  2305. if g := r.nodes(); !reflect.DeepEqual(g, w) {
  2306. t.Errorf("nodes = %v, want %v", g, w)
  2307. }
  2308. }
  2309. func TestPromotable(t *testing.T) {
  2310. id := uint64(1)
  2311. tests := []struct {
  2312. peers []uint64
  2313. wp bool
  2314. }{
  2315. {[]uint64{1}, true},
  2316. {[]uint64{1, 2, 3}, true},
  2317. {[]uint64{}, false},
  2318. {[]uint64{2, 3}, false},
  2319. }
  2320. for i, tt := range tests {
  2321. r := newTestRaft(id, tt.peers, 5, 1, NewMemoryStorage())
  2322. if g := r.promotable(); g != tt.wp {
  2323. t.Errorf("#%d: promotable = %v, want %v", i, g, tt.wp)
  2324. }
  2325. }
  2326. }
  2327. func TestRaftNodes(t *testing.T) {
  2328. tests := []struct {
  2329. ids []uint64
  2330. wids []uint64
  2331. }{
  2332. {
  2333. []uint64{1, 2, 3},
  2334. []uint64{1, 2, 3},
  2335. },
  2336. {
  2337. []uint64{3, 2, 1},
  2338. []uint64{1, 2, 3},
  2339. },
  2340. }
  2341. for i, tt := range tests {
  2342. r := newTestRaft(1, tt.ids, 10, 1, NewMemoryStorage())
  2343. if !reflect.DeepEqual(r.nodes(), tt.wids) {
  2344. t.Errorf("#%d: nodes = %+v, want %+v", i, r.nodes(), tt.wids)
  2345. }
  2346. }
  2347. }
  2348. func TestCampaignWhileLeader(t *testing.T) {
  2349. testCampaignWhileLeader(t, false)
  2350. }
  2351. func TestPreCampaignWhileLeader(t *testing.T) {
  2352. testCampaignWhileLeader(t, true)
  2353. }
  2354. func testCampaignWhileLeader(t *testing.T, preVote bool) {
  2355. cfg := newTestConfig(1, []uint64{1}, 5, 1, NewMemoryStorage())
  2356. cfg.PreVote = preVote
  2357. r := newRaft(cfg)
  2358. if r.state != StateFollower {
  2359. t.Errorf("expected new node to be follower but got %s", r.state)
  2360. }
  2361. // We don't call campaign() directly because it comes after the check
  2362. // for our current state.
  2363. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2364. if r.state != StateLeader {
  2365. t.Errorf("expected single-node election to become leader but got %s", r.state)
  2366. }
  2367. term := r.Term
  2368. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2369. if r.state != StateLeader {
  2370. t.Errorf("expected to remain leader but got %s", r.state)
  2371. }
  2372. if r.Term != term {
  2373. t.Errorf("expected to remain in term %v but got %v", term, r.Term)
  2374. }
  2375. }
  2376. // TestCommitAfterRemoveNode verifies that pending commands can become
  2377. // committed when a config change reduces the quorum requirements.
  2378. func TestCommitAfterRemoveNode(t *testing.T) {
  2379. // Create a cluster with two nodes.
  2380. s := NewMemoryStorage()
  2381. r := newTestRaft(1, []uint64{1, 2}, 5, 1, s)
  2382. r.becomeCandidate()
  2383. r.becomeLeader()
  2384. // Begin to remove the second node.
  2385. cc := pb.ConfChange{
  2386. Type: pb.ConfChangeRemoveNode,
  2387. NodeID: 2,
  2388. }
  2389. ccData, err := cc.Marshal()
  2390. if err != nil {
  2391. t.Fatal(err)
  2392. }
  2393. r.Step(pb.Message{
  2394. Type: pb.MsgProp,
  2395. Entries: []pb.Entry{
  2396. {Type: pb.EntryConfChange, Data: ccData},
  2397. },
  2398. })
  2399. // Stabilize the log and make sure nothing is committed yet.
  2400. if ents := nextEnts(r, s); len(ents) > 0 {
  2401. t.Fatalf("unexpected committed entries: %v", ents)
  2402. }
  2403. ccIndex := r.raftLog.lastIndex()
  2404. // While the config change is pending, make another proposal.
  2405. r.Step(pb.Message{
  2406. Type: pb.MsgProp,
  2407. Entries: []pb.Entry{
  2408. {Type: pb.EntryNormal, Data: []byte("hello")},
  2409. },
  2410. })
  2411. // Node 2 acknowledges the config change, committing it.
  2412. r.Step(pb.Message{
  2413. Type: pb.MsgAppResp,
  2414. From: 2,
  2415. Index: ccIndex,
  2416. })
  2417. ents := nextEnts(r, s)
  2418. if len(ents) != 2 {
  2419. t.Fatalf("expected two committed entries, got %v", ents)
  2420. }
  2421. if ents[0].Type != pb.EntryNormal || ents[0].Data != nil {
  2422. t.Fatalf("expected ents[0] to be empty, but got %v", ents[0])
  2423. }
  2424. if ents[1].Type != pb.EntryConfChange {
  2425. t.Fatalf("expected ents[1] to be EntryConfChange, got %v", ents[1])
  2426. }
  2427. // Apply the config change. This reduces quorum requirements so the
  2428. // pending command can now commit.
  2429. r.removeNode(2)
  2430. ents = nextEnts(r, s)
  2431. if len(ents) != 1 || ents[0].Type != pb.EntryNormal ||
  2432. string(ents[0].Data) != "hello" {
  2433. t.Fatalf("expected one committed EntryNormal, got %v", ents)
  2434. }
  2435. }
  2436. // TestLeaderTransferToUpToDateNode verifies transferring should succeed
  2437. // if the transferee has the most up-to-date log entries when transfer starts.
  2438. func TestLeaderTransferToUpToDateNode(t *testing.T) {
  2439. nt := newNetwork(nil, nil, nil)
  2440. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2441. lead := nt.peers[1].(*raft)
  2442. if lead.lead != 1 {
  2443. t.Fatalf("after election leader is %x, want 1", lead.lead)
  2444. }
  2445. // Transfer leadership to 2.
  2446. nt.send(pb.Message{From: 2, To: 1, Type: pb.MsgTransferLeader})
  2447. checkLeaderTransferState(t, lead, StateFollower, 2)
  2448. // After some log replication, transfer leadership back to 1.
  2449. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2450. nt.send(pb.Message{From: 1, To: 2, Type: pb.MsgTransferLeader})
  2451. checkLeaderTransferState(t, lead, StateLeader, 1)
  2452. }
  2453. // TestLeaderTransferToUpToDateNodeFromFollower verifies transferring should succeed
  2454. // if the transferee has the most up-to-date log entries when transfer starts.
  2455. // Not like TestLeaderTransferToUpToDateNode, where the leader transfer message
  2456. // is sent to the leader, in this test case every leader transfer message is sent
  2457. // to the follower.
  2458. func TestLeaderTransferToUpToDateNodeFromFollower(t *testing.T) {
  2459. nt := newNetwork(nil, nil, nil)
  2460. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2461. lead := nt.peers[1].(*raft)
  2462. if lead.lead != 1 {
  2463. t.Fatalf("after election leader is %x, want 1", lead.lead)
  2464. }
  2465. // Transfer leadership to 2.
  2466. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgTransferLeader})
  2467. checkLeaderTransferState(t, lead, StateFollower, 2)
  2468. // After some log replication, transfer leadership back to 1.
  2469. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2470. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgTransferLeader})
  2471. checkLeaderTransferState(t, lead, StateLeader, 1)
  2472. }
  2473. // TestLeaderTransferWithCheckQuorum ensures transferring leader still works
  2474. // even the current leader is still under its leader lease
  2475. func TestLeaderTransferWithCheckQuorum(t *testing.T) {
  2476. nt := newNetwork(nil, nil, nil)
  2477. for i := 1; i < 4; i++ {
  2478. r := nt.peers[uint64(i)].(*raft)
  2479. r.checkQuorum = true
  2480. setRandomizedElectionTimeout(r, r.electionTimeout+i)
  2481. }
  2482. // Letting peer 2 electionElapsed reach to timeout so that it can vote for peer 1
  2483. f := nt.peers[2].(*raft)
  2484. for i := 0; i < f.electionTimeout; i++ {
  2485. f.tick()
  2486. }
  2487. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2488. lead := nt.peers[1].(*raft)
  2489. if lead.lead != 1 {
  2490. t.Fatalf("after election leader is %x, want 1", lead.lead)
  2491. }
  2492. // Transfer leadership to 2.
  2493. nt.send(pb.Message{From: 2, To: 1, Type: pb.MsgTransferLeader})
  2494. checkLeaderTransferState(t, lead, StateFollower, 2)
  2495. // After some log replication, transfer leadership back to 1.
  2496. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2497. nt.send(pb.Message{From: 1, To: 2, Type: pb.MsgTransferLeader})
  2498. checkLeaderTransferState(t, lead, StateLeader, 1)
  2499. }
  2500. func TestLeaderTransferToSlowFollower(t *testing.T) {
  2501. defaultLogger.EnableDebug()
  2502. nt := newNetwork(nil, nil, nil)
  2503. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2504. nt.isolate(3)
  2505. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2506. nt.recover()
  2507. lead := nt.peers[1].(*raft)
  2508. if lead.prs[3].Match != 1 {
  2509. t.Fatalf("node 1 has match %x for node 3, want %x", lead.prs[3].Match, 1)
  2510. }
  2511. // Transfer leadership to 3 when node 3 is lack of log.
  2512. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2513. checkLeaderTransferState(t, lead, StateFollower, 3)
  2514. }
  2515. func TestLeaderTransferAfterSnapshot(t *testing.T) {
  2516. nt := newNetwork(nil, nil, nil)
  2517. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2518. nt.isolate(3)
  2519. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2520. lead := nt.peers[1].(*raft)
  2521. nextEnts(lead, nt.storage[1])
  2522. nt.storage[1].CreateSnapshot(lead.raftLog.applied, &pb.ConfState{Nodes: lead.nodes()}, nil)
  2523. nt.storage[1].Compact(lead.raftLog.applied)
  2524. nt.recover()
  2525. if lead.prs[3].Match != 1 {
  2526. t.Fatalf("node 1 has match %x for node 3, want %x", lead.prs[3].Match, 1)
  2527. }
  2528. // Transfer leadership to 3 when node 3 is lack of snapshot.
  2529. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2530. // Send pb.MsgHeartbeatResp to leader to trigger a snapshot for node 3.
  2531. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgHeartbeatResp})
  2532. checkLeaderTransferState(t, lead, StateFollower, 3)
  2533. }
  2534. func TestLeaderTransferToSelf(t *testing.T) {
  2535. nt := newNetwork(nil, nil, nil)
  2536. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2537. lead := nt.peers[1].(*raft)
  2538. // Transfer leadership to self, there will be noop.
  2539. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgTransferLeader})
  2540. checkLeaderTransferState(t, lead, StateLeader, 1)
  2541. }
  2542. func TestLeaderTransferToNonExistingNode(t *testing.T) {
  2543. nt := newNetwork(nil, nil, nil)
  2544. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2545. lead := nt.peers[1].(*raft)
  2546. // Transfer leadership to non-existing node, there will be noop.
  2547. nt.send(pb.Message{From: 4, To: 1, Type: pb.MsgTransferLeader})
  2548. checkLeaderTransferState(t, lead, StateLeader, 1)
  2549. }
  2550. func TestLeaderTransferTimeout(t *testing.T) {
  2551. nt := newNetwork(nil, nil, nil)
  2552. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2553. nt.isolate(3)
  2554. lead := nt.peers[1].(*raft)
  2555. // Transfer leadership to isolated node, wait for timeout.
  2556. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2557. if lead.leadTransferee != 3 {
  2558. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2559. }
  2560. for i := 0; i < lead.heartbeatTimeout; i++ {
  2561. lead.tick()
  2562. }
  2563. if lead.leadTransferee != 3 {
  2564. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2565. }
  2566. for i := 0; i < lead.electionTimeout-lead.heartbeatTimeout; i++ {
  2567. lead.tick()
  2568. }
  2569. checkLeaderTransferState(t, lead, StateLeader, 1)
  2570. }
  2571. func TestLeaderTransferIgnoreProposal(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. // Transfer leadership to isolated node to let transfer pending, then send proposal.
  2577. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2578. if lead.leadTransferee != 3 {
  2579. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2580. }
  2581. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  2582. if lead.prs[1].Match != 1 {
  2583. t.Fatalf("node 1 has match %x, want %x", lead.prs[1].Match, 1)
  2584. }
  2585. }
  2586. func TestLeaderTransferReceiveHigherTermVote(t *testing.T) {
  2587. nt := newNetwork(nil, nil, nil)
  2588. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2589. nt.isolate(3)
  2590. lead := nt.peers[1].(*raft)
  2591. // Transfer leadership to isolated node to let transfer pending.
  2592. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2593. if lead.leadTransferee != 3 {
  2594. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2595. }
  2596. nt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup, Index: 1, Term: 2})
  2597. checkLeaderTransferState(t, lead, StateFollower, 2)
  2598. }
  2599. func TestLeaderTransferRemoveNode(t *testing.T) {
  2600. nt := newNetwork(nil, nil, nil)
  2601. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2602. nt.ignore(pb.MsgTimeoutNow)
  2603. lead := nt.peers[1].(*raft)
  2604. // The leadTransferee is removed when leadship transferring.
  2605. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2606. if lead.leadTransferee != 3 {
  2607. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2608. }
  2609. lead.removeNode(3)
  2610. checkLeaderTransferState(t, lead, StateLeader, 1)
  2611. }
  2612. // TestLeaderTransferBack verifies leadership can transfer back to self when last transfer is pending.
  2613. func TestLeaderTransferBack(t *testing.T) {
  2614. nt := newNetwork(nil, nil, nil)
  2615. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2616. nt.isolate(3)
  2617. lead := nt.peers[1].(*raft)
  2618. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2619. if lead.leadTransferee != 3 {
  2620. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2621. }
  2622. // Transfer leadership back to self.
  2623. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgTransferLeader})
  2624. checkLeaderTransferState(t, lead, StateLeader, 1)
  2625. }
  2626. // TestLeaderTransferSecondTransferToAnotherNode verifies leader can transfer to another node
  2627. // when last transfer is pending.
  2628. func TestLeaderTransferSecondTransferToAnotherNode(t *testing.T) {
  2629. nt := newNetwork(nil, nil, nil)
  2630. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2631. nt.isolate(3)
  2632. lead := nt.peers[1].(*raft)
  2633. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2634. if lead.leadTransferee != 3 {
  2635. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2636. }
  2637. // Transfer leadership to another node.
  2638. nt.send(pb.Message{From: 2, To: 1, Type: pb.MsgTransferLeader})
  2639. checkLeaderTransferState(t, lead, StateFollower, 2)
  2640. }
  2641. // TestLeaderTransferSecondTransferToSameNode verifies second transfer leader request
  2642. // to the same node should not extend the timeout while the first one is pending.
  2643. func TestLeaderTransferSecondTransferToSameNode(t *testing.T) {
  2644. nt := newNetwork(nil, nil, nil)
  2645. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  2646. nt.isolate(3)
  2647. lead := nt.peers[1].(*raft)
  2648. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2649. if lead.leadTransferee != 3 {
  2650. t.Fatalf("wait transferring, leadTransferee = %v, want %v", lead.leadTransferee, 3)
  2651. }
  2652. for i := 0; i < lead.heartbeatTimeout; i++ {
  2653. lead.tick()
  2654. }
  2655. // Second transfer leadership request to the same node.
  2656. nt.send(pb.Message{From: 3, To: 1, Type: pb.MsgTransferLeader})
  2657. for i := 0; i < lead.electionTimeout-lead.heartbeatTimeout; i++ {
  2658. lead.tick()
  2659. }
  2660. checkLeaderTransferState(t, lead, StateLeader, 1)
  2661. }
  2662. func checkLeaderTransferState(t *testing.T, r *raft, state StateType, lead uint64) {
  2663. if r.state != state || r.lead != lead {
  2664. t.Fatalf("after transferring, node has state %v lead %v, want state %v lead %v", r.state, r.lead, state, lead)
  2665. }
  2666. if r.leadTransferee != None {
  2667. t.Fatalf("after transferring, node has leadTransferee %v, want leadTransferee %v", r.leadTransferee, None)
  2668. }
  2669. }
  2670. // TestTransferNonMember verifies that when a MsgTimeoutNow arrives at
  2671. // a node that has been removed from the group, nothing happens.
  2672. // (previously, if the node also got votes, it would panic as it
  2673. // transitioned to StateLeader)
  2674. func TestTransferNonMember(t *testing.T) {
  2675. r := newTestRaft(1, []uint64{2, 3, 4}, 5, 1, NewMemoryStorage())
  2676. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgTimeoutNow})
  2677. r.Step(pb.Message{From: 2, To: 1, Type: pb.MsgVoteResp})
  2678. r.Step(pb.Message{From: 3, To: 1, Type: pb.MsgVoteResp})
  2679. if r.state != StateFollower {
  2680. t.Fatalf("state is %s, want StateFollower", r.state)
  2681. }
  2682. }
  2683. func entsWithConfig(configFunc func(*Config), terms ...uint64) *raft {
  2684. storage := NewMemoryStorage()
  2685. for i, term := range terms {
  2686. storage.Append([]pb.Entry{{Index: uint64(i + 1), Term: term}})
  2687. }
  2688. cfg := newTestConfig(1, []uint64{}, 5, 1, storage)
  2689. if configFunc != nil {
  2690. configFunc(cfg)
  2691. }
  2692. sm := newRaft(cfg)
  2693. sm.reset(terms[len(terms)-1])
  2694. return sm
  2695. }
  2696. // votedWithConfig creates a raft state machine with Vote and Term set
  2697. // to the given value but no log entries (indicating that it voted in
  2698. // the given term but has not received any logs).
  2699. func votedWithConfig(configFunc func(*Config), vote, term uint64) *raft {
  2700. storage := NewMemoryStorage()
  2701. storage.SetHardState(pb.HardState{Vote: vote, Term: term})
  2702. cfg := newTestConfig(1, []uint64{}, 5, 1, storage)
  2703. if configFunc != nil {
  2704. configFunc(cfg)
  2705. }
  2706. sm := newRaft(cfg)
  2707. sm.reset(term)
  2708. return sm
  2709. }
  2710. type network struct {
  2711. peers map[uint64]stateMachine
  2712. storage map[uint64]*MemoryStorage
  2713. dropm map[connem]float64
  2714. ignorem map[pb.MessageType]bool
  2715. }
  2716. // newNetwork initializes a network from peers.
  2717. // A nil node will be replaced with a new *stateMachine.
  2718. // A *stateMachine will get its k, id.
  2719. // When using stateMachine, the address list is always [1, n].
  2720. func newNetwork(peers ...stateMachine) *network {
  2721. return newNetworkWithConfig(nil, peers...)
  2722. }
  2723. // newNetworkWithConfig is like newNetwork but calls the given func to
  2724. // modify the configuration of any state machines it creates.
  2725. func newNetworkWithConfig(configFunc func(*Config), peers ...stateMachine) *network {
  2726. size := len(peers)
  2727. peerAddrs := idsBySize(size)
  2728. npeers := make(map[uint64]stateMachine, size)
  2729. nstorage := make(map[uint64]*MemoryStorage, size)
  2730. for j, p := range peers {
  2731. id := peerAddrs[j]
  2732. switch v := p.(type) {
  2733. case nil:
  2734. nstorage[id] = NewMemoryStorage()
  2735. cfg := newTestConfig(id, peerAddrs, 10, 1, nstorage[id])
  2736. if configFunc != nil {
  2737. configFunc(cfg)
  2738. }
  2739. sm := newRaft(cfg)
  2740. npeers[id] = sm
  2741. case *raft:
  2742. v.id = id
  2743. v.prs = make(map[uint64]*Progress)
  2744. for i := 0; i < size; i++ {
  2745. v.prs[peerAddrs[i]] = &Progress{}
  2746. }
  2747. v.reset(v.Term)
  2748. npeers[id] = v
  2749. case *blackHole:
  2750. npeers[id] = v
  2751. default:
  2752. panic(fmt.Sprintf("unexpected state machine type: %T", p))
  2753. }
  2754. }
  2755. return &network{
  2756. peers: npeers,
  2757. storage: nstorage,
  2758. dropm: make(map[connem]float64),
  2759. ignorem: make(map[pb.MessageType]bool),
  2760. }
  2761. }
  2762. func preVoteConfig(c *Config) {
  2763. c.PreVote = true
  2764. }
  2765. func (nw *network) send(msgs ...pb.Message) {
  2766. for len(msgs) > 0 {
  2767. m := msgs[0]
  2768. p := nw.peers[m.To]
  2769. p.Step(m)
  2770. msgs = append(msgs[1:], nw.filter(p.readMessages())...)
  2771. }
  2772. }
  2773. func (nw *network) drop(from, to uint64, perc float64) {
  2774. nw.dropm[connem{from, to}] = perc
  2775. }
  2776. func (nw *network) cut(one, other uint64) {
  2777. nw.drop(one, other, 1)
  2778. nw.drop(other, one, 1)
  2779. }
  2780. func (nw *network) isolate(id uint64) {
  2781. for i := 0; i < len(nw.peers); i++ {
  2782. nid := uint64(i) + 1
  2783. if nid != id {
  2784. nw.drop(id, nid, 1.0)
  2785. nw.drop(nid, id, 1.0)
  2786. }
  2787. }
  2788. }
  2789. func (nw *network) ignore(t pb.MessageType) {
  2790. nw.ignorem[t] = true
  2791. }
  2792. func (nw *network) recover() {
  2793. nw.dropm = make(map[connem]float64)
  2794. nw.ignorem = make(map[pb.MessageType]bool)
  2795. }
  2796. func (nw *network) filter(msgs []pb.Message) []pb.Message {
  2797. mm := []pb.Message{}
  2798. for _, m := range msgs {
  2799. if nw.ignorem[m.Type] {
  2800. continue
  2801. }
  2802. switch m.Type {
  2803. case pb.MsgHup:
  2804. // hups never go over the network, so don't drop them but panic
  2805. panic("unexpected msgHup")
  2806. default:
  2807. perc := nw.dropm[connem{m.From, m.To}]
  2808. if n := rand.Float64(); n < perc {
  2809. continue
  2810. }
  2811. }
  2812. mm = append(mm, m)
  2813. }
  2814. return mm
  2815. }
  2816. type connem struct {
  2817. from, to uint64
  2818. }
  2819. type blackHole struct{}
  2820. func (blackHole) Step(pb.Message) error { return nil }
  2821. func (blackHole) readMessages() []pb.Message { return nil }
  2822. var nopStepper = &blackHole{}
  2823. func idsBySize(size int) []uint64 {
  2824. ids := make([]uint64, size)
  2825. for i := 0; i < size; i++ {
  2826. ids[i] = 1 + uint64(i)
  2827. }
  2828. return ids
  2829. }
  2830. // setRandomizedElectionTimeout set up the value by caller instead of choosing
  2831. // by system, in some test scenario we need to fill in some expected value to
  2832. // ensure the certainty
  2833. func setRandomizedElectionTimeout(r *raft, v int) {
  2834. r.randomizedElectionTimeout = v
  2835. }
  2836. func newTestConfig(id uint64, peers []uint64, election, heartbeat int, storage Storage) *Config {
  2837. return &Config{
  2838. ID: id,
  2839. peers: peers,
  2840. ElectionTick: election,
  2841. HeartbeatTick: heartbeat,
  2842. Storage: storage,
  2843. MaxSizePerMsg: noLimit,
  2844. MaxInflightMsgs: 256,
  2845. }
  2846. }
  2847. func newTestRaft(id uint64, peers []uint64, election, heartbeat int, storage Storage) *raft {
  2848. return newRaft(newTestConfig(id, peers, election, heartbeat, storage))
  2849. }