forked from 0zAND1z/dragonboat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nodehost_test.go
1535 lines (1431 loc) · 41.5 KB
/
nodehost_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 ([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.
// +build !dragonboat_slowtest
// +build !dragonboat_errorinjectiontest
package dragonboat
import (
"context"
"io"
"log"
"math/rand"
"os"
"path/filepath"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/lni/dragonboat/client"
"github.com/lni/dragonboat/config"
"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/logger"
"github.com/lni/dragonboat/raftio"
pb "github.com/lni/dragonboat/raftpb"
"github.com/lni/dragonboat/statemachine"
)
func ExampleNewNodeHost() {
// Let's say we want to put all LogDB's WAL data in a directory named wal,
// everything else is stored in a directory named dragonboat. Assume the
// RTT between nodes is 200 milliseconds, and the nodehost address is
// myhostname:5012
nhc := config.NodeHostConfig{
WALDir: "wal",
NodeHostDir: "dragonboat",
RTTMillisecond: 200,
RaftAddress: "myhostname:5012",
}
// Creates a nodehost instance using the above NodeHostConfig instnace.
nh := NewNodeHost(nhc)
log.Printf("nodehost created, running on %s", nh.RaftAddress())
}
func ExampleNodeHost_StartCluster() {
nhc := config.NodeHostConfig{
WALDir: "wal",
NodeHostDir: "dragonboat",
RTTMillisecond: 200,
RaftAddress: "myhostname:5012",
}
// Creates a nodehost instance using the above NodeHostConfig instnace.
nh := NewNodeHost(nhc)
// config for raft
rc := config.Config{
NodeID: 1,
ClusterID: 100,
ElectionRTT: 5,
HeartbeatRTT: 1,
CheckQuorum: true,
SnapshotEntries: 10000,
CompactionOverhead: 5000,
}
peers := make(map[uint64]string)
peers[100] = "myhostname1:5012"
peers[200] = "myhostname2:5012"
peers[300] = "myhostname3:5012"
// Use this NO-OP data store in this example
NewStateMachine := func(clusterID uint64, nodeID uint64) statemachine.IStateMachine {
return &tests.NoOP{}
}
if err := nh.StartCluster(peers, false, NewStateMachine, rc); err != nil {
log.Fatalf("failed to add cluster, %v\n", err)
}
}
func ExampleNodeHost_Propose(nh *NodeHost) {
// nh is a NodeHost instance, a Raft cluster with ID 100 has already been added
// this to NodeHost.
// see the example on StartCluster on how to start Raft cluster.
//
// Use NO-OP client session, cluster ID is 100
// Check the example on the GetNewSession method to see how to use a
// real client session object to make proposals.
cs := nh.GetNoOPSession(100)
// make a proposal with the proposal content "test-data", timeout is set to
// 2000 milliseconds.
rs, err := nh.Propose(cs, []byte("test-data"), 2000*time.Millisecond)
if err != nil {
// failed to start the proposal
return
}
defer rs.Release()
s := <-rs.CompletedC
if s.Timeout() {
// the proposal failed to complete before the deadline, maybe retry the
// request
} else if s.Completed() {
// the proposal has been committed and applied
// put the request state instance back to the recycle pool
} else if s.Terminated() {
// proposal terminated as the system is being shut down, time to exit
}
// note that s.Code == RequestRejected is not suppose to happen as we are
// using a NO-OP client session in this example.
}
func ExampleNodeHost_ReadIndex(nh *NodeHost) {
// nh is a NodeHost instance, a Raft cluster with ID 100 has already been added
// this to NodeHost.
// see the example on StartCluster on how to start Raft cluster.
data := make([]byte, 1024)
rs, err := nh.ReadIndex(100, 2000*time.Millisecond)
if err != nil {
// ReadIndex failed to start
return
}
defer rs.Release()
s := <-rs.CompletedC
if s.Timeout() {
// the ReadIndex operation failed to complete before the deadline, maybe
// retry the request
} else if s.Completed() {
// the ReadIndex operation completed. the local IStateMachine is ready to be
// queried
nh.ReadLocal(100, data)
} else if s.Terminated() {
// the ReadIndex operation terminated as the system is being shut down,
// time to exit
}
}
func ExampleNodeHost_RequestDeleteNode(nh *NodeHost) {
// nh is a NodeHost instance, a Raft cluster with ID 100 has already been added
// this to NodeHost.
// see the example on StartCluster on how to start Raft cluster.
//
// request node with ID 1 to be removed as a member node of raft cluster 100.
// the third parameter is OrderID, it is only relevant when using Master
// servers.
rs, err := nh.RequestDeleteNode(100, 1, 0, 2000*time.Millisecond)
if err != nil {
// failed to start the membership change request
return
}
defer rs.Release()
s := <-rs.CompletedC
if s.Timeout() {
// the request failed to complete before the deadline, maybe retry the
// request
} else if s.Completed() {
// the requested node has been removed from the raft cluster, ready to
// remove the node from the NodeHost running at myhostname1:5012, e.g.
// nh.RemoveCluster(100)
} else if s.Terminated() {
// request terminated as the system is being shut down, time to exit
} else if s.Rejected() {
// request rejected as it is out of order. this can only happen when
// you are using IMasterClient. Try again with a correct order id value.
}
}
func ExampleNodeHost_RequestAddNode(nh *NodeHost) {
// nh is a NodeHost instance, a Raft cluster with ID 100 has already been added
// this to NodeHost.
// see the example on StartCluster on how to start Raft cluster.
//
// request node with ID 4 running at myhostname4:5012 to be added as a member
// node of raft cluster 100. the fourth parameter is OrderID, it is only
// relevant when using Master servers.
rs, err := nh.RequestAddNode(100,
4, "myhostname4:5012", 0, 2000*time.Millisecond)
if err != nil {
// failed to start the membership change request
return
}
defer rs.Release()
s := <-rs.CompletedC
if s.Timeout() {
// the request failed to complete before the deadline, maybe retry the
// request
} else if s.Completed() {
// the requested new node has been added to the raft cluster, ready to
// add the node to the NodeHost running at myhostname4:5012. run the
// following code on the NodeHost running at myhostname4:5012 -
//
// NewStateMachine := func(clusterID uint64, nodeID uint64) statemachine.IStateMachine {
// return &tests.NoOP{}
// }
// rc := config.Config{
// NodeID: 4,
// ClusterID: 100,
// ElectionRTT: 5,
// HeartbeatRTT: 1,
// CheckQuorum: true,
// SnapshotEntries: 10000,
// CompactionOverhead: 5000,
// }
// nh.StartCluster(nil, true, NewStateMachine, rc)
} else if s.Terminated() {
// request terminated as the system is being shut down, time to exit
} else if s.Rejected() {
// request rejected as it is out of order. this can only happen when
// you are using IMasterClient. Try again with a correct order id value.
}
}
func ExampleNodeHost_GetNewSession(ctx context.Context, nh *NodeHost) {
// nh is a NodeHost instance, a Raft cluster with ID 100 has already been added
// this to NodeHost.
// see the example on StartCluster on how to start Raft cluster.
//
// Create a client session first, cluster ID is 100
// Check the example on the GetNewSession method to see how to use a
// real client session object to make proposals.
cs, err := nh.GetNewSession(ctx, 100)
if err != nil {
// failed to get the client session, if it is a timeout error then try
// again later.
return
}
defer nh.CloseSession(ctx, cs)
// make a proposal with the proposal content "test-data", timeout is set to
// 2000 milliseconds.
rs, err := nh.Propose(cs, []byte("test-data"), 2000*time.Millisecond)
if err != nil {
// failed to start the proposal
return
}
defer rs.Release()
s := <-rs.CompletedC
if s.Timeout() {
// the proposal failed to complete before the deadline. maybe retry
// the request with the same client session instance s.
// on timeout, there is actually no guarantee on whether the proposed
// entry has been applied or not, the idea is that when retrying with
// the same proposal using the same client session instance, dragonboat
// makes sure that the proposal is retried and it will be applied if
// and only if it has not been previously applied.
} else if s.Completed() {
// the proposal has been committed and applied, call
// s.ProposalCompleted() to notify the client session that the previous
// request has been successfully completed. this makes the client
// session ready to be used when you make the next proposal.
cs.ProposalCompleted()
} else if s.Terminated() {
// proposal terminated as the system is being shut down, time to exit
} else if s.Rejected() {
// client session s is not evicted from the server side, probably because
// there are too many concurrent client sessions. in case you want to
// strictly ensure that each proposal will never be applied twice, we
// recommend to fail the client program. Note that this is highly unlikely
// to happen.
panic("client session already evicted")
}
//
// now you can use the same client session instance s to make more proposals
//
}
func getTestNodeHostConfig() *config.NodeHostConfig {
return &config.NodeHostConfig{
WALDir: singleNodeHostTestDir,
NodeHostDir: singleNodeHostTestDir,
RTTMillisecond: 50,
RaftAddress: "localhost:1111",
}
}
type noopLogDB struct {
}
func (n *noopLogDB) Name() string { return "noopLogDB" }
func (n *noopLogDB) Close() {}
func (n *noopLogDB) GetLogDBThreadContext() raftio.IContext { return nil }
func (n *noopLogDB) HasNodeInfo(clusterID uint64, nodeID uint64) (bool, error) { return true, nil }
func (n *noopLogDB) CreateNodeInfo(clusterID uint64, nodeID uint64) error { return nil }
func (n *noopLogDB) ListNodeInfo() ([]raftio.NodeInfo, error) { return nil, nil }
func (n *noopLogDB) SaveBootstrapInfo(clusterID uint64, nodeID uint64, bs pb.Bootstrap) error {
return nil
}
func (n *noopLogDB) GetBootstrapInfo(clusterID uint64, nodeID uint64) (*pb.Bootstrap, error) {
return nil, nil
}
func (n *noopLogDB) SaveRaftState(updates []pb.Update, ctx raftio.IContext) error { return nil }
func (n *noopLogDB) IterateEntries(ents []pb.Entry,
size uint64, clusterID uint64, nodeID uint64, low uint64,
high uint64, maxSize uint64) ([]pb.Entry, uint64, error) {
return nil, 0, nil
}
func (n *noopLogDB) ReadRaftState(clusterID uint64, nodeID uint64,
lastIndex uint64) (*raftio.RaftState, error) {
return nil, nil
}
func (n *noopLogDB) RemoveEntriesTo(clusterID uint64, nodeID uint64, index uint64) error { return nil }
func (n *noopLogDB) SaveSnapshots([]pb.Update) error { return nil }
func (n *noopLogDB) DeleteSnapshot(clusterID uint64, nodeID uint64, index uint64) error { return nil }
func (n *noopLogDB) ListSnapshots(clusterID uint64, nodeID uint64) ([]pb.Snapshot, error) {
return nil, nil
}
/*
func TestRocksDBIsUsedByDefault(t *testing.T) {
defer leaktest.AfterTest(t)()
defer os.RemoveAll(singleNodeHostTestDir)
os.RemoveAll(singleNodeHostTestDir)
c := getTestNodeHostConfig()
nh := NewNodeHost(*c)
plog.Infof("new node host returned")
defer nh.Stop()
if nh.logdb.Name() != logdb.RocksDBLogDBName {
t.Errorf("logdb type name %s, expect %s",
nh.logdb.Name(), logdb.RocksDBLogDBName)
}
plog.Infof("all good")
}*/
func TestLogDBCanBeExtended(t *testing.T) {
defer leaktest.AfterTest(t)()
defer os.RemoveAll(singleNodeHostTestDir)
os.RemoveAll(singleNodeHostTestDir)
c := getTestNodeHostConfig()
ldb := &noopLogDB{}
c.LogDBFactory = func([]string, []string) (raftio.ILogDB, error) {
return ldb, nil
}
nh := NewNodeHost(*c)
defer nh.Stop()
if nh.logdb.Name() != ldb.Name() {
t.Errorf("logdb type name %s, expect %s", nh.logdb.Name(), ldb.Name())
}
}
func TestTCPTransportIsUsedByDefault(t *testing.T) {
defer leaktest.AfterTest(t)()
defer os.RemoveAll(singleNodeHostTestDir)
os.RemoveAll(singleNodeHostTestDir)
c := getTestNodeHostConfig()
nh := NewNodeHost(*c)
defer nh.Stop()
tt := nh.transport.(*transport.Transport)
if tt.GetRaftRPC().Name() != transport.TCPRaftRPCName {
t.Errorf("raft rpc type name %s, expect %s",
tt.GetRaftRPC().Name(), transport.TCPRaftRPCName)
}
}
func TestRaftRPCCanBeExtended(t *testing.T) {
defer leaktest.AfterTest(t)()
defer os.RemoveAll(singleNodeHostTestDir)
os.RemoveAll(singleNodeHostTestDir)
c := getTestNodeHostConfig()
c.RaftRPCFactory = transport.NewNOOPTransport
nh := NewNodeHost(*c)
defer nh.Stop()
tt := nh.transport.(*transport.Transport)
if tt.GetRaftRPC().Name() != transport.NOOPRaftName {
t.Errorf("raft rpc type name %s, expect %s",
tt.GetRaftRPC().Name(), transport.NOOPRaftName)
}
}
func TestMasterClientIsNotCreateWhenNoMasterServerIsConfigured(t *testing.T) {
defer leaktest.AfterTest(t)()
defer os.RemoveAll(singleNodeHostTestDir)
os.RemoveAll(singleNodeHostTestDir)
c := getTestNodeHostConfig()
nh := NewNodeHost(*c)
defer nh.Stop()
if nh.masterClient != nil {
t.Errorf("master client unexpectedly created")
}
}
type noopMasterClient struct {
sendCount uint64
handleCount uint64
}
func (n *noopMasterClient) Name() string { return "noop-masterclient" }
func (n *noopMasterClient) Stop() {}
func (n *noopMasterClient) GetDeploymentID(ctx context.Context,
url string) (uint64, error) {
return 1, nil
}
func (n *noopMasterClient) HandleMasterRequests(ctx context.Context) error {
atomic.AddUint64(&n.handleCount, 1)
return nil
}
func (n *noopMasterClient) SendNodeHostInfo(ctx context.Context, url string,
nhi NodeHostInfo) error {
atomic.AddUint64(&n.sendCount, 1)
return nil
}
func (n *noopMasterClient) getSendCount() uint64 {
return atomic.LoadUint64(&n.sendCount)
}
func (n *noopMasterClient) getHandleCount() uint64 {
return atomic.LoadUint64(&n.handleCount)
}
func TestMasterClientCanBeExtended(t *testing.T) {
defer leaktest.AfterTest(t)()
defer os.RemoveAll(singleNodeHostTestDir)
os.RemoveAll(singleNodeHostTestDir)
c := getTestNodeHostConfig()
c.MasterServers = []string{"localhost:22222"}
mc := &noopMasterClient{}
factory := func(*NodeHost) IMasterClient {
return mc
}
nh := NewNodeHostWithMasterClientFactory(*c, factory)
defer nh.Stop()
if nh.masterClient.Name() != mc.Name() {
t.Errorf("master client type name %s, expect %s",
nh.masterClient.Name(), mc.Name())
}
}
func TestMasterClientIsPeriodicallyUsed(t *testing.T) {
defer leaktest.AfterTest(t)()
defer os.RemoveAll(singleNodeHostTestDir)
os.RemoveAll(singleNodeHostTestDir)
ov := NodeHostInfoReportSecond
NodeHostInfoReportSecond = 1
c := getTestNodeHostConfig()
c.MasterServers = []string{"localhost:22222"}
mc := &noopMasterClient{}
factory := func(*NodeHost) IMasterClient {
return mc
}
nh := NewNodeHostWithMasterClientFactory(*c, factory)
defer func() { NodeHostInfoReportSecond = ov }()
defer nh.Stop()
if nh.masterClient.Name() != mc.Name() {
t.Errorf("master client type name %s, expect %s",
nh.masterClient.Name(), mc.Name())
}
var prevSendCount uint64
var prevHandleCount uint64
done := false
for iter := 1; iter < 50; iter++ {
prevSendCount = mc.getSendCount()
prevHandleCount = mc.getHandleCount()
time.Sleep(3 * time.Second)
sc := mc.getSendCount()
hc := mc.getHandleCount()
if sc >= prevSendCount+2 && hc >= prevHandleCount+2 {
done = true
break
} else {
plog.Infof("sc %d, prev sc %d, hc %d, prev hc %d",
sc, prevSendCount, hc, prevHandleCount)
}
}
if !done {
t.Errorf("SendNodeHostInfo or HandleMasterRequests not periodically called")
}
}
func TestDeploymentIDCanBeSetUsingNodeHostConfig(t *testing.T) {
defer leaktest.AfterTest(t)()
defer os.RemoveAll(singleNodeHostTestDir)
os.RemoveAll(singleNodeHostTestDir)
c := getTestNodeHostConfig()
c.DeploymentID = 100
nh := NewNodeHost(*c)
defer nh.Stop()
if nh.deploymentID != 100 {
t.Errorf("deployment id not set")
}
}
var (
singleNodeHostTestAddr = "localhost:26000"
singleNodeHostTestDir = "single_nodehost_test_dir_safe_to_delete"
)
type PST struct {
mu sync.Mutex
stopped bool
saved bool
restored bool
slowSave bool
}
func (n *PST) setRestored(v bool) {
n.mu.Lock()
defer n.mu.Unlock()
n.restored = v
}
func (n *PST) getRestored() bool {
n.mu.Lock()
defer n.mu.Unlock()
return n.restored
}
func (n *PST) Close() {}
// Lookup locally looks up the data.
func (n *PST) Lookup(key []byte) []byte {
return make([]byte, 1)
}
// Update updates the object.
func (n *PST) Update(data []byte) uint64 {
return uint64(len(data))
}
// SaveSnapshot saves the state of the object to the provided io.Writer object.
func (n *PST) SaveSnapshot(w io.Writer,
fileCollection statemachine.ISnapshotFileCollection,
done <-chan struct{}) (uint64, error) {
plog.Infof("save snapshot called")
n.saved = true
if !n.slowSave {
n, err := w.Write([]byte("random-data"))
if err != nil {
panic(err)
}
return uint64(n), nil
}
for {
time.Sleep(10 * time.Millisecond)
select {
case <-done:
n.stopped = true
plog.Infof("saveSnapshot stopped")
return 0, statemachine.ErrSnapshotStopped
default:
}
}
}
// RecoverFromSnapshot recovers the object from the snapshot specified by the
// io.Reader object.
func (n *PST) RecoverFromSnapshot(r io.Reader,
files []statemachine.SnapshotFile, done <-chan struct{}) error {
n.setRestored(true)
for {
time.Sleep(10 * time.Millisecond)
select {
case <-done:
n.stopped = true
return statemachine.ErrSnapshotStopped
default:
}
}
}
// GetHash returns a uint64 value representing the current state of the object.
func (n *PST) GetHash() uint64 {
// the hash value is always 0, so it is of course always consistent
return 0
}
func createSingleNodeTestNodeHost(addr string,
datadir string, slowSave bool) (*NodeHost, *PST, error) {
// config for raft
rc := config.Config{
NodeID: uint64(1),
ClusterID: 2,
ElectionRTT: 5,
HeartbeatRTT: 1,
CheckQuorum: true,
SnapshotEntries: 10,
CompactionOverhead: 5,
}
peers := make(map[uint64]string)
peers[1] = addr
nhc := config.NodeHostConfig{
WALDir: datadir,
NodeHostDir: datadir,
RTTMillisecond: 50,
RaftAddress: peers[1],
}
nh := NewNodeHost(nhc)
var pst *PST
newPST := func(clusterID uint64, nodeID uint64) statemachine.IStateMachine {
pst = &PST{slowSave: slowSave}
return pst
}
if err := nh.StartCluster(peers, false, newPST, rc); err != nil {
return nil, nil, err
}
return nh, pst, nil
}
func waitForLeaderToBeElected(t *testing.T, nh *NodeHost) {
for i := 0; i < 200; i++ {
_, ready, err := nh.GetLeaderID(2)
if err == nil && ready {
return
}
time.Sleep(100 * time.Millisecond)
}
t.Fatalf("failed to elect leader")
}
func createProposalsToTriggerSnapshot(t *testing.T,
nh *NodeHost, count uint64, timeoutExpected bool) {
for i := uint64(0); i < count; i++ {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
cs, err := nh.GetNewSession(ctx, 2)
if err != nil {
if err == ErrTimeout {
cancel()
return
}
t.Fatalf("unexpected error %v", err)
}
time.Sleep(100 * time.Millisecond)
if err := nh.CloseSession(ctx, cs); err != nil {
t.Fatalf("failed to close client session %v", err)
}
cancel()
}
if timeoutExpected {
t.Fatalf("failed to trigger ")
}
}
func TestJoinedClusterCanBeRestartedOrJoinedAgain(t *testing.T) {
defer leaktest.AfterTest(t)()
os.RemoveAll(singleNodeHostTestDir)
datadir := singleNodeHostTestDir
rc := config.Config{
NodeID: uint64(1),
ClusterID: 2,
ElectionRTT: 5,
HeartbeatRTT: 1,
CheckQuorum: true,
SnapshotEntries: 10,
CompactionOverhead: 5,
}
peers := make(map[uint64]string)
nhc := config.NodeHostConfig{
WALDir: datadir,
NodeHostDir: datadir,
RTTMillisecond: 50,
RaftAddress: singleNodeHostTestAddr,
}
nh := NewNodeHost(nhc)
defer nh.Stop()
newPST := func(clusterID uint64, nodeID uint64) statemachine.IStateMachine {
return &PST{}
}
if err := nh.StartCluster(peers, true, newPST, rc); err != nil {
t.Fatalf("failed to join the cluster")
}
if err := nh.StopCluster(2); err != nil {
t.Fatalf("failed to stop the cluster")
}
if err := nh.StartCluster(peers, true, newPST, rc); err != nil {
t.Fatalf("failed to join the cluster again")
}
if err := nh.StopCluster(2); err != nil {
t.Fatalf("failed to stop the cluster")
}
if err := nh.StartCluster(peers, false, newPST, rc); err != nil {
t.Fatalf("failed to restartthe cluster again")
}
}
func TestSnapshotCanBeStopped(t *testing.T) {
defer leaktest.AfterTest(t)()
os.RemoveAll(singleNodeHostTestDir)
nh, pst, err := createSingleNodeTestNodeHost(singleNodeHostTestAddr,
singleNodeHostTestDir, true)
if err != nil {
t.Fatalf("failed to create nodehost %v", err)
}
waitForLeaderToBeElected(t, nh)
defer os.RemoveAll(singleNodeHostTestDir)
createProposalsToTriggerSnapshot(t, nh, 50, true)
nh.Stop()
time.Sleep(100 * time.Millisecond)
if !pst.saved || !pst.stopped {
t.Errorf("snapshot not stopped")
}
}
func TestRecoverFromSnapshotCanBeStopped(t *testing.T) {
defer leaktest.AfterTest(t)()
os.RemoveAll(singleNodeHostTestDir)
nh, _, err := createSingleNodeTestNodeHost(singleNodeHostTestAddr,
singleNodeHostTestDir, false)
if err != nil {
t.Fatalf("failed to create nodehost %v", err)
}
waitForLeaderToBeElected(t, nh)
defer os.RemoveAll(singleNodeHostTestDir)
createProposalsToTriggerSnapshot(t, nh, 25, false)
nh.Stop()
nh, pst, err := createSingleNodeTestNodeHost(singleNodeHostTestAddr,
singleNodeHostTestDir, false)
if err != nil {
t.Fatalf("failed to restart nodehost %v", err)
}
wait := 0
for !pst.getRestored() {
time.Sleep(100 * time.Millisecond)
wait++
if wait > 100 {
break
}
}
nh.Stop()
wait = 0
for !pst.stopped {
time.Sleep(100 * time.Millisecond)
wait++
if wait > 100 {
break
}
}
if !pst.getRestored() {
t.Errorf("not restored")
}
if !pst.stopped {
t.Errorf("not stopped")
}
}
func TestRegisterASessionTwiceWillBeReported(t *testing.T) {
tf := func(t *testing.T, nh *NodeHost) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cs, err := nh.GetNewSession(ctx, 2)
if err != nil {
t.Errorf("failed to get client session %v", err)
}
cs.PrepareForRegister()
rs, err := nh.ProposeSession(cs, 5*time.Second)
if err != nil {
t.Errorf("failed to propose client session %v", err)
}
r := <-rs.CompletedC
if !r.Rejected() {
t.Errorf("failed to reject the cs registeration")
}
}
singleNodeHostTest(t, tf)
}
func TestUnregisterNotRegisterClientSessionWillBeReported(t *testing.T) {
tf := func(t *testing.T, nh *NodeHost) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cs, err := nh.GetNewSession(ctx, 2)
if err != nil {
t.Errorf("failed to get client session %v", err)
}
err = nh.CloseSession(ctx, cs)
if err != nil {
t.Errorf("failed to unregister the client session %v", err)
}
err = nh.CloseSession(ctx, cs)
if err != ErrRejected {
t.Errorf("failed to reject the request %v", err)
}
}
singleNodeHostTest(t, tf)
}
func testZombieSnapshotDirWillBeDeletedDuringAddCluster(t *testing.T, dirName string) {
nh, _, err := createSingleNodeTestNodeHost(singleNodeHostTestAddr,
singleNodeHostTestDir, false)
defer os.RemoveAll(singleNodeHostTestDir)
if err != nil {
t.Fatalf("failed to create nodehost %v", err)
}
if _, err = nh.serverCtx.PrepareSnapshotDir(nh.deploymentID, 2, 1); err != nil {
t.Fatalf("failed to get snap dir")
}
snapDir := nh.serverCtx.GetSnapshotDir(nh.deploymentID, 2, 1)
z1 := filepath.Join(snapDir, dirName)
plog.Infof("creating %s", z1)
if err = os.MkdirAll(z1, 0755); err != nil {
t.Fatalf("failed to create dir %v", err)
}
nh.Stop()
nh, _, err = createSingleNodeTestNodeHost(singleNodeHostTestAddr,
singleNodeHostTestDir, false)
defer nh.Stop()
if err != nil {
t.Fatalf("failed to create nodehost %v", err)
}
_, err = os.Stat(z1)
if !os.IsNotExist(err) {
t.Fatalf("failed to delete zombie dir")
}
}
func TestZombieSnapshotDirWillBeDeletedDuringAddCluster(t *testing.T) {
defer leaktest.AfterTest(t)()
testZombieSnapshotDirWillBeDeletedDuringAddCluster(t, "snapshot-AB-01.receiving")
testZombieSnapshotDirWillBeDeletedDuringAddCluster(t, "snapshot-AB-10.generating")
}
func singleNodeHostTest(t *testing.T, tf func(t *testing.T, nh *NodeHost)) {
defer leaktest.AfterTest(t)()
os.RemoveAll(singleNodeHostTestDir)
nh, _, err := createSingleNodeTestNodeHost(singleNodeHostTestAddr,
singleNodeHostTestDir, false)
if err != nil {
t.Fatalf("failed to create nodehost %v", err)
}
waitForLeaderToBeElected(t, nh)
defer os.RemoveAll(singleNodeHostTestDir)
defer nh.Stop()
tf(t, nh)
}
func testNodeHostReadIndex(t *testing.T) {
tf := func(t *testing.T, nh *NodeHost) {
rs, err := nh.ReadIndex(2, time.Second)
if err != nil {
t.Errorf("failed to read index %v", err)
}
v := <-rs.CompletedC
if !v.Completed() {
t.Errorf("failed to complete read index")
}
_, err = nh.ReadLocal(2, make([]byte, 128))
if err != nil {
t.Errorf("read local failed %v", err)
}
}
singleNodeHostTest(t, tf)
}
func TestNodeHostReadIndex(t *testing.T) {
testNodeHostReadIndex(t)
}
func TestNodeHostSyncIOAPIs(t *testing.T) {
tf := func(t *testing.T, nh *NodeHost) {
cs := nh.GetNoOPSession(2)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
v, err := nh.SyncPropose(ctx, cs, make([]byte, 128))
if err != nil {
t.Errorf("make proposal failed %v", err)
}
if v != 128 {
t.Errorf("unexpected result")
}
data, err := nh.SyncRead(ctx, 2, make([]byte, 128))
if err != nil {
t.Errorf("make linearizable read failed %v", err)
}
if len(data) == 0 {
t.Errorf("failed to get result")
}
if err := nh.StopCluster(2); err != nil {
t.Errorf("failed to stop cluster 2 %v", err)
}
}
singleNodeHostTest(t, tf)
}
func TestNodeHostAddNode(t *testing.T) {
tf := func(t *testing.T, nh *NodeHost) {
rs, err := nh.RequestAddNode(2, 2, "localhost:25000", 0, time.Second)
if err != nil {
t.Errorf("failed to add node %v", err)
}
v := <-rs.CompletedC
if !v.Completed() {
t.Errorf("failed to complete add node")
}
}
singleNodeHostTest(t, tf)
}
func TestNodeHostGetNodeUser(t *testing.T) {
tf := func(t *testing.T, nh *NodeHost) {
n, err := nh.GetNodeUser(2)
if err != nil {
t.Errorf("failed to get NodeUser")
}
if n == nil {
t.Errorf("got a nil NodeUser")
}
n, err = nh.GetNodeUser(123)
if err != ErrClusterNotFound {
t.Errorf("didn't return expected err")
}
if n != nil {
t.Errorf("got unexpected node user")
}
}
singleNodeHostTest(t, tf)
}
func TestNodeHostNodeUserPropose(t *testing.T) {
tf := func(t *testing.T, nh *NodeHost) {
n, err := nh.GetNodeUser(2)
if err != nil {
t.Errorf("failed to get NodeUser")
}
cs := nh.GetNoOPSession(2)
rs, err := n.Propose(cs, make([]byte, 16), time.Second)
if err != nil {
t.Errorf("failed to make propose %v", err)
}
v := <-rs.CompletedC
if !v.Completed() {
t.Errorf("failed to complete proposal")
}
}
singleNodeHostTest(t, tf)
}
func TestNodeHostNodeUserRead(t *testing.T) {
tf := func(t *testing.T, nh *NodeHost) {
n, err := nh.GetNodeUser(2)
if err != nil {
t.Errorf("failed to get NodeUser")
}
rs, err := n.ReadIndex(time.Second)
if err != nil {
t.Errorf("failed to read index %v", err)
}
v := <-rs.CompletedC
if !v.Completed() {
t.Errorf("failed to complete read index")
}
}
singleNodeHostTest(t, tf)
}
func TestNodeHostAddObserverRemoveNode(t *testing.T) {
tf := func(t *testing.T, nh *NodeHost) {
rs, err := nh.RequestAddObserver(2, 2, "localhost:25000", 0, time.Second)
if err != nil {
t.Errorf("failed to add node %v", err)
}
v := <-rs.CompletedC
if !v.Completed() {
t.Errorf("failed to complete add node")
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
membership, err := nh.GetClusterMembership(ctx, 2)
if err != nil {
t.Fatalf("failed to get cluster membership %v", err)
}
if len(membership.Nodes) != 1 || len(membership.Removed) != 0 {
t.Errorf("unexpected nodes/removed len")
}
if len(membership.Observers) != 1 {
t.Errorf("unexpected nodes len")
}
_, ok := membership.Observers[2]
if !ok {
t.Errorf("node 2 not added")
}
// remove it
rs, err = nh.RequestDeleteNode(2, 2, 0, time.Second)
if err != nil {
t.Errorf("failed to remove node %v", err)
}
v = <-rs.CompletedC
if !v.Completed() {
t.Errorf("failed to complete remove node")
}
ctx, cancel = context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
membership, err = nh.GetClusterMembership(ctx, 2)
if err != nil {
t.Fatalf("failed to get cluster membership %v", err)
}
if len(membership.Nodes) != 1 || len(membership.Removed) != 1 {
t.Errorf("unexpected nodes/removed len")
}
if len(membership.Observers) != 0 {