node_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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. "reflect"
  18. "testing"
  19. "time"
  20. "github.com/coreos/etcd/pkg/testutil"
  21. "github.com/coreos/etcd/raft/raftpb"
  22. "golang.org/x/net/context"
  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. wreadIndex := uint64(1)
  142. wrequestCtx := []byte("somedata")
  143. n := newNode()
  144. s := NewMemoryStorage()
  145. r := newTestRaft(1, []uint64{1}, 10, 1, s)
  146. r.readState.Index = wreadIndex
  147. r.readState.RequestCtx = wrequestCtx
  148. go n.run(r)
  149. n.Campaign(context.TODO())
  150. for {
  151. rd := <-n.Ready()
  152. if rd.Index != wreadIndex {
  153. t.Errorf("ReadIndex = %d, want %d", rd.Index, wreadIndex)
  154. }
  155. if !bytes.Equal(rd.RequestCtx, wrequestCtx) {
  156. t.Errorf("RequestCtx = %v, want %v", rd.RequestCtx, wrequestCtx)
  157. }
  158. s.Append(rd.Entries)
  159. if rd.SoftState.Lead == r.id {
  160. n.Advance()
  161. break
  162. }
  163. n.Advance()
  164. }
  165. r.step = appendStep
  166. wrequestCtx = []byte("somedata2")
  167. n.ReadIndex(context.TODO(), wrequestCtx)
  168. n.Stop()
  169. if len(msgs) != 1 {
  170. t.Fatalf("len(msgs) = %d, want %d", len(msgs), 1)
  171. }
  172. if msgs[0].Type != raftpb.MsgReadIndex {
  173. t.Errorf("msg type = %d, want %d", msgs[0].Type, raftpb.MsgReadIndex)
  174. }
  175. if !bytes.Equal(msgs[0].Entries[0].Data, wrequestCtx) {
  176. t.Errorf("data = %v, want %v", msgs[0].Entries[0].Data, wrequestCtx)
  177. }
  178. }
  179. // TestNodeProposeConfig ensures that node.ProposeConfChange sends the given configuration proposal
  180. // to the underlying raft.
  181. func TestNodeProposeConfig(t *testing.T) {
  182. msgs := []raftpb.Message{}
  183. appendStep := func(r *raft, m raftpb.Message) {
  184. msgs = append(msgs, m)
  185. }
  186. n := newNode()
  187. s := NewMemoryStorage()
  188. r := newTestRaft(1, []uint64{1}, 10, 1, s)
  189. go n.run(r)
  190. n.Campaign(context.TODO())
  191. for {
  192. rd := <-n.Ready()
  193. s.Append(rd.Entries)
  194. // change the step function to appendStep until this raft becomes leader
  195. if rd.SoftState.Lead == r.id {
  196. r.step = appendStep
  197. n.Advance()
  198. break
  199. }
  200. n.Advance()
  201. }
  202. cc := raftpb.ConfChange{Type: raftpb.ConfChangeAddNode, NodeID: 1}
  203. ccdata, err := cc.Marshal()
  204. if err != nil {
  205. t.Fatal(err)
  206. }
  207. n.ProposeConfChange(context.TODO(), cc)
  208. n.Stop()
  209. if len(msgs) != 1 {
  210. t.Fatalf("len(msgs) = %d, want %d", len(msgs), 1)
  211. }
  212. if msgs[0].Type != raftpb.MsgProp {
  213. t.Errorf("msg type = %d, want %d", msgs[0].Type, raftpb.MsgProp)
  214. }
  215. if !bytes.Equal(msgs[0].Entries[0].Data, ccdata) {
  216. t.Errorf("data = %v, want %v", msgs[0].Entries[0].Data, ccdata)
  217. }
  218. }
  219. // TestBlockProposal ensures that node will block proposal when it does not
  220. // know who is the current leader; node will accept proposal when it knows
  221. // who is the current leader.
  222. func TestBlockProposal(t *testing.T) {
  223. n := newNode()
  224. r := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  225. go n.run(r)
  226. defer n.Stop()
  227. errc := make(chan error, 1)
  228. go func() {
  229. errc <- n.Propose(context.TODO(), []byte("somedata"))
  230. }()
  231. testutil.WaitSchedule()
  232. select {
  233. case err := <-errc:
  234. t.Errorf("err = %v, want blocking", err)
  235. default:
  236. }
  237. n.Campaign(context.TODO())
  238. select {
  239. case err := <-errc:
  240. if err != nil {
  241. t.Errorf("err = %v, want %v", err, nil)
  242. }
  243. case <-time.After(10 * time.Second):
  244. t.Errorf("blocking proposal, want unblocking")
  245. }
  246. }
  247. // TestNodeTick ensures that node.Tick() will increase the
  248. // elapsed of the underlying raft state machine.
  249. func TestNodeTick(t *testing.T) {
  250. n := newNode()
  251. s := NewMemoryStorage()
  252. r := newTestRaft(1, []uint64{1}, 10, 1, s)
  253. go n.run(r)
  254. elapsed := r.electionElapsed
  255. n.Tick()
  256. testutil.WaitSchedule()
  257. n.Stop()
  258. if r.electionElapsed != elapsed+1 {
  259. t.Errorf("elapsed = %d, want %d", r.electionElapsed, elapsed+1)
  260. }
  261. }
  262. // TestNodeStop ensures that node.Stop() blocks until the node has stopped
  263. // processing, and that it is idempotent
  264. func TestNodeStop(t *testing.T) {
  265. n := newNode()
  266. s := NewMemoryStorage()
  267. r := newTestRaft(1, []uint64{1}, 10, 1, s)
  268. donec := make(chan struct{})
  269. go func() {
  270. n.run(r)
  271. close(donec)
  272. }()
  273. elapsed := r.electionElapsed
  274. n.Tick()
  275. testutil.WaitSchedule()
  276. n.Stop()
  277. select {
  278. case <-donec:
  279. case <-time.After(time.Second):
  280. t.Fatalf("timed out waiting for node to stop!")
  281. }
  282. if r.electionElapsed != elapsed+1 {
  283. t.Errorf("elapsed = %d, want %d", r.electionElapsed, elapsed+1)
  284. }
  285. // Further ticks should have no effect, the node is stopped.
  286. n.Tick()
  287. if r.electionElapsed != elapsed+1 {
  288. t.Errorf("elapsed = %d, want %d", r.electionElapsed, elapsed+1)
  289. }
  290. // Subsequent Stops should have no effect.
  291. n.Stop()
  292. }
  293. func TestReadyContainUpdates(t *testing.T) {
  294. tests := []struct {
  295. rd Ready
  296. wcontain bool
  297. }{
  298. {Ready{}, false},
  299. {Ready{SoftState: &SoftState{Lead: 1}}, true},
  300. {Ready{HardState: raftpb.HardState{Vote: 1}}, true},
  301. {Ready{Entries: make([]raftpb.Entry, 1, 1)}, true},
  302. {Ready{CommittedEntries: make([]raftpb.Entry, 1, 1)}, true},
  303. {Ready{Messages: make([]raftpb.Message, 1, 1)}, true},
  304. {Ready{Snapshot: raftpb.Snapshot{Metadata: raftpb.SnapshotMetadata{Index: 1}}}, true},
  305. }
  306. for i, tt := range tests {
  307. if g := tt.rd.containsUpdates(); g != tt.wcontain {
  308. t.Errorf("#%d: containUpdates = %v, want %v", i, g, tt.wcontain)
  309. }
  310. }
  311. }
  312. // TestNodeStart ensures that a node can be started correctly. The node should
  313. // start with correct configuration change entries, and can accept and commit
  314. // proposals.
  315. func TestNodeStart(t *testing.T) {
  316. ctx, cancel := context.WithCancel(context.Background())
  317. defer cancel()
  318. cc := raftpb.ConfChange{Type: raftpb.ConfChangeAddNode, NodeID: 1}
  319. ccdata, err := cc.Marshal()
  320. if err != nil {
  321. t.Fatalf("unexpected marshal error: %v", err)
  322. }
  323. wants := []Ready{
  324. {
  325. HardState: raftpb.HardState{Term: 1, Commit: 1, Vote: 0},
  326. Entries: []raftpb.Entry{
  327. {Type: raftpb.EntryConfChange, Term: 1, Index: 1, Data: ccdata},
  328. },
  329. CommittedEntries: []raftpb.Entry{
  330. {Type: raftpb.EntryConfChange, Term: 1, Index: 1, Data: ccdata},
  331. },
  332. },
  333. {
  334. HardState: raftpb.HardState{Term: 2, Commit: 3, Vote: 1},
  335. Entries: []raftpb.Entry{{Term: 2, Index: 3, Data: []byte("foo")}},
  336. CommittedEntries: []raftpb.Entry{{Term: 2, Index: 3, Data: []byte("foo")}},
  337. },
  338. }
  339. storage := NewMemoryStorage()
  340. c := &Config{
  341. ID: 1,
  342. ElectionTick: 10,
  343. HeartbeatTick: 1,
  344. Storage: storage,
  345. MaxSizePerMsg: noLimit,
  346. MaxInflightMsgs: 256,
  347. }
  348. n := StartNode(c, []Peer{{ID: 1}})
  349. defer n.Stop()
  350. g := <-n.Ready()
  351. if !reflect.DeepEqual(g, wants[0]) {
  352. t.Fatalf("#%d: g = %+v,\n w %+v", 1, g, wants[0])
  353. } else {
  354. storage.Append(g.Entries)
  355. n.Advance()
  356. }
  357. n.Campaign(ctx)
  358. rd := <-n.Ready()
  359. storage.Append(rd.Entries)
  360. n.Advance()
  361. n.Propose(ctx, []byte("foo"))
  362. if g2 := <-n.Ready(); !reflect.DeepEqual(g2, wants[1]) {
  363. t.Errorf("#%d: g = %+v,\n w %+v", 2, g2, wants[1])
  364. } else {
  365. storage.Append(g2.Entries)
  366. n.Advance()
  367. }
  368. select {
  369. case rd := <-n.Ready():
  370. t.Errorf("unexpected Ready: %+v", rd)
  371. case <-time.After(time.Millisecond):
  372. }
  373. }
  374. func TestNodeRestart(t *testing.T) {
  375. entries := []raftpb.Entry{
  376. {Term: 1, Index: 1},
  377. {Term: 1, Index: 2, Data: []byte("foo")},
  378. }
  379. st := raftpb.HardState{Term: 1, Commit: 1}
  380. want := Ready{
  381. HardState: st,
  382. // commit up to index commit index in st
  383. CommittedEntries: entries[:st.Commit],
  384. }
  385. storage := NewMemoryStorage()
  386. storage.SetHardState(st)
  387. storage.Append(entries)
  388. c := &Config{
  389. ID: 1,
  390. ElectionTick: 10,
  391. HeartbeatTick: 1,
  392. Storage: storage,
  393. MaxSizePerMsg: noLimit,
  394. MaxInflightMsgs: 256,
  395. }
  396. n := RestartNode(c)
  397. defer n.Stop()
  398. if g := <-n.Ready(); !reflect.DeepEqual(g, want) {
  399. t.Errorf("g = %+v,\n w %+v", g, want)
  400. }
  401. n.Advance()
  402. select {
  403. case rd := <-n.Ready():
  404. t.Errorf("unexpected Ready: %+v", rd)
  405. case <-time.After(time.Millisecond):
  406. }
  407. }
  408. func TestNodeRestartFromSnapshot(t *testing.T) {
  409. snap := raftpb.Snapshot{
  410. Metadata: raftpb.SnapshotMetadata{
  411. ConfState: raftpb.ConfState{Nodes: []uint64{1, 2}},
  412. Index: 2,
  413. Term: 1,
  414. },
  415. }
  416. entries := []raftpb.Entry{
  417. {Term: 1, Index: 3, Data: []byte("foo")},
  418. }
  419. st := raftpb.HardState{Term: 1, Commit: 3}
  420. want := Ready{
  421. HardState: st,
  422. // commit up to index commit index in st
  423. CommittedEntries: entries,
  424. }
  425. s := NewMemoryStorage()
  426. s.SetHardState(st)
  427. s.ApplySnapshot(snap)
  428. s.Append(entries)
  429. c := &Config{
  430. ID: 1,
  431. ElectionTick: 10,
  432. HeartbeatTick: 1,
  433. Storage: s,
  434. MaxSizePerMsg: noLimit,
  435. MaxInflightMsgs: 256,
  436. }
  437. n := RestartNode(c)
  438. defer n.Stop()
  439. if g := <-n.Ready(); !reflect.DeepEqual(g, want) {
  440. t.Errorf("g = %+v,\n w %+v", g, want)
  441. } else {
  442. n.Advance()
  443. }
  444. select {
  445. case rd := <-n.Ready():
  446. t.Errorf("unexpected Ready: %+v", rd)
  447. case <-time.After(time.Millisecond):
  448. }
  449. }
  450. func TestNodeAdvance(t *testing.T) {
  451. ctx, cancel := context.WithCancel(context.Background())
  452. defer cancel()
  453. storage := NewMemoryStorage()
  454. c := &Config{
  455. ID: 1,
  456. ElectionTick: 10,
  457. HeartbeatTick: 1,
  458. Storage: storage,
  459. MaxSizePerMsg: noLimit,
  460. MaxInflightMsgs: 256,
  461. }
  462. n := StartNode(c, []Peer{{ID: 1}})
  463. defer n.Stop()
  464. rd := <-n.Ready()
  465. storage.Append(rd.Entries)
  466. n.Advance()
  467. n.Campaign(ctx)
  468. <-n.Ready()
  469. n.Propose(ctx, []byte("foo"))
  470. select {
  471. case rd = <-n.Ready():
  472. t.Fatalf("unexpected Ready before Advance: %+v", rd)
  473. case <-time.After(time.Millisecond):
  474. }
  475. storage.Append(rd.Entries)
  476. n.Advance()
  477. select {
  478. case <-n.Ready():
  479. case <-time.After(100 * time.Millisecond):
  480. t.Errorf("expect Ready after Advance, but there is no Ready available")
  481. }
  482. }
  483. func TestSoftStateEqual(t *testing.T) {
  484. tests := []struct {
  485. st *SoftState
  486. we bool
  487. }{
  488. {&SoftState{}, true},
  489. {&SoftState{Lead: 1}, false},
  490. {&SoftState{RaftState: StateLeader}, false},
  491. }
  492. for i, tt := range tests {
  493. if g := tt.st.equal(&SoftState{}); g != tt.we {
  494. t.Errorf("#%d, equal = %v, want %v", i, g, tt.we)
  495. }
  496. }
  497. }
  498. func TestIsHardStateEqual(t *testing.T) {
  499. tests := []struct {
  500. st raftpb.HardState
  501. we bool
  502. }{
  503. {emptyState, true},
  504. {raftpb.HardState{Vote: 1}, false},
  505. {raftpb.HardState{Commit: 1}, false},
  506. {raftpb.HardState{Term: 1}, false},
  507. }
  508. for i, tt := range tests {
  509. if isHardStateEqual(tt.st, emptyState) != tt.we {
  510. t.Errorf("#%d, equal = %v, want %v", i, isHardStateEqual(tt.st, emptyState), tt.we)
  511. }
  512. }
  513. }