forked from lni/dragonboat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node_test.go
1373 lines (1310 loc) · 37.5 KB
/
node_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
// Copyright 2017-2019 Lei Ni (nilei81@gmail.com)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// +build !dragonboat_slowtest
// +build !dragonboat_errorinjectiontest
package dragonboat
import (
"context"
"fmt"
"io/ioutil"
"math/rand"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"sync"
"testing"
"time"
"github.com/lni/dragonboat/client"
"github.com/lni/dragonboat/config"
"github.com/lni/dragonboat/internal/logdb"
"github.com/lni/dragonboat/internal/raft"
"github.com/lni/dragonboat/internal/rsm"
"github.com/lni/dragonboat/internal/server"
"github.com/lni/dragonboat/internal/settings"
"github.com/lni/dragonboat/internal/tests"
"github.com/lni/dragonboat/internal/transport"
"github.com/lni/dragonboat/internal/utils/leaktest"
"github.com/lni/dragonboat/internal/utils/random"
"github.com/lni/dragonboat/raftio"
pb "github.com/lni/dragonboat/raftpb"
)
const (
raftTestTopDir = "raft_node_test_safe_to_delete"
logdbDir = "logdb_test_dir_safe_to_delete"
lowLatencyLogDBDir = "logdb_ll_test_dir_safe_to_delete"
snapDir = "snap_test_dir_safe_to_delete/snap-%d-%d"
testClusterID uint64 = 1100
tickMillisecond uint64 = 50
)
func getMemberNodes(r *rsm.StateMachine) []uint64 {
m, _, _, _ := r.GetMembership()
n := make([]uint64, 0)
for nid := range m {
n = append(n, nid)
}
return n
}
type testMessageRouter struct {
clusterID uint64
msgReceiveCh map[uint64]*server.MessageQueue
dropRate uint8
}
func mustComplete(rs *RequestState, t *testing.T) {
select {
case v := <-rs.CompletedC:
if !v.Completed() {
t.Fatalf("got %d, want %d", v, requestCompleted)
}
default:
t.Fatalf("failed to complete the proposal")
}
}
func mustReject(rs *RequestState, t *testing.T) {
select {
case v := <-rs.CompletedC:
if !v.Rejected() {
t.Errorf("got %d, want %d", v, requestRejected)
}
default:
t.Errorf("failed to complete the add node request")
}
}
func mustHasLeaderNode(nodes []*node, t *testing.T) *node {
for _, node := range nodes {
if node.isLeader() {
return node
}
}
t.Fatalf("no leader")
return nil
}
func newTestMessageRouter(clusterID uint64,
nodeIDList []uint64) *testMessageRouter {
chMap := make(map[uint64]*server.MessageQueue)
for _, nodeID := range nodeIDList {
ch := server.NewMessageQueue(1000, false, 0)
chMap[nodeID] = ch
}
rand.Seed(time.Now().UnixNano())
return &testMessageRouter{msgReceiveCh: chMap, clusterID: clusterID}
}
func (r *testMessageRouter) shouldDrop(msg pb.Message) bool {
if raft.IsLocalMessageType(msg.Type) {
return false
}
if r.dropRate == 0 {
return false
}
if rand.Uint32()%100 < uint32(r.dropRate) {
return true
}
return false
}
func (r *testMessageRouter) sendMessage(msg pb.Message) {
if msg.ClusterId != r.clusterID {
panic("cluster id does not match")
}
if r.shouldDrop(msg) {
return
}
if q, ok := r.msgReceiveCh[msg.To]; ok {
q.Add(msg)
}
}
func (r *testMessageRouter) getMessageReceiveChannel(clusterID uint64,
nodeID uint64) *server.MessageQueue {
if clusterID != r.clusterID {
panic("cluster id does not match")
}
ch, ok := r.msgReceiveCh[nodeID]
if !ok {
panic("node id not found in the test msg router")
}
return ch
}
func (r *testMessageRouter) addChannel(nodeID uint64, q *server.MessageQueue) {
r.msgReceiveCh[nodeID] = q
}
func cleanupTestDir() {
os.RemoveAll(raftTestTopDir)
}
func getTestRaftNodes(count int) ([]*node, []*rsm.StateMachine,
*testMessageRouter, raftio.ILogDB) {
return doGetTestRaftNodes(1, count, false, nil)
}
func doGetTestRaftNodes(startID uint64, count int, ordered bool,
ldb raftio.ILogDB) ([]*node, []*rsm.StateMachine,
*testMessageRouter, raftio.ILogDB) {
nodes := make([]*node, 0)
smList := make([]*rsm.StateMachine, 0)
nodeIDList := make([]uint64, 0)
// peers map
peers := make(map[uint64]string)
endID := startID + uint64(count-1)
for i := startID; i <= endID; i++ {
nodeIDList = append(nodeIDList, i)
peers[i] = fmt.Sprintf("peer:%d", 12345+i)
}
// pools
requestStatePool := &sync.Pool{}
requestStatePool.New = func() interface{} {
obj := &RequestState{}
obj.CompletedC = make(chan RequestResult, 1)
obj.pool = requestStatePool
return obj
}
var err error
if ldb == nil {
nodeLogDir := filepath.Join(raftTestTopDir, logdbDir)
nodeLowLatencyLogDir := filepath.Join(raftTestTopDir, lowLatencyLogDBDir)
os.MkdirAll(nodeLogDir, 0755)
os.MkdirAll(nodeLowLatencyLogDir, 0755)
ldb, err = logdb.OpenLogDB([]string{nodeLogDir}, []string{nodeLowLatencyLogDir})
if err != nil {
plog.Panicf("failed to open logdb, %v", err)
}
}
// message router
router := newTestMessageRouter(testClusterID, nodeIDList)
for i := startID; i <= endID; i++ {
// create the snapshotter object
nodeSnapDir := fmt.Sprintf(snapDir, testClusterID, i)
snapdir := filepath.Join(raftTestTopDir, nodeSnapDir)
os.MkdirAll(snapdir, 0755)
rootDirFunc := func(cid uint64, nid uint64) string {
return snapdir
}
snapshotter := newSnapshotter(testClusterID, i, rootDirFunc, ldb, nil)
// create the sm
sm := &tests.NoOP{}
ds := rsm.NewNativeStateMachine(sm, make(chan struct{}))
// node registry
nr := transport.NewNodes(settings.Soft.StreamConnections)
config := config.Config{
NodeID: uint64(i),
ClusterID: testClusterID,
ElectionRTT: 20,
HeartbeatRTT: 2,
CheckQuorum: true,
SnapshotEntries: 10,
CompactionOverhead: 10,
OrderedConfigChange: ordered,
}
addr := fmt.Sprintf("a%d", i)
ch := router.getMessageReceiveChannel(testClusterID, uint64(i))
node := newNode(addr,
peers,
true,
snapshotter,
ds,
func(uint64) {},
router.sendMessage,
ch,
make(chan struct{}),
nr,
requestStatePool,
config,
tickMillisecond,
ldb)
nodes = append(nodes, node)
smList = append(smList, node.sm)
}
return nodes, smList, router, ldb
}
var rtc raftio.IContext
func step(nodes []*node) bool {
hasEvent := false
nodeUpdates := make([]pb.Update, 0)
activeNodes := make([]*node, 0)
// step the events, collect all ready structs
for _, node := range nodes {
if !node.initialized() {
commit := rsm.Commit{
InitialSnapshot: true,
}
index, _ := node.sm.RecoverFromSnapshot(commit)
node.setInitialStatus(index)
}
if node.initialized() {
if node.handleEvents() {
hasEvent = true
ud, ok := node.getUpdate()
if ok {
nodeUpdates = append(nodeUpdates, ud)
activeNodes = append(activeNodes, node)
}
// quiesce state
if node.newQuiesceState() {
node.sendEnterQuiesceMessages()
}
}
}
}
// batch the snapshot records together and store them into the logdb
if err := nodes[0].logdb.SaveSnapshots(nodeUpdates); err != nil {
panic(err)
}
for idx, ud := range nodeUpdates {
node := activeNodes[idx]
node.processSnapshot(ud)
node.applyRaftUpdates(ud)
node.sendAppendMessages(ud)
node.processReadyToRead(ud)
}
if rtc == nil {
rtc = nodes[0].logdb.GetLogDBThreadContext()
} else {
rtc.Reset()
}
// persistent state and entries are saved first
// then the snapshot. order can not be change.
if err := nodes[0].logdb.SaveRaftState(nodeUpdates, rtc); err != nil {
panic(err)
}
for idx, ud := range nodeUpdates {
node := activeNodes[idx]
running := node.processRaftUpdate(ud)
node.commitRaftUpdate(ud)
if ud.LastApplied-node.getReqSnapshotIndex() > node.config.SnapshotEntries {
node.saveSnapshot()
}
if running {
commitRec, snapshotRequired := node.sm.Handle(make([]rsm.Commit, 0))
if snapshotRequired {
if commitRec.SnapshotAvailable || commitRec.InitialSnapshot {
if _, err := node.sm.RecoverFromSnapshot(commitRec); err != nil {
panic(err)
}
} else if commitRec.SnapshotRequested {
node.saveSnapshot()
}
}
}
}
return hasEvent
}
func singleStepNodes(nodes []*node, smList []*rsm.StateMachine,
r *testMessageRouter) {
for _, node := range nodes {
tickMsg := pb.Message{Type: pb.LocalTick, To: node.nodeID}
tickMsg.ClusterId = testClusterID
r.sendMessage(tickMsg)
}
step(nodes)
}
func stepNodes(nodes []*node, smList []*rsm.StateMachine,
r *testMessageRouter, timeout uint64) {
s := timeout/tickMillisecond + 10
for i := uint64(0); i < s; i++ {
for _, node := range nodes {
tickMsg := pb.Message{Type: pb.LocalTick, To: node.nodeID}
tickMsg.ClusterId = testClusterID
r.sendMessage(tickMsg)
}
step(nodes)
}
}
func stepNodesUntilThereIsLeader(nodes []*node, smList []*rsm.StateMachine,
r *testMessageRouter) {
count := 0
for {
stepNodes(nodes, smList, r, 1000)
count++
if isStableGroup(nodes) {
stepNodes(nodes, smList, r, 2000)
if isStableGroup(nodes) {
return
}
}
if count > 200 {
panic("failed to has any leader after 200 second")
}
}
}
func isStableGroup(nodes []*node) bool {
hasLeader := false
inElection := false
for _, node := range nodes {
if node.isLeader() {
hasLeader = true
continue
}
if node.node == nil || !node.isFollower() {
inElection = true
}
}
return hasLeader && !inElection
}
func stopNodes(nodes []*node) {
for _, node := range nodes {
node.close()
}
}
func TestNodeCanBeCreatedAndStarted(t *testing.T) {
defer leaktest.AfterTest(t)()
defer cleanupTestDir()
nodes, smList, router, ldb := getTestRaftNodes(3)
if len(nodes) != 3 {
t.Errorf("len(nodes)=%d, want 3", len(nodes))
}
if len(smList) != 3 {
t.Errorf("len(smList)=%d, want 3", len(smList))
}
defer stopNodes(nodes)
defer ldb.Close()
stepNodesUntilThereIsLeader(nodes, smList, router)
}
func getMaxLastApplied(smList []*rsm.StateMachine) uint64 {
maxLastApplied := uint64(0)
for _, sm := range smList {
la := sm.GetLastApplied()
if la > maxLastApplied {
maxLastApplied = la
}
}
return maxLastApplied
}
func getProposalTestClient(n *node,
nodes []*node, smList []*rsm.StateMachine,
router *testMessageRouter) (*client.Session, bool) {
cs := client.NewSession(n.clusterID, random.NewLockedRand())
cs.PrepareForRegister()
rs, err := n.pendingProposals.propose(cs, nil, nil, time.Duration(5*time.Second))
if err != nil {
plog.Errorf("error: %v", err)
return nil, false
}
stepNodes(nodes, smList, router, 5000)
select {
case v := <-rs.CompletedC:
if v.Completed() && v.GetResult() == cs.ClientID {
cs.PrepareForPropose()
return cs, true
}
plog.Infof("unknown result/code: %v", v)
case <-n.stopc:
plog.Errorf("stopc triggered")
return nil, false
}
plog.Errorf("failed get test client")
return nil, false
}
func closeProposalTestClient(n *node,
nodes []*node, smList []*rsm.StateMachine,
router *testMessageRouter, session *client.Session) {
session.PrepareForUnregister()
rs, err := n.pendingProposals.propose(session,
nil, nil, time.Duration(5*time.Second))
if err != nil {
return
}
stepNodes(nodes, smList, router, 5000)
select {
case v := <-rs.CompletedC:
if v.Completed() && v.GetResult() == session.ClientID {
return
}
case <-n.stopc:
return
}
}
func getTestTimeout(timeoutInMillisecond uint64) time.Duration {
return time.Duration(timeoutInMillisecond) * time.Millisecond
}
func makeCheckedTestProposal(t *testing.T, session *client.Session,
data []byte, timeoutInMillisecond uint64,
nodes []*node, smList []*rsm.StateMachine, router *testMessageRouter,
expectedCode RequestResultCode, checkResult bool, expectedResult uint64) {
n := mustHasLeaderNode(nodes, t)
timeout := getTestTimeout(timeoutInMillisecond)
rs, err := n.propose(session, data, nil, timeout)
if err != nil {
t.Fatalf("failed to make proposal")
}
stepNodes(nodes, smList, router, timeoutInMillisecond+1000)
select {
case v := <-rs.CompletedC:
if v.code != expectedCode {
t.Errorf("got %d, want %d", v, expectedCode)
}
if checkResult {
if v.GetResult() != expectedResult {
t.Errorf("result %d, want %d", v.GetResult(), expectedResult)
}
}
default:
t.Errorf("failed to complete the proposal")
}
}
func runRaftNodeTest(t *testing.T, quiesce bool,
tf func(t *testing.T, nodes []*node,
smList []*rsm.StateMachine, router *testMessageRouter, ldb raftio.ILogDB)) {
defer leaktest.AfterTest(t)()
defer cleanupTestDir()
nodes, smList, router, ldb := getTestRaftNodes(3)
if quiesce {
for idx := range nodes {
(nodes[idx]).quiesceManager.enabled = true
}
for _, node := range nodes {
if node.quiesced() {
t.Errorf("node quiesced on startup")
}
}
}
stepNodesUntilThereIsLeader(nodes, smList, router)
if len(nodes) != 3 {
t.Fatalf("failed to get 3 nodes")
}
defer stopNodes(nodes)
defer ldb.Close()
tf(t, nodes, smList, router, ldb)
}
func TestProposalCanBeMadeWithMessageDrops(t *testing.T) {
tf := func(t *testing.T, nodes []*node,
smList []*rsm.StateMachine, router *testMessageRouter, ldb raftio.ILogDB) {
router.dropRate = 3
n := mustHasLeaderNode(nodes, t)
var ok bool
var session *client.Session
for i := 0; i < 3; i++ {
session, ok = getProposalTestClient(n, nodes, smList, router)
if ok {
break
}
}
if session == nil {
t.Errorf("failed to get session")
return
}
for i := 0; i < 20; i++ {
plog.Infof("making proposal id %d", i)
maxLastApplied := getMaxLastApplied(smList)
makeCheckedTestProposal(t, session, []byte("test-data"), 4000,
nodes, smList, router, requestCompleted, false, 0)
session.ProposalCompleted()
if getMaxLastApplied(smList) != maxLastApplied+1 {
t.Errorf("didn't move the last applied value in smList")
}
}
closeProposalTestClient(n, nodes, smList, router, session)
}
runRaftNodeTest(t, false, tf)
}
func TestLeaderIDCanBeQueried(t *testing.T) {
tf := func(t *testing.T, nodes []*node,
smList []*rsm.StateMachine, router *testMessageRouter, ldb raftio.ILogDB) {
n := nodes[0]
v, ok := n.getLeaderID()
if !ok {
t.Errorf("failed to get leader id")
}
if v < 1 || v > 3 {
t.Errorf("unexpected leader id %d", v)
}
}
runRaftNodeTest(t, false, tf)
}
func TestMembershipCanBeLocallyRead(t *testing.T) {
tf := func(t *testing.T, nodes []*node,
smList []*rsm.StateMachine, router *testMessageRouter, ldb raftio.ILogDB) {
n := nodes[0]
v, _, _, _ := n.sm.GetMembership()
if len(v) != 3 {
t.Errorf("unexpected member count %d", len(v))
}
addr1, ok := v[1]
if !ok || addr1 != "peer:12346" {
t.Errorf("unexpected membership data %v", v)
}
addr2, ok := v[2]
if !ok || addr2 != "peer:12347" {
t.Errorf("unexpected membership data %v", v)
}
addr3, ok := v[3]
if !ok || addr3 != "peer:12348" {
t.Errorf("unexpected membership data %v", v)
}
}
runRaftNodeTest(t, false, tf)
}
func TestProposalWithClientSessionCanBeMade(t *testing.T) {
tf := func(t *testing.T, nodes []*node,
smList []*rsm.StateMachine, router *testMessageRouter, ldb raftio.ILogDB) {
n := nodes[0]
session, ok := getProposalTestClient(n, nodes, smList, router)
if !ok {
t.Errorf("failed to get session")
return
}
data := []byte("test-data")
maxLastApplied := getMaxLastApplied(smList)
makeCheckedTestProposal(t, session, data, 4000,
nodes, smList, router, requestCompleted, true, uint64(len(data)))
if getMaxLastApplied(smList) != maxLastApplied+1 {
t.Errorf("didn't move the last applied value in smList")
}
closeProposalTestClient(n, nodes, smList, router, session)
}
runRaftNodeTest(t, false, tf)
}
func TestProposalWithNotRegisteredClientWillBeRejected(t *testing.T) {
tf := func(t *testing.T, nodes []*node,
smList []*rsm.StateMachine, router *testMessageRouter, ldb raftio.ILogDB) {
n := nodes[0]
session, ok := getProposalTestClient(n, nodes, smList, router)
if !ok {
t.Errorf("failed to get session")
return
}
session.ClientID = 123456789
data := []byte("test-data")
maxLastApplied := getMaxLastApplied(smList)
makeCheckedTestProposal(t, session, data, 2000,
nodes, smList, router, requestRejected, true, 0)
if getMaxLastApplied(smList) != maxLastApplied+1 {
t.Errorf("didn't move the last applied value in smList")
}
}
runRaftNodeTest(t, false, tf)
}
func TestDuplicatedProposalReturnsTheSameResult(t *testing.T) {
tf := func(t *testing.T, nodes []*node,
smList []*rsm.StateMachine, router *testMessageRouter, ldb raftio.ILogDB) {
n := nodes[0]
session, ok := getProposalTestClient(n, nodes, smList, router)
if !ok {
t.Errorf("failed to get session")
return
}
data := []byte("test-data")
maxLastApplied := getMaxLastApplied(smList)
makeCheckedTestProposal(t, session, data, 2000,
nodes, smList, router, requestCompleted, true, uint64(len(data)))
if getMaxLastApplied(smList) != maxLastApplied+1 {
t.Errorf("didn't move the last applied value in smList")
}
data = []byte("test-data-2")
maxLastApplied = getMaxLastApplied(smList)
makeCheckedTestProposal(t, session, data, 2000,
nodes, smList, router, requestCompleted, true, uint64(len(data)-2))
if getMaxLastApplied(smList) != maxLastApplied+1 {
t.Errorf("didn't move the last applied value in smList")
}
closeProposalTestClient(n, nodes, smList, router, session)
}
runRaftNodeTest(t, false, tf)
}
func TestReproposeRespondedDataWillTimeout(t *testing.T) {
tf := func(t *testing.T, nodes []*node,
smList []*rsm.StateMachine, router *testMessageRouter, ldb raftio.ILogDB) {
n := nodes[0]
session, ok := getProposalTestClient(n, nodes, smList, router)
if !ok {
t.Errorf("failed to get session")
return
}
data := []byte("test-data")
maxLastApplied := getMaxLastApplied(smList)
_, err := n.propose(session, data, nil, time.Duration(2*time.Second))
if err != nil {
t.Fatalf("failed to make proposal")
}
stepNodes(nodes, smList, router, 2000)
if getMaxLastApplied(smList) != maxLastApplied+1 {
t.Errorf("didn't move the last applied value in smList")
}
respondedSeriesID := session.SeriesID
session.ProposalCompleted()
for i := 0; i < 3; i++ {
makeCheckedTestProposal(t, session, data, 2000,
nodes, smList, router, requestCompleted, true, uint64(len(data)))
session.ProposalCompleted()
respondedSeriesID = session.RespondedTo
}
session.SeriesID = respondedSeriesID
plog.Infof("series id %d, responded to %d",
session.SeriesID, session.RespondedTo)
rs, _ := n.propose(session, data, nil, time.Duration(2*time.Second))
stepNodes(nodes, smList, router, 2000)
select {
case v := <-rs.CompletedC:
if !v.Timeout() {
t.Errorf("didn't timeout, v: %d", v.code)
}
default:
t.Errorf("failed to complete the proposal")
}
}
runRaftNodeTest(t, false, tf)
}
func TestProposalsWithIllFormedSessionAreChecked(t *testing.T) {
tf := func(t *testing.T, nodes []*node,
smList []*rsm.StateMachine, router *testMessageRouter, ldb raftio.ILogDB) {
n := nodes[0]
s1 := client.NewSession(n.clusterID, random.NewLockedRand())
s1.SeriesID = client.SeriesIDForRegister
_, err := n.propose(s1, nil, nil, time.Second)
if err != ErrInvalidSession {
t.Errorf("not rejected")
}
s1 = client.NewSession(n.clusterID, random.NewLockedRand())
s1.SeriesID = client.SeriesIDForUnregister
_, err = n.propose(s1, nil, nil, time.Second)
if err != ErrInvalidSession {
t.Errorf("not rejected")
}
s1 = client.NewSession(n.clusterID, random.NewLockedRand())
s1.SeriesID = 100
s1.ClusterID = 123456
_, err = n.propose(s1, nil, nil, time.Second)
if err != ErrInvalidSession {
t.Errorf("not rejected")
}
s1 = client.NewSession(n.clusterID, random.NewLockedRand())
s1.SeriesID = 1
s1.ClientID = 0
_, err = n.propose(s1, nil, nil, time.Second)
if err != ErrInvalidSession {
t.Errorf("not rejected")
}
}
runRaftNodeTest(t, false, tf)
}
func TestProposalsWithCorruptedSessionWillPanic(t *testing.T) {
tf := func(t *testing.T, nodes []*node,
smList []*rsm.StateMachine, router *testMessageRouter, ldb raftio.ILogDB) {
n := nodes[0]
s1 := client.NewSession(n.clusterID, random.NewLockedRand())
s1.SeriesID = 100
s1.RespondedTo = 200
defer func() {
r := recover()
if r == nil {
t.Errorf("panic not triggered")
}
}()
n.propose(s1, nil, nil, time.Second)
}
runRaftNodeTest(t, false, tf)
}
func TestRaftNodeQuiesceCanBeDisabled(t *testing.T) {
defer leaktest.AfterTest(t)()
// quiesce is disabled by default
defer cleanupTestDir()
nodes, smList, router, ldb := getTestRaftNodes(3)
if len(nodes) != 3 {
t.Fatalf("failed to get 3 nodes")
}
for _, node := range nodes {
if node.quiesced() {
t.Errorf("node quiesced on startup")
}
}
stepNodesUntilThereIsLeader(nodes, smList, router)
defer stopNodes(nodes)
defer ldb.Close()
// need to step more than quiesce.threshold() as the startup
// config change messages are going to be recorded as activities
for i := uint64(0); i <= nodes[0].quiesceThreshold()*2; i++ {
singleStepNodes(nodes, smList, router)
}
for _, node := range nodes {
if node.quiesced() {
t.Errorf("node is quiesced when quiesce is not enabled")
}
}
}
func TestNodesCanEnterQuiesce(t *testing.T) {
tf := func(t *testing.T, nodes []*node,
smList []*rsm.StateMachine, router *testMessageRouter, ldb raftio.ILogDB) {
// need to step more than quiesce.threshold() as the startup
// config change messages are going to be recorded as activities
for i := uint64(0); i <= nodes[0].quiesceThreshold()*2; i++ {
singleStepNodes(nodes, smList, router)
}
for _, node := range nodes {
if !node.quiesced() {
t.Errorf("node failed to enter quiesced")
}
}
// step more, nodes should stay in quiesce state.
for i := uint64(0); i <= nodes[0].quiesceThreshold()*3; i++ {
singleStepNodes(nodes, smList, router)
}
for _, node := range nodes {
if !node.quiesced() {
t.Errorf("node failed to enter quiesced")
}
}
}
runRaftNodeTest(t, true, tf)
}
func TestNodesCanExitQuiesceByMakingProposal(t *testing.T) {
tf := func(t *testing.T, nodes []*node,
smList []*rsm.StateMachine, router *testMessageRouter, ldb raftio.ILogDB) {
// need to step more than quiesce.threshold() as the startup
// config change messages are going to be recorded as activities
for i := uint64(0); i <= nodes[0].quiesceThreshold()*2; i++ {
singleStepNodes(nodes, smList, router)
}
for _, node := range nodes {
if !node.quiesced() {
t.Errorf("node failed to enter quiesced")
}
}
n := nodes[0]
done := false
for i := 0; i < 5; i++ {
_, ok := getProposalTestClient(n, nodes, smList, router)
if ok {
done = true
break
}
}
if !done {
t.Errorf("failed to get proposal client -- didn't exit from quiesce?")
}
for i := uint64(0); i <= 3; i++ {
singleStepNodes(nodes, smList, router)
}
for _, node := range nodes {
if node.quiesced() {
t.Errorf("node failed to exit from quiesced")
}
}
}
runRaftNodeTest(t, true, tf)
}
func TestNodesCanExitQuiesceByReadIndex(t *testing.T) {
tf := func(t *testing.T, nodes []*node,
smList []*rsm.StateMachine, router *testMessageRouter, ldb raftio.ILogDB) {
// need to step more than quiesce.threshold() as the startup
// config change messages are going to be recorded as activities
for i := uint64(0); i <= nodes[0].quiesceThreshold()*2; i++ {
singleStepNodes(nodes, smList, router)
}
for _, node := range nodes {
if !node.quiesced() {
t.Errorf("node failed to enter quiesced")
}
}
n := nodes[0]
rs, err := n.read(nil, time.Second)
if err != nil {
t.Errorf("failed to read")
}
var done bool
for i := uint64(0); i <= 5; i++ {
singleStepNodes(nodes, smList, router)
select {
case <-rs.CompletedC:
done = true
default:
}
if done {
break
}
}
for _, node := range nodes {
if node.quiesced() {
t.Errorf("node failed to exit from quiesced")
}
}
}
runRaftNodeTest(t, true, tf)
}
func TestNodesCanExitQuiesceByConfigChange(t *testing.T) {
tf := func(t *testing.T, nodes []*node,
smList []*rsm.StateMachine, router *testMessageRouter, ldb raftio.ILogDB) {
// need to step more than quiesce.threshold() as the startup
// config change messages are going to be recorded as activities
for i := uint64(0); i <= nodes[0].quiesceThreshold()*2; i++ {
singleStepNodes(nodes, smList, router)
}
for _, node := range nodes {
if !node.quiesced() {
t.Errorf("node failed to enter quiesced")
}
}
n := nodes[0]
done := false
for i := 0; i < 5; i++ {
rs, err := n.requestAddNode(24680, "localhost:12345", time.Second)
if err != nil {
t.Errorf("request to add node failed, %v", err)
}
hasResp := false
for i := uint64(0); i < 25; i++ {
singleStepNodes(nodes, smList, router)
select {
case v := <-rs.CompletedC:
if v.Completed() {
done = true
}
hasResp = true
default:
continue
}
}
if !hasResp {
t.Errorf("config change timeout not fired")
return
}
if done {
break
}
}
for i := uint64(0); i < 20; i++ {
singleStepNodes(nodes, smList, router)
}
for _, node := range nodes {
if node.quiesced() {
t.Errorf("node failed to exit from quiesced")
}
}
}
runRaftNodeTest(t, true, tf)
}
func TestLinearizableReadCanBeMade(t *testing.T) {
tf := func(t *testing.T, nodes []*node,
smList []*rsm.StateMachine, router *testMessageRouter, ldb raftio.ILogDB) {
n := nodes[0]
session, ok := getProposalTestClient(n, nodes, smList, router)
if !ok {
t.Errorf("failed to get session")
return
}
rs, err := n.propose(session, []byte("test-data"), nil, time.Duration(2*time.Second))
if err != nil {
t.Fatalf("failed to make proposal")
}
stepNodes(nodes, smList, router, 2000)
mustComplete(rs, t)
closeProposalTestClient(n, nodes, smList, router, session)
rs, err = n.read(nil, time.Duration(2*time.Second))
if err != nil {
t.Fatalf("")
}
stepNodes(nodes, smList, router, 2500)
mustComplete(rs, t)
}
runRaftNodeTest(t, false, tf)
}
func testNodeCanBeAdded(t *testing.T) {
tf := func(t *testing.T, nodes []*node,
smList []*rsm.StateMachine, router *testMessageRouter, ldb raftio.ILogDB) {
router.dropRate = 3
n := mustHasLeaderNode(nodes, t)
rs, err := n.requestAddNode(4, "a4:4", time.Duration(5*time.Second))
if err != nil {
t.Fatalf("request to delete node failed")
}
stepNodes(nodes, smList, router, 6000)
mustComplete(rs, t)
for _, node := range nodes {
if !sliceEqual([]uint64{1, 2, 3, 4}, getMemberNodes(node.sm)) {
t.Errorf("failed to delete the node, %v", getMemberNodes(node.sm))
}
}
}
runRaftNodeTest(t, false, tf)
}
func TestNodeCanBeAddedWithMessageDrops(t *testing.T) {
defer leaktest.AfterTest(t)()
for i := 0; i < 10; i++ {
testNodeCanBeAdded(t)
}
}
func TestNodeCanBeDeleted(t *testing.T) {
tf := func(t *testing.T, nodes []*node,
smList []*rsm.StateMachine, router *testMessageRouter, ldb raftio.ILogDB) {
n := nodes[0]
rs, err := n.requestDeleteNode(2, time.Duration(2*time.Second))
if err != nil {
t.Fatalf("request to delete node failed")
}
stepNodes(nodes, smList, router, 2000)
mustComplete(rs, t)
if nodes[0].stopped() {
t.Errorf("node id 1 is not suppose to be in stopped state")
}
if !nodes[1].stopped() {
t.Errorf("node is not stopped")
}
if nodes[2].stopped() {
t.Errorf("node id 3 is not suppose to be in stopped state")