forked from 0zAND1z/dragonboat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
testutils_test.go
519 lines (486 loc) · 12.7 KB
/
testutils_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
// Copyright 2017-2019 Lei Ni ([email protected])
//
// 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.
package dragonboat
import (
"context"
"fmt"
"math/rand"
"os"
"path/filepath"
"strconv"
"sync/atomic"
"testing"
"time"
"github.com/golang/protobuf/proto"
"github.com/lni/dragonboat/client"
"github.com/lni/dragonboat/config"
serverConfig "github.com/lni/dragonboat/config"
"github.com/lni/dragonboat/internal/rsm"
"github.com/lni/dragonboat/internal/tests"
"github.com/lni/dragonboat/internal/tests/kvpb"
"github.com/lni/dragonboat/internal/utils/lang"
"github.com/lni/dragonboat/internal/utils/random"
)
type multiraftMonkeyTestAddrList struct {
addrList []string
}
func newMultiraftMonkeyTestAddrList() *multiraftMonkeyTestAddrList {
return &multiraftMonkeyTestAddrList{addrList: make([]string, 0)}
}
func (m *multiraftMonkeyTestAddrList) fill(base uint64) {
for i := uint64(1); i <= uint64(5); i++ {
addr := fmt.Sprintf("localhost:%d", base+i)
m.addrList = append(m.addrList, addr)
}
}
func (m *multiraftMonkeyTestAddrList) Size() uint64 {
return uint64(len(m.addrList))
}
func (m *multiraftMonkeyTestAddrList) Addresses() []string {
return m.addrList
}
func getMultiraftMonkeyTestAddrList() *multiraftMonkeyTestAddrList {
base := uint64(5400)
v := os.Getenv("MULTIRAFTMTPORT")
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 := newMultiraftMonkeyTestAddrList()
dl.fill(base)
return dl
}
const (
mtNumOfClusters uint64 = 64
mtWorkingDirectory = "monkey_testing_nh_dir_safe_to_delete"
)
type mtNodeHost struct {
listIndex uint64
dir string
nh *NodeHost
stopped bool
next int64
addresses []string
}
func (n *mtNodeHost) setNext(low int64, high int64) {
if high <= low {
panic("high <= low")
}
v := (low + rand.Int63()%(high-low)) * 1000000
plog.Infof("next event for node %d is scheduled in %d second",
n.listIndex+1, v/1000000000)
n.next = time.Now().UnixNano() + v
}
func (n *mtNodeHost) Running() bool {
return n.nh != nil && !n.stopped
}
func (n *mtNodeHost) Stop() {
if n.stopped {
panic("already stopped")
}
done := uint32(0)
go func() {
plog.Infof("going to stop the test node host, i %d", n.listIndex)
n.nh.Stop()
plog.Infof("test node host stopped, i %d", n.listIndex)
atomic.StoreUint32(&done, 1)
}()
count := 0
for {
time.Sleep(100 * time.Millisecond)
if atomic.LoadUint32(&done) == 1 {
break
}
count++
if count == 200 {
panic("failed to stop the node host")
}
}
n.stopped = true
}
func (n *mtNodeHost) Start() {
if !n.stopped {
panic("already running")
}
rc, nhc := getMTConfig()
config := serverConfig.NodeHostConfig{}
config = nhc
config.NodeHostDir = filepath.Join(n.dir, nhc.NodeHostDir)
config.WALDir = filepath.Join(n.dir, nhc.WALDir)
config.RaftAddress = n.addresses[n.listIndex]
nh := NewNodeHost(config)
n.nh = nh
peers := make(map[uint64]string)
for idx, v := range n.addresses {
peers[uint64(idx+1)] = v
}
createStateMachine := func(clusterID uint64, nodeID uint64,
done <-chan struct{}) rsm.IManagedStateMachine {
ds := tests.NewKVTest(clusterID, nodeID)
return rsm.NewNativeStateMachine(ds, done)
}
for i := uint64(1); i <= mtNumOfClusters; i++ {
rc.ClusterID = i
rc.NodeID = n.listIndex + 1
plog.Infof("starting cluster %d node %d", rc.ClusterID, rc.NodeID)
if err := n.nh.startCluster(peers,
false, createStateMachine, make(chan struct{}), rc); err != nil {
panic(err)
}
}
n.stopped = false
}
func (n *mtNodeHost) RestartCluster(clusterID uint64) {
if n.stopped {
panic("already stopped")
}
rc, _ := getMTConfig()
createStateMachine := func(clusterID uint64, nodeID uint64,
done <-chan struct{}) rsm.IManagedStateMachine {
ds := tests.NewKVTest(clusterID, nodeID)
return rsm.NewNativeStateMachine(ds, done)
}
rc.ClusterID = clusterID
// the extra 5 is to make it different from the initial
rc.NodeID = n.listIndex + 1 + 5 // make it different from the initial
plog.Infof("starting cluster %d node %d on node with list index %d",
rc.ClusterID, rc.NodeID, n.listIndex)
if err := n.nh.startCluster(nil,
true, createStateMachine, make(chan struct{}), rc); err != nil {
panic(err)
}
}
func getMTConfig() (config.Config, serverConfig.NodeHostConfig) {
rc := config.Config{
ElectionRTT: 20,
HeartbeatRTT: 1,
CheckQuorum: true,
SnapshotEntries: 5,
CompactionOverhead: 5,
}
nhc := serverConfig.NodeHostConfig{
WALDir: "nhmt",
NodeHostDir: "nhmt",
RTTMillisecond: 50,
}
return rc, nhc
}
func removeMTDirs() {
os.RemoveAll(mtWorkingDirectory)
}
func prepareMTDirs() []string {
removeMTDirs()
dl := getMultiraftMonkeyTestAddrList()
dirList := make([]string, 0)
for i := uint64(1); i <= dl.Size(); i++ {
nn := fmt.Sprintf("node%d", i)
nd := filepath.Join(mtWorkingDirectory, nn)
if err := os.MkdirAll(nd, 0755); err != nil {
panic(err)
}
dirList = append(dirList, nd)
}
return dirList
}
func createMTNodeHostList() []*mtNodeHost {
dirList := prepareMTDirs()
dl := getMultiraftMonkeyTestAddrList()
result := make([]*mtNodeHost, dl.Size())
for i := uint64(0); i < dl.Size(); i++ {
result[i] = &mtNodeHost{
listIndex: i,
stopped: true,
dir: dirList[i],
addresses: dl.Addresses(),
}
}
return result
}
func startAllClusters(nhList []*mtNodeHost) {
for _, node := range nhList {
node.Start()
}
}
func stopMTNodeHosts(nhList []*mtNodeHost) {
for _, v := range nhList {
v.Stop()
}
}
func waitForStableClusters(t *testing.T, nhList []*mtNodeHost, waitSeconds uint64) {
time.Sleep(3000 * time.Millisecond)
for {
done := tryWaitForStableClusters(t, nhList, waitSeconds)
if !done {
panic("failed to get a stable network")
}
time.Sleep(3 * time.Second)
done = tryWaitForStableClusters(t, nhList, waitSeconds)
if done {
return
}
time.Sleep(3 * time.Second)
}
}
func tryWaitForStableClusters(t *testing.T, nhList []*mtNodeHost,
waitSeconds uint64) bool {
waitMilliseconds := waitSeconds * 1000
totalWait := uint64(0)
var nodeReady bool
var leaderReady bool
for !nodeReady || !leaderReady {
nodeReady = true
leaderReady = true
leaderMap := make(map[uint64]bool)
time.Sleep(100 * time.Millisecond)
totalWait += 100
if totalWait >= waitMilliseconds {
return false
}
for _, n := range nhList {
if n == nil || n.nh == nil {
continue
}
nh := n.nh
nh.forEachCluster(func(cid uint64, node *node) bool {
leaderID, ok, err := nh.GetLeaderID(node.clusterID)
if err != nil {
nodeReady = false
return true
}
if ok && leaderID == node.nodeID {
leaderMap[node.clusterID] = true
}
return true
})
}
if uint64(len(leaderMap)) != mtNumOfClusters {
leaderReady = false
}
}
return true
}
func getRandomStringBytes(sz int) []byte {
return []byte(random.String(sz))
}
func makeRandomProposal(nhList []*mtNodeHost, count int) {
hasRunningNode := false
for _, n := range nhList {
if n.Running() {
hasRunningNode = true
}
}
if !hasRunningNode {
return
}
for i := 0; i < count; i++ {
idx := rand.Int() % len(nhList)
if nhList[idx].Running() {
valsz := rand.Int()%16 + 3
key := fmt.Sprintf("key-%d", rand.Int())
value := string(getRandomStringBytes(valsz))
kv := &kvpb.PBKV{
Key: &key,
Val: &value,
}
rec, err := proto.Marshal(kv)
if err != nil {
panic(err)
}
clusterID := rand.Uint64()%mtNumOfClusters + 1
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
session, err := nhList[idx].nh.GetNewSession(ctx, clusterID)
if err != nil {
plog.Errorf("couldn't get a proposal client for %d", clusterID)
continue
}
ctx, cancel = context.WithTimeout(context.Background(), time.Second)
defer cancel()
repeat := (rand.Int() % 3) + 1
for j := 0; j < repeat; j++ {
session.ProposalCompleted()
result, err := nhList[idx].nh.SyncPropose(ctx, session, rec)
if err != nil {
plog.Infof(err.Error())
continue
} else {
if result != uint64(len(rec)) {
plog.Panicf("result %d, want %d", result, len(rec))
}
ctx, cancel = context.WithTimeout(context.Background(), time.Second)
defer cancel()
readIdx := rand.Int() % len(nhList)
if !nhList[readIdx].Running() {
resp, err := nhList[readIdx].nh.SyncRead(ctx, clusterID, []byte(*kv.Key))
if err == nil {
if string(resp) != string(*kv.Val) {
plog.Panicf("got %s, want %s", string(resp), kv.Val)
}
}
}
}
}
if (rand.Int() % 10) > 2 {
f := func() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
nhList[idx].nh.CloseSession(ctx, session)
}
f()
}
} else {
plog.Infof("got a dead node, skipping it, %d", i)
i--
}
}
}
func waitLastAppliedToSync(t *testing.T, smList []*mtNodeHost) {
count := 0
for {
appliedMap := make(map[uint64]uint64)
notSynced := make([]uint64, 0)
for _, n := range smList {
nh := n.nh
nh.forEachCluster(func(clusterID uint64, rn *node) bool {
lastApplied := rn.sm.GetLastApplied()
existingLastApplied, ok := appliedMap[clusterID]
if !ok {
appliedMap[clusterID] = lastApplied
} else {
if existingLastApplied != lastApplied {
notSynced = append(notSynced, clusterID)
}
}
return true
})
}
if len(notSynced) > 0 {
time.Sleep(100 * time.Millisecond)
count++
} else {
return
}
if count == 1200 {
for _, n := range smList {
nh := n.nh
nh.forEachCluster(func(clusterID uint64, rn *node) bool {
if lang.ContainsUint64(clusterID, notSynced) {
plog.Infof("%s rn.lastApplied %d", rn.describe(), rn.sm.GetLastApplied())
rn.dumpRaftInfoToLog()
}
return true
})
}
t.Fatalf("failed to sync last applied")
}
}
}
func checkStateMachine(t *testing.T, smList []*mtNodeHost) {
hashMap := make(map[uint64]uint64)
sessionHashMap := make(map[uint64]uint64)
waitLastAppliedToSync(t, smList)
for _, n := range smList {
nh := n.nh
nh.forEachCluster(func(clusterID uint64, rn *node) bool {
hash := rn.getStateMachineHash()
sessionHash := rn.getSessionHash()
// check hash
existingHash, ok := hashMap[clusterID]
if !ok {
hashMap[clusterID] = hash
} else {
if existingHash != hash {
t.Errorf("hash mismatch, existing %d, new %d",
existingHash, hash)
}
}
// check session hash
existingHash, ok = sessionHashMap[clusterID]
if !ok {
sessionHashMap[clusterID] = sessionHash
} else {
if existingHash != sessionHash {
t.Errorf("session hash mismatch, existing %d, new %d",
existingHash, sessionHash)
}
}
return true
})
}
}
func testProposalCanBeMade(t *testing.T, node *mtNodeHost, data []byte) {
session := tryGetSession(node.nh, 1)
if session == nil {
t.Fatalf("failed to get client session")
}
defer func() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
node.nh.CloseSession(ctx, session)
}()
retry := 0
for retry < 5 {
retry++
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
_, err := node.nh.SyncPropose(ctx, session, data)
cancel()
if err != nil {
session.ProposalCompleted()
if retry == 5 {
t.Fatalf("failed to make proposal %v", err)
}
} else {
break
}
}
}
func testLinearizableReadReturnExpectedResult(t *testing.T, node *mtNodeHost,
query []byte, expected []byte) {
retry := 0
for retry < 5 {
retry++
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
result, err := node.nh.SyncRead(ctx, 1, query)
cancel()
if err != nil {
if retry == 5 {
t.Fatalf("failed to read, %v", err)
}
} else {
if string(result) != string(expected) {
t.Errorf("got size %d want size %d", len(result), len(expected))
}
break
}
}
}
func tryGetSession(nh *NodeHost, clusterID uint64) *client.Session {
var err error
var session *client.Session
for i := 0; i < 5; i++ {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
session, err = nh.GetNewSession(ctx, clusterID)
if err == nil {
return session
}
}
return nil
}