forked from lni/dragonboat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mtutils_test.go
1503 lines (1426 loc) · 42 KB
/
mtutils_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_monkeytest dragonboat_slowtest
package drummer
import (
"context"
"crypto/md5"
"encoding/binary"
"encoding/json"
"fmt"
"io/ioutil"
"math"
"math/rand"
"os"
"path/filepath"
"runtime"
"runtime/pprof"
"strconv"
"sync/atomic"
"testing"
"time"
"github.com/golang/protobuf/proto"
"github.com/lni/dragonboat"
"github.com/lni/dragonboat/config"
"github.com/lni/dragonboat/drummer/client"
pb "github.com/lni/dragonboat/drummer/drummerpb"
mr "github.com/lni/dragonboat/drummer/multiraftpb"
kvpb "github.com/lni/dragonboat/internal/tests/kvpb"
"github.com/lni/dragonboat/internal/tests/lcm"
"github.com/lni/dragonboat/internal/utils/logutil"
"github.com/lni/dragonboat/internal/utils/random"
"github.com/lni/dragonboat/internal/utils/syncutil"
"github.com/lni/dragonboat/raftpb"
)
const (
mtClusterID uint64 = 100
// these magic values allow us to immediately tell whether an interested node
// is the initial member of the cluster or joined later at certain point.
mtNodeID1 uint64 = 2345
mtNodeID2 uint64 = 6789
mtNodeID3 uint64 = 9876
monkeyTestSecondToRun uint64 = 1200
testClientWorkerCount uint64 = 32
numOfClustersInMonkeyTesting uint64 = 128
numOfTestDrummerNodes uint64 = 3
numOfTestNodeHostNodes uint64 = 5
LCMWorkerCount uint64 = 32
defaultBasePort uint64 = 5700
partitionCycle uint64 = 60
partitionMinSecond uint64 = 20
partitionMinStartSecond uint64 = 200
partitionCycleInterval uint64 = 60
partitionCycleMinInterval uint64 = 30
maxWaitForStopSecond int = 60
maxWaitForSyncSecond int = 120
waitForStableSecond uint64 = 25
// node uptime
nodeUpTimeLowMillisecond int64 = 150000
nodeUpTimeHighMillisecond int64 = 240000
lowUpTimeLowMillisecond int64 = 1000
lowUpTimeHighMillisecond int64 = 50000
defaultTestTimeout = 5 * time.Second
clusterCheckWaitSecond = 20 * time.Second
maxAllowedHeapSize = 1024 * 1024 * 1024 * 4
)
var (
mtNodeIDList = []uint64{
mtNodeID1,
mtNodeID2,
mtNodeID3,
}
caFile = "templates/tests/test-root-ca.crt"
certFile = "templates/tests/localhost.crt"
keyFile = "templates/tests/localhost.key"
)
type mtAddressList struct {
addressList []string
nodehostAddressList []string
apiAddressList []string
nodehostAPIAddressList []string
}
func newDrummerMonkeyTestAddr() *mtAddressList {
d := &mtAddressList{
addressList: make([]string, 0),
nodehostAddressList: make([]string, 0),
apiAddressList: make([]string, 0),
nodehostAPIAddressList: make([]string, 0),
}
return d
}
func (d *mtAddressList) fill(base uint64) {
port := base + 1
for i := uint64(0); i < uint64(numOfTestDrummerNodes); i++ {
addr := fmt.Sprintf("localhost:%d", port)
d.addressList = append(d.addressList, addr)
port++
}
for i := uint64(0); i < uint64(numOfTestNodeHostNodes); i++ {
addr := fmt.Sprintf("localhost:%d", port)
d.nodehostAddressList = append(d.nodehostAddressList, addr)
port++
}
for i := uint64(0); i < uint64(numOfTestDrummerNodes); i++ {
addr := fmt.Sprintf("localhost:%d", port)
d.apiAddressList = append(d.apiAddressList, addr)
port++
}
for i := uint64(0); i < uint64(numOfTestNodeHostNodes); i++ {
addr := fmt.Sprintf("localhost:%d", port)
d.nodehostAPIAddressList = append(d.nodehostAPIAddressList, addr)
port++
}
}
func getDrummerMonkeyTestAddrList() *mtAddressList {
base := defaultBasePort
v := os.Getenv("DRUMMERMTPORT")
if len(v) > 0 {
iv, err := strconv.Atoi(v)
if err != nil {
panic(err)
}
base = uint64(iv)
plog.Infof("using port base from env %d", base)
} else {
plog.Infof("using default port base %d", base)
}
dl := newDrummerMonkeyTestAddr()
dl.fill(base)
return dl
}
type nodeType uint64
const (
monkeyTestWorkingDir = "drummer_mt_pwd_safe_to_delete"
nodeTypeDrummer nodeType = iota
nodeTypeNodehost
)
func (t nodeType) String() string {
if t == nodeTypeDrummer {
return "DrummerNode"
} else if t == nodeTypeNodehost {
return "NodehostNode"
} else {
panic("unknown type")
}
}
func prepareMonkeyTestDirs(dl *mtAddressList) ([]string, []string) {
removeMonkeyTestDir()
drummerDirList := make([]string, 0)
nodehostDirList := make([]string, 0)
// drummer first
for i := uint64(1); i <= uint64(len(dl.addressList)); i++ {
nn := fmt.Sprintf("drummer-node-%d", i)
nd := filepath.Join(monkeyTestWorkingDir, nn)
if err := os.MkdirAll(nd, 0755); err != nil {
panic(err)
}
drummerDirList = append(drummerDirList, nd)
}
// nodehost dirs
for i := uint64(1); i <= uint64(len(dl.nodehostAddressList)); i++ {
nn := fmt.Sprintf("nodehost-node-%d", i)
nd := filepath.Join(monkeyTestWorkingDir, nn)
if err := os.MkdirAll(nd, 0755); err != nil {
panic(err)
}
nodehostDirList = append(nodehostDirList, nd)
}
return drummerDirList, nodehostDirList
}
func removeMonkeyTestDir() {
os.RemoveAll(monkeyTestWorkingDir)
}
func saveMonkeyTestDir() {
newName := fmt.Sprintf("%s-%d", monkeyTestWorkingDir, rand.Uint64())
plog.Infof("going to save the monkey test data dir to %s", newName)
if err := os.Rename(monkeyTestWorkingDir, newName); err != nil {
panic(err)
}
}
func getMonkeyTestConfig() (config.Config, config.NodeHostConfig) {
rc := config.Config{
ElectionRTT: 20,
HeartbeatRTT: 1,
CheckQuorum: true,
SnapshotEntries: 100,
CompactionOverhead: 100,
}
nhc := config.NodeHostConfig{
WALDir: "drummermt",
NodeHostDir: "drummermt",
RTTMillisecond: 50,
}
return rc, nhc
}
type testNode struct {
nodeType nodeType
listIndex uint64
dir string
nh *dragonboat.NodeHost
drummer *Drummer
apiServer *NodehostAPI
drummerStopped bool
stopped bool
partitionTestNode bool
partitionStartTime map[uint64]struct{}
partitionEndTime map[uint64]struct{}
next int64
stopper *syncutil.Stopper
mutualTLS bool
}
func (n *testNode) MustBeDrummerNode() {
if n.nodeType != nodeTypeDrummer {
panic("not drummer node")
}
}
func (n *testNode) MustBeNodehostNode() {
if n.nodeType != nodeTypeNodehost {
panic("not nodehost node")
}
}
func (n *testNode) IsDrummerLeader() bool {
n.MustBeDrummerNode()
return n.drummer.isLeaderDrummerNode()
}
func (n *testNode) DoPartitionTests(monkeyPlaySeconds uint64) {
st := partitionMinStartSecond
et := st
plog.Infof("node %d is set to use partition test mode", n.listIndex+1)
n.partitionTestNode = true
for {
partitionTime := rand.Uint64() % partitionCycle
if partitionTime < partitionMinSecond {
partitionTime = partitionMinSecond
}
interval := rand.Uint64() % partitionCycleInterval
if interval < partitionCycleMinInterval {
interval = partitionCycleMinInterval
}
st = et + interval
et = st + partitionTime
if st < monkeyPlaySeconds && et < monkeyPlaySeconds {
plog.Infof("adding a partition cycle, st %d, et %d", st, et)
n.partitionStartTime[st] = struct{}{}
n.partitionEndTime[et] = struct{}{}
} else {
return
}
}
}
func (n *testNode) IsPartitionTestNode() bool {
return n.partitionTestNode
}
func (n *testNode) Running() bool {
if n.nh != nil && !n.stopped {
return true
}
return false
}
func (n *testNode) Stop() {
if n.stopped {
panic("already stopped")
}
n.stopped = true
done := uint32(0)
go func() {
count := 0
for {
time.Sleep(100 * time.Millisecond)
if atomic.LoadUint32(&done) == 1 {
break
}
count++
if count == 10*maxWaitForStopSecond {
pprof.Lookup("goroutine").WriteTo(os.Stdout, 1)
plog.Panicf("failed to stop the nodehost %s, it is a %s, idx %d",
n.nh.RaftAddress(), n.nodeType, n.listIndex)
}
}
}()
addr := n.nh.RaftAddress()
if n.nodeType == nodeTypeDrummer {
plog.Infof("going to stop the drummer of %s", addr)
if n.drummer != nil && !n.drummerStopped {
n.drummer.Stop()
n.drummerStopped = true
}
plog.Infof("the drummer part of %s stopped", addr)
}
plog.Infof("going to stop the nh of %s", addr)
if n.apiServer != nil {
n.apiServer.Stop()
}
n.nh.Stop()
plog.Infof("the nh part of %s stopped", addr)
if n.stopper != nil {
plog.Infof("monkey node has a stopper, %s", addr)
n.stopper.Stop()
plog.Infof("stopper on monkey %s stopped", addr)
}
atomic.StoreUint32(&done, 1)
n.nh = nil
}
func (n *testNode) Start(dl *mtAddressList) {
if n.nodeType == nodeTypeDrummer {
n.startDrummerNode(dl)
} else if n.nodeType == nodeTypeNodehost {
n.startNodehostNode(dl)
} else {
panic("unknown node type")
}
}
func (n *testNode) GetMultiClusterAndTick() (*multiCluster, uint64, error) {
n.MustBeDrummerNode()
sc, err := n.drummer.getSchedulerContext()
if err != nil {
return nil, 0, err
}
return sc.ClusterImage, sc.Tick, nil
}
func (n *testNode) GetMultiCluster() (*multiCluster, error) {
n.MustBeDrummerNode()
sc, err := n.drummer.getSchedulerContext()
if err != nil {
return nil, err
}
return sc.ClusterImage, nil
}
func (n *testNode) GetNodeHostInfo() (*multiNodeHost, error) {
n.MustBeDrummerNode()
sc, err := n.drummer.getSchedulerContext()
if err != nil {
return nil, err
}
return sc.NodeHostImage, nil
}
func (n *testNode) setNodeNext(low int64, high int64) {
if high <= low {
panic("high <= low")
}
var v int64
ll := rand.Uint64()%10 == 0
if ll {
low = lowUpTimeLowMillisecond
high = lowUpTimeHighMillisecond
}
v = (low + rand.Int63()%(high-low)) * 1000000
plog.Infof("next event for %s %d is scheduled in %d second, %t",
n.nodeType, n.listIndex+1, v/1000000000, ll)
n.next = time.Now().UnixNano() + v
}
func (n *testNode) startDrummerNode(dl *mtAddressList) {
if n.nodeType != nodeTypeDrummer {
panic("trying to start a drummer on a non-drummer node")
}
if !n.stopped {
panic("already running")
}
rc, nhc := getMonkeyTestConfig()
config := config.NodeHostConfig{}
config = nhc
config.NodeHostDir = filepath.Join(n.dir, nhc.NodeHostDir)
config.WALDir = filepath.Join(n.dir, nhc.WALDir)
config.RaftAddress = dl.addressList[n.listIndex]
if n.mutualTLS {
config.MutualTLS = true
config.CAFile = caFile
config.CertFile = certFile
config.KeyFile = keyFile
}
plog.Infof("creating new nodehost for drummer node")
nh := dragonboat.NewNodeHostWithMasterClientFactory(config, client.NewDrummerClient)
plog.Infof("nodehost ready for drummer node")
n.nh = nh
peers := make(map[uint64]string)
for idx, v := range dl.addressList {
peers[uint64(idx+1)] = v
}
rc.NodeID = uint64(n.listIndex + 1)
rc.ClusterID = defaultClusterID
if err := nh.StartCluster(peers, false, NewDB, rc); err != nil {
panic(err)
}
plog.Infof("creating the drummer server")
grpcServerStopper := syncutil.NewStopper()
grpcHost := dl.apiAddressList[n.listIndex]
drummerServer := NewDrummer(nh, grpcHost)
drummerServer.Start()
plog.Infof("drummer server started")
n.drummer = drummerServer
n.drummerStopped = false
n.stopped = false
n.stopper = grpcServerStopper
}
func (n *testNode) startNodehostNode(dl *mtAddressList) {
if n.nodeType != nodeTypeNodehost {
panic("trying to start a drummer on a non-drummer node")
}
if !n.stopped {
panic("already running")
}
_, nhc := getMonkeyTestConfig()
config := config.NodeHostConfig{}
config = nhc
config.NodeHostDir = filepath.Join(n.dir, nhc.NodeHostDir)
config.WALDir = filepath.Join(n.dir, nhc.WALDir)
config.RaftAddress = dl.nodehostAddressList[n.listIndex]
config.APIAddress = dl.nodehostAPIAddressList[n.listIndex]
config.MasterServers = dl.apiAddressList
if n.mutualTLS {
config.MutualTLS = true
config.CAFile = caFile
config.CertFile = certFile
config.KeyFile = keyFile
}
plog.Infof("creating nodehost for nodehost node")
nh := dragonboat.NewNodeHostWithMasterClientFactory(config, client.NewDrummerClient)
plog.Infof("nodehost for nodehost node created")
n.nh = nh
n.apiServer = NewNodehostAPI(config.APIAddress, nh)
n.stopped = false
}
func checkPartitionedNodeHost(t *testing.T, nodes []*testNode) {
for _, node := range nodes {
node.MustBeNodehostNode()
if node.nh.IsPartitioned() {
t.Fatalf("nodehost is still in partitioned test mode")
}
}
}
func checkNodeHostSynced(t *testing.T, nodes []*testNode) {
count := 0
for {
appliedMap := make(map[uint64]uint64)
notSynced := make(map[uint64]bool)
for _, n := range nodes {
nh := n.nh
for _, rn := range nh.Clusters() {
clusterID := rn.ClusterID()
lastApplied := rn.GetLastApplied()
plog.Infof("%s reports last applied index %d",
logutil.DescribeNode(clusterID, rn.NodeID()), lastApplied)
existingLastApplied, ok := appliedMap[clusterID]
if !ok {
appliedMap[clusterID] = lastApplied
} else {
if existingLastApplied != lastApplied {
notSynced[clusterID] = true
}
}
}
}
if len(notSynced) > 0 {
time.Sleep(100 * time.Millisecond)
count++
} else {
return
}
// fail the test and dump details to log
if count == 10*maxWaitForSyncSecond {
dumpClusterInfoToLog(nodes, notSynced)
t.Fatalf("%d failed to sync last applied", len(notSynced))
}
}
}
func getEntryListHash(entries []raftpb.Entry) uint64 {
h := md5.New()
v := make([]byte, 8)
for _, ent := range entries {
binary.LittleEndian.PutUint64(v, ent.Index)
if _, err := h.Write(v); err != nil {
panic(err)
}
binary.LittleEndian.PutUint64(v, ent.Term)
if _, err := h.Write(v); err != nil {
panic(err)
}
binary.LittleEndian.PutUint64(v, uint64(ent.Type))
if _, err := h.Write(v); err != nil {
panic(err)
}
if _, err := h.Write(ent.Cmd); err != nil {
panic(err)
}
}
return binary.LittleEndian.Uint64(h.Sum(nil)[:8])
}
func getEntryHash(ent raftpb.Entry) uint64 {
h := md5.New()
_, err := h.Write(ent.Cmd)
if err != nil {
panic(err)
}
return binary.LittleEndian.Uint64(h.Sum(nil)[:8])
}
func snapshotDisabledInRaftConfig() bool {
cfg := config.Config{}
fn := "dragonboat-drummer.json"
if _, err := os.Stat(fn); os.IsNotExist(err) {
return false
}
data, err := ioutil.ReadFile(fn)
if err != nil {
panic(err)
}
if err := json.Unmarshal(data, &cfg); err != nil {
panic(err)
}
return cfg.SnapshotEntries == 0
}
func printEntryDetails(clusterID uint64,
nodeID uint64, entries []raftpb.Entry) {
for _, ent := range entries {
plog.Infof("%s, idx %d, term %d, type %s, entry len %d, hash %d",
logutil.DescribeNode(clusterID, nodeID), ent.Index, ent.Term, ent.Type,
len(ent.Cmd), getEntryHash(ent))
}
}
func checkLogdbEntriesSynced(t *testing.T, nodes []*testNode) {
hashMap := make(map[uint64]uint64)
notSynced := make(map[uint64]bool, 0)
for _, n := range nodes {
nh := n.nh
for _, rn := range nh.Clusters() {
nodeID := rn.NodeID()
clusterID := rn.ClusterID()
lastApplied := rn.GetLastApplied()
logdb := nh.GetLogDB()
entries, _, err := logdb.IterateEntries(nil,
0, clusterID, nodeID, 1, lastApplied+1, math.MaxUint64)
if err != nil {
t.Errorf("failed to get entries %v", err)
}
hash := getEntryListHash(entries)
plog.Infof("%s logdb entry hash %d, last applied %d, ent sz %d",
logutil.DescribeNode(clusterID, nodeID),
hash, lastApplied, len(entries))
printEntryDetails(clusterID, nodeID, entries)
existingHash, ok := hashMap[clusterID]
if !ok {
hashMap[clusterID] = hash
} else {
if existingHash != hash {
notSynced[clusterID] = true
}
}
}
}
if len(notSynced) > 0 {
dumpClusterInfoToLog(nodes, notSynced)
t.Fatalf("%d clusters failed to have logDB synced, %v",
len(notSynced), notSynced)
}
}
func dumpClusterInfoToLog(nodes []*testNode, clusterIDMap map[uint64]bool) {
for _, n := range nodes {
nh := n.nh
for _, rn := range nh.Clusters() {
clusterID := rn.ClusterID()
_, ok := clusterIDMap[clusterID]
if ok {
plog.Infof("%s rn.lastApplied %d",
logutil.DescribeNode(rn.ClusterID(), rn.NodeID()),
rn.GetLastApplied())
rn.DumpRaftInfoToLog()
}
}
}
}
func dumpClusterToRepairInfoToLog(cr []clusterRepair, tick uint64) {
plog.Infof("cluster to repair info, tick %d", tick)
for _, c := range cr {
plog.Infof("cluster id %d, config change idx %d, failed %v, ok %v, to start %v",
c.clusterID, c.cluster.ConfigChangeIndex, c.failedNodes, c.okNodes, c.nodesToStart)
}
}
func dumpUnavailableClusterInfoToLog(cl []cluster, tick uint64) {
plog.Infof("unavailable cluster info, tick %d", tick)
for _, c := range cl {
plog.Infof("cluster id %d, config change idx %d, nodes %v",
c.ClusterID, c.ConfigChangeIndex, c.Nodes)
}
}
func checkStateMachine(t *testing.T, nodes []*testNode) {
hashMap := make(map[uint64]uint64)
sessionHashMap := make(map[uint64]uint64)
membershipMap := make(map[uint64]uint64)
inconsistentClusters := make(map[uint64]bool)
for _, n := range nodes {
nh := n.nh
for _, rn := range nh.Clusters() {
clusterID := rn.ClusterID()
hash := rn.GetStateMachineHash()
sessionHash := rn.GetSessionHash()
membershipHash := rn.GetMembershipHash()
// check hash
existingHash, ok := hashMap[clusterID]
if !ok {
hashMap[clusterID] = hash
} else {
if existingHash != hash {
inconsistentClusters[clusterID] = true
t.Errorf("hash mismatch, cluster id %d, existing %d, new %d",
clusterID, existingHash, hash)
}
}
// check session hash
existingHash, ok = sessionHashMap[clusterID]
if !ok {
sessionHashMap[clusterID] = sessionHash
} else {
if existingHash != sessionHash {
inconsistentClusters[clusterID] = true
t.Errorf("session hash mismatch, cluster id %d, existing %d, new %d",
clusterID, existingHash, sessionHash)
}
}
// check membership
existingHash, ok = membershipMap[clusterID]
if !ok {
membershipMap[clusterID] = membershipHash
} else {
if existingHash != membershipHash {
inconsistentClusters[clusterID] = true
t.Errorf("membership hash mismatch, cluster id %d, %d vs %d",
clusterID, existingHash, membershipHash)
}
}
}
}
// dump details to log
if len(inconsistentClusters) > 0 {
dumpClusterInfoToLog(nodes, inconsistentClusters)
}
plog.Infof("hash map size %d, session hash map size %d",
len(hashMap), len(sessionHashMap))
}
func removeNodeHostTestDirForTesting(listIndex uint64) {
idx := listIndex + 1
nn := fmt.Sprintf("nodehost-node-%d", idx)
nd := filepath.Join(monkeyTestWorkingDir, nn)
plog.Infof("monkey is going to delete nodehost dir at %s for testing", nd)
if err := os.RemoveAll(nd); err != nil {
panic(err)
}
if err := os.MkdirAll(nd, 0755); err != nil {
panic(err)
}
}
func setRegionForNodehostNodes(nodes []*testNode, regions []string) {
for idx, node := range nodes {
node.MustBeNodehostNode()
node.nh.SetRegion(regions[idx])
}
}
func createTestNodeLists(dl *mtAddressList) ([]*testNode, []*testNode) {
drummerDirList, nodehostDirList := prepareMonkeyTestDirs(dl)
drummerNodes := make([]*testNode, len(dl.addressList))
nodehostNodes := make([]*testNode, len(dl.nodehostAddressList))
for i := uint64(0); i < uint64(len(dl.addressList)); i++ {
drummerNodes[i] = &testNode{
listIndex: i,
stopped: true,
dir: drummerDirList[i],
nodeType: nodeTypeDrummer,
partitionStartTime: make(map[uint64]struct{}),
partitionEndTime: make(map[uint64]struct{}),
}
}
for i := uint64(0); i < uint64(len(dl.nodehostAddressList)); i++ {
nodehostNodes[i] = &testNode{
listIndex: i,
stopped: true,
dir: nodehostDirList[i],
nodeType: nodeTypeNodehost,
partitionStartTime: make(map[uint64]struct{}),
partitionEndTime: make(map[uint64]struct{}),
}
}
return drummerNodes, nodehostNodes
}
func startTestNodes(nodes []*testNode, dl *mtAddressList) {
for _, node := range nodes {
if !node.Running() {
node.Start(dl)
}
}
}
func stopTestNodes(nodes []*testNode) {
for _, node := range nodes {
plog.Infof("going to stop test %s %d", node.nodeType, node.listIndex)
if node.Running() {
node.Stop()
} else {
plog.Infof("%s %d is not running, will not call stop on it",
node.nodeType, node.listIndex)
}
}
}
func waitForStableNodes(nodes []*testNode, seconds uint64) bool {
waitInBetweenSecond := time.Duration(3)
time.Sleep(waitInBetweenSecond * time.Second)
for {
done := tryWaitForStableNodes(nodes, seconds)
if !done {
return false
}
time.Sleep(waitInBetweenSecond * time.Second)
done = tryWaitForStableNodes(nodes, seconds)
if done {
return true
}
time.Sleep(waitInBetweenSecond * time.Second)
}
}
func tryWaitForStableNodes(nodes []*testNode, seconds uint64) bool {
waitMilliseconds := seconds * 1000
totalWait := uint64(0)
var nodeReady bool
var leaderReady bool
for !nodeReady || !leaderReady {
nodeReady = true
leaderReady = true
leaderMap := make(map[uint64]bool)
clusterSet := make(map[uint64]bool)
time.Sleep(100 * time.Millisecond)
totalWait += 100
if totalWait >= waitMilliseconds {
return false
}
for _, node := range nodes {
if node == nil || node.nh == nil {
continue
}
nh := node.nh
clusters := nh.Clusters()
for _, rn := range clusters {
clusterSet[rn.ClusterID()] = true
isLeader := rn.IsLeader()
isFollower := rn.IsFollower()
if !isLeader && !isFollower {
nodeReady = false
}
if isLeader {
leaderMap[rn.ClusterID()] = true
}
}
}
if len(leaderMap) != len(clusterSet) {
leaderReady = false
}
}
return true
}
func brutalMonkeyPlay(nodehosts []*testNode,
drummerNodes []*testNode, low int64, high int64) {
tt := rand.Uint64() % 3
nodes := make([]*testNode, 0)
if tt == 0 || tt == 2 {
nodes = append(nodes, nodehosts...)
}
if tt == 1 || tt == 2 {
nodes = append(nodes, drummerNodes...)
}
for _, node := range nodes {
if !node.IsPartitionTestNode() && node.Running() {
node.Stop()
plog.Infof("monkey brutally stopped %s %d", node.nodeType, node.listIndex+1)
node.setNodeNext(low, high)
}
}
}
func monkeyPlay(nodes []*testNode, low int64, high int64,
lt uint64, deleteDataTested bool, dl *mtAddressList) bool {
now := time.Now().UnixNano()
for _, node := range nodes {
if !node.IsPartitionTestNode() {
// crash mode
if node.next == 0 {
node.setNodeNext(low, high)
continue
}
if node.next > now {
continue
}
if node.Running() {
plog.Infof("monkey is going to stop %s %d",
node.nodeType, node.listIndex+1)
node.Stop()
plog.Infof("monkey stopped %s %d", node.nodeType, node.listIndex+1)
if rand.Uint64()%5 == 0 && !deleteDataTested && lt < 800 {
plog.Infof("monkey is going to delete all data belongs to %s %d",
node.nodeType, node.listIndex+1)
removeNodeHostTestDirForTesting(node.listIndex)
deleteDataTested = true
}
} else {
plog.Infof("monkey is going to start %s %d",
node.nodeType, node.listIndex+1)
node.Start(dl)
plog.Infof("monkey restarted %s %d", node.nodeType, node.listIndex+1)
}
node.setNodeNext(low, high)
} else {
// partition mode
_, ps := node.partitionStartTime[lt]
if ps {
plog.Infof("monkey is going to partition the node %d",
node.listIndex+1)
node.nh.PartitionNode()
}
_, pe := node.partitionEndTime[lt]
if pe {
plog.Infof("monkey is going to restore node %d from partition mode",
node.listIndex+1)
node.nh.RestorePartitionedNode()
}
}
}
return deleteDataTested
}
func stopDrummerActivity(nodehostNodes []*testNode, drummerNodes []*testNode) {
for _, n := range nodehostNodes {
n.nh.StopNodeHostInfoReporter()
}
for _, n := range drummerNodes {
n.stopper.Stop()
n.stopper = nil
n.drummer.Stop()
n.drummer.ctx, n.drummer.cancel = context.WithCancel(context.Background())
n.drummerStopped = true
}
}
func getLeaderDrummerIndex(nodes []*testNode) int {
for idx, n := range nodes {
n.MustBeDrummerNode()
if n.Running() && n.drummer.isLeaderDrummerNode() {
return idx
}
}
return -1
}
func moreThanOneDrummerLeader(nodes []*testNode) bool {
count := 0
for _, n := range nodes {
n.MustBeDrummerNode()
if n.Running() && n.drummer.isLeaderDrummerNode() {
count++
}
}
return count >= 2
}
func getDrummerClient(drummerAddressList []string,
mutualTLS bool) (pb.DrummerClient, *client.Connection) {
pool := client.NewDrummerConnectionPool()
for _, server := range drummerAddressList {
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
var conn *client.Connection
var err error
if mutualTLS {
conn, err = pool.GetTLSConnection(ctx, server, caFile, certFile, keyFile)
} else {
conn, err = pool.GetInsecureConnection(ctx, server)
}
cancel()
if err == nil {
return pb.NewDrummerClient(conn.ClientConn()), conn
}
}
return nil, nil
}
func submitTestJobs(count uint64,
appname string, dl *mtAddressList, mutualTLS bool) bool {
for i := 0; i < 5; i++ {
dc, connection := getDrummerClient(dl.apiAddressList, mutualTLS)
if dc == nil {
continue
}
defer connection.Close()
if err := submitMultipleTestClusters(count, appname, dc); err == nil {
return true
}
}
return false
}
func submitSimpleTestJob(dl *mtAddressList, mutualTLS bool) bool {
dc, connection := getDrummerClient(dl.apiAddressList, mutualTLS)
if dc == nil {
return false
}
defer connection.Close()
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
defer cancel()
if err := SubmitCreateDrummerChange(ctx,
dc, mtClusterID, mtNodeIDList, "kvtest"); err != nil {
plog.Errorf("failed to submit drummer change")
return false
}
regions := pb.Regions{
Region: []string{"region-1", "region-2", "region-3"},
Count: []uint64{1, 1, 1},
}
if err := SubmitRegions(ctx, dc, regions); err != nil {
plog.Errorf("failed to submit region info")
return false
}
plog.Infof("going to set the bootstrapped flag")
if err := SubmitBootstrappped(ctx, dc); err != nil {
plog.Errorf("failed to set bootstrapped flag")
return false
}
return true
}
func submitMultipleTestClusters(count uint64,
appname string, client pb.DrummerClient) error {
plog.Infof("going to send cluster info to drummer")
for i := uint64(0); i < count; i++ {
clusterID := i + 1
ctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)
if err := SubmitCreateDrummerChange(ctx,
client, clusterID, []uint64{2345, 6789, 9876}, appname); err != nil {
plog.Errorf("failed to submit drummer change, cluster %d, %v",
clusterID, err)
cancel()
return err