node_test.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. func TestReadyContainUpdates(t *testing.T) {
  128. tests := []struct {
  129. rd Ready
  130. wcontain bool
  131. }{
  132. {Ready{}, false},
  133. {Ready{SoftState: &SoftState{Lead: 1}}, true},
  134. {Ready{HardState: raftpb.HardState{Vote: 1}}, true},
  135. {Ready{Entries: make([]raftpb.Entry, 1, 1)}, true},
  136. {Ready{CommittedEntries: make([]raftpb.Entry, 1, 1)}, true},
  137. {Ready{Messages: make([]raftpb.Message, 1, 1)}, true},
  138. {Ready{Snapshot: raftpb.Snapshot{Index: 1}}, true},
  139. }
  140. for i, tt := range tests {
  141. if g := tt.rd.containsUpdates(); g != tt.wcontain {
  142. t.Errorf("#%d: containUpdates = %v, want %v", i, g, tt.wcontain)
  143. }
  144. }
  145. }
  146. // TestNodeStart ensures that a node can be started correctly. The node should
  147. // start with correct configuration change entries, and can accept and commit
  148. // proposals.
  149. func TestNodeStart(t *testing.T) {
  150. ctx, cancel := context.WithCancel(context.Background())
  151. defer cancel()
  152. cc := raftpb.ConfChange{Type: raftpb.ConfChangeAddNode, NodeID: 1}
  153. ccdata, err := cc.Marshal()
  154. if err != nil {
  155. t.Fatalf("unexpected marshal error: %v", err)
  156. }
  157. wants := []Ready{
  158. {
  159. SoftState: &SoftState{Lead: 1, Nodes: []uint64{1}, RaftState: StateLeader},
  160. HardState: raftpb.HardState{Term: 1, Commit: 2},
  161. Entries: []raftpb.Entry{
  162. {},
  163. {Type: raftpb.EntryConfChange, Term: 1, Index: 1, Data: ccdata},
  164. {Term: 1, Index: 2},
  165. },
  166. CommittedEntries: []raftpb.Entry{
  167. {Type: raftpb.EntryConfChange, Term: 1, Index: 1, Data: ccdata},
  168. {Term: 1, Index: 2},
  169. },
  170. },
  171. {
  172. HardState: raftpb.HardState{Term: 1, Commit: 3},
  173. Entries: []raftpb.Entry{{Term: 1, Index: 3, Data: []byte("foo")}},
  174. CommittedEntries: []raftpb.Entry{{Term: 1, Index: 3, Data: []byte("foo")}},
  175. },
  176. }
  177. n := StartNode(1, []Peer{{ID: 1}}, 10, 1)
  178. n.ApplyConfChange(cc)
  179. n.Campaign(ctx)
  180. if g := <-n.Ready(); !reflect.DeepEqual(g, wants[0]) {
  181. t.Errorf("#%d: g = %+v,\n w %+v", 1, g, wants[0])
  182. } else {
  183. n.Advance()
  184. }
  185. n.Propose(ctx, []byte("foo"))
  186. if g := <-n.Ready(); !reflect.DeepEqual(g, wants[1]) {
  187. t.Errorf("#%d: g = %+v,\n w %+v", 2, g, wants[1])
  188. } else {
  189. n.Advance()
  190. }
  191. select {
  192. case rd := <-n.Ready():
  193. t.Errorf("unexpected Ready: %+v", rd)
  194. default:
  195. }
  196. }
  197. func TestNodeRestart(t *testing.T) {
  198. entries := []raftpb.Entry{
  199. {},
  200. {Term: 1, Index: 1},
  201. {Term: 1, Index: 2, Data: []byte("foo")},
  202. }
  203. st := raftpb.HardState{Term: 1, Commit: 1}
  204. want := Ready{
  205. HardState: emptyState,
  206. // commit upto index commit index in st
  207. CommittedEntries: entries[1 : st.Commit+1],
  208. }
  209. n := RestartNode(1, 10, 1, nil, st, entries)
  210. if g := <-n.Ready(); !reflect.DeepEqual(g, want) {
  211. t.Errorf("g = %+v,\n w %+v", g, want)
  212. } else {
  213. n.Advance()
  214. }
  215. select {
  216. case rd := <-n.Ready():
  217. t.Errorf("unexpected Ready: %+v", rd)
  218. default:
  219. }
  220. }
  221. // TestCompacts ensures Node.Compact creates a correct raft snapshot and compacts
  222. // the raft log (call raft.compact)
  223. func TestNodeCompact(t *testing.T) {
  224. ctx := context.Background()
  225. n := newNode()
  226. r := newRaft(1, []uint64{1}, 10, 1)
  227. go n.run(r)
  228. n.Campaign(ctx)
  229. n.Propose(ctx, []byte("foo"))
  230. w := raftpb.Snapshot{
  231. Term: 1,
  232. Index: 2, // one nop + one proposal
  233. Data: []byte("a snapshot"),
  234. Nodes: []uint64{1},
  235. }
  236. testutil.ForceGosched()
  237. select {
  238. case <-n.Ready():
  239. n.Advance()
  240. default:
  241. t.Fatalf("unexpected proposal failure: unable to commit entry")
  242. }
  243. n.Compact(w.Index, w.Nodes, w.Data)
  244. testutil.ForceGosched()
  245. select {
  246. case rd := <-n.Ready():
  247. if !reflect.DeepEqual(rd.Snapshot, w) {
  248. t.Errorf("snap = %+v, want %+v", rd.Snapshot, w)
  249. }
  250. n.Advance()
  251. default:
  252. t.Fatalf("unexpected compact failure: unable to create a snapshot")
  253. }
  254. testutil.ForceGosched()
  255. // TODO: this test the run updates the snapi correctly... should be tested
  256. // separately with other kinds of updates
  257. select {
  258. case <-n.Ready():
  259. t.Fatalf("unexpected more ready")
  260. default:
  261. }
  262. n.Stop()
  263. if r.raftLog.offset != w.Index {
  264. t.Errorf("log.offset = %d, want %d", r.raftLog.offset, w.Index)
  265. }
  266. }
  267. func TestNodeAdvance(t *testing.T) {
  268. ctx, cancel := context.WithCancel(context.Background())
  269. defer cancel()
  270. n := StartNode(1, []Peer{{ID: 1}}, 10, 1)
  271. n.ApplyConfChange(raftpb.ConfChange{Type: raftpb.ConfChangeAddNode, NodeID: 1})
  272. n.Campaign(ctx)
  273. <-n.Ready()
  274. n.Propose(ctx, []byte("foo"))
  275. select {
  276. case rd := <-n.Ready():
  277. t.Fatalf("unexpected Ready before Advance: %+v", rd)
  278. default:
  279. }
  280. n.Advance()
  281. select {
  282. case <-n.Ready():
  283. default:
  284. t.Errorf("expect Ready after Advance, but there is no Ready available")
  285. }
  286. }
  287. func TestSoftStateEqual(t *testing.T) {
  288. tests := []struct {
  289. st *SoftState
  290. we bool
  291. }{
  292. {&SoftState{}, true},
  293. {&SoftState{Lead: 1}, false},
  294. {&SoftState{RaftState: StateLeader}, false},
  295. {&SoftState{Nodes: []uint64{1, 2}}, false},
  296. }
  297. for i, tt := range tests {
  298. if g := tt.st.equal(&SoftState{}); g != tt.we {
  299. t.Errorf("#%d, equal = %v, want %v", i, g, tt.we)
  300. }
  301. }
  302. }
  303. func TestIsHardStateEqual(t *testing.T) {
  304. tests := []struct {
  305. st raftpb.HardState
  306. we bool
  307. }{
  308. {emptyState, true},
  309. {raftpb.HardState{Vote: 1}, false},
  310. {raftpb.HardState{Commit: 1}, false},
  311. {raftpb.HardState{Term: 1}, false},
  312. }
  313. for i, tt := range tests {
  314. if isHardStateEqual(tt.st, emptyState) != tt.we {
  315. t.Errorf("#%d, equal = %v, want %v", i, isHardStateEqual(tt.st, emptyState), tt.we)
  316. }
  317. }
  318. }