node_test.go 13 KB

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