forked from hashicorp/raft
-
Notifications
You must be signed in to change notification settings - Fork 0
/
raft_test.go
2425 lines (2080 loc) · 64 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
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package raft
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"reflect"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/hashicorp/go-msgpack/codec"
)
// MockFSM is an implementation of the FSM interface, and just stores
// the logs sequentially.
type MockFSM struct {
sync.Mutex
logs [][]byte
}
type MockSnapshot struct {
logs [][]byte
maxIndex int
}
func (m *MockFSM) Apply(log *Log) interface{} {
m.Lock()
defer m.Unlock()
m.logs = append(m.logs, log.Data)
return len(m.logs)
}
func (m *MockFSM) Snapshot() (FSMSnapshot, error) {
m.Lock()
defer m.Unlock()
return &MockSnapshot{m.logs, len(m.logs)}, nil
}
func (m *MockFSM) Restore(inp io.ReadCloser) error {
m.Lock()
defer m.Unlock()
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(t *testing.T) *Config {
conf := DefaultConfig()
conf.HeartbeatTimeout = 50 * time.Millisecond
conf.ElectionTimeout = 50 * time.Millisecond
conf.LeaderLeaseTimeout = 50 * time.Millisecond
conf.CommitTimeout = 5 * time.Millisecond
conf.Logger = newTestLogger(t)
return conf
}
// This can be used as the destination for a logger and it'll
// map them into calls to testing.T.Log, so that you only see
// the logging for failed tests.
type testLoggerAdapter struct {
t *testing.T
prefix string
}
func (a *testLoggerAdapter) Write(d []byte) (int, error) {
if d[len(d)-1] == '\n' {
d = d[:len(d)-1]
}
if a.prefix != "" {
l := a.prefix + ": " + string(d)
if testing.Verbose() {
fmt.Printf("testLoggerAdapter verbose: %s\n", l)
}
a.t.Log(l)
return len(l), nil
}
a.t.Log(string(d))
return len(d), nil
}
func newTestLogger(t *testing.T) *log.Logger {
return log.New(&testLoggerAdapter{t: t}, "", log.Lmicroseconds)
}
func newTestLoggerWithPrefix(t *testing.T, prefix string) *log.Logger {
return log.New(&testLoggerAdapter{t: t, prefix: prefix}, "", log.Lmicroseconds)
}
type cluster struct {
dirs []string
stores []*InmemStore
fsms []*MockFSM
snaps []*FileSnapshotStore
trans []LoopbackTransport
rafts []*Raft
t *testing.T
observationCh chan Observation
conf *Config
propagateTimeout time.Duration
longstopTimeout time.Duration
logger *log.Logger
startTime time.Time
failedLock sync.Mutex
failedCh chan struct{}
failed bool
}
func (c *cluster) Merge(other *cluster) {
c.dirs = append(c.dirs, other.dirs...)
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...)
}
// notifyFailed will close the failed channel which can signal the goroutine
// running the test that another goroutine has detected a failure in order to
// terminate the test.
func (c *cluster) notifyFailed() {
c.failedLock.Lock()
defer c.failedLock.Unlock()
if !c.failed {
c.failed = true
close(c.failedCh)
}
}
// Failf provides a logging function that fails the tests, prints the output
// with microseconds, and does not mysteriously eat the string. This can be
// safely called from goroutines but won't immediately halt the test. The
// failedCh will be closed to allow blocking functions in the main thread to
// detect the failure and react. Note that you should arrange for the main
// thread to block until all goroutines have completed in order to reliably
// fail tests using this function.
func (c *cluster) Failf(format string, args ...interface{}) {
c.logger.Printf(format, args...)
c.t.Fail()
c.notifyFailed()
}
// FailNowf provides a logging function that fails the tests, prints the output
// with microseconds, and does not mysteriously eat the string. FailNowf must be
// called from the goroutine running the test or benchmark function, not from
// other goroutines created during the test. Calling FailNowf does not stop
// those other goroutines.
func (c *cluster) FailNowf(format string, args ...interface{}) {
c.logger.Printf(format, args...)
c.t.FailNow()
}
// Close shuts down the cluster and cleans up.
func (c *cluster) Close() {
var futures []Future
for _, r := range c.rafts {
futures = append(futures, r.Shutdown())
}
// Wait for shutdown
limit := time.AfterFunc(c.longstopTimeout, func() {
// We can't FailNowf here, and c.Failf won't do anything if we
// hang, so panic.
panic("timed out waiting for shutdown")
})
defer limit.Stop()
for _, f := range futures {
if err := f.Error(); err != nil {
c.FailNowf("[ERR] shutdown future err: %v", err)
}
}
for _, d := range c.dirs {
os.RemoveAll(d)
}
}
// WaitEventChan returns a channel which will signal if an observation is made
// or a timeout occurs. It is possible to set a filter to look for specific
// observations. Setting timeout to 0 means that it will wait forever until a
// non-filtered observation is made.
func (c *cluster) WaitEventChan(filter FilterFn, timeout time.Duration) <-chan struct{} {
ch := make(chan struct{})
go func() {
defer close(ch)
var timeoutCh <-chan time.Time
if timeout > 0 {
timeoutCh = time.After(timeout)
}
for {
select {
case <-timeoutCh:
return
case o, ok := <-c.observationCh:
if !ok || filter == nil || filter(&o) {
return
}
}
}
}()
return ch
}
// WaitEvent waits until an observation is made, a timeout occurs, or a test
// failure is signaled. It is possible to set a filter to look for specific
// observations. Setting timeout to 0 means that it will wait forever until a
// non-filtered observation is made or a test failure is signaled.
func (c *cluster) WaitEvent(filter FilterFn, timeout time.Duration) {
select {
case <-c.failedCh:
c.t.FailNow()
case <-c.WaitEventChan(filter, timeout):
}
}
// WaitForReplication blocks until every FSM in the cluster has the given
// length, or the long sanity check timeout expires.
func (c *cluster) WaitForReplication(fsmLength int) {
limitCh := time.After(c.longstopTimeout)
CHECK:
for {
ch := c.WaitEventChan(nil, c.conf.CommitTimeout)
select {
case <-c.failedCh:
c.t.FailNow()
case <-limitCh:
c.FailNowf("[ERR] Timeout waiting for replication")
case <-ch:
for _, fsm := range c.fsms {
fsm.Lock()
num := len(fsm.logs)
fsm.Unlock()
if num != fsmLength {
continue CHECK
}
}
return
}
}
}
// pollState takes a snapshot of the state of the cluster. This might not be
// stable, so use GetInState() to apply some additional checks when waiting
// for the cluster to achieve a particular state.
func (c *cluster) pollState(s RaftState) ([]*Raft, uint64) {
var highestTerm uint64
in := make([]*Raft, 0, 1)
for _, r := range c.rafts {
if r.State() == s {
in = append(in, r)
}
term := r.getCurrentTerm()
if term > highestTerm {
highestTerm = term
}
}
return in, highestTerm
}
// GetInState polls the state of the cluster and attempts to identify when it has
// settled into the given state.
func (c *cluster) GetInState(s RaftState) []*Raft {
c.logger.Printf("[INFO] Starting stability test for raft state: %+v", s)
limitCh := time.After(c.longstopTimeout)
// An election should complete after 2 * max(HeartbeatTimeout, ElectionTimeout)
// because of the randomised timer expiring in 1 x interval ... 2 x interval.
// We add a bit for propagation delay. If the election fails (e.g. because
// two elections start at once), we will have got something through our
// observer channel indicating a different state (i.e. one of the nodes
// will have moved to candidate state) which will reset the timer.
//
// Because of an implementation peculiarity, it can actually be 3 x timeout.
timeout := c.conf.HeartbeatTimeout
if timeout < c.conf.ElectionTimeout {
timeout = c.conf.ElectionTimeout
}
timeout = 2*timeout + c.conf.CommitTimeout
timer := time.NewTimer(timeout)
defer timer.Stop()
// Wait until we have a stable instate slice. Each time we see an
// observation a state has changed, recheck it and if it has changed,
// restart the timer.
var pollStartTime = time.Now()
for {
inState, highestTerm := c.pollState(s)
inStateTime := time.Now()
// Sometimes this routine is called very early on before the
// rafts have started up. We then timeout even though no one has
// even started an election. So if the highest term in use is
// zero, we know there are no raft processes that have yet issued
// a RequestVote, and we set a long time out. This is fixed when
// we hear the first RequestVote, at which point we reset the
// timer.
if highestTerm == 0 {
timer.Reset(c.longstopTimeout)
} else {
timer.Reset(timeout)
}
// Filter will wake up whenever we observe a RequestVote.
filter := func(ob *Observation) bool {
switch ob.Data.(type) {
case RaftState:
return true
case RequestVoteRequest:
return true
default:
return false
}
}
select {
case <-c.failedCh:
c.t.FailNow()
case <-limitCh:
c.FailNowf("[ERR] Timeout waiting for stable %s state", s)
case <-c.WaitEventChan(filter, 0):
c.logger.Printf("[DEBUG] Resetting stability timeout")
case t, ok := <-timer.C:
if !ok {
c.FailNowf("[ERR] Timer channel errored")
}
c.logger.Printf("[INFO] Stable state for %s reached at %s (%d nodes), %s from start of poll, %s from cluster start. Timeout at %s, %s after stability",
s, inStateTime, len(inState), inStateTime.Sub(pollStartTime), inStateTime.Sub(c.startTime), t, t.Sub(inStateTime))
return inState
}
}
}
// Leader waits for the cluster to elect a leader and stay in a stable state.
func (c *cluster) Leader() *Raft {
leaders := c.GetInState(Leader)
if len(leaders) != 1 {
c.FailNowf("[ERR] expected one leader: %v", leaders)
}
return leaders[0]
}
// Followers waits for the cluster to have N-1 followers and stay in a stable
// state.
func (c *cluster) Followers() []*Raft {
expFollowers := len(c.rafts) - 1
followers := c.GetInState(Follower)
if len(followers) != expFollowers {
c.FailNowf("[ERR] timeout waiting for %d followers (followers are %v)", expFollowers, followers)
}
return followers
}
// FullyConnect connects all the transports together.
func (c *cluster) FullyConnect() {
c.logger.Printf("[DEBUG] 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)
}
}
}
}
// Disconnect disconnects all transports from the given address.
func (c *cluster) Disconnect(a ServerAddress) {
c.logger.Printf("[DEBUG] Disconnecting %v", a)
for _, t := range c.trans {
if t.LocalAddr() == a {
t.DisconnectAll()
} else {
t.Disconnect(a)
}
}
}
// Partition keeps the given list of addresses connected but isolates them
// from the other members of the cluster.
func (c *cluster) Partition(far []ServerAddress) {
c.logger.Printf("[DEBUG] Partitioning %v", far)
// Gather the set of nodes on the "near" side of the partition (we
// will call the supplied list of nodes the "far" side).
near := make(map[ServerAddress]struct{})
OUTER:
for _, t := range c.trans {
l := t.LocalAddr()
for _, a := range far {
if l == a {
continue OUTER
}
}
near[l] = struct{}{}
}
// Now fixup all the connections. The near side will be separated from
// the far side, and vice-versa.
for _, t := range c.trans {
l := t.LocalAddr()
if _, ok := near[l]; ok {
for _, a := range far {
t.Disconnect(a)
}
} else {
for a, _ := range near {
t.Disconnect(a)
}
}
}
}
// IndexOf returns the index of the given raft instance.
func (c *cluster) IndexOf(r *Raft) int {
for i, n := range c.rafts {
if n == r {
return i
}
}
return -1
}
// EnsureLeader checks that ALL the nodes think the leader is the given expected
// leader.
func (c *cluster) EnsureLeader(t *testing.T, expect ServerAddress) {
// We assume c.Leader() has been called already; now check all the rafts
// think the leader is correct
fail := false
for _, r := range c.rafts {
leader := ServerAddress(r.Leader())
if leader != expect {
if leader == "" {
leader = "[none]"
}
if expect == "" {
c.logger.Printf("[ERR] Peer %s sees leader %v expected [none]", r, leader)
} else {
c.logger.Printf("[ERR] Peer %s sees leader %v expected %v", r, leader, expect)
}
fail = true
}
}
if fail {
c.FailNowf("[ERR] At least one peer has the wrong notion of leader")
}
}
// EnsureSame makes sure all the FSMs have the same contents.
func (c *cluster) EnsureSame(t *testing.T) {
limit := time.Now().Add(c.longstopTimeout)
first := c.fsms[0]
CHECK:
first.Lock()
for i, fsm := range c.fsms {
if i == 0 {
continue
}
fsm.Lock()
if len(first.logs) != len(fsm.logs) {
fsm.Unlock()
if time.Now().After(limit) {
c.FailNowf("[ERR] FSM log 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 {
fsm.Unlock()
if time.Now().After(limit) {
c.FailNowf("[ERR] FSM log mismatch at index %d", idx)
} else {
goto WAIT
}
}
}
fsm.Unlock()
}
first.Unlock()
return
WAIT:
first.Unlock()
c.WaitEvent(nil, c.conf.CommitTimeout)
goto CHECK
}
// getConfiguration returns the configuration of the given Raft instance, or
// fails the test if there's an error
func (c *cluster) getConfiguration(r *Raft) Configuration {
future := r.GetConfiguration()
if err := future.Error(); err != nil {
c.FailNowf("[ERR] failed to get configuration: %v", err)
return Configuration{}
}
return future.Configuration()
}
// EnsureSamePeers makes sure all the rafts have the same set of peers.
func (c *cluster) EnsureSamePeers(t *testing.T) {
limit := time.Now().Add(c.longstopTimeout)
peerSet := c.getConfiguration(c.rafts[0])
CHECK:
for i, raft := range c.rafts {
if i == 0 {
continue
}
otherSet := c.getConfiguration(raft)
if !reflect.DeepEqual(peerSet, otherSet) {
if time.Now().After(limit) {
c.FailNowf("[ERR] peer mismatch: %+v %+v", peerSet, otherSet)
} else {
goto WAIT
}
}
}
return
WAIT:
c.WaitEvent(nil, c.conf.CommitTimeout)
goto CHECK
}
// makeCluster will return a cluster with the given config and number of peers.
// If bootstrap is true, the servers will know about each other before starting,
// otherwise their transports will be wired up but they won't yet have configured
// each other.
func makeCluster(n int, bootstrap bool, t *testing.T, conf *Config) *cluster {
if conf == nil {
conf = inmemConfig(t)
}
c := &cluster{
observationCh: make(chan Observation, 1024),
conf: conf,
// Propagation takes a maximum of 2 heartbeat timeouts (time to
// get a new heartbeat that would cause a commit) plus a bit.
propagateTimeout: conf.HeartbeatTimeout*2 + conf.CommitTimeout,
longstopTimeout: 5 * time.Second,
logger: newTestLoggerWithPrefix(t, "cluster"),
failedCh: make(chan struct{}),
}
c.t = t
var configuration Configuration
// Setup the stores and transports
for i := 0; i < n; i++ {
dir, err := ioutil.TempDir("", "raft")
if err != nil {
c.FailNowf("[ERR] err: %v ", err)
}
store := NewInmemStore()
c.dirs = append(c.dirs, dir)
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)
localID := ServerID(fmt.Sprintf("server-%s", addr))
if conf.ProtocolVersion < 3 {
localID = ServerID(addr)
}
configuration.Servers = append(configuration.Servers, Server{
Suffrage: Voter,
ID: localID,
Address: addr,
})
}
// Wire the transports together
c.FullyConnect()
// Create all the rafts
c.startTime = time.Now()
for i := 0; i < n; i++ {
logs := c.stores[i]
store := c.stores[i]
snap := c.snaps[i]
trans := c.trans[i]
peerConf := conf
peerConf.LocalID = configuration.Servers[i].ID
peerConf.Logger = newTestLoggerWithPrefix(t, string(configuration.Servers[i].ID))
if bootstrap {
err := BootstrapCluster(peerConf, logs, store, snap, trans, configuration)
if err != nil {
c.FailNowf("[ERR] BootstrapCluster failed: %v", err)
}
}
raft, err := NewRaft(peerConf, c.fsms[i], logs, store, snap, trans)
if err != nil {
c.FailNowf("[ERR] NewRaft failed: %v", err)
}
raft.RegisterObserver(NewObserver(c.observationCh, false, nil))
if err != nil {
c.FailNowf("[ERR] RegisterObserver failed: %v", err)
}
c.rafts = append(c.rafts, raft)
}
return c
}
// See makeCluster. This adds the peers initially to the peer store.
func MakeCluster(n int, t *testing.T, conf *Config) *cluster {
return makeCluster(n, true, t, conf)
}
// See makeCluster. This doesn't add the peers initially to the peer store.
func MakeClusterNoBootstrap(n int, t *testing.T, conf *Config) *cluster {
return makeCluster(n, false, t, conf)
}
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() != ErrRaftShutdown {
c.FailNowf("[ERR] should be shutdown: %v", f.Error())
}
// TODO (slackpad) - Barrier, VerifyLeader, and GetConfiguration can get
// stuck if the buffered channel consumes the future but things are shut
// down so they never get processed.
if f := raft.AddVoter(ServerID("id"), ServerAddress("addr"), 0, 0); f.Error() != ErrRaftShutdown {
c.FailNowf("[ERR] should be shutdown: %v", f.Error())
}
if f := raft.AddNonvoter(ServerID("id"), ServerAddress("addr"), 0, 0); f.Error() != ErrRaftShutdown {
c.FailNowf("[ERR] should be shutdown: %v", f.Error())
}
if f := raft.RemoveServer(ServerID("id"), 0, 0); f.Error() != ErrRaftShutdown {
c.FailNowf("[ERR] should be shutdown: %v", f.Error())
}
if f := raft.DemoteVoter(ServerID("id"), 0, 0); f.Error() != ErrRaftShutdown {
c.FailNowf("[ERR] should be shutdown: %v", f.Error())
}
if f := raft.Snapshot(); f.Error() != ErrRaftShutdown {
c.FailNowf("[ERR] should be shutdown: %v", f.Error())
}
// Should be idempotent
if f := raft.Shutdown(); f.Error() != nil {
c.FailNowf("[ERR] shutdown should be idempotent")
}
}
func TestRaft_LiveBootstrap(t *testing.T) {
// Make the cluster.
c := MakeClusterNoBootstrap(3, t, nil)
defer c.Close()
// Build the configuration.
configuration := Configuration{}
for _, r := range c.rafts {
server := Server{
ID: r.localID,
Address: r.localAddr,
}
configuration.Servers = append(configuration.Servers, server)
}
// Bootstrap one of the nodes live.
boot := c.rafts[0].BootstrapCluster(configuration)
if err := boot.Error(); err != nil {
c.FailNowf("[ERR] bootstrap err: %v", err)
}
// Should be one leader.
c.Followers()
leader := c.Leader()
c.EnsureLeader(t, leader.localAddr)
// Should be able to apply.
future := leader.Apply([]byte("test"), c.conf.CommitTimeout)
if err := future.Error(); err != nil {
c.FailNowf("[ERR] apply err: %v", err)
}
c.WaitForReplication(1)
// Make sure the live bootstrap fails now that things are started up.
boot = c.rafts[0].BootstrapCluster(configuration)
if err := boot.Error(); err != ErrCantBootstrap {
c.FailNowf("[ERR] bootstrap should have failed: %v", err)
}
}
func TestRaft_RecoverCluster_NoState(t *testing.T) {
c := MakeClusterNoBootstrap(1, t, nil)
defer c.Close()
r := c.rafts[0]
configuration := Configuration{
Servers: []Server{
Server{
ID: r.localID,
Address: r.localAddr,
},
},
}
err := RecoverCluster(&r.conf, &MockFSM{}, r.logs, r.stable,
r.snapshots, r.trans, configuration)
if err == nil || !strings.Contains(err.Error(), "no initial state") {
c.FailNowf("[ERR] should have failed for no initial state: %v", err)
}
}
func TestRaft_RecoverCluster(t *testing.T) {
// Run with different number of applies which will cover no snapshot and
// snapshot + log scenarios. By sweeping through the trailing logs value
// we will also hit the case where we have a snapshot only.
runRecover := func(applies int) {
conf := inmemConfig(t)
conf.TrailingLogs = 10
c := MakeCluster(3, t, conf)
defer c.Close()
// Perform some commits.
c.logger.Printf("[DEBUG] Running with applies=%d", applies)
leader := c.Leader()
for i := 0; i < applies; i++ {
future := leader.Apply([]byte(fmt.Sprintf("test%d", i)), 0)
if err := future.Error(); err != nil {
c.FailNowf("[ERR] apply err: %v", err)
}
}
// Snap the configuration.
future := leader.GetConfiguration()
if err := future.Error(); err != nil {
c.FailNowf("[ERR] get configuration err: %v", err)
}
configuration := future.Configuration()
// Shut down the cluster.
for _, sec := range c.rafts {
if err := sec.Shutdown().Error(); err != nil {
c.FailNowf("[ERR] shutdown err: %v", err)
}
}
// Recover the cluster. We need to replace the transport and we
// replace the FSM so no state can carry over.
for i, r := range c.rafts {
before, err := r.snapshots.List()
if err != nil {
c.FailNowf("[ERR] snapshot list err: %v", err)
}
if err := RecoverCluster(&r.conf, &MockFSM{}, r.logs, r.stable,
r.snapshots, r.trans, configuration); err != nil {
c.FailNowf("[ERR] recover err: %v", err)
}
// Make sure the recovery looks right.
after, err := r.snapshots.List()
if err != nil {
c.FailNowf("[ERR] snapshot list err: %v", err)
}
if len(after) != len(before)+1 {
c.FailNowf("[ERR] expected a new snapshot, %d vs. %d", len(before), len(after))
}
first, err := r.logs.FirstIndex()
if err != nil {
c.FailNowf("[ERR] first log index err: %v", err)
}
last, err := r.logs.LastIndex()
if err != nil {
c.FailNowf("[ERR] last log index err: %v", err)
}
if first != 0 || last != 0 {
c.FailNowf("[ERR] expected empty logs, got %d/%d", first, last)
}
// Fire up the recovered Raft instance. We have to patch
// up the cluster state manually since this is an unusual
// operation.
_, trans := NewInmemTransport(r.localAddr)
r2, err := NewRaft(&r.conf, &MockFSM{}, r.logs, r.stable, r.snapshots, trans)
if err != nil {
c.FailNowf("[ERR] new raft err: %v", err)
}
c.rafts[i] = r2
c.trans[i] = r2.trans.(*InmemTransport)
c.fsms[i] = r2.fsm.(*MockFSM)
}
c.FullyConnect()
time.Sleep(c.propagateTimeout)
// Let things settle and make sure we recovered.
c.EnsureLeader(t, c.Leader().localAddr)
c.EnsureSame(t)
c.EnsureSamePeers(t)
}
for applies := 0; applies < 20; applies++ {
runRecover(applies)
}
}
func TestRaft_HasExistingState(t *testing.T) {
// Make a cluster.
c := MakeCluster(2, t, nil)
defer c.Close()
// Make a new cluster of 1.
c1 := MakeClusterNoBootstrap(1, t, nil)
// Make sure the initial state is clean.
hasState, err := HasExistingState(c1.rafts[0].logs, c1.rafts[0].stable, c1.rafts[0].snapshots)
if err != nil || hasState {
c.FailNowf("[ERR] should not have any existing state, %v", err)
}
// Merge clusters.
c.Merge(c1)
c.FullyConnect()
// Join the new node in.
future := c.Leader().AddVoter(c1.rafts[0].localID, c1.rafts[0].localAddr, 0, 0)
if err := future.Error(); err != nil {
c.FailNowf("[ERR] err: %v", err)
}
// Check the FSMs.
c.EnsureSame(t)
// Check the peers.
c.EnsureSamePeers(t)
// Ensure one leader.
c.EnsureLeader(t, c.Leader().localAddr)
// Make sure it's not clean.
hasState, err = HasExistingState(c1.rafts[0].logs, c1.rafts[0].stable, c1.rafts[0].snapshots)
if err != nil || !hasState {
c.FailNowf("[ERR] should have some existing state, %v", err)
}
}
func TestRaft_SingleNode(t *testing.T) {
conf := inmemConfig(t)
c := MakeCluster(1, t, conf)
defer c.Close()
raft := c.rafts[0]
// Watch leaderCh for change
select {
case v := <-raft.LeaderCh():
if !v {
c.FailNowf("[ERR] should become leader")
}
case <-time.After(conf.HeartbeatTimeout * 3):
c.FailNowf("[ERR] timeout becoming leader")
}
// Should be leader
if s := raft.State(); s != Leader {
c.FailNowf("[ERR] expected leader: %v", s)
}
// Should be able to apply
future := raft.Apply([]byte("test"), c.conf.HeartbeatTimeout)
if err := future.Error(); err != nil {
c.FailNowf("[ERR] err: %v", err)
}
// Check the response
if future.Response().(int) != 1 {
c.FailNowf("[ERR] bad response: %v", future.Response())
}
// Check the index
if idx := future.Index(); idx == 0 {
c.FailNowf("[ERR] bad index: %d", idx)
}
// Check that it is applied to the FSM
if len(c.fsms[0].logs) != 1 {
c.FailNowf("[ERR] 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
c.Followers()
leader := c.Leader()
c.EnsureLeader(t, leader.localAddr)
// Should be able to apply
future := leader.Apply([]byte("test"), c.conf.CommitTimeout)
if err := future.Error(); err != nil {
c.FailNowf("[ERR] err: %v", err)
}
c.WaitForReplication(1)
}
func TestRaft_LeaderFail(t *testing.T) {
// Make the cluster
c := MakeCluster(3, t, nil)
defer c.Close()
// Should be one leader
c.Followers()
leader := c.Leader()
// Should be able to apply
future := leader.Apply([]byte("test"), c.conf.CommitTimeout)
if err := future.Error(); err != nil {
c.FailNowf("[ERR] err: %v", err)
}
c.WaitForReplication(1)
// Disconnect the leader now
t.Logf("[INFO] Disconnecting %v", leader)
leaderTerm := leader.getCurrentTerm()
c.Disconnect(leader.localAddr)
// Wait for new leader
limit := time.Now().Add(c.longstopTimeout)
var newLead *Raft
for time.Now().Before(limit) && newLead == nil {
c.WaitEvent(nil, c.conf.CommitTimeout)
leaders := c.GetInState(Leader)
if len(leaders) == 1 && leaders[0] != leader {
newLead = leaders[0]
}
}
if newLead == nil {
c.FailNowf("[ERR] expected new leader")
}
// Ensure the term is greater
if newLead.getCurrentTerm() <= leaderTerm {
c.FailNowf("[ERR] expected newer term! %d %d (%v, %v)", newLead.getCurrentTerm(), leaderTerm, newLead, leader)
}
// Apply should work not work on old leader
future1 := leader.Apply([]byte("fail"), c.conf.CommitTimeout)