node_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. // Copyright 2015 CoreOS, Inc.
  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/Godeps/_workspace/src/golang.org/x/net/context"
  20. "github.com/coreos/etcd/pkg/testutil"
  21. "github.com/coreos/etcd/raft/raftpb"
  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 msgt == raftpb.MsgBeat || msgt == raftpb.MsgHup || msgt == raftpb.MsgUnreachable || msgt == raftpb.MsgSnapStatus || msgt == raftpb.MsgCheckQuorum {
  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(time.Millisecond * 100):
  95. t.Errorf("#%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. n.Stop()
  211. if r.electionElapsed != elapsed+1 {
  212. t.Errorf("elapsed = %d, want %d", r.electionElapsed, elapsed+1)
  213. }
  214. }
  215. // TestNodeStop ensures that node.Stop() blocks until the node has stopped
  216. // processing, and that it is idempotent
  217. func TestNodeStop(t *testing.T) {
  218. n := newNode()
  219. s := NewMemoryStorage()
  220. r := newTestRaft(1, []uint64{1}, 10, 1, s)
  221. donec := make(chan struct{})
  222. go func() {
  223. n.run(r)
  224. close(donec)
  225. }()
  226. elapsed := r.electionElapsed
  227. n.Tick()
  228. n.Stop()
  229. select {
  230. case <-donec:
  231. case <-time.After(time.Second):
  232. t.Fatalf("timed out waiting for node to stop!")
  233. }
  234. if r.electionElapsed != elapsed+1 {
  235. t.Errorf("elapsed = %d, want %d", r.electionElapsed, elapsed+1)
  236. }
  237. // Further ticks should have no effect, the node is stopped.
  238. n.Tick()
  239. if r.electionElapsed != elapsed+1 {
  240. t.Errorf("elapsed = %d, want %d", r.electionElapsed, elapsed+1)
  241. }
  242. // Subsequent Stops should have no effect.
  243. n.Stop()
  244. }
  245. func TestReadyContainUpdates(t *testing.T) {
  246. tests := []struct {
  247. rd Ready
  248. wcontain bool
  249. }{
  250. {Ready{}, false},
  251. {Ready{SoftState: &SoftState{Lead: 1}}, true},
  252. {Ready{HardState: raftpb.HardState{Vote: 1}}, true},
  253. {Ready{Entries: make([]raftpb.Entry, 1, 1)}, true},
  254. {Ready{CommittedEntries: make([]raftpb.Entry, 1, 1)}, true},
  255. {Ready{Messages: make([]raftpb.Message, 1, 1)}, true},
  256. {Ready{Snapshot: raftpb.Snapshot{Metadata: raftpb.SnapshotMetadata{Index: 1}}}, true},
  257. }
  258. for i, tt := range tests {
  259. if g := tt.rd.containsUpdates(); g != tt.wcontain {
  260. t.Errorf("#%d: containUpdates = %v, want %v", i, g, tt.wcontain)
  261. }
  262. }
  263. }
  264. // TestNodeStart ensures that a node can be started correctly. The node should
  265. // start with correct configuration change entries, and can accept and commit
  266. // proposals.
  267. func TestNodeStart(t *testing.T) {
  268. ctx, cancel := context.WithCancel(context.Background())
  269. defer cancel()
  270. cc := raftpb.ConfChange{Type: raftpb.ConfChangeAddNode, NodeID: 1}
  271. ccdata, err := cc.Marshal()
  272. if err != nil {
  273. t.Fatalf("unexpected marshal error: %v", err)
  274. }
  275. wants := []Ready{
  276. {
  277. SoftState: &SoftState{Lead: 1, RaftState: StateLeader},
  278. HardState: raftpb.HardState{Term: 2, Commit: 2, Vote: 1},
  279. Entries: []raftpb.Entry{
  280. {Type: raftpb.EntryConfChange, Term: 1, Index: 1, Data: ccdata},
  281. {Term: 2, Index: 2},
  282. },
  283. CommittedEntries: []raftpb.Entry{
  284. {Type: raftpb.EntryConfChange, Term: 1, Index: 1, Data: ccdata},
  285. {Term: 2, Index: 2},
  286. },
  287. },
  288. {
  289. HardState: raftpb.HardState{Term: 2, Commit: 3, Vote: 1},
  290. Entries: []raftpb.Entry{{Term: 2, Index: 3, Data: []byte("foo")}},
  291. CommittedEntries: []raftpb.Entry{{Term: 2, Index: 3, Data: []byte("foo")}},
  292. },
  293. }
  294. storage := NewMemoryStorage()
  295. c := &Config{
  296. ID: 1,
  297. ElectionTick: 10,
  298. HeartbeatTick: 1,
  299. Storage: storage,
  300. MaxSizePerMsg: noLimit,
  301. MaxInflightMsgs: 256,
  302. }
  303. n := StartNode(c, []Peer{{ID: 1}})
  304. defer n.Stop()
  305. n.Campaign(ctx)
  306. g := <-n.Ready()
  307. if !reflect.DeepEqual(g, wants[0]) {
  308. t.Fatalf("#%d: g = %+v,\n w %+v", 1, g, wants[0])
  309. } else {
  310. storage.Append(g.Entries)
  311. n.Advance()
  312. }
  313. n.Propose(ctx, []byte("foo"))
  314. if g2 := <-n.Ready(); !reflect.DeepEqual(g2, wants[1]) {
  315. t.Errorf("#%d: g = %+v,\n w %+v", 2, g2, wants[1])
  316. } else {
  317. storage.Append(g2.Entries)
  318. n.Advance()
  319. }
  320. select {
  321. case rd := <-n.Ready():
  322. t.Errorf("unexpected Ready: %+v", rd)
  323. case <-time.After(time.Millisecond):
  324. }
  325. }
  326. func TestNodeRestart(t *testing.T) {
  327. entries := []raftpb.Entry{
  328. {Term: 1, Index: 1},
  329. {Term: 1, Index: 2, Data: []byte("foo")},
  330. }
  331. st := raftpb.HardState{Term: 1, Commit: 1}
  332. want := Ready{
  333. HardState: st,
  334. // commit up to index commit index in st
  335. CommittedEntries: entries[:st.Commit],
  336. }
  337. storage := NewMemoryStorage()
  338. storage.SetHardState(st)
  339. storage.Append(entries)
  340. c := &Config{
  341. ID: 1,
  342. ElectionTick: 10,
  343. HeartbeatTick: 1,
  344. Storage: storage,
  345. MaxSizePerMsg: noLimit,
  346. MaxInflightMsgs: 256,
  347. }
  348. n := RestartNode(c)
  349. defer n.Stop()
  350. if g := <-n.Ready(); !reflect.DeepEqual(g, want) {
  351. t.Errorf("g = %+v,\n w %+v", g, want)
  352. }
  353. n.Advance()
  354. select {
  355. case rd := <-n.Ready():
  356. t.Errorf("unexpected Ready: %+v", rd)
  357. case <-time.After(time.Millisecond):
  358. }
  359. }
  360. func TestNodeRestartFromSnapshot(t *testing.T) {
  361. snap := raftpb.Snapshot{
  362. Metadata: raftpb.SnapshotMetadata{
  363. ConfState: raftpb.ConfState{Nodes: []uint64{1, 2}},
  364. Index: 2,
  365. Term: 1,
  366. },
  367. }
  368. entries := []raftpb.Entry{
  369. {Term: 1, Index: 3, Data: []byte("foo")},
  370. }
  371. st := raftpb.HardState{Term: 1, Commit: 3}
  372. want := Ready{
  373. HardState: st,
  374. // commit up to index commit index in st
  375. CommittedEntries: entries,
  376. }
  377. s := NewMemoryStorage()
  378. s.SetHardState(st)
  379. s.ApplySnapshot(snap)
  380. s.Append(entries)
  381. c := &Config{
  382. ID: 1,
  383. ElectionTick: 10,
  384. HeartbeatTick: 1,
  385. Storage: s,
  386. MaxSizePerMsg: noLimit,
  387. MaxInflightMsgs: 256,
  388. }
  389. n := RestartNode(c)
  390. defer n.Stop()
  391. if g := <-n.Ready(); !reflect.DeepEqual(g, want) {
  392. t.Errorf("g = %+v,\n w %+v", g, want)
  393. } else {
  394. n.Advance()
  395. }
  396. select {
  397. case rd := <-n.Ready():
  398. t.Errorf("unexpected Ready: %+v", rd)
  399. case <-time.After(time.Millisecond):
  400. }
  401. }
  402. func TestNodeAdvance(t *testing.T) {
  403. ctx, cancel := context.WithCancel(context.Background())
  404. defer cancel()
  405. storage := NewMemoryStorage()
  406. c := &Config{
  407. ID: 1,
  408. ElectionTick: 10,
  409. HeartbeatTick: 1,
  410. Storage: storage,
  411. MaxSizePerMsg: noLimit,
  412. MaxInflightMsgs: 256,
  413. }
  414. n := StartNode(c, []Peer{{ID: 1}})
  415. defer n.Stop()
  416. n.Campaign(ctx)
  417. <-n.Ready()
  418. n.Propose(ctx, []byte("foo"))
  419. var rd Ready
  420. select {
  421. case rd = <-n.Ready():
  422. t.Fatalf("unexpected Ready before Advance: %+v", rd)
  423. case <-time.After(time.Millisecond):
  424. }
  425. storage.Append(rd.Entries)
  426. n.Advance()
  427. select {
  428. case <-n.Ready():
  429. case <-time.After(100 * time.Millisecond):
  430. t.Errorf("expect Ready after Advance, but there is no Ready available")
  431. }
  432. }
  433. func TestSoftStateEqual(t *testing.T) {
  434. tests := []struct {
  435. st *SoftState
  436. we bool
  437. }{
  438. {&SoftState{}, true},
  439. {&SoftState{Lead: 1}, false},
  440. {&SoftState{RaftState: StateLeader}, false},
  441. }
  442. for i, tt := range tests {
  443. if g := tt.st.equal(&SoftState{}); g != tt.we {
  444. t.Errorf("#%d, equal = %v, want %v", i, g, tt.we)
  445. }
  446. }
  447. }
  448. func TestIsHardStateEqual(t *testing.T) {
  449. tests := []struct {
  450. st raftpb.HardState
  451. we bool
  452. }{
  453. {emptyState, true},
  454. {raftpb.HardState{Vote: 1}, false},
  455. {raftpb.HardState{Commit: 1}, false},
  456. {raftpb.HardState{Term: 1}, false},
  457. }
  458. for i, tt := range tests {
  459. if isHardStateEqual(tt.st, emptyState) != tt.we {
  460. t.Errorf("#%d, equal = %v, want %v", i, isHardStateEqual(tt.st, emptyState), tt.we)
  461. }
  462. }
  463. }