-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathraft_test.go
585 lines (485 loc) · 12.4 KB
/
raft_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
package yaft
import (
"bytes"
"errors"
"fmt"
"log"
"net"
"testing"
"time"
)
// MockFSM is an implementation of the FSM interface, and just stores
// the logs sequentially
type MockFSM struct {
logs [][]byte
}
func (m *MockFSM) Apply(log []byte) {
m.logs = append(m.logs, log)
}
func TestRaft_StartStop(t *testing.T) {
_, trans := NewDummyTransport()
store := NewDummyStore()
peers := &DummyPeerStore{}
fsm := &MockFSM{}
conf := DefaultConfig()
raft, err := NewRaft(conf, store, store, peers, fsm, trans)
if err != nil {
t.Fatalf("err: %v", err)
}
defer raft.Shutdown()
}
func inmemConfig() *Config {
return &Config{
HeartbeatTimeout: 10 * time.Millisecond,
ElectionTimeout: 10 * time.Millisecond,
CommitTimeout: time.Millisecond,
MaxAppendEntries: 16,
ShutdownOnRemove: true,
}
}
func TestRaft_SingleNode(t *testing.T) {
conf := inmemConfig()
_, trans := NewDummyTransport()
store := NewDummyStore()
peerStore := &DummyPeerStore{}
fsm := &MockFSM{}
raft, err := NewRaft(conf, store, store, peerStore, fsm, trans)
if err != nil {
t.Fatalf("err: %v", err)
}
defer raft.Shutdown()
time.Sleep(conf.HeartbeatTimeout * 4)
// Should be leader
if s := raft.State(); s != Leader {
t.Fatalf("expected leader: %v", s)
}
// Should be able to apply
future := raft.Apply([]byte("test"), time.Millisecond)
if err := future.Error(); err != nil {
t.Fatalf("err: %v", err)
}
// Check that it is applied to the FSM
if len(fsm.logs) != 1 {
t.Fatalf("did not apply to FSM!")
}
}
type cluster struct {
stores []*DummyStore
fsms []*MockFSM
trans []*InmemTransport
rafts []*Raft
}
func (c *cluster) Merge(other *cluster) {
c.stores = append(c.stores, other.stores...)
c.fsms = append(c.fsms, other.fsms...)
c.trans = append(c.trans, other.trans...)
c.rafts = append(c.rafts, other.rafts...)
}
func (c *cluster) Close() {
for _, r := range c.rafts {
r.Shutdown()
}
}
func (c *cluster) GetState(s RaftState) []*Raft {
in := make([]*Raft, 0, 1)
for _, r := range c.rafts {
if r.State() == s {
in = append(in, r)
}
}
return in
}
func (c *cluster) Leader() *Raft {
timeout := time.AfterFunc(250*time.Millisecond, func() {
panic("timeout waiting for leader")
})
defer timeout.Stop()
for len(c.GetState(Leader)) < 1 {
time.Sleep(time.Millisecond)
}
leaders := c.GetState(Leader)
if len(leaders) != 1 {
panic(fmt.Errorf("expected one leader: %v", leaders))
}
return leaders[0]
}
func (c *cluster) FullyConnect() {
for i, t1 := range c.trans {
for j, t2 := range c.trans {
if i != j {
t1.Connect(t2.LocalAddr(), t2)
t2.Connect(t1.LocalAddr(), t1)
}
}
}
}
func (c *cluster) Disconnect(a net.Addr) {
for _, t := range c.trans {
if t.localAddr == a {
t.DisconnectAll()
} else {
t.Disconnect(a)
}
}
}
func (c *cluster) EnsureSame(t *testing.T) {
first := c.fsms[0]
for i, fsm := range c.fsms {
if i == 0 {
continue
}
if len(first.logs) != len(fsm.logs) {
t.Fatalf("length mismatch: %d %d",
len(first.logs), len(fsm.logs))
}
for idx := 0; idx < len(first.logs); idx++ {
if bytes.Compare(first.logs[idx], fsm.logs[idx]) != 0 {
t.Fatalf("log mismatch at index %d", idx)
}
}
}
}
func MakeCluster(n int, t *testing.T, conf *Config) *cluster {
c := &cluster{}
peers := make([]net.Addr, 0, n)
// Setup the stores and transports
for i := 0; i < n; i++ {
store := NewDummyStore()
c.stores = append(c.stores, store)
c.fsms = append(c.fsms, &MockFSM{})
addr, trans := NewDummyTransport()
c.trans = append(c.trans, trans)
peers = append(peers, addr)
}
// Wire the transports together
c.FullyConnect()
// Create all the rafts
for i := 0; i < n; i++ {
if conf == nil {
conf = inmemConfig()
}
store := c.stores[i]
trans := c.trans[i]
fsm := c.fsms[i]
peerStore := &DummyPeerStore{peers}
// Start raft
raft, err := NewRaft(conf, store, store, peerStore, fsm, trans)
if err != nil {
t.Fatalf("err: %v", err)
}
c.rafts = append(c.rafts, raft)
}
return c
}
func TestRaft_TripleNode(t *testing.T) {
// Make the cluster
c := MakeCluster(3, t, nil)
defer c.Close()
leader := c.Leader()
// Should be able to apply
future := leader.Apply([]byte("test"), time.Millisecond)
if err := future.Error(); err != nil {
t.Fatalf("err: %v", err)
}
// Wait for replication
time.Sleep(3 * time.Millisecond)
// Check that it is applied to the FSM
for _, fsm := range c.fsms {
if len(fsm.logs) != 1 {
t.Fatalf("did not apply to FSM!")
}
}
}
func TestRaft_LeaderFail(t *testing.T) {
// Make the cluster
c := MakeCluster(3, t, nil)
defer c.Close()
leader := c.Leader()
// Should be able to apply
future := leader.Apply([]byte("test"), time.Millisecond)
if err := future.Error(); err != nil {
t.Fatalf("err: %v", err)
}
// Wait for replication
time.Sleep(3 * time.Millisecond)
// Disconnect the leader now
c.Disconnect(leader.localAddr)
// Wait for two leaders
limit := time.Now().Add(100 * time.Millisecond)
var leaders []*Raft
for time.Now().Before(limit) && len(leaders) != 2 {
time.Sleep(10 * time.Millisecond)
leaders = c.GetState(Leader)
}
if len(leaders) != 2 {
t.Fatalf("expected two leader: %v", leaders)
return // Shut Up IDE
}
// Get the 'new' leader
var newLead *Raft
if leaders[0] == leader {
newLead = leaders[1]
} else {
newLead = leaders[0]
}
// Ensure the term is greater
if newLead.getCurrentTerm() <= leader.getCurrentTerm() {
t.Fatalf("expected newer term!")
}
// Apply should work not work on old leader
future1 := leader.Apply([]byte("fail"), time.Millisecond)
// Apply should work on newer leader
future2 := newLead.Apply([]byte("apply"), time.Millisecond)
// Future2 should work
if err := future2.Error(); err != nil {
t.Fatalf("err: %v", err)
}
// Reconnect the networks
c.FullyConnect()
// Future1 should fail
if err := future1.Error(); err != ErrLeadershipLost {
t.Fatalf("err: %v", err)
}
// Wait for log replication
time.Sleep(10 * time.Millisecond)
// Check two entries are applied to the FSM
for _, fsm := range c.fsms {
if len(fsm.logs) != 2 {
t.Fatalf("did not apply both to FSM!")
}
if bytes.Compare(fsm.logs[0], []byte("test")) != 0 {
t.Fatalf("first entry should be 'test'")
}
if bytes.Compare(fsm.logs[1], []byte("apply")) != 0 {
t.Fatalf("second entry should be 'apply'")
}
}
}
func TestRaft_BehindFollower(t *testing.T) {
// Make the cluster
c := MakeCluster(3, t, nil)
defer c.Close()
// Disconnect one follower
followers := c.GetState(Follower)
behind := followers[0]
c.Disconnect(behind.localAddr)
// Commit a lot of things
leader := c.Leader()
var future ApplyDefer
for i := 0; i < 100; i++ {
future = leader.Apply([]byte(fmt.Sprintf("test%d", i)), 0)
}
// Wait for the last future to apply
if err := future.Error(); err != nil {
t.Fatalf("err: %v", err)
}
// Reconnect the behind node
c.FullyConnect()
// Wait for replication
time.Sleep(100 * time.Millisecond)
// Ensure all the logs are the same
c.EnsureSame(t)
}
func TestRaft_ApplyNonLeader(t *testing.T) {
// Make the cluster
c := MakeCluster(5, t, nil)
defer c.Close()
// Wait for a leader
c.Leader()
time.Sleep(10 * time.Millisecond)
// Try to apply to them
followers := c.GetState(Follower)
if len(followers) != 4 {
t.Fatalf("Expected 4 followers")
}
follower := followers[0]
// Try to apply
future := follower.Apply([]byte("test"), time.Millisecond)
if future.Error() != ErrNotLeader {
t.Fatalf("should not apply on follower")
}
// Should be cached
if future.Error() != ErrNotLeader {
t.Fatalf("should not apply on follower")
}
}
func TestRaft_ApplyConcurrent(t *testing.T) {
// Make the cluster
conf := inmemConfig()
conf.HeartbeatTimeout = 100 * time.Millisecond
c := MakeCluster(3, t, conf)
defer c.Close()
// Wait for a leader
leader := c.Leader()
for i := 0; i < 100; i++ {
go func(i int) {
future := leader.Apply([]byte(fmt.Sprintf("test%d", i)), 0)
if err := future.Error(); err != nil {
t.Errorf("err: %v", err)
return
}
}(i)
}
// Wait for replication
time.Sleep(50 * time.Millisecond)
// Check the FSMs
c.EnsureSame(t)
}
func TestRaft_JoinNode(t *testing.T) {
// Make a cluster
c := MakeCluster(2, t, nil)
defer c.Close()
// Apply a log to this cluster to ensure it is 'newer'
leader := c.Leader()
future := leader.Apply([]byte("first"), 0)
if err := future.Error(); err != nil {
t.Fatalf("err: %v", err)
} else {
log.Printf("[INFO] Applied log")
}
// Make a new cluster of 1
c1 := MakeCluster(1, t, nil)
// Merge clusters
c.Merge(c1)
c.FullyConnect()
// Wait until we have 2 leaders
limit := time.Now().Add(100 * time.Millisecond)
var leaders []*Raft
for time.Now().Before(limit) && len(leaders) != 2 {
time.Sleep(10 * time.Millisecond)
leaders = c.GetState(Leader)
}
if len(leaders) != 2 {
t.Fatalf("expected two leader: %v", leaders)
}
// Join the new node in
future = leader.AddPeer(c1.rafts[0].localAddr)
if err := future.Error(); err != nil {
t.Fatalf("err: %v", err)
}
// Wait until we have 2 followers
limit = time.Now().Add(100 * time.Millisecond)
var followers []*Raft
for time.Now().Before(limit) && len(followers) != 2 {
time.Sleep(10 * time.Millisecond)
followers = c.GetState(Follower)
}
if len(followers) != 2 {
t.Fatalf("expected two followers: %v", followers)
}
// Check the FSMs
c.EnsureSame(t)
}
func TestRaft_RemoveFollower(t *testing.T) {
// Make a cluster
c := MakeCluster(3, t, nil)
defer c.Close()
// Get the leader
leader := c.Leader()
// Wait until we have 2 followers
limit := time.Now().Add(100 * time.Millisecond)
var followers []*Raft
for time.Now().Before(limit) && len(followers) != 2 {
time.Sleep(10 * time.Millisecond)
followers = c.GetState(Follower)
}
if len(followers) != 2 {
t.Fatalf("expected two followers: %v", followers)
}
// Remove a follower
follower := followers[0]
future := leader.RemovePeer(follower.localAddr)
if err := future.Error(); err != nil {
t.Fatalf("err: %v", err)
}
// Wait a while
time.Sleep(20 * time.Millisecond)
// Other nodes should have fewer peers
if len(leader.peers) != 1 {
t.Fatalf("too many peers")
return
}
if len(followers[1].peers) != 1 {
t.Fatalf("too many peers")
}
}
func TestRaft_RemoveLeader(t *testing.T) {
// Make a cluster
c := MakeCluster(3, t, nil)
defer c.Close()
// Get the leader
leader := c.Leader()
// Wait until we have 2 followers
limit := time.Now().Add(100 * time.Millisecond)
var followers []*Raft
for time.Now().Before(limit) && len(followers) != 2 {
time.Sleep(10 * time.Millisecond)
followers = c.GetState(Follower)
}
if len(followers) != 2 {
t.Fatalf("expected two followers: %v", followers)
}
// Remove the leader
leader.RemovePeer(leader.localAddr)
// Wait a while
time.Sleep(20 * time.Millisecond)
// Should have a new leader
newLeader := c.Leader()
// Other nodes should have fewer peers
if len(newLeader.peers) != 1 {
t.Fatalf("too many peers")
}
// Old leader should be shutdown
if leader.State() != Shutdown {
t.Fatalf("leader should be shutdown")
}
}
func TestRaft_AfterShutdown(t *testing.T) {
store := NewDummyStore()
_, trans := NewDummyTransport()
fsm := &MockFSM{}
conf := DefaultConfig()
peers := &DummyPeerStore{}
raft, err := NewRaft(conf, store, store, peers, fsm, trans)
if err != nil {
t.Fatalf("err: %v", err)
}
raft.Shutdown()
// Everything should fail now
if f := raft.Apply(nil, 0); !errors.Is(f.Error(), ErrRaftShutdown) {
t.Fatalf("should be shutdown: %v", f.Error())
}
if f := raft.AddPeer(NewInmemAddr()); !errors.Is(f.Error(), ErrRaftShutdown) {
t.Fatalf("should be shutdown: %v", f.Error())
}
if f := raft.RemovePeer(NewInmemAddr()); !errors.Is(f.Error(), ErrRaftShutdown) {
t.Fatalf("should be shutdown: %v", f.Error())
}
// Should be idempotent
raft.Shutdown()
}
func TestRaft_ApplyConcurrent_Timeout(t *testing.T) {
// Make the cluster
conf := inmemConfig()
conf.HeartbeatTimeout = 100 * time.Millisecond
c := MakeCluster(1, t, conf)
defer c.Close()
// Wait for a leader
leader := c.Leader()
// Enough enqueues should cause at least one timeout...
didTimeout := false
for i := 0; i < 200; i++ {
go func(i int) {
future := leader.Apply([]byte(fmt.Sprintf("test%d", i)), time.Microsecond)
if errors.Is(future.Error(), ErrEnqueueTimeout) {
didTimeout = true
}
}(i)
}
// Wait
time.Sleep(20 * time.Millisecond)
// Some should have failed
if !didTimeout {
t.Fatalf("expected a timeout")
}
}