raft_test.go 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770
  1. // Copyright 2015 CoreOS, Inc.
  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 Interface 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 TestProgressUpdate(t *testing.T) {
  43. prevM, prevN := uint64(3), uint64(5)
  44. tests := []struct {
  45. update uint64
  46. wm uint64
  47. wn uint64
  48. }{
  49. {prevM - 1, prevM, prevN}, // do not decrease match, next
  50. {prevM, prevM, prevN}, // do not decrease next
  51. {prevM + 1, prevM + 1, prevN}, // increase match, do not decrease next
  52. {prevM + 2, prevM + 2, prevN + 1}, // increase match, next
  53. }
  54. for i, tt := range tests {
  55. p := &Progress{
  56. Match: prevM,
  57. Next: prevN,
  58. }
  59. p.update(tt.update)
  60. if p.Match != tt.wm {
  61. t.Errorf("#%d: match= %d, want %d", i, p.Match, tt.wm)
  62. }
  63. if p.Next != tt.wn {
  64. t.Errorf("#%d: next= %d, want %d", i, p.Next, tt.wn)
  65. }
  66. }
  67. }
  68. func TestProgressMaybeDecr(t *testing.T) {
  69. tests := []struct {
  70. m uint64
  71. n uint64
  72. rejected uint64
  73. last uint64
  74. w bool
  75. wn uint64
  76. }{
  77. {
  78. // match != 0 is always false
  79. 1, 0, 0, 0, false, 0,
  80. },
  81. {
  82. // match != 0 and to is greater than match
  83. // directly decrease to match+1
  84. 5, 10, 5, 5, false, 10,
  85. },
  86. {
  87. // match != 0 and to is greater than match
  88. // directly decrease to match+1
  89. 5, 10, 4, 4, false, 10,
  90. },
  91. {
  92. // match != 0 and to is not greater than match
  93. 5, 10, 9, 9, true, 6,
  94. },
  95. {
  96. // next-1 != rejected is always false
  97. 0, 0, 0, 0, false, 0,
  98. },
  99. {
  100. // next-1 != rejected is always false
  101. 0, 10, 5, 5, false, 10,
  102. },
  103. {
  104. // next>1 = decremented by 1
  105. 0, 10, 9, 9, true, 9,
  106. },
  107. {
  108. // next>1 = decremented by 1
  109. 0, 2, 1, 1, true, 1,
  110. },
  111. {
  112. // next<=1 = reset to 1
  113. 0, 1, 0, 0, true, 1,
  114. },
  115. {
  116. // decrease to min(rejected, last+1)
  117. 0, 10, 9, 2, true, 3,
  118. },
  119. {
  120. // rejected < 1, reset to 1
  121. 0, 10, 9, 0, true, 1,
  122. },
  123. }
  124. for i, tt := range tests {
  125. p := &Progress{
  126. Match: tt.m,
  127. Next: tt.n,
  128. }
  129. if g := p.maybeDecrTo(tt.rejected, tt.last); g != tt.w {
  130. t.Errorf("#%d: maybeDecrTo= %t, want %t", i, g, tt.w)
  131. }
  132. if gm := p.Match; gm != tt.m {
  133. t.Errorf("#%d: match= %d, want %d", i, gm, tt.m)
  134. }
  135. if gn := p.Next; gn != tt.wn {
  136. t.Errorf("#%d: next= %d, want %d", i, gn, tt.wn)
  137. }
  138. }
  139. }
  140. func TestProgressShouldWait(t *testing.T) {
  141. tests := []struct {
  142. m uint64
  143. wait int
  144. w bool
  145. }{
  146. // match != 0 is always not wait
  147. {1, 0, false},
  148. {1, 1, false},
  149. {0, 1, true},
  150. {0, 0, false},
  151. }
  152. for i, tt := range tests {
  153. p := &Progress{
  154. Match: tt.m,
  155. Wait: tt.wait,
  156. }
  157. if g := p.shouldWait(); g != tt.w {
  158. t.Errorf("#%d: shouldwait = %t, want %t", i, g, tt.w)
  159. }
  160. }
  161. }
  162. // TestProgressWaitReset ensures that progress.Update and progress.DercTo
  163. // will reset progress.wait.
  164. func TestProgressWaitReset(t *testing.T) {
  165. p := &Progress{
  166. Wait: 1,
  167. }
  168. p.maybeDecrTo(1, 1)
  169. if p.Wait != 0 {
  170. t.Errorf("wait= %d, want 0", p.Wait)
  171. }
  172. p.Wait = 1
  173. p.update(2)
  174. if p.Wait != 0 {
  175. t.Errorf("wait= %d, want 0", p.Wait)
  176. }
  177. }
  178. // TestProgressDecr ensures raft.heartbeat decreases progress.wait by heartbeat.
  179. func TestProgressDecr(t *testing.T) {
  180. r := newRaft(1, []uint64{1, 2}, 5, 1, NewMemoryStorage(), 0)
  181. r.becomeCandidate()
  182. r.becomeLeader()
  183. r.prs[2].Wait = r.heartbeatTimeout * 2
  184. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  185. if r.prs[2].Wait != r.heartbeatTimeout*(2-1) {
  186. t.Errorf("wait = %d, want %d", r.prs[2].Wait, r.heartbeatTimeout*(2-1))
  187. }
  188. }
  189. func TestProgressWait(t *testing.T) {
  190. r := newRaft(1, []uint64{1, 2}, 5, 1, NewMemoryStorage(), 0)
  191. r.becomeCandidate()
  192. r.becomeLeader()
  193. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  194. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  195. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  196. ms := r.readMessages()
  197. if len(ms) != 1 {
  198. t.Errorf("len(ms) = %d, want 1", len(ms))
  199. }
  200. }
  201. func TestLeaderElection(t *testing.T) {
  202. tests := []struct {
  203. *network
  204. state StateType
  205. }{
  206. {newNetwork(nil, nil, nil), StateLeader},
  207. {newNetwork(nil, nil, nopStepper), StateLeader},
  208. {newNetwork(nil, nopStepper, nopStepper), StateCandidate},
  209. {newNetwork(nil, nopStepper, nopStepper, nil), StateCandidate},
  210. {newNetwork(nil, nopStepper, nopStepper, nil, nil), StateLeader},
  211. // three logs further along than 0
  212. {newNetwork(nil, ents(1), ents(2), ents(1, 3), nil), StateFollower},
  213. // logs converge
  214. {newNetwork(ents(1), nil, ents(2), ents(1), nil), StateLeader},
  215. }
  216. for i, tt := range tests {
  217. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  218. sm := tt.network.peers[1].(*raft)
  219. if sm.state != tt.state {
  220. t.Errorf("#%d: state = %s, want %s", i, sm.state, tt.state)
  221. }
  222. if g := sm.Term; g != 1 {
  223. t.Errorf("#%d: term = %d, want %d", i, g, 1)
  224. }
  225. }
  226. }
  227. func TestLogReplication(t *testing.T) {
  228. tests := []struct {
  229. *network
  230. msgs []pb.Message
  231. wcommitted uint64
  232. }{
  233. {
  234. newNetwork(nil, nil, nil),
  235. []pb.Message{
  236. {From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}},
  237. },
  238. 2,
  239. },
  240. {
  241. newNetwork(nil, nil, nil),
  242. []pb.Message{
  243. {From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}},
  244. {From: 1, To: 2, Type: pb.MsgHup},
  245. {From: 1, To: 2, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}},
  246. },
  247. 4,
  248. },
  249. }
  250. for i, tt := range tests {
  251. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  252. for _, m := range tt.msgs {
  253. tt.send(m)
  254. }
  255. for j, x := range tt.network.peers {
  256. sm := x.(*raft)
  257. if sm.raftLog.committed != tt.wcommitted {
  258. t.Errorf("#%d.%d: committed = %d, want %d", i, j, sm.raftLog.committed, tt.wcommitted)
  259. }
  260. ents := []pb.Entry{}
  261. for _, e := range nextEnts(sm, tt.network.storage[j]) {
  262. if e.Data != nil {
  263. ents = append(ents, e)
  264. }
  265. }
  266. props := []pb.Message{}
  267. for _, m := range tt.msgs {
  268. if m.Type == pb.MsgProp {
  269. props = append(props, m)
  270. }
  271. }
  272. for k, m := range props {
  273. if !bytes.Equal(ents[k].Data, m.Entries[0].Data) {
  274. t.Errorf("#%d.%d: data = %d, want %d", i, j, ents[k].Data, m.Entries[0].Data)
  275. }
  276. }
  277. }
  278. }
  279. }
  280. func TestSingleNodeCommit(t *testing.T) {
  281. tt := newNetwork(nil)
  282. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  283. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  284. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  285. sm := tt.peers[1].(*raft)
  286. if sm.raftLog.committed != 3 {
  287. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 3)
  288. }
  289. }
  290. // TestCannotCommitWithoutNewTermEntry tests the entries cannot be committed
  291. // when leader changes, no new proposal comes in and ChangeTerm proposal is
  292. // filtered.
  293. func TestCannotCommitWithoutNewTermEntry(t *testing.T) {
  294. tt := newNetwork(nil, nil, nil, nil, nil)
  295. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  296. // 0 cannot reach 2,3,4
  297. tt.cut(1, 3)
  298. tt.cut(1, 4)
  299. tt.cut(1, 5)
  300. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  301. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  302. sm := tt.peers[1].(*raft)
  303. if sm.raftLog.committed != 1 {
  304. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 1)
  305. }
  306. // network recovery
  307. tt.recover()
  308. // avoid committing ChangeTerm proposal
  309. tt.ignore(pb.MsgApp)
  310. // elect 2 as the new leader with term 2
  311. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  312. // no log entries from previous term should be committed
  313. sm = tt.peers[2].(*raft)
  314. if sm.raftLog.committed != 1 {
  315. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 1)
  316. }
  317. tt.recover()
  318. // send heartbeat; reset wait
  319. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgBeat})
  320. // append an entry at current term
  321. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  322. // expect the committed to be advanced
  323. if sm.raftLog.committed != 5 {
  324. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 5)
  325. }
  326. }
  327. // TestCommitWithoutNewTermEntry tests the entries could be committed
  328. // when leader changes, no new proposal comes in.
  329. func TestCommitWithoutNewTermEntry(t *testing.T) {
  330. tt := newNetwork(nil, nil, nil, nil, nil)
  331. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  332. // 0 cannot reach 2,3,4
  333. tt.cut(1, 3)
  334. tt.cut(1, 4)
  335. tt.cut(1, 5)
  336. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  337. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("some data")}}})
  338. sm := tt.peers[1].(*raft)
  339. if sm.raftLog.committed != 1 {
  340. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 1)
  341. }
  342. // network recovery
  343. tt.recover()
  344. // elect 1 as the new leader with term 2
  345. // after append a ChangeTerm entry from the current term, all entries
  346. // should be committed
  347. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  348. if sm.raftLog.committed != 4 {
  349. t.Errorf("committed = %d, want %d", sm.raftLog.committed, 4)
  350. }
  351. }
  352. func TestDuelingCandidates(t *testing.T) {
  353. a := newRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage(), 0)
  354. b := newRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage(), 0)
  355. c := newRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage(), 0)
  356. nt := newNetwork(a, b, c)
  357. nt.cut(1, 3)
  358. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  359. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  360. nt.recover()
  361. nt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  362. wlog := &raftLog{
  363. storage: &MemoryStorage{ents: []pb.Entry{{}, pb.Entry{Data: nil, Term: 1, Index: 1}}},
  364. committed: 1,
  365. unstable: unstable{offset: 2},
  366. }
  367. tests := []struct {
  368. sm *raft
  369. state StateType
  370. term uint64
  371. raftLog *raftLog
  372. }{
  373. {a, StateFollower, 2, wlog},
  374. {b, StateFollower, 2, wlog},
  375. {c, StateFollower, 2, newLog(NewMemoryStorage())},
  376. }
  377. for i, tt := range tests {
  378. if g := tt.sm.state; g != tt.state {
  379. t.Errorf("#%d: state = %s, want %s", i, g, tt.state)
  380. }
  381. if g := tt.sm.Term; g != tt.term {
  382. t.Errorf("#%d: term = %d, want %d", i, g, tt.term)
  383. }
  384. base := ltoa(tt.raftLog)
  385. if sm, ok := nt.peers[1+uint64(i)].(*raft); ok {
  386. l := ltoa(sm.raftLog)
  387. if g := diffu(base, l); g != "" {
  388. t.Errorf("#%d: diff:\n%s", i, g)
  389. }
  390. } else {
  391. t.Logf("#%d: empty log", i)
  392. }
  393. }
  394. }
  395. func TestCandidateConcede(t *testing.T) {
  396. tt := newNetwork(nil, nil, nil)
  397. tt.isolate(1)
  398. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  399. tt.send(pb.Message{From: 3, To: 3, Type: pb.MsgHup})
  400. // heal the partition
  401. tt.recover()
  402. // send heartbeat; reset wait
  403. tt.send(pb.Message{From: 3, To: 3, Type: pb.MsgBeat})
  404. data := []byte("force follower")
  405. // send a proposal to 3 to flush out a MsgApp to 1
  406. tt.send(pb.Message{From: 3, To: 3, Type: pb.MsgProp, Entries: []pb.Entry{{Data: data}}})
  407. // send heartbeat; flush out commit
  408. tt.send(pb.Message{From: 3, To: 3, Type: pb.MsgBeat})
  409. a := tt.peers[1].(*raft)
  410. if g := a.state; g != StateFollower {
  411. t.Errorf("state = %s, want %s", g, StateFollower)
  412. }
  413. if g := a.Term; g != 1 {
  414. t.Errorf("term = %d, want %d", g, 1)
  415. }
  416. wantLog := ltoa(&raftLog{
  417. storage: &MemoryStorage{
  418. ents: []pb.Entry{{}, {Data: nil, Term: 1, Index: 1}, {Term: 1, Index: 2, Data: data}},
  419. },
  420. unstable: unstable{offset: 3},
  421. committed: 2,
  422. })
  423. for i, p := range tt.peers {
  424. if sm, ok := p.(*raft); ok {
  425. l := ltoa(sm.raftLog)
  426. if g := diffu(wantLog, l); g != "" {
  427. t.Errorf("#%d: diff:\n%s", i, g)
  428. }
  429. } else {
  430. t.Logf("#%d: empty log", i)
  431. }
  432. }
  433. }
  434. func TestSingleNodeCandidate(t *testing.T) {
  435. tt := newNetwork(nil)
  436. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  437. sm := tt.peers[1].(*raft)
  438. if sm.state != StateLeader {
  439. t.Errorf("state = %d, want %d", sm.state, StateLeader)
  440. }
  441. }
  442. func TestOldMessages(t *testing.T) {
  443. tt := newNetwork(nil, nil, nil)
  444. // make 0 leader @ term 3
  445. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  446. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgHup})
  447. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  448. // pretend we're an old leader trying to make progress; this entry is expected to be ignored.
  449. tt.send(pb.Message{From: 2, To: 1, Type: pb.MsgApp, Term: 2, Entries: []pb.Entry{{Index: 3, Term: 2}}})
  450. // commit a new entry
  451. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  452. ilog := &raftLog{
  453. storage: &MemoryStorage{
  454. ents: []pb.Entry{
  455. {}, {Data: nil, Term: 1, Index: 1},
  456. {Data: nil, Term: 2, Index: 2}, {Data: nil, Term: 3, Index: 3},
  457. {Data: []byte("somedata"), Term: 3, Index: 4},
  458. },
  459. },
  460. unstable: unstable{offset: 5},
  461. committed: 4,
  462. }
  463. base := ltoa(ilog)
  464. for i, p := range tt.peers {
  465. if sm, ok := p.(*raft); ok {
  466. l := ltoa(sm.raftLog)
  467. if g := diffu(base, l); g != "" {
  468. t.Errorf("#%d: diff:\n%s", i, g)
  469. }
  470. } else {
  471. t.Logf("#%d: empty log", i)
  472. }
  473. }
  474. }
  475. // TestOldMessagesReply - optimization - reply with new term.
  476. func TestProposal(t *testing.T) {
  477. tests := []struct {
  478. *network
  479. success bool
  480. }{
  481. {newNetwork(nil, nil, nil), true},
  482. {newNetwork(nil, nil, nopStepper), true},
  483. {newNetwork(nil, nopStepper, nopStepper), false},
  484. {newNetwork(nil, nopStepper, nopStepper, nil), false},
  485. {newNetwork(nil, nopStepper, nopStepper, nil, nil), true},
  486. }
  487. for j, tt := range tests {
  488. send := func(m pb.Message) {
  489. defer func() {
  490. // only recover is we expect it to panic so
  491. // panics we don't expect go up.
  492. if !tt.success {
  493. e := recover()
  494. if e != nil {
  495. t.Logf("#%d: err: %s", j, e)
  496. }
  497. }
  498. }()
  499. tt.send(m)
  500. }
  501. data := []byte("somedata")
  502. // promote 0 the leader
  503. send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  504. send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: data}}})
  505. wantLog := newLog(NewMemoryStorage())
  506. if tt.success {
  507. wantLog = &raftLog{
  508. storage: &MemoryStorage{
  509. ents: []pb.Entry{{}, {Data: nil, Term: 1, Index: 1}, {Term: 1, Index: 2, Data: data}},
  510. },
  511. unstable: unstable{offset: 3},
  512. committed: 2}
  513. }
  514. base := ltoa(wantLog)
  515. for i, p := range tt.peers {
  516. if sm, ok := p.(*raft); ok {
  517. l := ltoa(sm.raftLog)
  518. if g := diffu(base, l); g != "" {
  519. t.Errorf("#%d: diff:\n%s", i, g)
  520. }
  521. } else {
  522. t.Logf("#%d: empty log", i)
  523. }
  524. }
  525. sm := tt.network.peers[1].(*raft)
  526. if g := sm.Term; g != 1 {
  527. t.Errorf("#%d: term = %d, want %d", j, g, 1)
  528. }
  529. }
  530. }
  531. func TestProposalByProxy(t *testing.T) {
  532. data := []byte("somedata")
  533. tests := []*network{
  534. newNetwork(nil, nil, nil),
  535. newNetwork(nil, nil, nopStepper),
  536. }
  537. for j, tt := range tests {
  538. // promote 0 the leader
  539. tt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  540. // propose via follower
  541. tt.send(pb.Message{From: 2, To: 2, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  542. wantLog := &raftLog{
  543. storage: &MemoryStorage{
  544. ents: []pb.Entry{{}, {Data: nil, Term: 1, Index: 1}, {Term: 1, Data: data, Index: 2}},
  545. },
  546. unstable: unstable{offset: 3},
  547. committed: 2}
  548. base := ltoa(wantLog)
  549. for i, p := range tt.peers {
  550. if sm, ok := p.(*raft); ok {
  551. l := ltoa(sm.raftLog)
  552. if g := diffu(base, l); g != "" {
  553. t.Errorf("#%d: diff:\n%s", i, g)
  554. }
  555. } else {
  556. t.Logf("#%d: empty log", i)
  557. }
  558. }
  559. sm := tt.peers[1].(*raft)
  560. if g := sm.Term; g != 1 {
  561. t.Errorf("#%d: term = %d, want %d", j, g, 1)
  562. }
  563. }
  564. }
  565. func TestCommit(t *testing.T) {
  566. tests := []struct {
  567. matches []uint64
  568. logs []pb.Entry
  569. smTerm uint64
  570. w uint64
  571. }{
  572. // single
  573. {[]uint64{1}, []pb.Entry{{Index: 1, Term: 1}}, 1, 1},
  574. {[]uint64{1}, []pb.Entry{{Index: 1, Term: 1}}, 2, 0},
  575. {[]uint64{2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 2, 2},
  576. {[]uint64{1}, []pb.Entry{{Index: 1, Term: 2}}, 2, 1},
  577. // odd
  578. {[]uint64{2, 1, 1}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 1, 1},
  579. {[]uint64{2, 1, 1}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}}, 2, 0},
  580. {[]uint64{2, 1, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 2, 2},
  581. {[]uint64{2, 1, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}}, 2, 0},
  582. // even
  583. {[]uint64{2, 1, 1, 1}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 1, 1},
  584. {[]uint64{2, 1, 1, 1}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}}, 2, 0},
  585. {[]uint64{2, 1, 1, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 1, 1},
  586. {[]uint64{2, 1, 1, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}}, 2, 0},
  587. {[]uint64{2, 1, 2, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}}, 2, 2},
  588. {[]uint64{2, 1, 2, 2}, []pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 1}}, 2, 0},
  589. }
  590. for i, tt := range tests {
  591. storage := NewMemoryStorage()
  592. storage.Append(tt.logs)
  593. storage.hardState = pb.HardState{Term: tt.smTerm}
  594. sm := newRaft(1, []uint64{1}, 5, 1, storage, 0)
  595. for j := 0; j < len(tt.matches); j++ {
  596. sm.setProgress(uint64(j)+1, tt.matches[j], tt.matches[j]+1)
  597. }
  598. sm.maybeCommit()
  599. if g := sm.raftLog.committed; g != tt.w {
  600. t.Errorf("#%d: committed = %d, want %d", i, g, tt.w)
  601. }
  602. }
  603. }
  604. func TestIsElectionTimeout(t *testing.T) {
  605. tests := []struct {
  606. elapse int
  607. wprobability float64
  608. round bool
  609. }{
  610. {5, 0, false},
  611. {13, 0.3, true},
  612. {15, 0.5, true},
  613. {18, 0.8, true},
  614. {20, 1, false},
  615. }
  616. for i, tt := range tests {
  617. sm := newRaft(1, []uint64{1}, 10, 1, NewMemoryStorage(), 0)
  618. sm.elapsed = tt.elapse
  619. c := 0
  620. for j := 0; j < 10000; j++ {
  621. if sm.isElectionTimeout() {
  622. c++
  623. }
  624. }
  625. got := float64(c) / 10000.0
  626. if tt.round {
  627. got = math.Floor(got*10+0.5) / 10.0
  628. }
  629. if got != tt.wprobability {
  630. t.Errorf("#%d: possibility = %v, want %v", i, got, tt.wprobability)
  631. }
  632. }
  633. }
  634. // ensure that the Step function ignores the message from old term and does not pass it to the
  635. // acutal stepX function.
  636. func TestStepIgnoreOldTermMsg(t *testing.T) {
  637. called := false
  638. fakeStep := func(r *raft, m pb.Message) {
  639. called = true
  640. }
  641. sm := newRaft(1, []uint64{1}, 10, 1, NewMemoryStorage(), 0)
  642. sm.step = fakeStep
  643. sm.Term = 2
  644. sm.Step(pb.Message{Type: pb.MsgApp, Term: sm.Term - 1})
  645. if called == true {
  646. t.Errorf("stepFunc called = %v , want %v", called, false)
  647. }
  648. }
  649. // TestHandleMsgApp ensures:
  650. // 1. Reply false if log doesn’t contain an entry at prevLogIndex whose term matches prevLogTerm.
  651. // 2. If an existing entry conflicts with a new one (same index but different terms),
  652. // delete the existing entry and all that follow it; append any new entries not already in the log.
  653. // 3. If leaderCommit > commitIndex, set commitIndex = min(leaderCommit, index of last new entry).
  654. func TestHandleMsgApp(t *testing.T) {
  655. tests := []struct {
  656. m pb.Message
  657. wIndex uint64
  658. wCommit uint64
  659. wReject bool
  660. }{
  661. // Ensure 1
  662. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 3, Index: 2, Commit: 3}, 2, 0, true}, // previous log mismatch
  663. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 3, Index: 3, Commit: 3}, 2, 0, true}, // previous log non-exist
  664. // Ensure 2
  665. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 1, Index: 1, Commit: 1}, 2, 1, false},
  666. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 0, Index: 0, Commit: 1, Entries: []pb.Entry{{Index: 1, Term: 2}}}, 1, 1, false},
  667. {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},
  668. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 2, Index: 2, Commit: 4, Entries: []pb.Entry{{Index: 3, Term: 2}}}, 3, 3, false},
  669. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 1, Index: 1, Commit: 4, Entries: []pb.Entry{{Index: 2, Term: 2}}}, 2, 2, false},
  670. // Ensure 3
  671. {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
  672. {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
  673. {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
  674. {pb.Message{Type: pb.MsgApp, Term: 2, LogTerm: 2, Index: 2, Commit: 4}, 2, 2, false}, // commit up to log.last()
  675. }
  676. for i, tt := range tests {
  677. storage := NewMemoryStorage()
  678. storage.Append([]pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}})
  679. sm := newRaft(1, []uint64{1}, 10, 1, storage, 0)
  680. sm.becomeFollower(2, None)
  681. sm.handleAppendEntries(tt.m)
  682. if sm.raftLog.lastIndex() != tt.wIndex {
  683. t.Errorf("#%d: lastIndex = %d, want %d", i, sm.raftLog.lastIndex(), tt.wIndex)
  684. }
  685. if sm.raftLog.committed != tt.wCommit {
  686. t.Errorf("#%d: committed = %d, want %d", i, sm.raftLog.committed, tt.wCommit)
  687. }
  688. m := sm.readMessages()
  689. if len(m) != 1 {
  690. t.Fatalf("#%d: msg = nil, want 1", i)
  691. }
  692. if m[0].Reject != tt.wReject {
  693. t.Errorf("#%d: reject = %v, want %v", i, m[0].Reject, tt.wReject)
  694. }
  695. }
  696. }
  697. // TestHandleHeartbeat ensures that the follower commits to the commit in the message.
  698. func TestHandleHeartbeat(t *testing.T) {
  699. commit := uint64(2)
  700. tests := []struct {
  701. m pb.Message
  702. wCommit uint64
  703. }{
  704. {pb.Message{From: 2, To: 1, Type: pb.MsgApp, Term: 2, Commit: commit + 1}, commit + 1},
  705. {pb.Message{From: 2, To: 1, Type: pb.MsgApp, Term: 2, Commit: commit - 1}, commit}, // do not decrease commit
  706. }
  707. for i, tt := range tests {
  708. storage := NewMemoryStorage()
  709. storage.Append([]pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}, {Index: 3, Term: 3}})
  710. sm := newRaft(1, []uint64{1, 2}, 5, 1, storage, 0)
  711. sm.becomeFollower(2, 2)
  712. sm.raftLog.commitTo(commit)
  713. sm.handleHeartbeat(tt.m)
  714. if sm.raftLog.committed != tt.wCommit {
  715. t.Errorf("#%d: committed = %d, want %d", i, sm.raftLog.committed, tt.wCommit)
  716. }
  717. m := sm.readMessages()
  718. if len(m) != 1 {
  719. t.Fatalf("#%d: msg = nil, want 1", i)
  720. }
  721. if m[0].Type != pb.MsgHeartbeatResp {
  722. t.Errorf("#%d: type = %v, want MsgHeartbeatResp", i, m[0].Type)
  723. }
  724. }
  725. }
  726. // TestHandleHeartbeatResp ensures that we re-send log entries when we get a heartbeat response.
  727. func TestHandleHeartbeatResp(t *testing.T) {
  728. storage := NewMemoryStorage()
  729. storage.Append([]pb.Entry{{Index: 1, Term: 1}, {Index: 2, Term: 2}, {Index: 3, Term: 3}})
  730. sm := newRaft(1, []uint64{1, 2}, 5, 1, storage, 0)
  731. sm.becomeCandidate()
  732. sm.becomeLeader()
  733. sm.raftLog.commitTo(sm.raftLog.lastIndex())
  734. // A heartbeat response from a node that is behind; re-send MsgApp
  735. sm.Step(pb.Message{From: 2, Type: pb.MsgHeartbeatResp})
  736. msgs := sm.readMessages()
  737. if len(msgs) != 1 {
  738. t.Fatalf("len(msgs) = %d, want 1", len(msgs))
  739. }
  740. if msgs[0].Type != pb.MsgApp {
  741. t.Errorf("type = %v, want MsgApp", msgs[0].Type)
  742. }
  743. // A second heartbeat response with no AppResp does not re-send because we are in the wait state.
  744. sm.Step(pb.Message{From: 2, Type: pb.MsgHeartbeatResp})
  745. msgs = sm.readMessages()
  746. if len(msgs) != 0 {
  747. t.Fatalf("len(msgs) = %d, want 0", len(msgs))
  748. }
  749. // Send a heartbeat to reset the wait state; next heartbeat will re-send MsgApp.
  750. sm.bcastHeartbeat()
  751. sm.Step(pb.Message{From: 2, Type: pb.MsgHeartbeatResp})
  752. msgs = sm.readMessages()
  753. if len(msgs) != 2 {
  754. t.Fatalf("len(msgs) = %d, want 2", len(msgs))
  755. }
  756. if msgs[0].Type != pb.MsgHeartbeat {
  757. t.Errorf("type = %v, want MsgHeartbeat", msgs[0].Type)
  758. }
  759. if msgs[1].Type != pb.MsgApp {
  760. t.Errorf("type = %v, want MsgApp", msgs[1].Type)
  761. }
  762. // Once we have an MsgAppResp, heartbeats no longer send MsgApp.
  763. sm.Step(pb.Message{
  764. From: 2,
  765. Type: pb.MsgAppResp,
  766. Index: msgs[1].Index + uint64(len(msgs[1].Entries)),
  767. })
  768. // Consume the message sent in response to MsgAppResp
  769. sm.readMessages()
  770. sm.bcastHeartbeat() // reset wait state
  771. sm.Step(pb.Message{From: 2, Type: pb.MsgHeartbeatResp})
  772. msgs = sm.readMessages()
  773. if len(msgs) != 1 {
  774. t.Fatalf("len(msgs) = %d, want 1: %+v", len(msgs), msgs)
  775. }
  776. if msgs[0].Type != pb.MsgHeartbeat {
  777. t.Errorf("type = %v, want MsgHeartbeat", msgs[0].Type)
  778. }
  779. }
  780. // TestMsgAppRespWaitReset verifies the waitReset behavior of a leader
  781. // MsgAppResp.
  782. func TestMsgAppRespWaitReset(t *testing.T) {
  783. sm := newRaft(1, []uint64{1, 2, 3}, 5, 1, NewMemoryStorage(), 0)
  784. sm.becomeCandidate()
  785. sm.becomeLeader()
  786. // The new leader has just emitted a new Term 4 entry; consume those messages
  787. // from the outgoing queue.
  788. sm.bcastAppend()
  789. sm.readMessages()
  790. // Node 2 acks the first entry, making it committed.
  791. sm.Step(pb.Message{
  792. From: 2,
  793. Type: pb.MsgAppResp,
  794. Index: 1,
  795. })
  796. if sm.Commit != 1 {
  797. t.Fatalf("expected Commit to be 1, got %d", sm.Commit)
  798. }
  799. // Also consume the MsgApp messages that update Commit on the followers.
  800. sm.readMessages()
  801. // A new command is now proposed on node 1.
  802. sm.Step(pb.Message{
  803. From: 1,
  804. Type: pb.MsgProp,
  805. Entries: []pb.Entry{{}},
  806. })
  807. // The command is broadcast to all nodes not in the wait state.
  808. // Node 2 left the wait state due to its MsgAppResp, but node 3 is still waiting.
  809. msgs := sm.readMessages()
  810. if len(msgs) != 1 {
  811. t.Fatalf("expected 1 message, got %d: %+v", len(msgs), msgs)
  812. }
  813. if msgs[0].Type != pb.MsgApp || msgs[0].To != 2 {
  814. t.Errorf("expected MsgApp to node 2, got %s to %d", msgs[0].Type, msgs[0].To)
  815. }
  816. if len(msgs[0].Entries) != 1 || msgs[0].Entries[0].Index != 2 {
  817. t.Errorf("expected to send entry 2, but got %v", msgs[0].Entries)
  818. }
  819. // Now Node 3 acks the first entry. This releases the wait and entry 2 is sent.
  820. sm.Step(pb.Message{
  821. From: 3,
  822. Type: pb.MsgAppResp,
  823. Index: 1,
  824. })
  825. msgs = sm.readMessages()
  826. if len(msgs) != 1 {
  827. t.Fatalf("expected 1 message, got %d: %+v", len(msgs), msgs)
  828. }
  829. if msgs[0].Type != pb.MsgApp || msgs[0].To != 3 {
  830. t.Errorf("expected MsgApp to node 3, got %s to %d", msgs[0].Type, msgs[0].To)
  831. }
  832. if len(msgs[0].Entries) != 1 || msgs[0].Entries[0].Index != 2 {
  833. t.Errorf("expected to send entry 2, but got %v", msgs[0].Entries)
  834. }
  835. }
  836. func TestRecvMsgVote(t *testing.T) {
  837. tests := []struct {
  838. state StateType
  839. i, term uint64
  840. voteFor uint64
  841. wreject bool
  842. }{
  843. {StateFollower, 0, 0, None, true},
  844. {StateFollower, 0, 1, None, true},
  845. {StateFollower, 0, 2, None, true},
  846. {StateFollower, 0, 3, None, false},
  847. {StateFollower, 1, 0, None, true},
  848. {StateFollower, 1, 1, None, true},
  849. {StateFollower, 1, 2, None, true},
  850. {StateFollower, 1, 3, None, false},
  851. {StateFollower, 2, 0, None, true},
  852. {StateFollower, 2, 1, None, true},
  853. {StateFollower, 2, 2, None, false},
  854. {StateFollower, 2, 3, None, false},
  855. {StateFollower, 3, 0, None, true},
  856. {StateFollower, 3, 1, None, true},
  857. {StateFollower, 3, 2, None, false},
  858. {StateFollower, 3, 3, None, false},
  859. {StateFollower, 3, 2, 2, false},
  860. {StateFollower, 3, 2, 1, true},
  861. {StateLeader, 3, 3, 1, true},
  862. {StateCandidate, 3, 3, 1, true},
  863. }
  864. for i, tt := range tests {
  865. sm := newRaft(1, []uint64{1}, 10, 1, NewMemoryStorage(), 0)
  866. sm.state = tt.state
  867. switch tt.state {
  868. case StateFollower:
  869. sm.step = stepFollower
  870. case StateCandidate:
  871. sm.step = stepCandidate
  872. case StateLeader:
  873. sm.step = stepLeader
  874. }
  875. sm.HardState = pb.HardState{Vote: tt.voteFor}
  876. sm.raftLog = &raftLog{
  877. storage: &MemoryStorage{ents: []pb.Entry{{}, {Index: 1, Term: 2}, {Index: 2, Term: 2}}},
  878. unstable: unstable{offset: 3},
  879. }
  880. sm.Step(pb.Message{Type: pb.MsgVote, From: 2, Index: tt.i, LogTerm: tt.term})
  881. msgs := sm.readMessages()
  882. if g := len(msgs); g != 1 {
  883. t.Fatalf("#%d: len(msgs) = %d, want 1", i, g)
  884. continue
  885. }
  886. if g := msgs[0].Reject; g != tt.wreject {
  887. t.Errorf("#%d, m.Reject = %v, want %v", i, g, tt.wreject)
  888. }
  889. }
  890. }
  891. func TestStateTransition(t *testing.T) {
  892. tests := []struct {
  893. from StateType
  894. to StateType
  895. wallow bool
  896. wterm uint64
  897. wlead uint64
  898. }{
  899. {StateFollower, StateFollower, true, 1, None},
  900. {StateFollower, StateCandidate, true, 1, None},
  901. {StateFollower, StateLeader, false, 0, None},
  902. {StateCandidate, StateFollower, true, 0, None},
  903. {StateCandidate, StateCandidate, true, 1, None},
  904. {StateCandidate, StateLeader, true, 0, 1},
  905. {StateLeader, StateFollower, true, 1, None},
  906. {StateLeader, StateCandidate, false, 1, None},
  907. {StateLeader, StateLeader, true, 0, 1},
  908. }
  909. for i, tt := range tests {
  910. func() {
  911. defer func() {
  912. if r := recover(); r != nil {
  913. if tt.wallow == true {
  914. t.Errorf("%d: allow = %v, want %v", i, false, true)
  915. }
  916. }
  917. }()
  918. sm := newRaft(1, []uint64{1}, 10, 1, NewMemoryStorage(), 0)
  919. sm.state = tt.from
  920. switch tt.to {
  921. case StateFollower:
  922. sm.becomeFollower(tt.wterm, tt.wlead)
  923. case StateCandidate:
  924. sm.becomeCandidate()
  925. case StateLeader:
  926. sm.becomeLeader()
  927. }
  928. if sm.Term != tt.wterm {
  929. t.Errorf("%d: term = %d, want %d", i, sm.Term, tt.wterm)
  930. }
  931. if sm.lead != tt.wlead {
  932. t.Errorf("%d: lead = %d, want %d", i, sm.lead, tt.wlead)
  933. }
  934. }()
  935. }
  936. }
  937. func TestAllServerStepdown(t *testing.T) {
  938. tests := []struct {
  939. state StateType
  940. wstate StateType
  941. wterm uint64
  942. windex uint64
  943. }{
  944. {StateFollower, StateFollower, 3, 0},
  945. {StateCandidate, StateFollower, 3, 0},
  946. {StateLeader, StateFollower, 3, 1},
  947. }
  948. tmsgTypes := [...]pb.MessageType{pb.MsgVote, pb.MsgApp}
  949. tterm := uint64(3)
  950. for i, tt := range tests {
  951. sm := newRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage(), 0)
  952. switch tt.state {
  953. case StateFollower:
  954. sm.becomeFollower(1, None)
  955. case StateCandidate:
  956. sm.becomeCandidate()
  957. case StateLeader:
  958. sm.becomeCandidate()
  959. sm.becomeLeader()
  960. }
  961. for j, msgType := range tmsgTypes {
  962. sm.Step(pb.Message{From: 2, Type: msgType, Term: tterm, LogTerm: tterm})
  963. if sm.state != tt.wstate {
  964. t.Errorf("#%d.%d state = %v , want %v", i, j, sm.state, tt.wstate)
  965. }
  966. if sm.Term != tt.wterm {
  967. t.Errorf("#%d.%d term = %v , want %v", i, j, sm.Term, tt.wterm)
  968. }
  969. if uint64(sm.raftLog.lastIndex()) != tt.windex {
  970. t.Errorf("#%d.%d index = %v , want %v", i, j, sm.raftLog.lastIndex(), tt.windex)
  971. }
  972. if uint64(len(sm.raftLog.allEntries())) != tt.windex {
  973. t.Errorf("#%d.%d len(ents) = %v , want %v", i, j, len(sm.raftLog.allEntries()), tt.windex)
  974. }
  975. wlead := uint64(2)
  976. if msgType == pb.MsgVote {
  977. wlead = None
  978. }
  979. if sm.lead != wlead {
  980. t.Errorf("#%d, sm.lead = %d, want %d", i, sm.lead, None)
  981. }
  982. }
  983. }
  984. }
  985. func TestLeaderAppResp(t *testing.T) {
  986. // initial progress: match = 0; next = 3
  987. tests := []struct {
  988. index uint64
  989. reject bool
  990. // progress
  991. wmatch uint64
  992. wnext uint64
  993. // message
  994. wmsgNum int
  995. windex uint64
  996. wcommitted uint64
  997. }{
  998. {3, true, 0, 3, 0, 0, 0}, // stale resp; no replies
  999. {2, true, 0, 2, 1, 1, 0}, // denied resp; leader does not commit; decrease next and send probing msg
  1000. {2, false, 2, 4, 2, 2, 2}, // accept resp; leader commits; broadcast with commit index
  1001. {0, false, 0, 3, 0, 0, 0}, // ignore heartbeat replies
  1002. }
  1003. for i, tt := range tests {
  1004. // sm term is 1 after it becomes the leader.
  1005. // thus the last log term must be 1 to be committed.
  1006. sm := newRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage(), 0)
  1007. sm.raftLog = &raftLog{
  1008. storage: &MemoryStorage{ents: []pb.Entry{{}, {Index: 1, Term: 0}, {Index: 2, Term: 1}}},
  1009. unstable: unstable{offset: 3},
  1010. }
  1011. sm.becomeCandidate()
  1012. sm.becomeLeader()
  1013. sm.readMessages()
  1014. sm.Step(pb.Message{From: 2, Type: pb.MsgAppResp, Index: tt.index, Term: sm.Term, Reject: tt.reject, RejectHint: tt.index})
  1015. p := sm.prs[2]
  1016. if p.Match != tt.wmatch {
  1017. t.Errorf("#%d match = %d, want %d", i, p.Match, tt.wmatch)
  1018. }
  1019. if p.Next != tt.wnext {
  1020. t.Errorf("#%d next = %d, want %d", i, p.Next, tt.wnext)
  1021. }
  1022. msgs := sm.readMessages()
  1023. if len(msgs) != tt.wmsgNum {
  1024. t.Errorf("#%d msgNum = %d, want %d", i, len(msgs), tt.wmsgNum)
  1025. }
  1026. for j, msg := range msgs {
  1027. if msg.Index != tt.windex {
  1028. t.Errorf("#%d.%d index = %d, want %d", i, j, msg.Index, tt.windex)
  1029. }
  1030. if msg.Commit != tt.wcommitted {
  1031. t.Errorf("#%d.%d commit = %d, want %d", i, j, msg.Commit, tt.wcommitted)
  1032. }
  1033. }
  1034. }
  1035. }
  1036. // When the leader receives a heartbeat tick, it should
  1037. // send a MsgApp with m.Index = 0, m.LogTerm=0 and empty entries.
  1038. func TestBcastBeat(t *testing.T) {
  1039. offset := uint64(1000)
  1040. // make a state machine with log.offset = 1000
  1041. s := pb.Snapshot{
  1042. Metadata: pb.SnapshotMetadata{
  1043. Index: offset,
  1044. Term: 1,
  1045. ConfState: pb.ConfState{Nodes: []uint64{1, 2, 3}},
  1046. },
  1047. }
  1048. storage := NewMemoryStorage()
  1049. storage.ApplySnapshot(s)
  1050. sm := newRaft(1, nil, 10, 1, storage, 0)
  1051. sm.Term = 1
  1052. sm.becomeCandidate()
  1053. sm.becomeLeader()
  1054. for i := 0; i < 10; i++ {
  1055. sm.appendEntry(pb.Entry{Index: uint64(i) + 1})
  1056. }
  1057. // slow follower
  1058. sm.prs[2].Match, sm.prs[2].Next = 5, 6
  1059. // normal follower
  1060. sm.prs[3].Match, sm.prs[3].Next = sm.raftLog.lastIndex(), sm.raftLog.lastIndex()+1
  1061. sm.Step(pb.Message{Type: pb.MsgBeat})
  1062. msgs := sm.readMessages()
  1063. if len(msgs) != 2 {
  1064. t.Fatalf("len(msgs) = %v, want 2", len(msgs))
  1065. }
  1066. wantCommitMap := map[uint64]uint64{
  1067. 2: min(sm.raftLog.committed, sm.prs[2].Match),
  1068. 3: min(sm.raftLog.committed, sm.prs[3].Match),
  1069. }
  1070. for i, m := range msgs {
  1071. if m.Type != pb.MsgHeartbeat {
  1072. t.Fatalf("#%d: type = %v, want = %v", i, m.Type, pb.MsgHeartbeat)
  1073. }
  1074. if m.Index != 0 {
  1075. t.Fatalf("#%d: prevIndex = %d, want %d", i, m.Index, 0)
  1076. }
  1077. if m.LogTerm != 0 {
  1078. t.Fatalf("#%d: prevTerm = %d, want %d", i, m.LogTerm, 0)
  1079. }
  1080. if wantCommitMap[m.To] == 0 {
  1081. t.Fatalf("#%d: unexpected to %d", i, m.To)
  1082. } else {
  1083. if m.Commit != wantCommitMap[m.To] {
  1084. t.Fatalf("#%d: commit = %d, want %d", i, m.Commit, wantCommitMap[m.To])
  1085. }
  1086. delete(wantCommitMap, m.To)
  1087. }
  1088. if len(m.Entries) != 0 {
  1089. t.Fatalf("#%d: len(entries) = %d, want 0", i, len(m.Entries))
  1090. }
  1091. }
  1092. }
  1093. // tests the output of the statemachine when receiving MsgBeat
  1094. func TestRecvMsgBeat(t *testing.T) {
  1095. tests := []struct {
  1096. state StateType
  1097. wMsg int
  1098. }{
  1099. {StateLeader, 2},
  1100. // candidate and follower should ignore MsgBeat
  1101. {StateCandidate, 0},
  1102. {StateFollower, 0},
  1103. }
  1104. for i, tt := range tests {
  1105. sm := newRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage(), 0)
  1106. sm.raftLog = &raftLog{storage: &MemoryStorage{ents: []pb.Entry{{}, {Index: 1, Term: 0}, {Index: 2, Term: 1}}}}
  1107. sm.Term = 1
  1108. sm.state = tt.state
  1109. switch tt.state {
  1110. case StateFollower:
  1111. sm.step = stepFollower
  1112. case StateCandidate:
  1113. sm.step = stepCandidate
  1114. case StateLeader:
  1115. sm.step = stepLeader
  1116. }
  1117. sm.Step(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  1118. msgs := sm.readMessages()
  1119. if len(msgs) != tt.wMsg {
  1120. t.Errorf("%d: len(msgs) = %d, want %d", i, len(msgs), tt.wMsg)
  1121. }
  1122. for _, m := range msgs {
  1123. if m.Type != pb.MsgHeartbeat {
  1124. t.Errorf("%d: msg.type = %v, want %v", i, m.Type, pb.MsgHeartbeat)
  1125. }
  1126. }
  1127. }
  1128. }
  1129. func TestLeaderIncreaseNext(t *testing.T) {
  1130. previousEnts := []pb.Entry{{Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3}}
  1131. tests := []struct {
  1132. // progress
  1133. match uint64
  1134. next uint64
  1135. wnext uint64
  1136. }{
  1137. // match is not zero, optimistically increase next
  1138. // previous entries + noop entry + propose + 1
  1139. {1, 2, uint64(len(previousEnts) + 1 + 1 + 1)},
  1140. // match is zero, not optimistically increase next
  1141. {0, 2, 2},
  1142. }
  1143. for i, tt := range tests {
  1144. sm := newRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage(), 0)
  1145. sm.raftLog.append(previousEnts...)
  1146. sm.becomeCandidate()
  1147. sm.becomeLeader()
  1148. sm.prs[2].Match, sm.prs[2].Next = tt.match, tt.next
  1149. sm.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  1150. p := sm.prs[2]
  1151. if p.Next != tt.wnext {
  1152. t.Errorf("#%d next = %d, want %d", i, p.Next, tt.wnext)
  1153. }
  1154. }
  1155. }
  1156. func TestUnreachable(t *testing.T) {
  1157. previousEnts := []pb.Entry{{Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3}}
  1158. s := NewMemoryStorage()
  1159. s.Append(previousEnts)
  1160. r := newRaft(1, []uint64{1, 2}, 10, 1, s, 0)
  1161. r.becomeCandidate()
  1162. r.becomeLeader()
  1163. r.readMessages()
  1164. // set node 2 to unreachable
  1165. r.prs[2].Match = 3
  1166. r.prs[2].Next = 4
  1167. r.prs[2].Wait = 0
  1168. r.prs[2].unreachable()
  1169. for i := 0; i < 3; i++ {
  1170. // node 2 is unreachable, we expect that raft will only send out one msgAPP per heartbeat timeout
  1171. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  1172. msg := r.readMessages()
  1173. if len(msg) != 1 {
  1174. t.Errorf("len(msg) = %d, want %d", len(msg), 1)
  1175. }
  1176. if msg[0].Index != 3 {
  1177. t.Errorf("index = %d, want %d", msg[0].Index, 3)
  1178. }
  1179. if r.prs[2].Wait != r.heartbeatTimeout {
  1180. t.Errorf("wait = %d, want %d", r.prs[1].Wait, r.heartbeatTimeout)
  1181. }
  1182. for j := 0; j < 10; j++ {
  1183. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  1184. if l := len(r.readMessages()); l != 0 {
  1185. t.Errorf("len(msg) = %d, want %d", l, 0)
  1186. }
  1187. }
  1188. // do a heartbeat
  1189. for j := 0; j < r.heartbeatTimeout; j++ {
  1190. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgBeat})
  1191. }
  1192. // consume the heartbeat
  1193. msg = r.readMessages()
  1194. if len(msg) != 1 {
  1195. t.Errorf("len(msg) = %d, want %d", len(msg), 1)
  1196. }
  1197. if msg[0].Type != pb.MsgHeartbeat {
  1198. t.Errorf("type = %s, want %s", msg[0].Type, pb.MsgHeartbeat)
  1199. }
  1200. }
  1201. // recover node 2
  1202. r.prs[2].reachable()
  1203. for i := 0; i < 10; i++ {
  1204. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Data: []byte("somedata")}}})
  1205. msgs := r.readMessages()
  1206. if len(msgs) != 1 {
  1207. t.Errorf("len(msg) = %d, want %d", len(msgs), 1)
  1208. }
  1209. }
  1210. }
  1211. func TestRestore(t *testing.T) {
  1212. s := pb.Snapshot{
  1213. Metadata: pb.SnapshotMetadata{
  1214. Index: 11, // magic number
  1215. Term: 11, // magic number
  1216. ConfState: pb.ConfState{Nodes: []uint64{1, 2, 3}},
  1217. },
  1218. }
  1219. storage := NewMemoryStorage()
  1220. sm := newRaft(1, []uint64{1, 2}, 10, 1, storage, 0)
  1221. if ok := sm.restore(s); !ok {
  1222. t.Fatal("restore fail, want succeed")
  1223. }
  1224. if sm.raftLog.lastIndex() != s.Metadata.Index {
  1225. t.Errorf("log.lastIndex = %d, want %d", sm.raftLog.lastIndex(), s.Metadata.Index)
  1226. }
  1227. if sm.raftLog.term(s.Metadata.Index) != s.Metadata.Term {
  1228. t.Errorf("log.lastTerm = %d, want %d", sm.raftLog.term(s.Metadata.Index), s.Metadata.Term)
  1229. }
  1230. sg := sm.nodes()
  1231. if !reflect.DeepEqual(sg, s.Metadata.ConfState.Nodes) {
  1232. t.Errorf("sm.Nodes = %+v, want %+v", sg, s.Metadata.ConfState.Nodes)
  1233. }
  1234. if ok := sm.restore(s); ok {
  1235. t.Fatal("restore succeed, want fail")
  1236. }
  1237. }
  1238. func TestRestoreIgnoreSnapshot(t *testing.T) {
  1239. previousEnts := []pb.Entry{{Term: 1, Index: 1}, {Term: 1, Index: 2}, {Term: 1, Index: 3}}
  1240. commit := uint64(1)
  1241. storage := NewMemoryStorage()
  1242. sm := newRaft(1, []uint64{1, 2}, 10, 1, storage, 0)
  1243. sm.raftLog.append(previousEnts...)
  1244. sm.raftLog.commitTo(commit)
  1245. s := pb.Snapshot{
  1246. Metadata: pb.SnapshotMetadata{
  1247. Index: commit,
  1248. Term: 1,
  1249. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  1250. },
  1251. }
  1252. // ignore snapshot
  1253. if ok := sm.restore(s); ok {
  1254. t.Errorf("restore = %t, want %t", ok, false)
  1255. }
  1256. if sm.raftLog.committed != commit {
  1257. t.Errorf("commit = %d, want %d", sm.raftLog.committed, commit)
  1258. }
  1259. // ignore snapshot and fast forward commit
  1260. s.Metadata.Index = commit + 1
  1261. if ok := sm.restore(s); ok {
  1262. t.Errorf("restore = %t, want %t", ok, false)
  1263. }
  1264. if sm.raftLog.committed != commit+1 {
  1265. t.Errorf("commit = %d, want %d", sm.raftLog.committed, commit+1)
  1266. }
  1267. }
  1268. func TestProvideSnap(t *testing.T) {
  1269. // restore the statemachin from a snapshot
  1270. // so it has a compacted log and a snapshot
  1271. s := pb.Snapshot{
  1272. Metadata: pb.SnapshotMetadata{
  1273. Index: 11, // magic number
  1274. Term: 11, // magic number
  1275. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  1276. },
  1277. }
  1278. storage := NewMemoryStorage()
  1279. sm := newRaft(1, []uint64{1}, 10, 1, storage, 0)
  1280. sm.restore(s)
  1281. sm.becomeCandidate()
  1282. sm.becomeLeader()
  1283. // force set the next of node 1, so that
  1284. // node 1 needs a snapshot
  1285. sm.prs[2].Next = sm.raftLog.firstIndex()
  1286. sm.Step(pb.Message{From: 2, To: 1, Type: pb.MsgAppResp, Index: sm.prs[2].Next - 1, Reject: true})
  1287. msgs := sm.readMessages()
  1288. if len(msgs) != 1 {
  1289. t.Fatalf("len(msgs) = %d, want 1", len(msgs))
  1290. }
  1291. m := msgs[0]
  1292. if m.Type != pb.MsgSnap {
  1293. t.Errorf("m.Type = %v, want %v", m.Type, pb.MsgSnap)
  1294. }
  1295. }
  1296. func TestRestoreFromSnapMsg(t *testing.T) {
  1297. s := pb.Snapshot{
  1298. Metadata: pb.SnapshotMetadata{
  1299. Index: 11, // magic number
  1300. Term: 11, // magic number
  1301. ConfState: pb.ConfState{Nodes: []uint64{1, 2}},
  1302. },
  1303. }
  1304. m := pb.Message{Type: pb.MsgSnap, From: 1, Term: 2, Snapshot: s}
  1305. sm := newRaft(2, []uint64{1, 2}, 10, 1, NewMemoryStorage(), 0)
  1306. sm.Step(m)
  1307. // TODO(bdarnell): what should this test?
  1308. }
  1309. func TestSlowNodeRestore(t *testing.T) {
  1310. nt := newNetwork(nil, nil, nil)
  1311. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgHup})
  1312. nt.isolate(3)
  1313. for j := 0; j <= 100; j++ {
  1314. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  1315. }
  1316. lead := nt.peers[1].(*raft)
  1317. nextEnts(lead, nt.storage[1])
  1318. nt.storage[1].CreateSnapshot(lead.raftLog.applied, &pb.ConfState{Nodes: lead.nodes()}, nil)
  1319. nt.storage[1].Compact(lead.raftLog.applied)
  1320. nt.recover()
  1321. // trigger a snapshot
  1322. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  1323. follower := nt.peers[3].(*raft)
  1324. // trigger a commit
  1325. nt.send(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{}}})
  1326. if follower.raftLog.committed != lead.raftLog.committed {
  1327. t.Errorf("follower.committed = %d, want %d", follower.raftLog.committed, lead.raftLog.committed)
  1328. }
  1329. }
  1330. // TestStepConfig tests that when raft step msgProp in EntryConfChange type,
  1331. // it appends the entry to log and sets pendingConf to be true.
  1332. func TestStepConfig(t *testing.T) {
  1333. // a raft that cannot make progress
  1334. r := newRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage(), 0)
  1335. r.becomeCandidate()
  1336. r.becomeLeader()
  1337. index := r.raftLog.lastIndex()
  1338. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange}}})
  1339. if g := r.raftLog.lastIndex(); g != index+1 {
  1340. t.Errorf("index = %d, want %d", g, index+1)
  1341. }
  1342. if r.pendingConf != true {
  1343. t.Errorf("pendingConf = %v, want true", r.pendingConf)
  1344. }
  1345. }
  1346. // TestStepIgnoreConfig tests that if raft step the second msgProp in
  1347. // EntryConfChange type when the first one is uncommitted, the node will set
  1348. // the proposal to noop and keep its original state.
  1349. func TestStepIgnoreConfig(t *testing.T) {
  1350. // a raft that cannot make progress
  1351. r := newRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage(), 0)
  1352. r.becomeCandidate()
  1353. r.becomeLeader()
  1354. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange}}})
  1355. index := r.raftLog.lastIndex()
  1356. pendingConf := r.pendingConf
  1357. r.Step(pb.Message{From: 1, To: 1, Type: pb.MsgProp, Entries: []pb.Entry{{Type: pb.EntryConfChange}}})
  1358. wents := []pb.Entry{{Type: pb.EntryNormal, Term: 1, Index: 3, Data: nil}}
  1359. if ents := r.raftLog.entries(index + 1); !reflect.DeepEqual(ents, wents) {
  1360. t.Errorf("ents = %+v, want %+v", ents, wents)
  1361. }
  1362. if r.pendingConf != pendingConf {
  1363. t.Errorf("pendingConf = %v, want %v", r.pendingConf, pendingConf)
  1364. }
  1365. }
  1366. // TestRecoverPendingConfig tests that new leader recovers its pendingConf flag
  1367. // based on uncommitted entries.
  1368. func TestRecoverPendingConfig(t *testing.T) {
  1369. tests := []struct {
  1370. entType pb.EntryType
  1371. wpending bool
  1372. }{
  1373. {pb.EntryNormal, false},
  1374. {pb.EntryConfChange, true},
  1375. }
  1376. for i, tt := range tests {
  1377. r := newRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage(), 0)
  1378. r.appendEntry(pb.Entry{Type: tt.entType})
  1379. r.becomeCandidate()
  1380. r.becomeLeader()
  1381. if r.pendingConf != tt.wpending {
  1382. t.Errorf("#%d: pendingConf = %v, want %v", i, r.pendingConf, tt.wpending)
  1383. }
  1384. }
  1385. }
  1386. // TestRecoverDoublePendingConfig tests that new leader will panic if
  1387. // there exist two uncommitted config entries.
  1388. func TestRecoverDoublePendingConfig(t *testing.T) {
  1389. func() {
  1390. defer func() {
  1391. if err := recover(); err == nil {
  1392. t.Errorf("expect panic, but nothing happens")
  1393. }
  1394. }()
  1395. r := newRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage(), 0)
  1396. r.appendEntry(pb.Entry{Type: pb.EntryConfChange})
  1397. r.appendEntry(pb.Entry{Type: pb.EntryConfChange})
  1398. r.becomeCandidate()
  1399. r.becomeLeader()
  1400. }()
  1401. }
  1402. // TestAddNode tests that addNode could update pendingConf and nodes correctly.
  1403. func TestAddNode(t *testing.T) {
  1404. r := newRaft(1, []uint64{1}, 10, 1, NewMemoryStorage(), 0)
  1405. r.pendingConf = true
  1406. r.addNode(2)
  1407. if r.pendingConf != false {
  1408. t.Errorf("pendingConf = %v, want false", r.pendingConf)
  1409. }
  1410. nodes := r.nodes()
  1411. wnodes := []uint64{1, 2}
  1412. if !reflect.DeepEqual(nodes, wnodes) {
  1413. t.Errorf("nodes = %v, want %v", nodes, wnodes)
  1414. }
  1415. }
  1416. // TestRemoveNode tests that removeNode could update pendingConf, nodes and
  1417. // and removed list correctly.
  1418. func TestRemoveNode(t *testing.T) {
  1419. r := newRaft(1, []uint64{1, 2}, 10, 1, NewMemoryStorage(), 0)
  1420. r.pendingConf = true
  1421. r.removeNode(2)
  1422. if r.pendingConf != false {
  1423. t.Errorf("pendingConf = %v, want false", r.pendingConf)
  1424. }
  1425. w := []uint64{1}
  1426. if g := r.nodes(); !reflect.DeepEqual(g, w) {
  1427. t.Errorf("nodes = %v, want %v", g, w)
  1428. }
  1429. }
  1430. func TestPromotable(t *testing.T) {
  1431. id := uint64(1)
  1432. tests := []struct {
  1433. peers []uint64
  1434. wp bool
  1435. }{
  1436. {[]uint64{1}, true},
  1437. {[]uint64{1, 2, 3}, true},
  1438. {[]uint64{}, false},
  1439. {[]uint64{2, 3}, false},
  1440. }
  1441. for i, tt := range tests {
  1442. r := newRaft(id, tt.peers, 5, 1, NewMemoryStorage(), 0)
  1443. if g := r.promotable(); g != tt.wp {
  1444. t.Errorf("#%d: promotable = %v, want %v", i, g, tt.wp)
  1445. }
  1446. }
  1447. }
  1448. func TestRaftNodes(t *testing.T) {
  1449. tests := []struct {
  1450. ids []uint64
  1451. wids []uint64
  1452. }{
  1453. {
  1454. []uint64{1, 2, 3},
  1455. []uint64{1, 2, 3},
  1456. },
  1457. {
  1458. []uint64{3, 2, 1},
  1459. []uint64{1, 2, 3},
  1460. },
  1461. }
  1462. for i, tt := range tests {
  1463. r := newRaft(1, tt.ids, 10, 1, NewMemoryStorage(), 0)
  1464. if !reflect.DeepEqual(r.nodes(), tt.wids) {
  1465. t.Errorf("#%d: nodes = %+v, want %+v", i, r.nodes(), tt.wids)
  1466. }
  1467. }
  1468. }
  1469. func ents(terms ...uint64) *raft {
  1470. storage := NewMemoryStorage()
  1471. for i, term := range terms {
  1472. storage.Append([]pb.Entry{{Index: uint64(i + 1), Term: term}})
  1473. }
  1474. sm := newRaft(1, []uint64{}, 5, 1, storage, 0)
  1475. sm.reset(0)
  1476. return sm
  1477. }
  1478. type network struct {
  1479. peers map[uint64]Interface
  1480. storage map[uint64]*MemoryStorage
  1481. dropm map[connem]float64
  1482. ignorem map[pb.MessageType]bool
  1483. }
  1484. // newNetwork initializes a network from peers.
  1485. // A nil node will be replaced with a new *stateMachine.
  1486. // A *stateMachine will get its k, id.
  1487. // When using stateMachine, the address list is always [1, n].
  1488. func newNetwork(peers ...Interface) *network {
  1489. size := len(peers)
  1490. peerAddrs := idsBySize(size)
  1491. npeers := make(map[uint64]Interface, size)
  1492. nstorage := make(map[uint64]*MemoryStorage, size)
  1493. for j, p := range peers {
  1494. id := peerAddrs[j]
  1495. switch v := p.(type) {
  1496. case nil:
  1497. nstorage[id] = NewMemoryStorage()
  1498. sm := newRaft(id, peerAddrs, 10, 1, nstorage[id], 0)
  1499. npeers[id] = sm
  1500. case *raft:
  1501. v.id = id
  1502. v.prs = make(map[uint64]*Progress)
  1503. for i := 0; i < size; i++ {
  1504. v.prs[peerAddrs[i]] = &Progress{}
  1505. }
  1506. v.reset(0)
  1507. npeers[id] = v
  1508. case *blackHole:
  1509. npeers[id] = v
  1510. default:
  1511. panic(fmt.Sprintf("unexpected state machine type: %T", p))
  1512. }
  1513. }
  1514. return &network{
  1515. peers: npeers,
  1516. storage: nstorage,
  1517. dropm: make(map[connem]float64),
  1518. ignorem: make(map[pb.MessageType]bool),
  1519. }
  1520. }
  1521. func (nw *network) send(msgs ...pb.Message) {
  1522. for len(msgs) > 0 {
  1523. m := msgs[0]
  1524. p := nw.peers[m.To]
  1525. p.Step(m)
  1526. msgs = append(msgs[1:], nw.filter(p.readMessages())...)
  1527. }
  1528. }
  1529. func (nw *network) drop(from, to uint64, perc float64) {
  1530. nw.dropm[connem{from, to}] = perc
  1531. }
  1532. func (nw *network) cut(one, other uint64) {
  1533. nw.drop(one, other, 1)
  1534. nw.drop(other, one, 1)
  1535. }
  1536. func (nw *network) isolate(id uint64) {
  1537. for i := 0; i < len(nw.peers); i++ {
  1538. nid := uint64(i) + 1
  1539. if nid != id {
  1540. nw.drop(id, nid, 1.0)
  1541. nw.drop(nid, id, 1.0)
  1542. }
  1543. }
  1544. }
  1545. func (nw *network) ignore(t pb.MessageType) {
  1546. nw.ignorem[t] = true
  1547. }
  1548. func (nw *network) recover() {
  1549. nw.dropm = make(map[connem]float64)
  1550. nw.ignorem = make(map[pb.MessageType]bool)
  1551. }
  1552. func (nw *network) filter(msgs []pb.Message) []pb.Message {
  1553. mm := []pb.Message{}
  1554. for _, m := range msgs {
  1555. if nw.ignorem[m.Type] {
  1556. continue
  1557. }
  1558. switch m.Type {
  1559. case pb.MsgHup:
  1560. // hups never go over the network, so don't drop them but panic
  1561. panic("unexpected msgHup")
  1562. default:
  1563. perc := nw.dropm[connem{m.From, m.To}]
  1564. if n := rand.Float64(); n < perc {
  1565. continue
  1566. }
  1567. }
  1568. mm = append(mm, m)
  1569. }
  1570. return mm
  1571. }
  1572. type connem struct {
  1573. from, to uint64
  1574. }
  1575. type blackHole struct{}
  1576. func (blackHole) Step(pb.Message) error { return nil }
  1577. func (blackHole) readMessages() []pb.Message { return nil }
  1578. var nopStepper = &blackHole{}
  1579. func idsBySize(size int) []uint64 {
  1580. ids := make([]uint64, size)
  1581. for i := 0; i < size; i++ {
  1582. ids[i] = 1 + uint64(i)
  1583. }
  1584. return ids
  1585. }