node_test.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  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. "strings"
  20. "testing"
  21. "time"
  22. "go.etcd.io/etcd/pkg/testutil"
  23. "go.etcd.io/etcd/raft/raftpb"
  24. )
  25. // readyWithTimeout selects from n.Ready() with a 1-second timeout. It
  26. // panics on timeout, which is better than the indefinite wait that
  27. // would occur if this channel were read without being wrapped in a
  28. // select.
  29. func readyWithTimeout(n Node) Ready {
  30. select {
  31. case rd := <-n.Ready():
  32. return rd
  33. case <-time.After(time.Second):
  34. panic("timed out waiting for ready")
  35. }
  36. }
  37. // TestNodeStep ensures that node.Step sends msgProp to propc chan
  38. // and other kinds of messages to recvc chan.
  39. func TestNodeStep(t *testing.T) {
  40. for i, msgn := range raftpb.MessageType_name {
  41. n := &node{
  42. propc: make(chan msgWithResult, 1),
  43. recvc: make(chan raftpb.Message, 1),
  44. }
  45. msgt := raftpb.MessageType(i)
  46. n.Step(context.TODO(), raftpb.Message{Type: msgt})
  47. // Proposal goes to proc chan. Others go to recvc chan.
  48. if msgt == raftpb.MsgProp {
  49. select {
  50. case <-n.propc:
  51. default:
  52. t.Errorf("%d: cannot receive %s on propc chan", msgt, msgn)
  53. }
  54. } else {
  55. if IsLocalMsg(msgt) {
  56. select {
  57. case <-n.recvc:
  58. t.Errorf("%d: step should ignore %s", msgt, msgn)
  59. default:
  60. }
  61. } else {
  62. select {
  63. case <-n.recvc:
  64. default:
  65. t.Errorf("%d: cannot receive %s on recvc chan", msgt, msgn)
  66. }
  67. }
  68. }
  69. }
  70. }
  71. // Cancel and Stop should unblock Step()
  72. func TestNodeStepUnblock(t *testing.T) {
  73. // a node without buffer to block step
  74. n := &node{
  75. propc: make(chan msgWithResult),
  76. done: make(chan struct{}),
  77. }
  78. ctx, cancel := context.WithCancel(context.Background())
  79. stopFunc := func() { close(n.done) }
  80. tests := []struct {
  81. unblock func()
  82. werr error
  83. }{
  84. {stopFunc, ErrStopped},
  85. {cancel, context.Canceled},
  86. }
  87. for i, tt := range tests {
  88. errc := make(chan error, 1)
  89. go func() {
  90. err := n.Step(ctx, raftpb.Message{Type: raftpb.MsgProp})
  91. errc <- err
  92. }()
  93. tt.unblock()
  94. select {
  95. case err := <-errc:
  96. if err != tt.werr {
  97. t.Errorf("#%d: err = %v, want %v", i, err, tt.werr)
  98. }
  99. //clean up side-effect
  100. if ctx.Err() != nil {
  101. ctx = context.TODO()
  102. }
  103. select {
  104. case <-n.done:
  105. n.done = make(chan struct{})
  106. default:
  107. }
  108. case <-time.After(1 * time.Second):
  109. t.Fatalf("#%d: failed to unblock step", i)
  110. }
  111. }
  112. }
  113. // TestNodePropose ensures that node.Propose sends the given proposal to the underlying raft.
  114. func TestNodePropose(t *testing.T) {
  115. msgs := []raftpb.Message{}
  116. appendStep := func(r *raft, m raftpb.Message) error {
  117. msgs = append(msgs, m)
  118. return nil
  119. }
  120. n := newNode()
  121. s := NewMemoryStorage()
  122. r := newTestRaft(1, []uint64{1}, 10, 1, s)
  123. go n.run(r)
  124. n.Campaign(context.TODO())
  125. for {
  126. rd := <-n.Ready()
  127. s.Append(rd.Entries)
  128. // change the step function to appendStep until this raft becomes leader
  129. if rd.SoftState.Lead == r.id {
  130. r.step = appendStep
  131. n.Advance()
  132. break
  133. }
  134. n.Advance()
  135. }
  136. n.Propose(context.TODO(), []byte("somedata"))
  137. n.Stop()
  138. if len(msgs) != 1 {
  139. t.Fatalf("len(msgs) = %d, want %d", len(msgs), 1)
  140. }
  141. if msgs[0].Type != raftpb.MsgProp {
  142. t.Errorf("msg type = %d, want %d", msgs[0].Type, raftpb.MsgProp)
  143. }
  144. if !bytes.Equal(msgs[0].Entries[0].Data, []byte("somedata")) {
  145. t.Errorf("data = %v, want %v", msgs[0].Entries[0].Data, []byte("somedata"))
  146. }
  147. }
  148. // TestNodeReadIndex ensures that node.ReadIndex sends the MsgReadIndex message to the underlying raft.
  149. // It also ensures that ReadState can be read out through ready chan.
  150. func TestNodeReadIndex(t *testing.T) {
  151. msgs := []raftpb.Message{}
  152. appendStep := func(r *raft, m raftpb.Message) error {
  153. msgs = append(msgs, m)
  154. return nil
  155. }
  156. wrs := []ReadState{{Index: uint64(1), RequestCtx: []byte("somedata")}}
  157. n := newNode()
  158. s := NewMemoryStorage()
  159. r := newTestRaft(1, []uint64{1}, 10, 1, s)
  160. r.readStates = wrs
  161. go n.run(r)
  162. n.Campaign(context.TODO())
  163. for {
  164. rd := <-n.Ready()
  165. if !reflect.DeepEqual(rd.ReadStates, wrs) {
  166. t.Errorf("ReadStates = %v, want %v", rd.ReadStates, wrs)
  167. }
  168. s.Append(rd.Entries)
  169. if rd.SoftState.Lead == r.id {
  170. n.Advance()
  171. break
  172. }
  173. n.Advance()
  174. }
  175. r.step = appendStep
  176. wrequestCtx := []byte("somedata2")
  177. n.ReadIndex(context.TODO(), wrequestCtx)
  178. n.Stop()
  179. if len(msgs) != 1 {
  180. t.Fatalf("len(msgs) = %d, want %d", len(msgs), 1)
  181. }
  182. if msgs[0].Type != raftpb.MsgReadIndex {
  183. t.Errorf("msg type = %d, want %d", msgs[0].Type, raftpb.MsgReadIndex)
  184. }
  185. if !bytes.Equal(msgs[0].Entries[0].Data, wrequestCtx) {
  186. t.Errorf("data = %v, want %v", msgs[0].Entries[0].Data, wrequestCtx)
  187. }
  188. }
  189. // TestDisableProposalForwarding ensures that proposals are not forwarded to
  190. // the leader when DisableProposalForwarding is true.
  191. func TestDisableProposalForwarding(t *testing.T) {
  192. r1 := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  193. r2 := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  194. cfg3 := newTestConfig(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  195. cfg3.DisableProposalForwarding = true
  196. r3 := newRaft(cfg3)
  197. nt := newNetwork(r1, r2, r3)
  198. // elect r1 as leader
  199. nt.send(raftpb.Message{From: 1, To: 1, Type: raftpb.MsgHup})
  200. var testEntries = []raftpb.Entry{{Data: []byte("testdata")}}
  201. // send proposal to r2(follower) where DisableProposalForwarding is false
  202. r2.Step(raftpb.Message{From: 2, To: 2, Type: raftpb.MsgProp, Entries: testEntries})
  203. // verify r2(follower) does forward the proposal when DisableProposalForwarding is false
  204. if len(r2.msgs) != 1 {
  205. t.Fatalf("len(r2.msgs) expected 1, got %d", len(r2.msgs))
  206. }
  207. // send proposal to r3(follower) where DisableProposalForwarding is true
  208. r3.Step(raftpb.Message{From: 3, To: 3, Type: raftpb.MsgProp, Entries: testEntries})
  209. // verify r3(follower) does not forward the proposal when DisableProposalForwarding is true
  210. if len(r3.msgs) != 0 {
  211. t.Fatalf("len(r3.msgs) expected 0, got %d", len(r3.msgs))
  212. }
  213. }
  214. // TestNodeReadIndexToOldLeader ensures that raftpb.MsgReadIndex to old leader
  215. // gets forwarded to the new leader and 'send' method does not attach its term.
  216. func TestNodeReadIndexToOldLeader(t *testing.T) {
  217. r1 := newTestRaft(1, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  218. r2 := newTestRaft(2, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  219. r3 := newTestRaft(3, []uint64{1, 2, 3}, 10, 1, NewMemoryStorage())
  220. nt := newNetwork(r1, r2, r3)
  221. // elect r1 as leader
  222. nt.send(raftpb.Message{From: 1, To: 1, Type: raftpb.MsgHup})
  223. var testEntries = []raftpb.Entry{{Data: []byte("testdata")}}
  224. // send readindex request to r2(follower)
  225. r2.Step(raftpb.Message{From: 2, To: 2, Type: raftpb.MsgReadIndex, Entries: testEntries})
  226. // verify r2(follower) forwards this message to r1(leader) with term not set
  227. if len(r2.msgs) != 1 {
  228. t.Fatalf("len(r2.msgs) expected 1, got %d", len(r2.msgs))
  229. }
  230. readIndxMsg1 := raftpb.Message{From: 2, To: 1, Type: raftpb.MsgReadIndex, Entries: testEntries}
  231. if !reflect.DeepEqual(r2.msgs[0], readIndxMsg1) {
  232. t.Fatalf("r2.msgs[0] expected %+v, got %+v", readIndxMsg1, r2.msgs[0])
  233. }
  234. // send readindex request to r3(follower)
  235. r3.Step(raftpb.Message{From: 3, To: 3, Type: raftpb.MsgReadIndex, Entries: testEntries})
  236. // verify r3(follower) forwards this message to r1(leader) with term not set as well.
  237. if len(r3.msgs) != 1 {
  238. t.Fatalf("len(r3.msgs) expected 1, got %d", len(r3.msgs))
  239. }
  240. readIndxMsg2 := raftpb.Message{From: 3, To: 1, Type: raftpb.MsgReadIndex, Entries: testEntries}
  241. if !reflect.DeepEqual(r3.msgs[0], readIndxMsg2) {
  242. t.Fatalf("r3.msgs[0] expected %+v, got %+v", readIndxMsg2, r3.msgs[0])
  243. }
  244. // now elect r3 as leader
  245. nt.send(raftpb.Message{From: 3, To: 3, Type: raftpb.MsgHup})
  246. // let r1 steps the two messages previously we got from r2, r3
  247. r1.Step(readIndxMsg1)
  248. r1.Step(readIndxMsg2)
  249. // verify r1(follower) forwards these messages again to r3(new leader)
  250. if len(r1.msgs) != 2 {
  251. t.Fatalf("len(r1.msgs) expected 1, got %d", len(r1.msgs))
  252. }
  253. readIndxMsg3 := raftpb.Message{From: 1, To: 3, Type: raftpb.MsgReadIndex, Entries: testEntries}
  254. if !reflect.DeepEqual(r1.msgs[0], readIndxMsg3) {
  255. t.Fatalf("r1.msgs[0] expected %+v, got %+v", readIndxMsg3, r1.msgs[0])
  256. }
  257. if !reflect.DeepEqual(r1.msgs[1], readIndxMsg3) {
  258. t.Fatalf("r1.msgs[1] expected %+v, got %+v", readIndxMsg3, r1.msgs[1])
  259. }
  260. }
  261. // TestNodeProposeConfig ensures that node.ProposeConfChange sends the given configuration proposal
  262. // to the underlying raft.
  263. func TestNodeProposeConfig(t *testing.T) {
  264. msgs := []raftpb.Message{}
  265. appendStep := func(r *raft, m raftpb.Message) error {
  266. msgs = append(msgs, m)
  267. return nil
  268. }
  269. n := newNode()
  270. s := NewMemoryStorage()
  271. r := newTestRaft(1, []uint64{1}, 10, 1, s)
  272. go n.run(r)
  273. n.Campaign(context.TODO())
  274. for {
  275. rd := <-n.Ready()
  276. s.Append(rd.Entries)
  277. // change the step function to appendStep until this raft becomes leader
  278. if rd.SoftState.Lead == r.id {
  279. r.step = appendStep
  280. n.Advance()
  281. break
  282. }
  283. n.Advance()
  284. }
  285. cc := raftpb.ConfChange{Type: raftpb.ConfChangeAddNode, NodeID: 1}
  286. ccdata, err := cc.Marshal()
  287. if err != nil {
  288. t.Fatal(err)
  289. }
  290. n.ProposeConfChange(context.TODO(), cc)
  291. n.Stop()
  292. if len(msgs) != 1 {
  293. t.Fatalf("len(msgs) = %d, want %d", len(msgs), 1)
  294. }
  295. if msgs[0].Type != raftpb.MsgProp {
  296. t.Errorf("msg type = %d, want %d", msgs[0].Type, raftpb.MsgProp)
  297. }
  298. if !bytes.Equal(msgs[0].Entries[0].Data, ccdata) {
  299. t.Errorf("data = %v, want %v", msgs[0].Entries[0].Data, ccdata)
  300. }
  301. }
  302. // TestNodeProposeAddDuplicateNode ensures that two proposes to add the same node should
  303. // not affect the later propose to add new node.
  304. func TestNodeProposeAddDuplicateNode(t *testing.T) {
  305. n := newNode()
  306. s := NewMemoryStorage()
  307. r := newTestRaft(1, []uint64{1}, 10, 1, s)
  308. go n.run(r)
  309. n.Campaign(context.TODO())
  310. rdyEntries := make([]raftpb.Entry, 0)
  311. ticker := time.NewTicker(time.Millisecond * 100)
  312. defer ticker.Stop()
  313. done := make(chan struct{})
  314. stop := make(chan struct{})
  315. applyConfChan := make(chan struct{})
  316. go func() {
  317. defer close(done)
  318. for {
  319. select {
  320. case <-stop:
  321. return
  322. case <-ticker.C:
  323. n.Tick()
  324. case rd := <-n.Ready():
  325. s.Append(rd.Entries)
  326. applied := false
  327. for _, e := range rd.Entries {
  328. rdyEntries = append(rdyEntries, e)
  329. switch e.Type {
  330. case raftpb.EntryNormal:
  331. case raftpb.EntryConfChange:
  332. var cc raftpb.ConfChange
  333. cc.Unmarshal(e.Data)
  334. n.ApplyConfChange(cc)
  335. applied = true
  336. }
  337. }
  338. n.Advance()
  339. if applied {
  340. applyConfChan <- struct{}{}
  341. }
  342. }
  343. }
  344. }()
  345. cc1 := raftpb.ConfChange{Type: raftpb.ConfChangeAddNode, NodeID: 1}
  346. ccdata1, _ := cc1.Marshal()
  347. n.ProposeConfChange(context.TODO(), cc1)
  348. <-applyConfChan
  349. // try add the same node again
  350. n.ProposeConfChange(context.TODO(), cc1)
  351. <-applyConfChan
  352. // the new node join should be ok
  353. cc2 := raftpb.ConfChange{Type: raftpb.ConfChangeAddNode, NodeID: 2}
  354. ccdata2, _ := cc2.Marshal()
  355. n.ProposeConfChange(context.TODO(), cc2)
  356. <-applyConfChan
  357. close(stop)
  358. <-done
  359. if len(rdyEntries) != 4 {
  360. t.Errorf("len(entry) = %d, want %d, %v\n", len(rdyEntries), 4, rdyEntries)
  361. }
  362. if !bytes.Equal(rdyEntries[1].Data, ccdata1) {
  363. t.Errorf("data = %v, want %v", rdyEntries[1].Data, ccdata1)
  364. }
  365. if !bytes.Equal(rdyEntries[3].Data, ccdata2) {
  366. t.Errorf("data = %v, want %v", rdyEntries[3].Data, ccdata2)
  367. }
  368. n.Stop()
  369. }
  370. // TestBlockProposal ensures that node will block proposal when it does not
  371. // know who is the current leader; node will accept proposal when it knows
  372. // who is the current leader.
  373. func TestBlockProposal(t *testing.T) {
  374. n := newNode()
  375. r := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  376. go n.run(r)
  377. defer n.Stop()
  378. errc := make(chan error, 1)
  379. go func() {
  380. errc <- n.Propose(context.TODO(), []byte("somedata"))
  381. }()
  382. testutil.WaitSchedule()
  383. select {
  384. case err := <-errc:
  385. t.Errorf("err = %v, want blocking", err)
  386. default:
  387. }
  388. n.Campaign(context.TODO())
  389. select {
  390. case err := <-errc:
  391. if err != nil {
  392. t.Errorf("err = %v, want %v", err, nil)
  393. }
  394. case <-time.After(10 * time.Second):
  395. t.Errorf("blocking proposal, want unblocking")
  396. }
  397. }
  398. func TestNodeProposeWaitDropped(t *testing.T) {
  399. msgs := []raftpb.Message{}
  400. droppingMsg := []byte("test_dropping")
  401. dropStep := func(r *raft, m raftpb.Message) error {
  402. if m.Type == raftpb.MsgProp && strings.Contains(m.String(), string(droppingMsg)) {
  403. t.Logf("dropping message: %v", m.String())
  404. return ErrProposalDropped
  405. }
  406. msgs = append(msgs, m)
  407. return nil
  408. }
  409. n := newNode()
  410. s := NewMemoryStorage()
  411. r := newTestRaft(1, []uint64{1}, 10, 1, s)
  412. go n.run(r)
  413. n.Campaign(context.TODO())
  414. for {
  415. rd := <-n.Ready()
  416. s.Append(rd.Entries)
  417. // change the step function to dropStep until this raft becomes leader
  418. if rd.SoftState.Lead == r.id {
  419. r.step = dropStep
  420. n.Advance()
  421. break
  422. }
  423. n.Advance()
  424. }
  425. proposalTimeout := time.Millisecond * 100
  426. ctx, cancel := context.WithTimeout(context.Background(), proposalTimeout)
  427. // propose with cancel should be cancelled earyly if dropped
  428. err := n.Propose(ctx, droppingMsg)
  429. if err != ErrProposalDropped {
  430. t.Errorf("should drop proposal : %v", err)
  431. }
  432. cancel()
  433. n.Stop()
  434. if len(msgs) != 0 {
  435. t.Fatalf("len(msgs) = %d, want %d", len(msgs), 1)
  436. }
  437. }
  438. // TestNodeTick ensures that node.Tick() will increase the
  439. // elapsed of the underlying raft state machine.
  440. func TestNodeTick(t *testing.T) {
  441. n := newNode()
  442. s := NewMemoryStorage()
  443. r := newTestRaft(1, []uint64{1}, 10, 1, s)
  444. go n.run(r)
  445. elapsed := r.electionElapsed
  446. n.Tick()
  447. for len(n.tickc) != 0 {
  448. time.Sleep(100 * time.Millisecond)
  449. }
  450. n.Stop()
  451. if r.electionElapsed != elapsed+1 {
  452. t.Errorf("elapsed = %d, want %d", r.electionElapsed, elapsed+1)
  453. }
  454. }
  455. // TestNodeStop ensures that node.Stop() blocks until the node has stopped
  456. // processing, and that it is idempotent
  457. func TestNodeStop(t *testing.T) {
  458. n := newNode()
  459. s := NewMemoryStorage()
  460. r := newTestRaft(1, []uint64{1}, 10, 1, s)
  461. donec := make(chan struct{})
  462. go func() {
  463. n.run(r)
  464. close(donec)
  465. }()
  466. status := n.Status()
  467. n.Stop()
  468. select {
  469. case <-donec:
  470. case <-time.After(time.Second):
  471. t.Fatalf("timed out waiting for node to stop!")
  472. }
  473. emptyStatus := Status{}
  474. if reflect.DeepEqual(status, emptyStatus) {
  475. t.Errorf("status = %v, want not empty", status)
  476. }
  477. // Further status should return be empty, the node is stopped.
  478. status = n.Status()
  479. if !reflect.DeepEqual(status, emptyStatus) {
  480. t.Errorf("status = %v, want empty", status)
  481. }
  482. // Subsequent Stops should have no effect.
  483. n.Stop()
  484. }
  485. func TestReadyContainUpdates(t *testing.T) {
  486. tests := []struct {
  487. rd Ready
  488. wcontain bool
  489. }{
  490. {Ready{}, false},
  491. {Ready{SoftState: &SoftState{Lead: 1}}, true},
  492. {Ready{HardState: raftpb.HardState{Vote: 1}}, true},
  493. {Ready{Entries: make([]raftpb.Entry, 1)}, true},
  494. {Ready{CommittedEntries: make([]raftpb.Entry, 1)}, true},
  495. {Ready{Messages: make([]raftpb.Message, 1)}, true},
  496. {Ready{Snapshot: raftpb.Snapshot{Metadata: raftpb.SnapshotMetadata{Index: 1}}}, true},
  497. }
  498. for i, tt := range tests {
  499. if g := tt.rd.containsUpdates(); g != tt.wcontain {
  500. t.Errorf("#%d: containUpdates = %v, want %v", i, g, tt.wcontain)
  501. }
  502. }
  503. }
  504. // TestNodeStart ensures that a node can be started correctly. The node should
  505. // start with correct configuration change entries, and can accept and commit
  506. // proposals.
  507. func TestNodeStart(t *testing.T) {
  508. ctx, cancel := context.WithCancel(context.Background())
  509. defer cancel()
  510. cc := raftpb.ConfChange{Type: raftpb.ConfChangeAddNode, NodeID: 1}
  511. ccdata, err := cc.Marshal()
  512. if err != nil {
  513. t.Fatalf("unexpected marshal error: %v", err)
  514. }
  515. wants := []Ready{
  516. {
  517. HardState: raftpb.HardState{Term: 1, Commit: 1, Vote: 0},
  518. Entries: []raftpb.Entry{
  519. {Type: raftpb.EntryConfChange, Term: 1, Index: 1, Data: ccdata},
  520. },
  521. CommittedEntries: []raftpb.Entry{
  522. {Type: raftpb.EntryConfChange, Term: 1, Index: 1, Data: ccdata},
  523. },
  524. MustSync: true,
  525. },
  526. {
  527. HardState: raftpb.HardState{Term: 2, Commit: 3, Vote: 1},
  528. Entries: []raftpb.Entry{{Term: 2, Index: 3, Data: []byte("foo")}},
  529. CommittedEntries: []raftpb.Entry{{Term: 2, Index: 3, Data: []byte("foo")}},
  530. MustSync: true,
  531. },
  532. }
  533. storage := NewMemoryStorage()
  534. c := &Config{
  535. ID: 1,
  536. ElectionTick: 10,
  537. HeartbeatTick: 1,
  538. Storage: storage,
  539. MaxSizePerMsg: noLimit,
  540. MaxInflightMsgs: 256,
  541. }
  542. n := StartNode(c, []Peer{{ID: 1}})
  543. defer n.Stop()
  544. g := <-n.Ready()
  545. if !reflect.DeepEqual(g, wants[0]) {
  546. t.Fatalf("#%d: g = %+v,\n w %+v", 1, g, wants[0])
  547. } else {
  548. storage.Append(g.Entries)
  549. n.Advance()
  550. }
  551. n.Campaign(ctx)
  552. rd := <-n.Ready()
  553. storage.Append(rd.Entries)
  554. n.Advance()
  555. n.Propose(ctx, []byte("foo"))
  556. if g2 := <-n.Ready(); !reflect.DeepEqual(g2, wants[1]) {
  557. t.Errorf("#%d: g = %+v,\n w %+v", 2, g2, wants[1])
  558. } else {
  559. storage.Append(g2.Entries)
  560. n.Advance()
  561. }
  562. select {
  563. case rd := <-n.Ready():
  564. t.Errorf("unexpected Ready: %+v", rd)
  565. case <-time.After(time.Millisecond):
  566. }
  567. }
  568. func TestNodeRestart(t *testing.T) {
  569. entries := []raftpb.Entry{
  570. {Term: 1, Index: 1},
  571. {Term: 1, Index: 2, Data: []byte("foo")},
  572. }
  573. st := raftpb.HardState{Term: 1, Commit: 1}
  574. want := Ready{
  575. HardState: st,
  576. // commit up to index commit index in st
  577. CommittedEntries: entries[:st.Commit],
  578. MustSync: true,
  579. }
  580. storage := NewMemoryStorage()
  581. storage.SetHardState(st)
  582. storage.Append(entries)
  583. c := &Config{
  584. ID: 1,
  585. ElectionTick: 10,
  586. HeartbeatTick: 1,
  587. Storage: storage,
  588. MaxSizePerMsg: noLimit,
  589. MaxInflightMsgs: 256,
  590. }
  591. n := RestartNode(c)
  592. defer n.Stop()
  593. if g := <-n.Ready(); !reflect.DeepEqual(g, want) {
  594. t.Errorf("g = %+v,\n w %+v", g, want)
  595. }
  596. n.Advance()
  597. select {
  598. case rd := <-n.Ready():
  599. t.Errorf("unexpected Ready: %+v", rd)
  600. case <-time.After(time.Millisecond):
  601. }
  602. }
  603. func TestNodeRestartFromSnapshot(t *testing.T) {
  604. snap := raftpb.Snapshot{
  605. Metadata: raftpb.SnapshotMetadata{
  606. ConfState: raftpb.ConfState{Nodes: []uint64{1, 2}},
  607. Index: 2,
  608. Term: 1,
  609. },
  610. }
  611. entries := []raftpb.Entry{
  612. {Term: 1, Index: 3, Data: []byte("foo")},
  613. }
  614. st := raftpb.HardState{Term: 1, Commit: 3}
  615. want := Ready{
  616. HardState: st,
  617. // commit up to index commit index in st
  618. CommittedEntries: entries,
  619. MustSync: true,
  620. }
  621. s := NewMemoryStorage()
  622. s.SetHardState(st)
  623. s.ApplySnapshot(snap)
  624. s.Append(entries)
  625. c := &Config{
  626. ID: 1,
  627. ElectionTick: 10,
  628. HeartbeatTick: 1,
  629. Storage: s,
  630. MaxSizePerMsg: noLimit,
  631. MaxInflightMsgs: 256,
  632. }
  633. n := RestartNode(c)
  634. defer n.Stop()
  635. if g := <-n.Ready(); !reflect.DeepEqual(g, want) {
  636. t.Errorf("g = %+v,\n w %+v", g, want)
  637. } else {
  638. n.Advance()
  639. }
  640. select {
  641. case rd := <-n.Ready():
  642. t.Errorf("unexpected Ready: %+v", rd)
  643. case <-time.After(time.Millisecond):
  644. }
  645. }
  646. func TestNodeAdvance(t *testing.T) {
  647. ctx, cancel := context.WithCancel(context.Background())
  648. defer cancel()
  649. storage := NewMemoryStorage()
  650. c := &Config{
  651. ID: 1,
  652. ElectionTick: 10,
  653. HeartbeatTick: 1,
  654. Storage: storage,
  655. MaxSizePerMsg: noLimit,
  656. MaxInflightMsgs: 256,
  657. }
  658. n := StartNode(c, []Peer{{ID: 1}})
  659. defer n.Stop()
  660. rd := <-n.Ready()
  661. storage.Append(rd.Entries)
  662. n.Advance()
  663. n.Campaign(ctx)
  664. <-n.Ready()
  665. n.Propose(ctx, []byte("foo"))
  666. select {
  667. case rd = <-n.Ready():
  668. t.Fatalf("unexpected Ready before Advance: %+v", rd)
  669. case <-time.After(time.Millisecond):
  670. }
  671. storage.Append(rd.Entries)
  672. n.Advance()
  673. select {
  674. case <-n.Ready():
  675. case <-time.After(100 * time.Millisecond):
  676. t.Errorf("expect Ready after Advance, but there is no Ready available")
  677. }
  678. }
  679. func TestSoftStateEqual(t *testing.T) {
  680. tests := []struct {
  681. st *SoftState
  682. we bool
  683. }{
  684. {&SoftState{}, true},
  685. {&SoftState{Lead: 1}, false},
  686. {&SoftState{RaftState: StateLeader}, false},
  687. }
  688. for i, tt := range tests {
  689. if g := tt.st.equal(&SoftState{}); g != tt.we {
  690. t.Errorf("#%d, equal = %v, want %v", i, g, tt.we)
  691. }
  692. }
  693. }
  694. func TestIsHardStateEqual(t *testing.T) {
  695. tests := []struct {
  696. st raftpb.HardState
  697. we bool
  698. }{
  699. {emptyState, true},
  700. {raftpb.HardState{Vote: 1}, false},
  701. {raftpb.HardState{Commit: 1}, false},
  702. {raftpb.HardState{Term: 1}, false},
  703. }
  704. for i, tt := range tests {
  705. if isHardStateEqual(tt.st, emptyState) != tt.we {
  706. t.Errorf("#%d, equal = %v, want %v", i, isHardStateEqual(tt.st, emptyState), tt.we)
  707. }
  708. }
  709. }
  710. func TestNodeProposeAddLearnerNode(t *testing.T) {
  711. ticker := time.NewTicker(time.Millisecond * 100)
  712. defer ticker.Stop()
  713. n := newNode()
  714. s := NewMemoryStorage()
  715. r := newTestRaft(1, []uint64{1}, 10, 1, s)
  716. go n.run(r)
  717. n.Campaign(context.TODO())
  718. stop := make(chan struct{})
  719. done := make(chan struct{})
  720. applyConfChan := make(chan struct{})
  721. go func() {
  722. defer close(done)
  723. for {
  724. select {
  725. case <-stop:
  726. return
  727. case <-ticker.C:
  728. n.Tick()
  729. case rd := <-n.Ready():
  730. s.Append(rd.Entries)
  731. t.Logf("raft: %v", rd.Entries)
  732. for _, ent := range rd.Entries {
  733. if ent.Type != raftpb.EntryConfChange {
  734. continue
  735. }
  736. var cc raftpb.ConfChange
  737. cc.Unmarshal(ent.Data)
  738. state := n.ApplyConfChange(cc)
  739. if len(state.Learners) == 0 ||
  740. state.Learners[0] != cc.NodeID ||
  741. cc.NodeID != 2 {
  742. t.Errorf("apply conf change should return new added learner: %v", state.String())
  743. }
  744. if len(state.Nodes) != 1 {
  745. t.Errorf("add learner should not change the nodes: %v", state.String())
  746. }
  747. t.Logf("apply raft conf %v changed to: %v", cc, state.String())
  748. applyConfChan <- struct{}{}
  749. }
  750. n.Advance()
  751. }
  752. }
  753. }()
  754. cc := raftpb.ConfChange{Type: raftpb.ConfChangeAddLearnerNode, NodeID: 2}
  755. n.ProposeConfChange(context.TODO(), cc)
  756. <-applyConfChan
  757. close(stop)
  758. <-done
  759. }
  760. func TestAppendPagination(t *testing.T) {
  761. const maxSizePerMsg = 2048
  762. n := newNetworkWithConfig(func(c *Config) {
  763. c.MaxSizePerMsg = maxSizePerMsg
  764. }, nil, nil, nil)
  765. seenFullMessage := false
  766. // Inspect all messages to see that we never exceed the limit, but
  767. // we do see messages of larger than half the limit.
  768. n.msgHook = func(m raftpb.Message) bool {
  769. if m.Type == raftpb.MsgApp {
  770. size := 0
  771. for _, e := range m.Entries {
  772. size += len(e.Data)
  773. }
  774. if size > maxSizePerMsg {
  775. t.Errorf("sent MsgApp that is too large: %d bytes", size)
  776. }
  777. if size > maxSizePerMsg/2 {
  778. seenFullMessage = true
  779. }
  780. }
  781. return true
  782. }
  783. n.send(raftpb.Message{From: 1, To: 1, Type: raftpb.MsgHup})
  784. // Partition the network while we make our proposals. This forces
  785. // the entries to be batched into larger messages.
  786. n.isolate(1)
  787. blob := []byte(strings.Repeat("a", 1000))
  788. for i := 0; i < 5; i++ {
  789. n.send(raftpb.Message{From: 1, To: 1, Type: raftpb.MsgProp, Entries: []raftpb.Entry{{Data: blob}}})
  790. }
  791. n.recover()
  792. // After the partition recovers, tick the clock to wake everything
  793. // back up and send the messages.
  794. n.send(raftpb.Message{From: 1, To: 1, Type: raftpb.MsgBeat})
  795. if !seenFullMessage {
  796. t.Error("didn't see any messages more than half the max size; something is wrong with this test")
  797. }
  798. }
  799. func TestCommitPagination(t *testing.T) {
  800. s := NewMemoryStorage()
  801. cfg := newTestConfig(1, []uint64{1}, 10, 1, s)
  802. cfg.MaxSizePerMsg = 2048
  803. r := newRaft(cfg)
  804. n := newNode()
  805. go n.run(r)
  806. n.Campaign(context.TODO())
  807. rd := readyWithTimeout(&n)
  808. if len(rd.CommittedEntries) != 1 {
  809. t.Fatalf("expected 1 (empty) entry, got %d", len(rd.CommittedEntries))
  810. }
  811. s.Append(rd.Entries)
  812. n.Advance()
  813. blob := []byte(strings.Repeat("a", 1000))
  814. for i := 0; i < 3; i++ {
  815. if err := n.Propose(context.TODO(), blob); err != nil {
  816. t.Fatal(err)
  817. }
  818. }
  819. // The 3 proposals will commit in two batches.
  820. rd = readyWithTimeout(&n)
  821. if len(rd.CommittedEntries) != 2 {
  822. t.Fatalf("expected 2 entries in first batch, got %d", len(rd.CommittedEntries))
  823. }
  824. s.Append(rd.Entries)
  825. n.Advance()
  826. rd = readyWithTimeout(&n)
  827. if len(rd.CommittedEntries) != 1 {
  828. t.Fatalf("expected 1 entry in second batch, got %d", len(rd.CommittedEntries))
  829. }
  830. s.Append(rd.Entries)
  831. n.Advance()
  832. }