node_test.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. /*
  2. Copyright 2014 CoreOS, Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package raft
  14. import (
  15. "reflect"
  16. "testing"
  17. "time"
  18. "github.com/coreos/etcd/Godeps/_workspace/src/code.google.com/p/go.net/context"
  19. "github.com/coreos/etcd/pkg/testutil"
  20. "github.com/coreos/etcd/raft/raftpb"
  21. )
  22. // TestNodeStep ensures that node.Step sends msgProp to propc chan
  23. // and other kinds of messages to recvc chan.
  24. func TestNodeStep(t *testing.T) {
  25. for i, msgn := range raftpb.MessageType_name {
  26. n := &node{
  27. propc: make(chan raftpb.Message, 1),
  28. recvc: make(chan raftpb.Message, 1),
  29. }
  30. msgt := raftpb.MessageType(i)
  31. n.Step(context.TODO(), raftpb.Message{Type: msgt})
  32. // Proposal goes to proc chan. Others go to recvc chan.
  33. if msgt == raftpb.MsgProp {
  34. select {
  35. case <-n.propc:
  36. default:
  37. t.Errorf("%d: cannot receive %s on propc chan", msgt, msgn)
  38. }
  39. } else {
  40. if msgt == raftpb.MsgBeat || msgt == raftpb.MsgHup {
  41. select {
  42. case <-n.recvc:
  43. t.Errorf("%d: step should ignore %s", msgt, msgn)
  44. default:
  45. }
  46. } else {
  47. select {
  48. case <-n.recvc:
  49. default:
  50. t.Errorf("%d: cannot receive %s on recvc chan", msgt, msgn)
  51. }
  52. }
  53. }
  54. }
  55. }
  56. // Cancel and Stop should unblock Step()
  57. func TestNodeStepUnblock(t *testing.T) {
  58. // a node without buffer to block step
  59. n := &node{
  60. propc: make(chan raftpb.Message),
  61. done: make(chan struct{}),
  62. }
  63. ctx, cancel := context.WithCancel(context.Background())
  64. stopFunc := func() { close(n.done) }
  65. tests := []struct {
  66. unblock func()
  67. werr error
  68. }{
  69. {stopFunc, ErrStopped},
  70. {cancel, context.Canceled},
  71. }
  72. for i, tt := range tests {
  73. errc := make(chan error, 1)
  74. go func() {
  75. err := n.Step(ctx, raftpb.Message{Type: raftpb.MsgProp})
  76. errc <- err
  77. }()
  78. tt.unblock()
  79. select {
  80. case err := <-errc:
  81. if err != tt.werr {
  82. t.Errorf("#%d: err = %v, want %v", i, err, tt.werr)
  83. }
  84. //clean up side-effect
  85. if ctx.Err() != nil {
  86. ctx = context.TODO()
  87. }
  88. select {
  89. case <-n.done:
  90. n.done = make(chan struct{})
  91. default:
  92. }
  93. case <-time.After(time.Millisecond * 100):
  94. t.Errorf("#%d: failed to unblock step", i)
  95. }
  96. }
  97. }
  98. // TestBlockProposal ensures that node will block proposal when it does not
  99. // know who is the current leader; node will accept proposal when it knows
  100. // who is the current leader.
  101. func TestBlockProposal(t *testing.T) {
  102. n := newNode()
  103. r := newRaft(1, []uint64{1}, 10, 1)
  104. go n.run(r)
  105. defer n.Stop()
  106. errc := make(chan error, 1)
  107. go func() {
  108. errc <- n.Propose(context.TODO(), []byte("somedata"))
  109. }()
  110. testutil.ForceGosched()
  111. select {
  112. case err := <-errc:
  113. t.Errorf("err = %v, want blocking", err)
  114. default:
  115. }
  116. n.Campaign(context.TODO())
  117. testutil.ForceGosched()
  118. select {
  119. case err := <-errc:
  120. if err != nil {
  121. t.Errorf("err = %v, want %v", err, nil)
  122. }
  123. default:
  124. t.Errorf("blocking proposal, want unblocking")
  125. }
  126. }
  127. // TestNodeTick ensures that node.Tick() will increase the
  128. // elapsed of the underly raft state machine.
  129. func TestNodeTick(t *testing.T) {
  130. n := newNode()
  131. r := newRaft(1, []uint64{1}, 10, 1)
  132. go n.run(r)
  133. elapsed := r.elapsed
  134. n.Tick()
  135. n.Stop()
  136. if r.elapsed != elapsed+1 {
  137. t.Errorf("elapsed = %d, want %d", r.elapsed, elapsed+1)
  138. }
  139. }
  140. func TestReadyContainUpdates(t *testing.T) {
  141. tests := []struct {
  142. rd Ready
  143. wcontain bool
  144. }{
  145. {Ready{}, false},
  146. {Ready{SoftState: &SoftState{Lead: 1}}, true},
  147. {Ready{HardState: raftpb.HardState{Vote: 1}}, true},
  148. {Ready{Entries: make([]raftpb.Entry, 1, 1)}, true},
  149. {Ready{CommittedEntries: make([]raftpb.Entry, 1, 1)}, true},
  150. {Ready{Messages: make([]raftpb.Message, 1, 1)}, true},
  151. {Ready{Snapshot: raftpb.Snapshot{Index: 1}}, true},
  152. }
  153. for i, tt := range tests {
  154. if g := tt.rd.containsUpdates(); g != tt.wcontain {
  155. t.Errorf("#%d: containUpdates = %v, want %v", i, g, tt.wcontain)
  156. }
  157. }
  158. }
  159. // TestNodeStart ensures that a node can be started correctly. The node should
  160. // start with correct configuration change entries, and can accept and commit
  161. // proposals.
  162. func TestNodeStart(t *testing.T) {
  163. ctx, cancel := context.WithCancel(context.Background())
  164. defer cancel()
  165. cc := raftpb.ConfChange{Type: raftpb.ConfChangeAddNode, NodeID: 1}
  166. ccdata, err := cc.Marshal()
  167. if err != nil {
  168. t.Fatalf("unexpected marshal error: %v", err)
  169. }
  170. wants := []Ready{
  171. {
  172. SoftState: &SoftState{Lead: 1, Nodes: []uint64{1}, RaftState: StateLeader},
  173. HardState: raftpb.HardState{Term: 1, Commit: 2},
  174. Entries: []raftpb.Entry{
  175. {},
  176. {Type: raftpb.EntryConfChange, Term: 1, Index: 1, Data: ccdata},
  177. {Term: 1, Index: 2},
  178. },
  179. CommittedEntries: []raftpb.Entry{
  180. {Type: raftpb.EntryConfChange, Term: 1, Index: 1, Data: ccdata},
  181. {Term: 1, Index: 2},
  182. },
  183. },
  184. {
  185. HardState: raftpb.HardState{Term: 1, Commit: 3},
  186. Entries: []raftpb.Entry{{Term: 1, Index: 3, Data: []byte("foo")}},
  187. CommittedEntries: []raftpb.Entry{{Term: 1, Index: 3, Data: []byte("foo")}},
  188. },
  189. }
  190. n := StartNode(1, []Peer{{ID: 1}}, 10, 1)
  191. n.ApplyConfChange(cc)
  192. n.Campaign(ctx)
  193. if g := <-n.Ready(); !reflect.DeepEqual(g, wants[0]) {
  194. t.Errorf("#%d: g = %+v,\n w %+v", 1, g, wants[0])
  195. } else {
  196. n.Advance()
  197. }
  198. n.Propose(ctx, []byte("foo"))
  199. if g := <-n.Ready(); !reflect.DeepEqual(g, wants[1]) {
  200. t.Errorf("#%d: g = %+v,\n w %+v", 2, g, wants[1])
  201. } else {
  202. n.Advance()
  203. }
  204. select {
  205. case rd := <-n.Ready():
  206. t.Errorf("unexpected Ready: %+v", rd)
  207. default:
  208. }
  209. }
  210. func TestNodeRestart(t *testing.T) {
  211. entries := []raftpb.Entry{
  212. {},
  213. {Term: 1, Index: 1},
  214. {Term: 1, Index: 2, Data: []byte("foo")},
  215. }
  216. st := raftpb.HardState{Term: 1, Commit: 1}
  217. want := Ready{
  218. HardState: emptyState,
  219. // commit upto index commit index in st
  220. CommittedEntries: entries[1 : st.Commit+1],
  221. }
  222. n := RestartNode(1, 10, 1, nil, st, entries)
  223. if g := <-n.Ready(); !reflect.DeepEqual(g, want) {
  224. t.Errorf("g = %+v,\n w %+v", g, want)
  225. } else {
  226. n.Advance()
  227. }
  228. select {
  229. case rd := <-n.Ready():
  230. t.Errorf("unexpected Ready: %+v", rd)
  231. default:
  232. }
  233. }
  234. // TestCompacts ensures Node.Compact creates a correct raft snapshot and compacts
  235. // the raft log (call raft.compact)
  236. func TestNodeCompact(t *testing.T) {
  237. ctx := context.Background()
  238. n := newNode()
  239. r := newRaft(1, []uint64{1}, 10, 1)
  240. go n.run(r)
  241. n.Campaign(ctx)
  242. n.Propose(ctx, []byte("foo"))
  243. w := raftpb.Snapshot{
  244. Term: 1,
  245. Index: 2, // one nop + one proposal
  246. Data: []byte("a snapshot"),
  247. Nodes: []uint64{1},
  248. }
  249. testutil.ForceGosched()
  250. select {
  251. case <-n.Ready():
  252. n.Advance()
  253. default:
  254. t.Fatalf("unexpected proposal failure: unable to commit entry")
  255. }
  256. n.Compact(w.Index, w.Nodes, w.Data)
  257. testutil.ForceGosched()
  258. select {
  259. case rd := <-n.Ready():
  260. if !reflect.DeepEqual(rd.Snapshot, w) {
  261. t.Errorf("snap = %+v, want %+v", rd.Snapshot, w)
  262. }
  263. n.Advance()
  264. default:
  265. t.Fatalf("unexpected compact failure: unable to create a snapshot")
  266. }
  267. testutil.ForceGosched()
  268. // TODO: this test the run updates the snapi correctly... should be tested
  269. // separately with other kinds of updates
  270. select {
  271. case <-n.Ready():
  272. t.Fatalf("unexpected more ready")
  273. default:
  274. }
  275. n.Stop()
  276. if r.raftLog.offset != w.Index {
  277. t.Errorf("log.offset = %d, want %d", r.raftLog.offset, w.Index)
  278. }
  279. }
  280. func TestNodeAdvance(t *testing.T) {
  281. ctx, cancel := context.WithCancel(context.Background())
  282. defer cancel()
  283. n := StartNode(1, []Peer{{ID: 1}}, 10, 1)
  284. n.ApplyConfChange(raftpb.ConfChange{Type: raftpb.ConfChangeAddNode, NodeID: 1})
  285. n.Campaign(ctx)
  286. <-n.Ready()
  287. n.Propose(ctx, []byte("foo"))
  288. select {
  289. case rd := <-n.Ready():
  290. t.Fatalf("unexpected Ready before Advance: %+v", rd)
  291. default:
  292. }
  293. n.Advance()
  294. select {
  295. case <-n.Ready():
  296. default:
  297. t.Errorf("expect Ready after Advance, but there is no Ready available")
  298. }
  299. }
  300. func TestSoftStateEqual(t *testing.T) {
  301. tests := []struct {
  302. st *SoftState
  303. we bool
  304. }{
  305. {&SoftState{}, true},
  306. {&SoftState{Lead: 1}, false},
  307. {&SoftState{RaftState: StateLeader}, false},
  308. {&SoftState{Nodes: []uint64{1, 2}}, false},
  309. }
  310. for i, tt := range tests {
  311. if g := tt.st.equal(&SoftState{}); g != tt.we {
  312. t.Errorf("#%d, equal = %v, want %v", i, g, tt.we)
  313. }
  314. }
  315. }
  316. func TestIsHardStateEqual(t *testing.T) {
  317. tests := []struct {
  318. st raftpb.HardState
  319. we bool
  320. }{
  321. {emptyState, true},
  322. {raftpb.HardState{Vote: 1}, false},
  323. {raftpb.HardState{Commit: 1}, false},
  324. {raftpb.HardState{Term: 1}, false},
  325. }
  326. for i, tt := range tests {
  327. if isHardStateEqual(tt.st, emptyState) != tt.we {
  328. t.Errorf("#%d, equal = %v, want %v", i, isHardStateEqual(tt.st, emptyState), tt.we)
  329. }
  330. }
  331. }