node_test.go 12 KB

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