node_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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. "reflect"
  17. "testing"
  18. "time"
  19. "github.com/coreos/etcd/pkg/testutil"
  20. "github.com/coreos/etcd/raft/raftpb"
  21. "golang.org/x/net/context"
  22. )
  23. // TestNodeStep ensures that node.Step sends msgProp to propc chan
  24. // and other kinds of messages to recvc chan.
  25. func TestNodeStep(t *testing.T) {
  26. for i, msgn := range raftpb.MessageType_name {
  27. n := &node{
  28. propc: make(chan raftpb.Message, 1),
  29. recvc: make(chan raftpb.Message, 1),
  30. }
  31. msgt := raftpb.MessageType(i)
  32. n.Step(context.TODO(), raftpb.Message{Type: msgt})
  33. // Proposal goes to proc chan. Others go to recvc chan.
  34. if msgt == raftpb.MsgProp {
  35. select {
  36. case <-n.propc:
  37. default:
  38. t.Errorf("%d: cannot receive %s on propc chan", msgt, msgn)
  39. }
  40. } else {
  41. if IsLocalMsg(msgt) {
  42. select {
  43. case <-n.recvc:
  44. t.Errorf("%d: step should ignore %s", msgt, msgn)
  45. default:
  46. }
  47. } else {
  48. select {
  49. case <-n.recvc:
  50. default:
  51. t.Errorf("%d: cannot receive %s on recvc chan", msgt, msgn)
  52. }
  53. }
  54. }
  55. }
  56. }
  57. // Cancel and Stop should unblock Step()
  58. func TestNodeStepUnblock(t *testing.T) {
  59. // a node without buffer to block step
  60. n := &node{
  61. propc: make(chan raftpb.Message),
  62. done: make(chan struct{}),
  63. }
  64. ctx, cancel := context.WithCancel(context.Background())
  65. stopFunc := func() { close(n.done) }
  66. tests := []struct {
  67. unblock func()
  68. werr error
  69. }{
  70. {stopFunc, ErrStopped},
  71. {cancel, context.Canceled},
  72. }
  73. for i, tt := range tests {
  74. errc := make(chan error, 1)
  75. go func() {
  76. err := n.Step(ctx, raftpb.Message{Type: raftpb.MsgProp})
  77. errc <- err
  78. }()
  79. tt.unblock()
  80. select {
  81. case err := <-errc:
  82. if err != tt.werr {
  83. t.Errorf("#%d: err = %v, want %v", i, err, tt.werr)
  84. }
  85. //clean up side-effect
  86. if ctx.Err() != nil {
  87. ctx = context.TODO()
  88. }
  89. select {
  90. case <-n.done:
  91. n.done = make(chan struct{})
  92. default:
  93. }
  94. case <-time.After(1 * time.Second):
  95. t.Fatalf("#%d: failed to unblock step", i)
  96. }
  97. }
  98. }
  99. // TestNodePropose ensures that node.Propose sends the given proposal to the underlying raft.
  100. func TestNodePropose(t *testing.T) {
  101. msgs := []raftpb.Message{}
  102. appendStep := func(r *raft, m raftpb.Message) {
  103. msgs = append(msgs, m)
  104. }
  105. n := newNode()
  106. s := NewMemoryStorage()
  107. r := newTestRaft(1, []uint64{1}, 10, 1, s)
  108. go n.run(r)
  109. n.Campaign(context.TODO())
  110. for {
  111. rd := <-n.Ready()
  112. s.Append(rd.Entries)
  113. // change the step function to appendStep until this raft becomes leader
  114. if rd.SoftState.Lead == r.id {
  115. r.step = appendStep
  116. n.Advance()
  117. break
  118. }
  119. n.Advance()
  120. }
  121. n.Propose(context.TODO(), []byte("somedata"))
  122. n.Stop()
  123. if len(msgs) != 1 {
  124. t.Fatalf("len(msgs) = %d, want %d", len(msgs), 1)
  125. }
  126. if msgs[0].Type != raftpb.MsgProp {
  127. t.Errorf("msg type = %d, want %d", msgs[0].Type, raftpb.MsgProp)
  128. }
  129. if !reflect.DeepEqual(msgs[0].Entries[0].Data, []byte("somedata")) {
  130. t.Errorf("data = %v, want %v", msgs[0].Entries[0].Data, []byte("somedata"))
  131. }
  132. }
  133. // TestNodeReadIndex ensures that node.ReadIndex sends the MsgReadIndex message to the underlying raft.
  134. // It also ensures that ReadState can be read out through ready chan.
  135. func TestNodeReadIndex(t *testing.T) {
  136. msgs := []raftpb.Message{}
  137. appendStep := func(r *raft, m raftpb.Message) {
  138. msgs = append(msgs, m)
  139. }
  140. wreadIndex := uint64(1)
  141. wrequestCtx := []byte("somedata")
  142. n := newNode()
  143. s := NewMemoryStorage()
  144. r := newTestRaft(1, []uint64{1}, 10, 1, s)
  145. r.readState.Index = wreadIndex
  146. r.readState.RequestCtx = wrequestCtx
  147. go n.run(r)
  148. n.Campaign(context.TODO())
  149. for {
  150. rd := <-n.Ready()
  151. if rd.Index != wreadIndex {
  152. t.Errorf("ReadIndex = %d, want %d", rd.Index, wreadIndex)
  153. }
  154. if !reflect.DeepEqual(rd.RequestCtx, wrequestCtx) {
  155. t.Errorf("RequestCtx = %v, want %v", rd.RequestCtx, wrequestCtx)
  156. }
  157. s.Append(rd.Entries)
  158. if rd.SoftState.Lead == r.id {
  159. n.Advance()
  160. break
  161. }
  162. n.Advance()
  163. }
  164. r.step = appendStep
  165. wrequestCtx = []byte("somedata2")
  166. n.ReadIndex(context.TODO(), wrequestCtx)
  167. n.Stop()
  168. if len(msgs) != 1 {
  169. t.Fatalf("len(msgs) = %d, want %d", len(msgs), 1)
  170. }
  171. if msgs[0].Type != raftpb.MsgReadIndex {
  172. t.Errorf("msg type = %d, want %d", msgs[0].Type, raftpb.MsgReadIndex)
  173. }
  174. if !reflect.DeepEqual(msgs[0].Entries[0].Data, wrequestCtx) {
  175. t.Errorf("data = %v, want %v", msgs[0].Entries[0].Data, wrequestCtx)
  176. }
  177. }
  178. // TestNodeProposeConfig ensures that node.ProposeConfChange sends the given configuration proposal
  179. // to the underlying raft.
  180. func TestNodeProposeConfig(t *testing.T) {
  181. msgs := []raftpb.Message{}
  182. appendStep := func(r *raft, m raftpb.Message) {
  183. msgs = append(msgs, m)
  184. }
  185. n := newNode()
  186. s := NewMemoryStorage()
  187. r := newTestRaft(1, []uint64{1}, 10, 1, s)
  188. go n.run(r)
  189. n.Campaign(context.TODO())
  190. for {
  191. rd := <-n.Ready()
  192. s.Append(rd.Entries)
  193. // change the step function to appendStep until this raft becomes leader
  194. if rd.SoftState.Lead == r.id {
  195. r.step = appendStep
  196. n.Advance()
  197. break
  198. }
  199. n.Advance()
  200. }
  201. cc := raftpb.ConfChange{Type: raftpb.ConfChangeAddNode, NodeID: 1}
  202. ccdata, err := cc.Marshal()
  203. if err != nil {
  204. t.Fatal(err)
  205. }
  206. n.ProposeConfChange(context.TODO(), cc)
  207. n.Stop()
  208. if len(msgs) != 1 {
  209. t.Fatalf("len(msgs) = %d, want %d", len(msgs), 1)
  210. }
  211. if msgs[0].Type != raftpb.MsgProp {
  212. t.Errorf("msg type = %d, want %d", msgs[0].Type, raftpb.MsgProp)
  213. }
  214. if !reflect.DeepEqual(msgs[0].Entries[0].Data, ccdata) {
  215. t.Errorf("data = %v, want %v", msgs[0].Entries[0].Data, ccdata)
  216. }
  217. }
  218. // TestBlockProposal ensures that node will block proposal when it does not
  219. // know who is the current leader; node will accept proposal when it knows
  220. // who is the current leader.
  221. func TestBlockProposal(t *testing.T) {
  222. n := newNode()
  223. r := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
  224. go n.run(r)
  225. defer n.Stop()
  226. errc := make(chan error, 1)
  227. go func() {
  228. errc <- n.Propose(context.TODO(), []byte("somedata"))
  229. }()
  230. testutil.WaitSchedule()
  231. select {
  232. case err := <-errc:
  233. t.Errorf("err = %v, want blocking", err)
  234. default:
  235. }
  236. n.Campaign(context.TODO())
  237. select {
  238. case err := <-errc:
  239. if err != nil {
  240. t.Errorf("err = %v, want %v", err, nil)
  241. }
  242. case <-time.After(10 * time.Second):
  243. t.Errorf("blocking proposal, want unblocking")
  244. }
  245. }
  246. // TestNodeTick ensures that node.Tick() will increase the
  247. // elapsed of the underlying raft state machine.
  248. func TestNodeTick(t *testing.T) {
  249. n := newNode()
  250. s := NewMemoryStorage()
  251. r := newTestRaft(1, []uint64{1}, 10, 1, s)
  252. go n.run(r)
  253. elapsed := r.electionElapsed
  254. n.Tick()
  255. testutil.WaitSchedule()
  256. n.Stop()
  257. if r.electionElapsed != elapsed+1 {
  258. t.Errorf("elapsed = %d, want %d", r.electionElapsed, elapsed+1)
  259. }
  260. }
  261. // TestNodeStop ensures that node.Stop() blocks until the node has stopped
  262. // processing, and that it is idempotent
  263. func TestNodeStop(t *testing.T) {
  264. n := newNode()
  265. s := NewMemoryStorage()
  266. r := newTestRaft(1, []uint64{1}, 10, 1, s)
  267. donec := make(chan struct{})
  268. go func() {
  269. n.run(r)
  270. close(donec)
  271. }()
  272. elapsed := r.electionElapsed
  273. n.Tick()
  274. testutil.WaitSchedule()
  275. n.Stop()
  276. select {
  277. case <-donec:
  278. case <-time.After(time.Second):
  279. t.Fatalf("timed out waiting for node to stop!")
  280. }
  281. if r.electionElapsed != elapsed+1 {
  282. t.Errorf("elapsed = %d, want %d", r.electionElapsed, elapsed+1)
  283. }
  284. // Further ticks should have no effect, the node is stopped.
  285. n.Tick()
  286. if r.electionElapsed != elapsed+1 {
  287. t.Errorf("elapsed = %d, want %d", r.electionElapsed, elapsed+1)
  288. }
  289. // Subsequent Stops should have no effect.
  290. n.Stop()
  291. }
  292. func TestReadyContainUpdates(t *testing.T) {
  293. tests := []struct {
  294. rd Ready
  295. wcontain bool
  296. }{
  297. {Ready{}, false},
  298. {Ready{SoftState: &SoftState{Lead: 1}}, true},
  299. {Ready{HardState: raftpb.HardState{Vote: 1}}, true},
  300. {Ready{Entries: make([]raftpb.Entry, 1, 1)}, true},
  301. {Ready{CommittedEntries: make([]raftpb.Entry, 1, 1)}, true},
  302. {Ready{Messages: make([]raftpb.Message, 1, 1)}, true},
  303. {Ready{Snapshot: raftpb.Snapshot{Metadata: raftpb.SnapshotMetadata{Index: 1}}}, true},
  304. }
  305. for i, tt := range tests {
  306. if g := tt.rd.containsUpdates(); g != tt.wcontain {
  307. t.Errorf("#%d: containUpdates = %v, want %v", i, g, tt.wcontain)
  308. }
  309. }
  310. }
  311. // TestNodeStart ensures that a node can be started correctly. The node should
  312. // start with correct configuration change entries, and can accept and commit
  313. // proposals.
  314. func TestNodeStart(t *testing.T) {
  315. ctx, cancel := context.WithCancel(context.Background())
  316. defer cancel()
  317. cc := raftpb.ConfChange{Type: raftpb.ConfChangeAddNode, NodeID: 1}
  318. ccdata, err := cc.Marshal()
  319. if err != nil {
  320. t.Fatalf("unexpected marshal error: %v", err)
  321. }
  322. wants := []Ready{
  323. {
  324. SoftState: &SoftState{Lead: 1, RaftState: StateLeader},
  325. HardState: raftpb.HardState{Term: 2, Commit: 2, Vote: 1},
  326. Entries: []raftpb.Entry{
  327. {Type: raftpb.EntryConfChange, Term: 1, Index: 1, Data: ccdata},
  328. {Term: 2, Index: 2},
  329. },
  330. CommittedEntries: []raftpb.Entry{
  331. {Type: raftpb.EntryConfChange, Term: 1, Index: 1, Data: ccdata},
  332. {Term: 2, Index: 2},
  333. },
  334. },
  335. {
  336. HardState: raftpb.HardState{Term: 2, Commit: 3, Vote: 1},
  337. Entries: []raftpb.Entry{{Term: 2, Index: 3, Data: []byte("foo")}},
  338. CommittedEntries: []raftpb.Entry{{Term: 2, Index: 3, Data: []byte("foo")}},
  339. },
  340. }
  341. storage := NewMemoryStorage()
  342. c := &Config{
  343. ID: 1,
  344. ElectionTick: 10,
  345. HeartbeatTick: 1,
  346. Storage: storage,
  347. MaxSizePerMsg: noLimit,
  348. MaxInflightMsgs: 256,
  349. }
  350. n := StartNode(c, []Peer{{ID: 1}})
  351. defer n.Stop()
  352. n.Campaign(ctx)
  353. g := <-n.Ready()
  354. if !reflect.DeepEqual(g, wants[0]) {
  355. t.Fatalf("#%d: g = %+v,\n w %+v", 1, g, wants[0])
  356. } else {
  357. storage.Append(g.Entries)
  358. n.Advance()
  359. }
  360. n.Propose(ctx, []byte("foo"))
  361. if g2 := <-n.Ready(); !reflect.DeepEqual(g2, wants[1]) {
  362. t.Errorf("#%d: g = %+v,\n w %+v", 2, g2, wants[1])
  363. } else {
  364. storage.Append(g2.Entries)
  365. n.Advance()
  366. }
  367. select {
  368. case rd := <-n.Ready():
  369. t.Errorf("unexpected Ready: %+v", rd)
  370. case <-time.After(time.Millisecond):
  371. }
  372. }
  373. func TestNodeRestart(t *testing.T) {
  374. entries := []raftpb.Entry{
  375. {Term: 1, Index: 1},
  376. {Term: 1, Index: 2, Data: []byte("foo")},
  377. }
  378. st := raftpb.HardState{Term: 1, Commit: 1}
  379. want := Ready{
  380. HardState: st,
  381. // commit up to index commit index in st
  382. CommittedEntries: entries[:st.Commit],
  383. }
  384. storage := NewMemoryStorage()
  385. storage.SetHardState(st)
  386. storage.Append(entries)
  387. c := &Config{
  388. ID: 1,
  389. ElectionTick: 10,
  390. HeartbeatTick: 1,
  391. Storage: storage,
  392. MaxSizePerMsg: noLimit,
  393. MaxInflightMsgs: 256,
  394. }
  395. n := RestartNode(c)
  396. defer n.Stop()
  397. if g := <-n.Ready(); !reflect.DeepEqual(g, want) {
  398. t.Errorf("g = %+v,\n w %+v", g, want)
  399. }
  400. n.Advance()
  401. select {
  402. case rd := <-n.Ready():
  403. t.Errorf("unexpected Ready: %+v", rd)
  404. case <-time.After(time.Millisecond):
  405. }
  406. }
  407. func TestNodeRestartFromSnapshot(t *testing.T) {
  408. snap := raftpb.Snapshot{
  409. Metadata: raftpb.SnapshotMetadata{
  410. ConfState: raftpb.ConfState{Nodes: []uint64{1, 2}},
  411. Index: 2,
  412. Term: 1,
  413. },
  414. }
  415. entries := []raftpb.Entry{
  416. {Term: 1, Index: 3, Data: []byte("foo")},
  417. }
  418. st := raftpb.HardState{Term: 1, Commit: 3}
  419. want := Ready{
  420. HardState: st,
  421. // commit up to index commit index in st
  422. CommittedEntries: entries,
  423. }
  424. s := NewMemoryStorage()
  425. s.SetHardState(st)
  426. s.ApplySnapshot(snap)
  427. s.Append(entries)
  428. c := &Config{
  429. ID: 1,
  430. ElectionTick: 10,
  431. HeartbeatTick: 1,
  432. Storage: s,
  433. MaxSizePerMsg: noLimit,
  434. MaxInflightMsgs: 256,
  435. }
  436. n := RestartNode(c)
  437. defer n.Stop()
  438. if g := <-n.Ready(); !reflect.DeepEqual(g, want) {
  439. t.Errorf("g = %+v,\n w %+v", g, want)
  440. } else {
  441. n.Advance()
  442. }
  443. select {
  444. case rd := <-n.Ready():
  445. t.Errorf("unexpected Ready: %+v", rd)
  446. case <-time.After(time.Millisecond):
  447. }
  448. }
  449. func TestNodeAdvance(t *testing.T) {
  450. ctx, cancel := context.WithCancel(context.Background())
  451. defer cancel()
  452. storage := NewMemoryStorage()
  453. c := &Config{
  454. ID: 1,
  455. ElectionTick: 10,
  456. HeartbeatTick: 1,
  457. Storage: storage,
  458. MaxSizePerMsg: noLimit,
  459. MaxInflightMsgs: 256,
  460. }
  461. n := StartNode(c, []Peer{{ID: 1}})
  462. defer n.Stop()
  463. n.Campaign(ctx)
  464. <-n.Ready()
  465. n.Propose(ctx, []byte("foo"))
  466. var rd Ready
  467. select {
  468. case rd = <-n.Ready():
  469. t.Fatalf("unexpected Ready before Advance: %+v", rd)
  470. case <-time.After(time.Millisecond):
  471. }
  472. storage.Append(rd.Entries)
  473. n.Advance()
  474. select {
  475. case <-n.Ready():
  476. case <-time.After(100 * time.Millisecond):
  477. t.Errorf("expect Ready after Advance, but there is no Ready available")
  478. }
  479. }
  480. func TestSoftStateEqual(t *testing.T) {
  481. tests := []struct {
  482. st *SoftState
  483. we bool
  484. }{
  485. {&SoftState{}, true},
  486. {&SoftState{Lead: 1}, false},
  487. {&SoftState{RaftState: StateLeader}, false},
  488. }
  489. for i, tt := range tests {
  490. if g := tt.st.equal(&SoftState{}); g != tt.we {
  491. t.Errorf("#%d, equal = %v, want %v", i, g, tt.we)
  492. }
  493. }
  494. }
  495. func TestIsHardStateEqual(t *testing.T) {
  496. tests := []struct {
  497. st raftpb.HardState
  498. we bool
  499. }{
  500. {emptyState, true},
  501. {raftpb.HardState{Vote: 1}, false},
  502. {raftpb.HardState{Commit: 1}, false},
  503. {raftpb.HardState{Term: 1}, false},
  504. }
  505. for i, tt := range tests {
  506. if isHardStateEqual(tt.st, emptyState) != tt.we {
  507. t.Errorf("#%d, equal = %v, want %v", i, isHardStateEqual(tt.st, emptyState), tt.we)
  508. }
  509. }
  510. }