node_test.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  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. "context"
  18. "reflect"
  19. "testing"
  20. "time"
  21. "github.com/coreos/etcd/pkg/testutil"
  22. "github.com/coreos/etcd/raft/raftpb"
  23. )
  24. // TestNodeStep ensures that node.Step sends msgProp to propc chan
  25. // and other kinds of messages to recvc chan.
  26. func TestNodeStep(t *testing.T) {
  27. for i, msgn := range raftpb.MessageType_name {
  28. n := &node{
  29. propc: make(chan raftpb.Message, 1),
  30. recvc: make(chan raftpb.Message, 1),
  31. }
  32. msgt := raftpb.MessageType(i)
  33. n.Step(context.TODO(), raftpb.Message{Type: msgt})
  34. // Proposal goes to proc chan. Others go to recvc chan.
  35. if msgt == raftpb.MsgProp {
  36. select {
  37. case <-n.propc:
  38. default:
  39. t.Errorf("%d: cannot receive %s on propc chan", msgt, msgn)
  40. }
  41. } else {
  42. if IsLocalMsg(msgt) {
  43. select {
  44. case <-n.recvc:
  45. t.Errorf("%d: step should ignore %s", msgt, msgn)
  46. default:
  47. }
  48. } else {
  49. select {
  50. case <-n.recvc:
  51. default:
  52. t.Errorf("%d: cannot receive %s on recvc chan", msgt, msgn)
  53. }
  54. }
  55. }
  56. }
  57. }
  58. // Cancel and Stop should unblock Step()
  59. func TestNodeStepUnblock(t *testing.T) {
  60. // a node without buffer to block step
  61. n := &node{
  62. propc: make(chan raftpb.Message),
  63. done: make(chan struct{}),
  64. }
  65. ctx, cancel := context.WithCancel(context.Background())
  66. stopFunc := func() { close(n.done) }
  67. tests := []struct {
  68. unblock func()
  69. werr error
  70. }{
  71. {stopFunc, ErrStopped},
  72. {cancel, context.Canceled},
  73. }
  74. for i, tt := range tests {
  75. errc := make(chan error, 1)
  76. go func() {
  77. err := n.Step(ctx, raftpb.Message{Type: raftpb.MsgProp})
  78. errc <- err
  79. }()
  80. tt.unblock()
  81. select {
  82. case err := <-errc:
  83. if err != tt.werr {
  84. t.Errorf("#%d: err = %v, want %v", i, err, tt.werr)
  85. }
  86. //clean up side-effect
  87. if ctx.Err() != nil {
  88. ctx = context.TODO()
  89. }
  90. select {
  91. case <-n.done:
  92. n.done = make(chan struct{})
  93. default:
  94. }
  95. case <-time.After(1 * time.Second):
  96. t.Fatalf("#%d: failed to unblock step", i)
  97. }
  98. }
  99. }
  100. // TestNodePropose ensures that node.Propose sends the given proposal to the underlying raft.
  101. func TestNodePropose(t *testing.T) {
  102. msgs := []raftpb.Message{}
  103. appendStep := func(r *raft, m raftpb.Message) {
  104. msgs = append(msgs, m)
  105. }
  106. n := newNode()
  107. s := NewMemoryStorage()
  108. r := newTestRaft(1, []uint64{1}, 10, 1, s)
  109. go n.run(r)
  110. n.Campaign(context.TODO())
  111. for {
  112. rd := <-n.Ready()
  113. s.Append(rd.Entries)
  114. // change the step function to appendStep until this raft becomes leader
  115. if rd.SoftState.Lead == r.id {
  116. r.step = appendStep
  117. n.Advance()
  118. break
  119. }
  120. n.Advance()
  121. }
  122. n.Propose(context.TODO(), []byte("somedata"))
  123. n.Stop()
  124. if len(msgs) != 1 {
  125. t.Fatalf("len(msgs) = %d, want %d", len(msgs), 1)
  126. }
  127. if msgs[0].Type != raftpb.MsgProp {
  128. t.Errorf("msg type = %d, want %d", msgs[0].Type, raftpb.MsgProp)
  129. }
  130. if !bytes.Equal(msgs[0].Entries[0].Data, []byte("somedata")) {
  131. t.Errorf("data = %v, want %v", msgs[0].Entries[0].Data, []byte("somedata"))
  132. }
  133. }
  134. // TestNodeReadIndex ensures that node.ReadIndex sends the MsgReadIndex message to the underlying raft.
  135. // It also ensures that ReadState can be read out through ready chan.
  136. func TestNodeReadIndex(t *testing.T) {
  137. msgs := []raftpb.Message{}
  138. appendStep := func(r *raft, m raftpb.Message) {
  139. msgs = append(msgs, m)
  140. }
  141. wrs := []ReadState{{Index: uint64(1), RequestCtx: []byte("somedata")}}
  142. n := newNode()
  143. s := NewMemoryStorage()
  144. r := newTestRaft(1, []uint64{1}, 10, 1, s)
  145. r.readStates = wrs
  146. go n.run(r)
  147. n.Campaign(context.TODO())
  148. for {
  149. rd := <-n.Ready()
  150. if !reflect.DeepEqual(rd.ReadStates, wrs) {
  151. t.Errorf("ReadStates = %v, want %v", rd.ReadStates, wrs)
  152. }
  153. s.Append(rd.Entries)
  154. if rd.SoftState.Lead == r.id {
  155. n.Advance()
  156. break
  157. }
  158. n.Advance()
  159. }
  160. r.step = appendStep
  161. wrequestCtx := []byte("somedata2")
  162. n.ReadIndex(context.TODO(), wrequestCtx)
  163. n.Stop()
  164. if len(msgs) != 1 {
  165. t.Fatalf("len(msgs) = %d, want %d", len(msgs), 1)
  166. }
  167. if msgs[0].Type != raftpb.MsgReadIndex {
  168. t.Errorf("msg type = %d, want %d", msgs[0].Type, raftpb.MsgReadIndex)
  169. }
  170. if !bytes.Equal(msgs[0].Entries[0].Data, wrequestCtx) {
  171. t.Errorf("data = %v, want %v", msgs[0].Entries[0].Data, wrequestCtx)
  172. }
  173. }
  174. // TestDisableProposalForwarding ensures that proposals are not forwarded to
  175. // the leader when DisableProposalForwarding is true.
  176. func TestDisableProposalForwarding(t *testing.T) {
  177. r1 := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  178. r2 := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  179. cfg3 := newTestConfig(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  180. cfg3.DisableProposalForwarding = true
  181. r3 := newRaft(cfg3)
  182. nt := newNetwork(r1, r2, r3)
  183. // elect r1 as leader
  184. nt.send(raftpb.Message{From: 1, To: 1, Type: raftpb.MsgHup})
  185. var testEntries = []raftpb.Entry{{Data: []byte("testdata")}}
  186. // send proposal to r2(follower) where DisableProposalForwarding is false
  187. r2.Step(raftpb.Message{From: 2, To: 2, Type: raftpb.MsgProp, Entries: testEntries})
  188. // verify r2(follower) does forward the proposal when DisableProposalForwarding is false
  189. if len(r2.msgs) != 1 {
  190. t.Fatalf("len(r2.msgs) expected 1, got %d", len(r2.msgs))
  191. }
  192. // send proposal to r3(follower) where DisableProposalForwarding is true
  193. r3.Step(raftpb.Message{From: 3, To: 3, Type: raftpb.MsgProp, Entries: testEntries})
  194. // verify r3(follower) does not forward the proposal when DisableProposalForwarding is true
  195. if len(r3.msgs) != 0 {
  196. t.Fatalf("len(r3.msgs) expected 0, got %d", len(r3.msgs))
  197. }
  198. }
  199. // TestNodeReadIndexToOldLeader ensures that raftpb.MsgReadIndex to old leader
  200. // gets forwarded to the new leader and 'send' method does not attach its term.
  201. func TestNodeReadIndexToOldLeader(t *testing.T) {
  202. r1 := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  203. r2 := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  204. r3 := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  205. nt := newNetwork(r1, r2, r3)
  206. // elect r1 as leader
  207. nt.send(raftpb.Message{From: 1, To: 1, Type: raftpb.MsgHup})
  208. var testEntries = []raftpb.Entry{{Data: []byte("testdata")}}
  209. // send readindex request to r2(follower)
  210. r2.Step(raftpb.Message{From: 2, To: 2, Type: raftpb.MsgReadIndex, Entries: testEntries})
  211. // verify r2(follower) forwards this message to r1(leader) with term not set
  212. if len(r2.msgs) != 1 {
  213. t.Fatalf("len(r2.msgs) expected 1, got %d", len(r2.msgs))
  214. }
  215. readIndxMsg1 := raftpb.Message{From: 2, To: 1, Type: raftpb.MsgReadIndex, Entries: testEntries}
  216. if !reflect.DeepEqual(r2.msgs[0], readIndxMsg1) {
  217. t.Fatalf("r2.msgs[0] expected %+v, got %+v", readIndxMsg1, r2.msgs[0])
  218. }
  219. // send readindex request to r3(follower)
  220. r3.Step(raftpb.Message{From: 3, To: 3, Type: raftpb.MsgReadIndex, Entries: testEntries})
  221. // verify r3(follower) forwards this message to r1(leader) with term not set as well.
  222. if len(r3.msgs) != 1 {
  223. t.Fatalf("len(r3.msgs) expected 1, got %d", len(r3.msgs))
  224. }
  225. readIndxMsg2 := raftpb.Message{From: 3, To: 1, Type: raftpb.MsgReadIndex, Entries: testEntries}
  226. if !reflect.DeepEqual(r3.msgs[0], readIndxMsg2) {
  227. t.Fatalf("r3.msgs[0] expected %+v, got %+v", readIndxMsg2, r3.msgs[0])
  228. }
  229. // now elect r3 as leader
  230. nt.send(raftpb.Message{From: 3, To: 3, Type: raftpb.MsgHup})
  231. // let r1 steps the two messages previously we got from r2, r3
  232. r1.Step(readIndxMsg1)
  233. r1.Step(readIndxMsg2)
  234. // verify r1(follower) forwards these messages again to r3(new leader)
  235. if len(r1.msgs) != 2 {
  236. t.Fatalf("len(r1.msgs) expected 1, got %d", len(r1.msgs))
  237. }
  238. readIndxMsg3 := raftpb.Message{From: 1, To: 3, Type: raftpb.MsgReadIndex, Entries: testEntries}
  239. if !reflect.DeepEqual(r1.msgs[0], readIndxMsg3) {
  240. t.Fatalf("r1.msgs[0] expected %+v, got %+v", readIndxMsg3, r1.msgs[0])
  241. }
  242. if !reflect.DeepEqual(r1.msgs[1], readIndxMsg3) {
  243. t.Fatalf("r1.msgs[1] expected %+v, got %+v", readIndxMsg3, r1.msgs[1])
  244. }
  245. }
  246. // TestNodeProposeConfig ensures that node.ProposeConfChange sends the given configuration proposal
  247. // to the underlying raft.
  248. func TestNodeProposeConfig(t *testing.T) {
  249. msgs := []raftpb.Message{}
  250. appendStep := func(r *raft, m raftpb.Message) {
  251. msgs = append(msgs, m)
  252. }
  253. n := newNode()
  254. s := NewMemoryStorage()
  255. r := newTestRaft(1, []uint64{1}, 10, 1, s)
  256. go n.run(r)
  257. n.Campaign(context.TODO())
  258. for {
  259. rd := <-n.Ready()
  260. s.Append(rd.Entries)
  261. // change the step function to appendStep until this raft becomes leader
  262. if rd.SoftState.Lead == r.id {
  263. r.step = appendStep
  264. n.Advance()
  265. break
  266. }
  267. n.Advance()
  268. }
  269. cc := raftpb.ConfChange{Type: raftpb.ConfChangeAddNode, NodeID: 1}
  270. ccdata, err := cc.Marshal()
  271. if err != nil {
  272. t.Fatal(err)
  273. }
  274. n.ProposeConfChange(context.TODO(), cc)
  275. n.Stop()
  276. if len(msgs) != 1 {
  277. t.Fatalf("len(msgs) = %d, want %d", len(msgs), 1)
  278. }
  279. if msgs[0].Type != raftpb.MsgProp {
  280. t.Errorf("msg type = %d, want %d", msgs[0].Type, raftpb.MsgProp)
  281. }
  282. if !bytes.Equal(msgs[0].Entries[0].Data, ccdata) {
  283. t.Errorf("data = %v, want %v", msgs[0].Entries[0].Data, ccdata)
  284. }
  285. }
  286. // TestNodeProposeAddDuplicateNode ensures that two proposes to add the same node should
  287. // not affect the later propose to add new node.
  288. func TestNodeProposeAddDuplicateNode(t *testing.T) {
  289. n := newNode()
  290. s := NewMemoryStorage()
  291. r := newTestRaft(1, []uint64{1}, 10, 1, s)
  292. go n.run(r)
  293. n.Campaign(context.TODO())
  294. rdyEntries := make([]raftpb.Entry, 0)
  295. ticker := time.NewTicker(time.Millisecond * 100)
  296. defer ticker.Stop()
  297. done := make(chan struct{})
  298. stop := make(chan struct{})
  299. applyConfChan := make(chan struct{})
  300. go func() {
  301. defer close(done)
  302. for {
  303. select {
  304. case <-stop:
  305. return
  306. case <-ticker.C:
  307. n.Tick()
  308. case rd := <-n.Ready():
  309. s.Append(rd.Entries)
  310. applied := false
  311. for _, e := range rd.Entries {
  312. rdyEntries = append(rdyEntries, e)
  313. switch e.Type {
  314. case raftpb.EntryNormal:
  315. case raftpb.EntryConfChange:
  316. var cc raftpb.ConfChange
  317. cc.Unmarshal(e.Data)
  318. n.ApplyConfChange(cc)
  319. applied = true
  320. }
  321. }
  322. n.Advance()
  323. if applied {
  324. applyConfChan <- struct{}{}
  325. }
  326. }
  327. }
  328. }()
  329. cc1 := raftpb.ConfChange{Type: raftpb.ConfChangeAddNode, NodeID: 1}
  330. ccdata1, _ := cc1.Marshal()
  331. n.ProposeConfChange(context.TODO(), cc1)
  332. <-applyConfChan
  333. // try add the same node again
  334. n.ProposeConfChange(context.TODO(), cc1)
  335. <-applyConfChan
  336. // the new node join should be ok
  337. cc2 := raftpb.ConfChange{Type: raftpb.ConfChangeAddNode, NodeID: 2}
  338. ccdata2, _ := cc2.Marshal()
  339. n.ProposeConfChange(context.TODO(), cc2)
  340. <-applyConfChan
  341. close(stop)
  342. <-done
  343. if len(rdyEntries) != 4 {
  344. t.Errorf("len(entry) = %d, want %d, %v\n", len(rdyEntries), 4, rdyEntries)
  345. }
  346. if !bytes.Equal(rdyEntries[1].Data, ccdata1) {
  347. t.Errorf("data = %v, want %v", rdyEntries[1].Data, ccdata1)
  348. }
  349. if !bytes.Equal(rdyEntries[3].Data, ccdata2) {
  350. t.Errorf("data = %v, want %v", rdyEntries[3].Data, ccdata2)
  351. }
  352. n.Stop()
  353. }
  354. // TestBlockProposal ensures that node will block proposal when it does not
  355. // know who is the current leader; node will accept proposal when it knows
  356. // who is the current leader.
  357. func TestBlockProposal(t *testing.T) {
  358. n := newNode()
  359. r := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  360. go n.run(r)
  361. defer n.Stop()
  362. errc := make(chan error, 1)
  363. go func() {
  364. errc <- n.Propose(context.TODO(), []byte("somedata"))
  365. }()
  366. testutil.WaitSchedule()
  367. select {
  368. case err := <-errc:
  369. t.Errorf("err = %v, want blocking", err)
  370. default:
  371. }
  372. n.Campaign(context.TODO())
  373. select {
  374. case err := <-errc:
  375. if err != nil {
  376. t.Errorf("err = %v, want %v", err, nil)
  377. }
  378. case <-time.After(10 * time.Second):
  379. t.Errorf("blocking proposal, want unblocking")
  380. }
  381. }
  382. // TestNodeTick ensures that node.Tick() will increase the
  383. // elapsed of the underlying raft state machine.
  384. func TestNodeTick(t *testing.T) {
  385. n := newNode()
  386. s := NewMemoryStorage()
  387. r := newTestRaft(1, []uint64{1}, 10, 1, s)
  388. go n.run(r)
  389. elapsed := r.electionElapsed
  390. n.Tick()
  391. for len(n.tickc) != 0 {
  392. time.Sleep(100 * time.Millisecond)
  393. }
  394. n.Stop()
  395. if r.electionElapsed != elapsed+1 {
  396. t.Errorf("elapsed = %d, want %d", r.electionElapsed, elapsed+1)
  397. }
  398. }
  399. // TestNodeStop ensures that node.Stop() blocks until the node has stopped
  400. // processing, and that it is idempotent
  401. func TestNodeStop(t *testing.T) {
  402. n := newNode()
  403. s := NewMemoryStorage()
  404. r := newTestRaft(1, []uint64{1}, 10, 1, s)
  405. donec := make(chan struct{})
  406. go func() {
  407. n.run(r)
  408. close(donec)
  409. }()
  410. status := n.Status()
  411. n.Stop()
  412. select {
  413. case <-donec:
  414. case <-time.After(time.Second):
  415. t.Fatalf("timed out waiting for node to stop!")
  416. }
  417. emptyStatus := Status{}
  418. if reflect.DeepEqual(status, emptyStatus) {
  419. t.Errorf("status = %v, want not empty", status)
  420. }
  421. // Further status should return be empty, the node is stopped.
  422. status = n.Status()
  423. if !reflect.DeepEqual(status, emptyStatus) {
  424. t.Errorf("status = %v, want empty", status)
  425. }
  426. // Subsequent Stops should have no effect.
  427. n.Stop()
  428. }
  429. func TestReadyContainUpdates(t *testing.T) {
  430. tests := []struct {
  431. rd Ready
  432. wcontain bool
  433. }{
  434. {Ready{}, false},
  435. {Ready{SoftState: &SoftState{Lead: 1}}, true},
  436. {Ready{HardState: raftpb.HardState{Vote: 1}}, true},
  437. {Ready{Entries: make([]raftpb.Entry, 1)}, true},
  438. {Ready{CommittedEntries: make([]raftpb.Entry, 1)}, true},
  439. {Ready{Messages: make([]raftpb.Message, 1)}, true},
  440. {Ready{Snapshot: raftpb.Snapshot{Metadata: raftpb.SnapshotMetadata{Index: 1}}}, true},
  441. }
  442. for i, tt := range tests {
  443. if g := tt.rd.containsUpdates(); g != tt.wcontain {
  444. t.Errorf("#%d: containUpdates = %v, want %v", i, g, tt.wcontain)
  445. }
  446. }
  447. }
  448. // TestNodeStart ensures that a node can be started correctly. The node should
  449. // start with correct configuration change entries, and can accept and commit
  450. // proposals.
  451. func TestNodeStart(t *testing.T) {
  452. ctx, cancel := context.WithCancel(context.Background())
  453. defer cancel()
  454. cc := raftpb.ConfChange{Type: raftpb.ConfChangeAddNode, NodeID: 1}
  455. ccdata, err := cc.Marshal()
  456. if err != nil {
  457. t.Fatalf("unexpected marshal error: %v", err)
  458. }
  459. wants := []Ready{
  460. {
  461. HardState: raftpb.HardState{Term: 1, Commit: 1, Vote: 0},
  462. Entries: []raftpb.Entry{
  463. {Type: raftpb.EntryConfChange, Term: 1, Index: 1, Data: ccdata},
  464. },
  465. CommittedEntries: []raftpb.Entry{
  466. {Type: raftpb.EntryConfChange, Term: 1, Index: 1, Data: ccdata},
  467. },
  468. MustSync: true,
  469. },
  470. {
  471. HardState: raftpb.HardState{Term: 2, Commit: 3, Vote: 1},
  472. Entries: []raftpb.Entry{{Term: 2, Index: 3, Data: []byte("foo")}},
  473. CommittedEntries: []raftpb.Entry{{Term: 2, Index: 3, Data: []byte("foo")}},
  474. MustSync: true,
  475. },
  476. }
  477. storage := NewMemoryStorage()
  478. c := &Config{
  479. ID: 1,
  480. ElectionTick: 10,
  481. HeartbeatTick: 1,
  482. Storage: storage,
  483. MaxSizePerMsg: noLimit,
  484. MaxInflightMsgs: 256,
  485. }
  486. n := StartNode(c, []Peer{{ID: 1}})
  487. defer n.Stop()
  488. g := <-n.Ready()
  489. if !reflect.DeepEqual(g, wants[0]) {
  490. t.Fatalf("#%d: g = %+v,\n w %+v", 1, g, wants[0])
  491. } else {
  492. storage.Append(g.Entries)
  493. n.Advance()
  494. }
  495. n.Campaign(ctx)
  496. rd := <-n.Ready()
  497. storage.Append(rd.Entries)
  498. n.Advance()
  499. n.Propose(ctx, []byte("foo"))
  500. if g2 := <-n.Ready(); !reflect.DeepEqual(g2, wants[1]) {
  501. t.Errorf("#%d: g = %+v,\n w %+v", 2, g2, wants[1])
  502. } else {
  503. storage.Append(g2.Entries)
  504. n.Advance()
  505. }
  506. select {
  507. case rd := <-n.Ready():
  508. t.Errorf("unexpected Ready: %+v", rd)
  509. case <-time.After(time.Millisecond):
  510. }
  511. }
  512. func TestNodeRestart(t *testing.T) {
  513. entries := []raftpb.Entry{
  514. {Term: 1, Index: 1},
  515. {Term: 1, Index: 2, Data: []byte("foo")},
  516. }
  517. st := raftpb.HardState{Term: 1, Commit: 1}
  518. want := Ready{
  519. HardState: st,
  520. // commit up to index commit index in st
  521. CommittedEntries: entries[:st.Commit],
  522. MustSync: true,
  523. }
  524. storage := NewMemoryStorage()
  525. storage.SetHardState(st)
  526. storage.Append(entries)
  527. c := &Config{
  528. ID: 1,
  529. ElectionTick: 10,
  530. HeartbeatTick: 1,
  531. Storage: storage,
  532. MaxSizePerMsg: noLimit,
  533. MaxInflightMsgs: 256,
  534. }
  535. n := RestartNode(c)
  536. defer n.Stop()
  537. if g := <-n.Ready(); !reflect.DeepEqual(g, want) {
  538. t.Errorf("g = %+v,\n w %+v", g, want)
  539. }
  540. n.Advance()
  541. select {
  542. case rd := <-n.Ready():
  543. t.Errorf("unexpected Ready: %+v", rd)
  544. case <-time.After(time.Millisecond):
  545. }
  546. }
  547. func TestNodeRestartFromSnapshot(t *testing.T) {
  548. snap := raftpb.Snapshot{
  549. Metadata: raftpb.SnapshotMetadata{
  550. ConfState: raftpb.ConfState{Nodes: []uint64{1, 2}},
  551. Index: 2,
  552. Term: 1,
  553. },
  554. }
  555. entries := []raftpb.Entry{
  556. {Term: 1, Index: 3, Data: []byte("foo")},
  557. }
  558. st := raftpb.HardState{Term: 1, Commit: 3}
  559. want := Ready{
  560. HardState: st,
  561. // commit up to index commit index in st
  562. CommittedEntries: entries,
  563. MustSync: true,
  564. }
  565. s := NewMemoryStorage()
  566. s.SetHardState(st)
  567. s.ApplySnapshot(snap)
  568. s.Append(entries)
  569. c := &Config{
  570. ID: 1,
  571. ElectionTick: 10,
  572. HeartbeatTick: 1,
  573. Storage: s,
  574. MaxSizePerMsg: noLimit,
  575. MaxInflightMsgs: 256,
  576. }
  577. n := RestartNode(c)
  578. defer n.Stop()
  579. if g := <-n.Ready(); !reflect.DeepEqual(g, want) {
  580. t.Errorf("g = %+v,\n w %+v", g, want)
  581. } else {
  582. n.Advance()
  583. }
  584. select {
  585. case rd := <-n.Ready():
  586. t.Errorf("unexpected Ready: %+v", rd)
  587. case <-time.After(time.Millisecond):
  588. }
  589. }
  590. func TestNodeAdvance(t *testing.T) {
  591. ctx, cancel := context.WithCancel(context.Background())
  592. defer cancel()
  593. storage := NewMemoryStorage()
  594. c := &Config{
  595. ID: 1,
  596. ElectionTick: 10,
  597. HeartbeatTick: 1,
  598. Storage: storage,
  599. MaxSizePerMsg: noLimit,
  600. MaxInflightMsgs: 256,
  601. }
  602. n := StartNode(c, []Peer{{ID: 1}})
  603. defer n.Stop()
  604. rd := <-n.Ready()
  605. storage.Append(rd.Entries)
  606. n.Advance()
  607. n.Campaign(ctx)
  608. <-n.Ready()
  609. n.Propose(ctx, []byte("foo"))
  610. select {
  611. case rd = <-n.Ready():
  612. t.Fatalf("unexpected Ready before Advance: %+v", rd)
  613. case <-time.After(time.Millisecond):
  614. }
  615. storage.Append(rd.Entries)
  616. n.Advance()
  617. select {
  618. case <-n.Ready():
  619. case <-time.After(100 * time.Millisecond):
  620. t.Errorf("expect Ready after Advance, but there is no Ready available")
  621. }
  622. }
  623. func TestSoftStateEqual(t *testing.T) {
  624. tests := []struct {
  625. st *SoftState
  626. we bool
  627. }{
  628. {&SoftState{}, true},
  629. {&SoftState{Lead: 1}, false},
  630. {&SoftState{RaftState: StateLeader}, false},
  631. }
  632. for i, tt := range tests {
  633. if g := tt.st.equal(&SoftState{}); g != tt.we {
  634. t.Errorf("#%d, equal = %v, want %v", i, g, tt.we)
  635. }
  636. }
  637. }
  638. func TestIsHardStateEqual(t *testing.T) {
  639. tests := []struct {
  640. st raftpb.HardState
  641. we bool
  642. }{
  643. {emptyState, true},
  644. {raftpb.HardState{Vote: 1}, false},
  645. {raftpb.HardState{Commit: 1}, false},
  646. {raftpb.HardState{Term: 1}, false},
  647. }
  648. for i, tt := range tests {
  649. if isHardStateEqual(tt.st, emptyState) != tt.we {
  650. t.Errorf("#%d, equal = %v, want %v", i, isHardStateEqual(tt.st, emptyState), tt.we)
  651. }
  652. }
  653. }