node_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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.ForceGosched()
  186. select {
  187. case err := <-errc:
  188. t.Errorf("err = %v, want blocking", err)
  189. default:
  190. }
  191. n.Campaign(context.TODO())
  192. testutil.ForceGosched()
  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. n := StartNode(1, []Peer{{ID: 1}}, 10, 1, storage)
  297. n.Campaign(ctx)
  298. g := <-n.Ready()
  299. if !reflect.DeepEqual(g, wants[0]) {
  300. t.Fatalf("#%d: g = %+v,\n w %+v", 1, g, wants[0])
  301. } else {
  302. storage.Append(g.Entries)
  303. n.Advance()
  304. }
  305. n.Propose(ctx, []byte("foo"))
  306. if g2 := <-n.Ready(); !reflect.DeepEqual(g2, wants[1]) {
  307. t.Errorf("#%d: g = %+v,\n w %+v", 2, g2, wants[1])
  308. } else {
  309. storage.Append(g2.Entries)
  310. n.Advance()
  311. }
  312. select {
  313. case rd := <-n.Ready():
  314. t.Errorf("unexpected Ready: %+v", rd)
  315. case <-time.After(time.Millisecond):
  316. }
  317. }
  318. func TestNodeRestart(t *testing.T) {
  319. entries := []raftpb.Entry{
  320. {Term: 1, Index: 1},
  321. {Term: 1, Index: 2, Data: []byte("foo")},
  322. }
  323. st := raftpb.HardState{Term: 1, Commit: 1}
  324. want := Ready{
  325. HardState: emptyState,
  326. // commit up to index commit index in st
  327. CommittedEntries: entries[:st.Commit],
  328. }
  329. storage := NewMemoryStorage()
  330. storage.SetHardState(st)
  331. storage.Append(entries)
  332. n := RestartNode(1, 10, 1, storage, 0)
  333. if g := <-n.Ready(); !reflect.DeepEqual(g, want) {
  334. t.Errorf("g = %+v,\n w %+v", g, want)
  335. }
  336. n.Advance()
  337. select {
  338. case rd := <-n.Ready():
  339. t.Errorf("unexpected Ready: %+v", rd)
  340. case <-time.After(time.Millisecond):
  341. }
  342. }
  343. func TestNodeRestartFromSnapshot(t *testing.T) {
  344. snap := raftpb.Snapshot{
  345. Metadata: raftpb.SnapshotMetadata{
  346. ConfState: raftpb.ConfState{Nodes: []uint64{1, 2}},
  347. Index: 2,
  348. Term: 1,
  349. },
  350. }
  351. entries := []raftpb.Entry{
  352. {Term: 1, Index: 3, Data: []byte("foo")},
  353. }
  354. st := raftpb.HardState{Term: 1, Commit: 3}
  355. want := Ready{
  356. HardState: emptyState,
  357. // commit up to index commit index in st
  358. CommittedEntries: entries,
  359. }
  360. s := NewMemoryStorage()
  361. s.SetHardState(st)
  362. s.ApplySnapshot(snap)
  363. s.Append(entries)
  364. n := RestartNode(1, 10, 1, s, 0)
  365. if g := <-n.Ready(); !reflect.DeepEqual(g, want) {
  366. t.Errorf("g = %+v,\n w %+v", g, want)
  367. } else {
  368. n.Advance()
  369. }
  370. select {
  371. case rd := <-n.Ready():
  372. t.Errorf("unexpected Ready: %+v", rd)
  373. case <-time.After(time.Millisecond):
  374. }
  375. }
  376. func TestNodeAdvance(t *testing.T) {
  377. ctx, cancel := context.WithCancel(context.Background())
  378. defer cancel()
  379. storage := NewMemoryStorage()
  380. n := StartNode(1, []Peer{{ID: 1}}, 10, 1, storage)
  381. n.Campaign(ctx)
  382. <-n.Ready()
  383. n.Propose(ctx, []byte("foo"))
  384. var rd Ready
  385. select {
  386. case rd = <-n.Ready():
  387. t.Fatalf("unexpected Ready before Advance: %+v", rd)
  388. case <-time.After(time.Millisecond):
  389. }
  390. storage.Append(rd.Entries)
  391. n.Advance()
  392. select {
  393. case <-n.Ready():
  394. case <-time.After(time.Millisecond):
  395. t.Errorf("expect Ready after Advance, but there is no Ready available")
  396. }
  397. }
  398. func TestSoftStateEqual(t *testing.T) {
  399. tests := []struct {
  400. st *SoftState
  401. we bool
  402. }{
  403. {&SoftState{}, true},
  404. {&SoftState{Lead: 1}, false},
  405. {&SoftState{RaftState: StateLeader}, false},
  406. }
  407. for i, tt := range tests {
  408. if g := tt.st.equal(&SoftState{}); g != tt.we {
  409. t.Errorf("#%d, equal = %v, want %v", i, g, tt.we)
  410. }
  411. }
  412. }
  413. func TestIsHardStateEqual(t *testing.T) {
  414. tests := []struct {
  415. st raftpb.HardState
  416. we bool
  417. }{
  418. {emptyState, true},
  419. {raftpb.HardState{Vote: 1}, false},
  420. {raftpb.HardState{Commit: 1}, false},
  421. {raftpb.HardState{Term: 1}, false},
  422. }
  423. for i, tt := range tests {
  424. if isHardStateEqual(tt.st, emptyState) != tt.we {
  425. t.Errorf("#%d, equal = %v, want %v", i, isHardStateEqual(tt.st, emptyState), tt.we)
  426. }
  427. }
  428. }