forked from hashicorp/raft
-
Notifications
You must be signed in to change notification settings - Fork 0
/
raft_test.go
939 lines (783 loc) · 19.8 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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
package raft
import (
"bytes"
"fmt"
"github.com/ugorji/go/codec"
"io"
"log"
"net"
"os"
"reflect"
"testing"
"time"
)
// MockFSM is an implementation of the FSM interface, and just stores
// the logs sequentially
type MockFSM struct {
logs [][]byte
}
type MockSnapshot struct {
logs [][]byte
maxIndex int
}
func (m *MockFSM) Apply(log []byte) interface{} {
m.logs = append(m.logs, log)
return len(m.logs)
}
func (m *MockFSM) Snapshot() (FSMSnapshot, error) {
return &MockSnapshot{m.logs, len(m.logs)}, nil
}
func (m *MockFSM) Restore(inp io.ReadCloser) error {
defer inp.Close()
hd := codec.MsgpackHandle{}
dec := codec.NewDecoder(inp, &hd)
m.logs = nil
return dec.Decode(&m.logs)
}
func (m *MockSnapshot) Persist(sink SnapshotSink) error {
hd := codec.MsgpackHandle{}
enc := codec.NewEncoder(sink, &hd)
if err := enc.Encode(m.logs[:m.maxIndex]); err != nil {
sink.Cancel()
return err
}
sink.Close()
return nil
}
func (m *MockSnapshot) Release() {
}
// Return configurations optimized for in-memory
func inmemConfig() *Config {
conf := DefaultConfig()
conf.HeartbeatTimeout = 10 * time.Millisecond
conf.ElectionTimeout = 10 * time.Millisecond
conf.CommitTimeout = time.Millisecond
return conf
}
type cluster struct {
dirs []string
logs []*LevelDBLogStore
stores []*LevelDBStableStore
fsms []*MockFSM
snaps []*FileSnapshotStore
trans []*InmemTransport
rafts []*Raft
}
func (c *cluster) Merge(other *cluster) {
c.dirs = append(c.dirs, other.dirs...)
c.logs = append(c.logs, other.logs...)
c.stores = append(c.stores, other.stores...)
c.fsms = append(c.fsms, other.fsms...)
c.snaps = append(c.snaps, other.snaps...)
c.trans = append(c.trans, other.trans...)
c.rafts = append(c.rafts, other.rafts...)
}
func (c *cluster) Close() {
var futures []Future
for _, r := range c.rafts {
futures = append(futures, r.Shutdown())
}
// Wait for shutdown
timer := time.AfterFunc(200*time.Millisecond, func() {
panic("timed out waiting for shutdown")
})
for _, f := range futures {
if err := f.Error(); err != nil {
panic(fmt.Errorf("shutdown future err: %v", err))
}
}
timer.Stop()
for _, l := range c.logs {
l.Close()
}
for _, s := range c.stores {
s.Close()
}
for _, d := range c.dirs {
os.RemoveAll(d)
}
}
func (c *cluster) GetInState(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.GetInState(Leader)) < 1 {
time.Sleep(time.Millisecond)
}
leaders := c.GetInState(Leader)
if len(leaders) != 1 {
panic(fmt.Errorf("expected one leader: %v", leaders))
}
return leaders[0]
}
func (c *cluster) FullyConnect() {
log.Printf("[WARN] Fully Connecting")
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) {
log.Printf("[WARN] Disconnecting %v", a)
for _, t := range c.trans {
if t.localAddr == a {
t.DisconnectAll()
} else {
t.Disconnect(a)
}
}
}
func (c *cluster) EnsureLeader(t *testing.T, expect net.Addr) {
limit := time.Now().Add(100 * time.Millisecond)
CHECK:
for _, r := range c.rafts {
leader := r.Leader()
if expect == nil {
if leader != nil {
if time.Now().After(limit) {
t.Fatalf("leader %v expected nil", leader)
} else {
goto WAIT
}
}
} else {
if leader == nil || leader.String() != expect.String() {
if time.Now().After(limit) {
t.Fatalf("leader %v expected %v", leader, expect)
} else {
goto WAIT
}
}
}
}
return
WAIT:
time.Sleep(10 * time.Millisecond)
goto CHECK
}
func (c *cluster) EnsureSame(t *testing.T) {
limit := time.Now().Add(200 * time.Millisecond)
first := c.fsms[0]
CHECK:
for i, fsm := range c.fsms {
if i == 0 {
continue
}
if len(first.logs) != len(fsm.logs) {
if time.Now().After(limit) {
t.Fatalf("length mismatch: %d %d",
len(first.logs), len(fsm.logs))
} else {
goto WAIT
}
}
for idx := 0; idx < len(first.logs); idx++ {
if bytes.Compare(first.logs[idx], fsm.logs[idx]) != 0 {
if time.Now().After(limit) {
t.Fatalf("log mismatch at index %d", idx)
} else {
goto WAIT
}
}
}
}
return
WAIT:
time.Sleep(20 * time.Millisecond)
goto CHECK
}
func raftToPeerSet(r *Raft) map[string]struct{} {
peers := make(map[string]struct{})
peers[r.localAddr.String()] = struct{}{}
for _, p := range r.peers {
peers[p.String()] = struct{}{}
}
return peers
}
func (c *cluster) EnsureSamePeers(t *testing.T) {
limit := time.Now().Add(200 * time.Millisecond)
peerSet := raftToPeerSet(c.rafts[0])
CHECK:
for i, raft := range c.rafts {
if i == 0 {
continue
}
otherSet := raftToPeerSet(raft)
if !reflect.DeepEqual(peerSet, otherSet) {
if time.Now().After(limit) {
t.Fatalf("peer mismatch: %v %v", peerSet, otherSet)
} else {
goto WAIT
}
}
}
return
WAIT:
time.Sleep(20 * time.Millisecond)
goto CHECK
}
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++ {
dir, logs, store := LevelDBTestStore(t)
c.dirs = append(c.dirs, dir)
c.logs = append(c.logs, logs)
c.stores = append(c.stores, store)
c.fsms = append(c.fsms, &MockFSM{})
dir2, snap := FileSnapTest(t)
c.dirs = append(c.dirs, dir2)
c.snaps = append(c.snaps, snap)
addr, trans := NewInmemTransport()
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()
}
logs := c.logs[i]
store := c.stores[i]
snap := c.snaps[i]
trans := c.trans[i]
peerStore := &StaticPeers{peers}
raft, err := NewRaft(conf, c.fsms[i], logs, store, snap, peerStore, trans)
if err != nil {
t.Fatalf("err: %v", err)
}
c.rafts = append(c.rafts, raft)
}
return c
}
func TestRaft_StartStop(t *testing.T) {
c := MakeCluster(1, t, nil)
c.Close()
}
func TestRaft_AfterShutdown(t *testing.T) {
c := MakeCluster(1, t, nil)
c.Close()
raft := c.rafts[0]
// Everything should fail now
if f := raft.Apply(nil, 0); f.Error() != RaftShutdown {
t.Fatalf("should be shutdown: %v", f.Error())
}
if f := raft.AddPeer(NewInmemAddr()); f.Error() != RaftShutdown {
t.Fatalf("should be shutdown: %v", f.Error())
}
if f := raft.RemovePeer(NewInmemAddr()); f.Error() != RaftShutdown {
t.Fatalf("should be shutdown: %v", f.Error())
}
if f := raft.Snapshot(); f.Error() != RaftShutdown {
t.Fatalf("should be shutdown: %v", f.Error())
}
// Should be idempotent
raft.Shutdown()
}
func TestRaft_SingleNode(t *testing.T) {
conf := inmemConfig()
c := MakeCluster(1, t, conf)
defer c.Close()
raft := c.rafts[0]
time.Sleep(conf.HeartbeatTimeout * 3)
// 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 the response
if future.Response().(int) != 1 {
t.Fatalf("bad response: %v", future.Response())
}
// Check that it is applied to the FSM
if len(c.fsms[0].logs) != 1 {
t.Fatalf("did not apply to FSM!")
}
}
func TestRaft_TripleNode(t *testing.T) {
// Make the cluster
c := MakeCluster(3, t, nil)
defer c.Close()
// Should be one leader
leader := c.Leader()
c.EnsureLeader(t, leader.localAddr)
// 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()
// Should be one leader
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
log.Printf("[INFO] Disconnecting %v", leader)
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.GetInState(Leader)
}
if len(leaders) != 2 {
t.Fatalf("expected two leader: %v", leaders)
}
// 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
log.Printf("[INFO] Reconnecting %v", leader)
c.FullyConnect()
// Future1 should fail
if err := future1.Error(); err != LeadershipLost {
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! %v", fsm.logs)
}
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
leader := c.Leader()
followers := c.GetInState(Follower)
behind := followers[0]
c.Disconnect(behind.localAddr)
// Commit a lot of things
var future Future
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)
} else {
log.Printf("[INFO] Finished apply without behind follower")
}
// Reconnect the behind node
c.FullyConnect()
// Ensure all the logs are the same
c.EnsureSame(t)
// Ensure one leader
leader = c.Leader()
c.EnsureLeader(t, leader.localAddr)
}
func TestRaft_ApplyNonLeader(t *testing.T) {
// Make the cluster
c := MakeCluster(3, t, nil)
defer c.Close()
// Wait for a leader
c.Leader()
time.Sleep(10 * time.Millisecond)
// Try to apply to them
followers := c.GetInState(Follower)
if len(followers) != 2 {
t.Fatalf("Expected 2 followers")
}
follower := followers[0]
// Try to apply
future := follower.Apply([]byte("test"), time.Millisecond)
if future.Error() != NotLeader {
t.Fatalf("should not apply on follower")
}
// Should be cached
if future.Error() != NotLeader {
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()
applyF := func(i int) {
future := leader.Apply([]byte(fmt.Sprintf("test%d", i)), 0)
if err := future.Error(); err != nil {
t.Fatalf("err: %v", err)
}
}
// Concurrently apply
for i := 0; i < 100; i++ {
go applyF(i)
}
// Block on the last one
applyF(100)
// Check the FSMs
c.EnsureSame(t)
}
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 future.Error() == EnqueueTimeout {
didTimeout = true
}
}(i)
}
// Wait
time.Sleep(20 * time.Millisecond)
// Some should have failed
if !didTimeout {
t.Fatalf("expected a timeout")
}
}
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'
var future Future
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.GetInState(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.GetInState(Follower)
}
if len(followers) != 2 {
t.Fatalf("expected two followers: %v", followers)
}
// Check the FSMs
c.EnsureSame(t)
// Check the peers
c.EnsureSamePeers(t)
// Ensure one leader
leader = c.Leader()
c.EnsureLeader(t, leader.localAddr)
}
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.GetInState(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")
}
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.GetInState(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()
// Wait a bit for log application
time.Sleep(20 * time.Millisecond)
// 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")
}
// Old leader should have no peers
if len(leader.peers) != 0 {
t.Fatalf("leader should have no peers")
}
}
func TestRaft_RemoveLeader_SplitCluster(t *testing.T) {
// Enable operation after a remove
conf := inmemConfig()
conf.ShutdownOnRemove = false
// Make a cluster
c := MakeCluster(3, t, conf)
defer c.Close()
// Get the leader
leader := c.Leader()
// Remove the leader
leader.RemovePeer(leader.localAddr)
// 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.GetInState(Leader)
}
if len(leaders) != 2 {
t.Fatalf("expected two leader: %v", leaders)
}
// Old leader should have no peers
if len(leader.peers) != 0 {
t.Fatalf("leader should have no peers")
}
}
func TestRaft_AddKnownPeer(t *testing.T) {
// Make a cluster
c := MakeCluster(3, t, nil)
defer c.Close()
// Get the leader
leader := c.Leader()
followers := c.GetInState(Follower)
// Add a follower
future := leader.AddPeer(followers[0].localAddr)
// Should be already added
if err := future.Error(); err != KnownPeer {
t.Fatalf("err: %v", err)
}
}
func TestRaft_RemoveUnknownPeer(t *testing.T) {
// Make a cluster
c := MakeCluster(3, t, nil)
defer c.Close()
// Get the leader
leader := c.Leader()
// Remove unknown
future := leader.RemovePeer(NewInmemAddr())
// Should be already added
if err := future.Error(); err != UnknownPeer {
t.Fatalf("err: %v", err)
}
}
func TestRaft_SnapshotRestore(t *testing.T) {
// Make the cluster
conf := inmemConfig()
conf.TrailingLogs = 10
c := MakeCluster(1, t, conf)
defer c.Close()
// Commit a lot of things
leader := c.Leader()
var future Future
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)
}
// Take a snapshot
snapFuture := leader.Snapshot()
if err := snapFuture.Error(); err != nil {
t.Fatalf("err: %v", err)
}
// Check for snapshot
if snaps, _ := leader.snapshots.List(); len(snaps) != 1 {
t.Fatalf("should have a snapshot")
}
// Logs should be trimmed
if idx, _ := leader.logs.FirstIndex(); idx != 92 {
t.Fatalf("should trim logs to 92: %d", idx)
}
// Shutdown
shutdown := leader.Shutdown()
if err := shutdown.Error(); err != nil {
t.Fatalf("err: %v", err)
}
// Restart the Raft
r := leader
r, err := NewRaft(r.conf, r.fsm, r.logs, r.stable,
r.snapshots, r.peerStore, r.trans)
if err != nil {
t.Fatalf("err: %v", err)
}
c.rafts[0] = r
// We should have restored from the snapshot!
if last := r.getLastApplied(); last != 101 {
t.Fatalf("bad last: %v", last)
}
}
func TestRaft_AutoSnapshot(t *testing.T) {
// Make the cluster
conf := inmemConfig()
conf.SnapshotInterval = 5 * time.Millisecond
conf.SnapshotThreshold = 50
conf.TrailingLogs = 10
c := MakeCluster(1, t, conf)
defer c.Close()
// Commit a lot of things
leader := c.Leader()
var future Future
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)
}
// Wait for a snapshot to happen
time.Sleep(50 * time.Millisecond)
// Check for snapshot
if snaps, _ := leader.snapshots.List(); len(snaps) == 0 {
t.Fatalf("should have a snapshot")
}
}
func TestRaft_SendSnapshotFollower(t *testing.T) {
// Make the cluster
conf := inmemConfig()
conf.TrailingLogs = 10
c := MakeCluster(3, t, conf)
defer c.Close()
// Disconnect one follower
followers := c.GetInState(Follower)
behind := followers[0]
c.Disconnect(behind.localAddr)
// Commit a lot of things
leader := c.Leader()
var future Future
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)
} else {
log.Printf("[INFO] Finished apply without behind follower")
}
// Snapshot, this will truncate logs!
for _, r := range c.rafts {
future = r.Snapshot()
if err := future.Error(); err != nil {
t.Fatalf("err: %v", err)
}
}
// Reconnect the behind node
c.FullyConnect()
// Ensure all the logs are the same
c.EnsureSame(t)
}