node_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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 {
  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. testutil.WaitSchedule()
  193. select {
  194. case err := <-errc:
  195. if err != nil {
  196. t.Errorf("err = %v, want %v", err, nil)
  197. }
  198. default:
  199. t.Errorf("blocking proposal, want unblocking")
  200. }
  201. }
  202. // TestNodeTick ensures that node.Tick() will increase the
  203. // elapsed of the underlying raft state machine.
  204. func TestNodeTick(t *testing.T) {
  205. n := newNode()
  206. s := NewMemoryStorage()
  207. r := newTestRaft(1, []uint64{1}, 10, 1, s)
  208. go n.run(r)
  209. elapsed := r.elapsed
  210. n.Tick()
  211. n.Stop()
  212. if r.elapsed != elapsed+1 {
  213. t.Errorf("elapsed = %d, want %d", r.elapsed, 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.elapsed
  228. n.Tick()
  229. n.Stop()
  230. select {
  231. case <-donec:
  232. case <-time.After(time.Second):
  233. t.Fatalf("timed out waiting for node to stop!")
  234. }
  235. if r.elapsed != elapsed+1 {
  236. t.Errorf("elapsed = %d, want %d", r.elapsed, elapsed+1)
  237. }
  238. // Further ticks should have no effect, the node is stopped.
  239. n.Tick()
  240. if r.elapsed != elapsed+1 {
  241. t.Errorf("elapsed = %d, want %d", r.elapsed, elapsed+1)
  242. }
  243. // Subsequent Stops should have no effect.
  244. n.Stop()
  245. }
  246. func TestReadyContainUpdates(t *testing.T) {
  247. tests := []struct {
  248. rd Ready
  249. wcontain bool
  250. }{
  251. {Ready{}, false},
  252. {Ready{SoftState: &SoftState{Lead: 1}}, true},
  253. {Ready{HardState: raftpb.HardState{Vote: 1}}, true},
  254. {Ready{Entries: make([]raftpb.Entry, 1, 1)}, true},
  255. {Ready{CommittedEntries: make([]raftpb.Entry, 1, 1)}, true},
  256. {Ready{Messages: make([]raftpb.Message, 1, 1)}, true},
  257. {Ready{Snapshot: raftpb.Snapshot{Metadata: raftpb.SnapshotMetadata{Index: 1}}}, true},
  258. }
  259. for i, tt := range tests {
  260. if g := tt.rd.containsUpdates(); g != tt.wcontain {
  261. t.Errorf("#%d: containUpdates = %v, want %v", i, g, tt.wcontain)
  262. }
  263. }
  264. }
  265. // TestNodeStart ensures that a node can be started correctly. The node should
  266. // start with correct configuration change entries, and can accept and commit
  267. // proposals.
  268. func TestNodeStart(t *testing.T) {
  269. ctx, cancel := context.WithCancel(context.Background())
  270. defer cancel()
  271. cc := raftpb.ConfChange{Type: raftpb.ConfChangeAddNode, NodeID: 1}
  272. ccdata, err := cc.Marshal()
  273. if err != nil {
  274. t.Fatalf("unexpected marshal error: %v", err)
  275. }
  276. wants := []Ready{
  277. {
  278. SoftState: &SoftState{Lead: 1, RaftState: StateLeader},
  279. HardState: raftpb.HardState{Term: 2, Commit: 2, Vote: 1},
  280. Entries: []raftpb.Entry{
  281. {Type: raftpb.EntryConfChange, Term: 1, Index: 1, Data: ccdata},
  282. {Term: 2, Index: 2},
  283. },
  284. CommittedEntries: []raftpb.Entry{
  285. {Type: raftpb.EntryConfChange, Term: 1, Index: 1, Data: ccdata},
  286. {Term: 2, Index: 2},
  287. },
  288. },
  289. {
  290. HardState: raftpb.HardState{Term: 2, Commit: 3, Vote: 1},
  291. Entries: []raftpb.Entry{{Term: 2, Index: 3, Data: []byte("foo")}},
  292. CommittedEntries: []raftpb.Entry{{Term: 2, Index: 3, Data: []byte("foo")}},
  293. },
  294. }
  295. storage := NewMemoryStorage()
  296. c := &Config{
  297. ID: 1,
  298. ElectionTick: 10,
  299. HeartbeatTick: 1,
  300. Storage: storage,
  301. MaxSizePerMsg: noLimit,
  302. MaxInflightMsgs: 256,
  303. }
  304. n := StartNode(c, []Peer{{ID: 1}})
  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. if g := <-n.Ready(); !reflect.DeepEqual(g, want) {
  350. t.Errorf("g = %+v,\n w %+v", g, want)
  351. }
  352. n.Advance()
  353. select {
  354. case rd := <-n.Ready():
  355. t.Errorf("unexpected Ready: %+v", rd)
  356. case <-time.After(time.Millisecond):
  357. }
  358. }
  359. func TestNodeRestartFromSnapshot(t *testing.T) {
  360. snap := raftpb.Snapshot{
  361. Metadata: raftpb.SnapshotMetadata{
  362. ConfState: raftpb.ConfState{Nodes: []uint64{1, 2}},
  363. Index: 2,
  364. Term: 1,
  365. },
  366. }
  367. entries := []raftpb.Entry{
  368. {Term: 1, Index: 3, Data: []byte("foo")},
  369. }
  370. st := raftpb.HardState{Term: 1, Commit: 3}
  371. want := Ready{
  372. HardState: st,
  373. // commit up to index commit index in st
  374. CommittedEntries: entries,
  375. }
  376. s := NewMemoryStorage()
  377. s.SetHardState(st)
  378. s.ApplySnapshot(snap)
  379. s.Append(entries)
  380. c := &Config{
  381. ID: 1,
  382. ElectionTick: 10,
  383. HeartbeatTick: 1,
  384. Storage: s,
  385. MaxSizePerMsg: noLimit,
  386. MaxInflightMsgs: 256,
  387. }
  388. n := RestartNode(c)
  389. if g := <-n.Ready(); !reflect.DeepEqual(g, want) {
  390. t.Errorf("g = %+v,\n w %+v", g, want)
  391. } else {
  392. n.Advance()
  393. }
  394. select {
  395. case rd := <-n.Ready():
  396. t.Errorf("unexpected Ready: %+v", rd)
  397. case <-time.After(time.Millisecond):
  398. }
  399. }
  400. func TestNodeAdvance(t *testing.T) {
  401. ctx, cancel := context.WithCancel(context.Background())
  402. defer cancel()
  403. storage := NewMemoryStorage()
  404. c := &Config{
  405. ID: 1,
  406. ElectionTick: 10,
  407. HeartbeatTick: 1,
  408. Storage: storage,
  409. MaxSizePerMsg: noLimit,
  410. MaxInflightMsgs: 256,
  411. }
  412. n := StartNode(c, []Peer{{ID: 1}})
  413. n.Campaign(ctx)
  414. <-n.Ready()
  415. n.Propose(ctx, []byte("foo"))
  416. var rd Ready
  417. select {
  418. case rd = <-n.Ready():
  419. t.Fatalf("unexpected Ready before Advance: %+v", rd)
  420. case <-time.After(time.Millisecond):
  421. }
  422. storage.Append(rd.Entries)
  423. n.Advance()
  424. select {
  425. case <-n.Ready():
  426. case <-time.After(time.Millisecond):
  427. t.Errorf("expect Ready after Advance, but there is no Ready available")
  428. }
  429. }
  430. func TestSoftStateEqual(t *testing.T) {
  431. tests := []struct {
  432. st *SoftState
  433. we bool
  434. }{
  435. {&SoftState{}, true},
  436. {&SoftState{Lead: 1}, false},
  437. {&SoftState{RaftState: StateLeader}, false},
  438. }
  439. for i, tt := range tests {
  440. if g := tt.st.equal(&SoftState{}); g != tt.we {
  441. t.Errorf("#%d, equal = %v, want %v", i, g, tt.we)
  442. }
  443. }
  444. }
  445. func TestIsHardStateEqual(t *testing.T) {
  446. tests := []struct {
  447. st raftpb.HardState
  448. we bool
  449. }{
  450. {emptyState, true},
  451. {raftpb.HardState{Vote: 1}, false},
  452. {raftpb.HardState{Commit: 1}, false},
  453. {raftpb.HardState{Term: 1}, false},
  454. }
  455. for i, tt := range tests {
  456. if isHardStateEqual(tt.st, emptyState) != tt.we {
  457. t.Errorf("#%d, equal = %v, want %v", i, isHardStateEqual(tt.st, emptyState), tt.we)
  458. }
  459. }
  460. }