-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathnode_liveness_test.go
1185 lines (1057 loc) · 37.2 KB
/
node_liveness_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 2016 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package kvserver_test
import (
"context"
"fmt"
"reflect"
"sort"
"sync/atomic"
"testing"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/config"
"github.com/cockroachdb/cockroach/pkg/config/zonepb"
"github.com/cockroachdb/cockroach/pkg/gossip"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvserverbase"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvserverpb"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/rpc"
"github.com/cockroachdb/cockroach/pkg/server"
"github.com/cockroachdb/cockroach/pkg/server/serverpb"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/skip"
"github.com/cockroachdb/cockroach/pkg/testutils/testcluster"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/logtags"
"github.com/gogo/protobuf/proto"
"github.com/stretchr/testify/require"
"golang.org/x/sync/errgroup"
)
func verifyLiveness(t *testing.T, mtc *multiTestContext) {
testutils.SucceedsSoon(t, func() error {
for i, nl := range mtc.nodeLivenesses {
for _, g := range mtc.gossips {
live, err := nl.IsLive(g.NodeID.Get())
if err != nil {
return err
} else if !live {
return errors.Errorf("node %d not live", g.NodeID.Get())
}
}
if a, e := nl.Metrics().LiveNodes.Value(), int64(len(mtc.nodeLivenesses)); a != e {
return errors.Errorf("expected node %d's LiveNodes metric to be %d; got %d",
mtc.gossips[i].NodeID.Get(), e, a)
}
}
return nil
})
}
func pauseNodeLivenessHeartbeatLoops(mtc *multiTestContext) func() {
var enableFns []func()
for _, nl := range mtc.nodeLivenesses {
enableFns = append(enableFns, nl.PauseHeartbeatLoopForTest())
}
return func() {
for _, fn := range enableFns {
fn()
}
}
}
func TestNodeLiveness(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
mtc := &multiTestContext{}
defer mtc.Stop()
mtc.Start(t, 3)
// Verify liveness of all nodes for all nodes.
verifyLiveness(t, mtc)
pauseNodeLivenessHeartbeatLoops(mtc)
// Advance clock past the liveness threshold to verify IsLive becomes false.
mtc.manualClock.Increment(mtc.nodeLivenesses[0].GetLivenessThreshold().Nanoseconds() + 1)
for idx, nl := range mtc.nodeLivenesses {
nodeID := mtc.gossips[idx].NodeID.Get()
live, err := nl.IsLive(nodeID)
if err != nil {
t.Error(err)
} else if live {
t.Errorf("expected node %d to be considered not-live after advancing node clock", nodeID)
}
testutils.SucceedsSoon(t, func() error {
if a, e := nl.Metrics().LiveNodes.Value(), int64(0); a != e {
return errors.Errorf("expected node %d's LiveNodes metric to be %d; got %d",
nodeID, e, a)
}
return nil
})
}
// Trigger a manual heartbeat and verify liveness is reestablished.
for _, nl := range mtc.nodeLivenesses {
l, err := nl.Self()
if err != nil {
t.Fatal(err)
}
for {
err := nl.Heartbeat(context.Background(), l)
if err == nil {
break
}
if errors.Is(err, kvserver.ErrEpochIncremented) {
log.Warningf(context.Background(), "retrying after %s", err)
continue
}
t.Fatal(err)
}
}
verifyLiveness(t, mtc)
// Verify metrics counts.
for i, nl := range mtc.nodeLivenesses {
if c := nl.Metrics().HeartbeatSuccesses.Count(); c < 2 {
t.Errorf("node %d: expected metrics count >= 2; got %d", (i + 1), c)
}
}
}
func TestNodeLivenessInitialIncrement(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
mtc := &multiTestContext{}
defer mtc.Stop()
mtc.Start(t, 1)
// Verify liveness of all nodes for all nodes.
verifyLiveness(t, mtc)
liveness, err := mtc.nodeLivenesses[0].GetLiveness(mtc.gossips[0].NodeID.Get())
if err != nil {
t.Fatal(err)
}
if liveness.Epoch != 1 {
t.Errorf("expected epoch to be set to 1 initially; got %d", liveness.Epoch)
}
// Restart the node and verify the epoch is incremented with initial heartbeat.
mtc.stopStore(0)
mtc.restartStore(0)
verifyEpochIncremented(t, mtc, 0)
}
// TestNodeLivenessAppearsAtStart tests that liveness records are written right
// when nodes are added to the cluster (during bootstrap, and when connecting to
// a bootstrapped node). The test verifies that the liveness records found are
// what we expect them to be.
func TestNodeLivenessAppearsAtStart(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
tc := testcluster.StartTestCluster(t, 3, base.TestClusterArgs{})
defer tc.Stopper().Stop(ctx)
// Verify liveness records exist for all nodes.
for i := 0; i < tc.NumServers(); i++ {
nodeID := tc.Server(i).NodeID()
nl := tc.Server(i).NodeLiveness().(*kvserver.NodeLiveness)
if live, err := nl.IsLive(nodeID); err != nil {
t.Fatal(err)
} else if !live {
t.Fatalf("node %d not live", nodeID)
}
livenessRec, err := nl.GetLiveness(nodeID)
if err != nil {
t.Fatal(err)
}
if livenessRec.NodeID != nodeID {
t.Fatalf("expected node ID %d, got %d", nodeID, livenessRec.NodeID)
}
// We expect epoch=2 as nodes first create a liveness record at epoch=1,
// and then increment it during their first heartbeat.
if livenessRec.Epoch != 2 {
t.Fatalf("expected epoch=2, got epoch=%d", livenessRec.Epoch)
}
if !livenessRec.Membership.Active() {
t.Fatalf("expected membership=active, got membership=%s", livenessRec.Membership)
}
}
}
func verifyEpochIncremented(t *testing.T, mtc *multiTestContext, nodeIdx int) {
testutils.SucceedsSoon(t, func() error {
liveness, err := mtc.nodeLivenesses[nodeIdx].GetLiveness(mtc.gossips[nodeIdx].NodeID.Get())
if err != nil {
return err
}
if liveness.Epoch < 2 {
return errors.Errorf("expected epoch to be >=2 on restart but was %d", liveness.Epoch)
}
return nil
})
}
// TestRedundantNodeLivenessHeartbeatsAvoided tests that in a thundering herd
// scenario with many goroutines rush to synchronously heartbeat a node's
// liveness record, redundant heartbeats are detected and avoided.
func TestRedundantNodeLivenessHeartbeatsAvoided(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
mtc := &multiTestContext{}
defer mtc.Stop()
mtc.Start(t, 1)
nl := mtc.nodeLivenesses[0]
nlActive, _ := mtc.storeConfig.NodeLivenessDurations()
// Verify liveness of all nodes for all nodes.
verifyLiveness(t, mtc)
nl.PauseHeartbeatLoopForTest()
enableSync := nl.PauseSynchronousHeartbeatsForTest()
liveness, err := nl.Self()
require.NoError(t, err)
hbBefore := nl.Metrics().HeartbeatSuccesses.Count()
require.Equal(t, int64(0), nl.Metrics().HeartbeatsInFlight.Value())
// Issue a set of synchronous node liveness heartbeats. Mimic the kind of
// thundering herd we see due to lease acquisitions when a node's liveness
// epoch is incremented.
var g errgroup.Group
const herdSize = 30
for i := 0; i < herdSize; i++ {
g.Go(func() error {
before := mtc.clock().Now()
if err := nl.Heartbeat(ctx, liveness); err != nil {
return err
}
livenessAfter, err := nl.Self()
if err != nil {
return err
}
exp := livenessAfter.Expiration
minExp := hlc.LegacyTimestamp(before.Add(nlActive.Nanoseconds(), 0))
if exp.Less(minExp) {
return errors.Errorf("expected min expiration %v, found %v", minExp, exp)
}
return nil
})
}
// Wait for all heartbeats to be in-flight, at which point they will have
// already computed their minimum expiration time.
testutils.SucceedsSoon(t, func() error {
inFlight := nl.Metrics().HeartbeatsInFlight.Value()
if inFlight < herdSize {
return errors.Errorf("not all heartbeats in-flight, want %d, got %d", herdSize, inFlight)
} else if inFlight > herdSize {
t.Fatalf("unexpected in-flight heartbeat count: %d", inFlight)
}
return nil
})
// Allow the heartbeats to proceed. Only a single one should end up touching
// the liveness record. The rest should be considered redundant.
enableSync()
require.NoError(t, g.Wait())
require.Equal(t, hbBefore+1, nl.Metrics().HeartbeatSuccesses.Count())
require.Equal(t, int64(0), nl.Metrics().HeartbeatsInFlight.Value())
// Send one more heartbeat. Should update liveness record.
liveness, err = nl.Self()
require.NoError(t, err)
require.NoError(t, nl.Heartbeat(ctx, liveness))
require.Equal(t, hbBefore+2, nl.Metrics().HeartbeatSuccesses.Count())
require.Equal(t, int64(0), nl.Metrics().HeartbeatsInFlight.Value())
}
// TestNodeIsLiveCallback verifies that the liveness callback for a
// node is invoked when it changes from state false to true.
func TestNodeIsLiveCallback(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
mtc := &multiTestContext{}
defer mtc.Stop()
mtc.Start(t, 3)
// Verify liveness of all nodes for all nodes.
verifyLiveness(t, mtc)
pauseNodeLivenessHeartbeatLoops(mtc)
var cbMu syncutil.Mutex
cbs := map[roachpb.NodeID]struct{}{}
mtc.nodeLivenesses[0].RegisterCallback(func(l kvserverpb.Liveness) {
cbMu.Lock()
defer cbMu.Unlock()
cbs[l.NodeID] = struct{}{}
})
// Advance clock past the liveness threshold.
mtc.manualClock.Increment(mtc.nodeLivenesses[0].GetLivenessThreshold().Nanoseconds() + 1)
// Trigger a manual heartbeat and verify callbacks for each node ID are invoked.
for _, nl := range mtc.nodeLivenesses {
l, err := nl.Self()
if err != nil {
t.Fatal(err)
}
if err := nl.Heartbeat(context.Background(), l); err != nil {
t.Fatal(err)
}
}
testutils.SucceedsSoon(t, func() error {
cbMu.Lock()
defer cbMu.Unlock()
for _, g := range mtc.gossips {
nodeID := g.NodeID.Get()
if _, ok := cbs[nodeID]; !ok {
return errors.Errorf("expected IsLive callback for node %d", nodeID)
}
}
return nil
})
}
// TestNodeHeartbeatCallback verifies that HeartbeatCallback is invoked whenever
// this node updates its own liveness status.
func TestNodeHeartbeatCallback(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
mtc := &multiTestContext{}
defer mtc.Stop()
mtc.Start(t, 3)
// Verify liveness of all nodes for all nodes.
verifyLiveness(t, mtc)
pauseNodeLivenessHeartbeatLoops(mtc)
// Verify that last update time has been set for all nodes.
verifyUptimes := func() error {
expected := mtc.clock().Now()
for i, s := range mtc.stores {
uptm, err := s.ReadLastUpTimestamp(context.Background())
if err != nil {
return errors.Wrapf(err, "error reading last up time from store %d", i)
}
if a, e := uptm.WallTime, expected.WallTime; a != e {
return errors.Errorf("store %d last uptime = %d; wanted %d", i, a, e)
}
}
return nil
}
if err := verifyUptimes(); err != nil {
t.Fatal(err)
}
// Advance clock past the liveness threshold and force a manual heartbeat on
// all node liveness objects, which should update the last up time for each
// store.
mtc.manualClock.Increment(mtc.nodeLivenesses[0].GetLivenessThreshold().Nanoseconds() + 1)
for _, nl := range mtc.nodeLivenesses {
l, err := nl.Self()
if err != nil {
t.Fatal(err)
}
if err := nl.Heartbeat(context.Background(), l); err != nil {
t.Fatal(err)
}
}
// NB: since the heartbeat callback is invoked synchronously in
// `Heartbeat()` which this goroutine invoked, we don't need to wrap this in
// a retry.
if err := verifyUptimes(); err != nil {
t.Fatal(err)
}
}
// TestNodeLivenessEpochIncrement verifies that incrementing the epoch
// of a node requires the node to be considered not-live and that on
// increment, no other nodes believe the epoch-incremented node to be
// live.
func TestNodeLivenessEpochIncrement(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
mtc := &multiTestContext{}
defer mtc.Stop()
mtc.Start(t, 2)
verifyLiveness(t, mtc)
pauseNodeLivenessHeartbeatLoops(mtc)
// First try to increment the epoch of a known-live node.
deadNodeID := mtc.gossips[1].NodeID.Get()
oldLiveness, err := mtc.nodeLivenesses[0].GetLiveness(deadNodeID)
if err != nil {
t.Fatal(err)
}
if err := mtc.nodeLivenesses[0].IncrementEpoch(
ctx, oldLiveness.Liveness,
); !testutils.IsError(err, "cannot increment epoch on live node") {
t.Fatalf("expected error incrementing a live node: %+v", err)
}
// Advance clock past liveness threshold & increment epoch.
mtc.manualClock.Increment(mtc.nodeLivenesses[0].GetLivenessThreshold().Nanoseconds() + 1)
if err := mtc.nodeLivenesses[0].IncrementEpoch(ctx, oldLiveness.Liveness); err != nil {
t.Fatalf("unexpected error incrementing a non-live node: %+v", err)
}
// Verify that the epoch has been advanced.
testutils.SucceedsSoon(t, func() error {
newLiveness, err := mtc.nodeLivenesses[0].GetLiveness(deadNodeID)
if err != nil {
return err
}
if newLiveness.Epoch != oldLiveness.Epoch+1 {
return errors.Errorf("expected epoch to increment")
}
if newLiveness.Expiration != oldLiveness.Expiration {
return errors.Errorf("expected expiration to remain unchanged")
}
if live, err := mtc.nodeLivenesses[0].IsLive(deadNodeID); live || err != nil {
return errors.Errorf("expected dead node to remain dead after epoch increment %t: %v", live, err)
}
return nil
})
// Verify epoch increment metric count.
if c := mtc.nodeLivenesses[0].Metrics().EpochIncrements.Count(); c != 1 {
t.Errorf("expected epoch increment == 1; got %d", c)
}
// Verify error on incrementing an already-incremented epoch.
if err := mtc.nodeLivenesses[0].IncrementEpoch(
ctx, oldLiveness.Liveness,
); !errors.Is(err, kvserver.ErrEpochAlreadyIncremented) {
t.Fatalf("unexpected error incrementing a non-live node: %+v", err)
}
// Verify error incrementing with a too-high expectation for liveness epoch.
oldLiveness.Epoch = 3
if err := mtc.nodeLivenesses[0].IncrementEpoch(
ctx, oldLiveness.Liveness,
); !testutils.IsError(err, "unexpected liveness epoch 2; expected >= 3") {
t.Fatalf("expected error incrementing with a too-high expected epoch: %+v", err)
}
}
// TestNodeLivenessRestart verifies that if nodes are shutdown and
// restarted, the node liveness records are re-gossiped immediately.
func TestNodeLivenessRestart(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
mtc := &multiTestContext{}
defer mtc.Stop()
mtc.Start(t, 2)
// After verifying node is in liveness table, stop store.
verifyLiveness(t, mtc)
mtc.stopStore(0)
// Clear the liveness records in store 1's gossip to make sure we're
// seeing the liveness record properly gossiped at store startup.
var expKeys []string
for _, g := range mtc.gossips {
key := gossip.MakeNodeLivenessKey(g.NodeID.Get())
expKeys = append(expKeys, key)
if err := g.AddInfoProto(key, &kvserverpb.Liveness{}, 0); err != nil {
t.Fatal(err)
}
}
sort.Strings(expKeys)
// Register a callback to gossip in order to verify liveness records
// are re-gossiped.
var keysMu struct {
syncutil.Mutex
keys []string
}
livenessRegex := gossip.MakePrefixPattern(gossip.KeyNodeLivenessPrefix)
mtc.gossips[0].RegisterCallback(livenessRegex, func(key string, _ roachpb.Value) {
keysMu.Lock()
defer keysMu.Unlock()
for _, k := range keysMu.keys {
if k == key {
return
}
}
keysMu.keys = append(keysMu.keys, key)
})
// Restart store and verify gossip contains liveness record for nodes 1&2.
mtc.restartStore(0)
testutils.SucceedsSoon(t, func() error {
keysMu.Lock()
defer keysMu.Unlock()
sort.Strings(keysMu.keys)
if !reflect.DeepEqual(keysMu.keys, expKeys) {
return errors.Errorf("expected keys %+v != keys %+v", expKeys, keysMu.keys)
}
return nil
})
}
// TestNodeLivenessSelf verifies that a node keeps its own most recent liveness
// heartbeat info in preference to anything which might be received belatedly
// through gossip.
//
// Note that this test originally injected a Gossip update with a higher Epoch
// and semantics have since changed to make the "self" record less special. It
// is updated like any other node's record, with appropriate safeguards against
// clobbering in place.
func TestNodeLivenessSelf(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
mtc := &multiTestContext{}
defer mtc.Stop()
mtc.Start(t, 1)
g := mtc.gossips[0]
pauseNodeLivenessHeartbeatLoops(mtc)
// Verify liveness is properly initialized. This needs to be wrapped in a
// SucceedsSoon because node liveness gets initialized via an async gossip
// callback.
var liveness kvserver.LivenessRecord
testutils.SucceedsSoon(t, func() error {
var err error
liveness, err = mtc.nodeLivenesses[0].GetLiveness(g.NodeID.Get())
return err
})
if err := mtc.nodeLivenesses[0].Heartbeat(context.Background(), liveness.Liveness); err != nil {
t.Fatal(err)
}
// Gossip random nonsense for liveness and verify that asking for
// the node's own node ID returns the "correct" value.
key := gossip.MakeNodeLivenessKey(g.NodeID.Get())
var count int32
g.RegisterCallback(key, func(_ string, val roachpb.Value) {
atomic.AddInt32(&count, 1)
})
testutils.SucceedsSoon(t, func() error {
fakeBehindLiveness := liveness
fakeBehindLiveness.Epoch-- // almost certainly results in zero
if err := g.AddInfoProto(key, &fakeBehindLiveness, 0); err != nil {
t.Fatal(err)
}
if atomic.LoadInt32(&count) < 2 {
return errors.New("expected count >= 2")
}
return nil
})
// Self should not see the fake liveness, but have kept the real one.
l := mtc.nodeLivenesses[0]
lGetRec, err := l.GetLiveness(g.NodeID.Get())
require.NoError(t, err)
lGet := lGetRec.Liveness
lSelf, err := l.Self()
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(lGet, lSelf) {
t.Errorf("expected GetLiveness() to return same value as Self(): %+v != %+v", lGet, lSelf)
}
if lGet.Epoch == 2 || lSelf.NodeID == 2 {
t.Errorf("expected GetLiveness() and Self() not to return artificially gossiped liveness: %+v, %+v", lGet, lSelf)
}
}
func TestNodeLivenessGetIsLiveMap(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
mtc := &multiTestContext{}
defer mtc.Stop()
mtc.Start(t, 3)
verifyLiveness(t, mtc)
pauseNodeLivenessHeartbeatLoops(mtc)
lMap := mtc.nodeLivenesses[0].GetIsLiveMap()
l1, _ := mtc.nodeLivenesses[0].GetLiveness(1)
l2, _ := mtc.nodeLivenesses[0].GetLiveness(2)
l3, _ := mtc.nodeLivenesses[0].GetLiveness(3)
expectedLMap := kvserver.IsLiveMap{
1: {Liveness: l1.Liveness, IsLive: true},
2: {Liveness: l2.Liveness, IsLive: true},
3: {Liveness: l3.Liveness, IsLive: true},
}
if !reflect.DeepEqual(expectedLMap, lMap) {
t.Errorf("expected liveness map %+v; got %+v", expectedLMap, lMap)
}
// Advance the clock but only heartbeat node 0.
mtc.manualClock.Increment(mtc.nodeLivenesses[0].GetLivenessThreshold().Nanoseconds() + 1)
liveness, _ := mtc.nodeLivenesses[0].GetLiveness(mtc.gossips[0].NodeID.Get())
testutils.SucceedsSoon(t, func() error {
if err := mtc.nodeLivenesses[0].Heartbeat(context.Background(), liveness.Liveness); err != nil {
if errors.Is(err, kvserver.ErrEpochIncremented) {
return err
}
t.Fatal(err)
}
return nil
})
// Now verify only node 0 is live.
lMap = mtc.nodeLivenesses[0].GetIsLiveMap()
l1, _ = mtc.nodeLivenesses[0].GetLiveness(1)
l2, _ = mtc.nodeLivenesses[0].GetLiveness(2)
l3, _ = mtc.nodeLivenesses[0].GetLiveness(3)
expectedLMap = kvserver.IsLiveMap{
1: {Liveness: l1.Liveness, IsLive: true},
2: {Liveness: l2.Liveness, IsLive: false},
3: {Liveness: l3.Liveness, IsLive: false},
}
if !reflect.DeepEqual(expectedLMap, lMap) {
t.Errorf("expected liveness map %+v; got %+v", expectedLMap, lMap)
}
}
func TestNodeLivenessGetLivenesses(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
mtc := &multiTestContext{}
defer mtc.Stop()
mtc.Start(t, 3)
verifyLiveness(t, mtc)
pauseNodeLivenessHeartbeatLoops(mtc)
livenesses := mtc.nodeLivenesses[0].GetLivenesses()
actualLMapNodes := make(map[roachpb.NodeID]struct{})
originalExpiration := mtc.clock().PhysicalNow() + mtc.nodeLivenesses[0].GetLivenessThreshold().Nanoseconds()
for _, l := range livenesses {
if a, e := l.Epoch, int64(1); a != e {
t.Errorf("liveness record had epoch %d, wanted %d", a, e)
}
if a, e := l.Expiration.WallTime, originalExpiration; a != e {
t.Errorf("liveness record had expiration %d, wanted %d", a, e)
}
actualLMapNodes[l.NodeID] = struct{}{}
}
expectedLMapNodes := map[roachpb.NodeID]struct{}{1: {}, 2: {}, 3: {}}
if !reflect.DeepEqual(actualLMapNodes, expectedLMapNodes) {
t.Errorf("got liveness map nodes %+v; wanted %+v", actualLMapNodes, expectedLMapNodes)
}
// Advance the clock but only heartbeat node 0.
mtc.manualClock.Increment(mtc.nodeLivenesses[0].GetLivenessThreshold().Nanoseconds() + 1)
liveness, _ := mtc.nodeLivenesses[0].GetLiveness(mtc.gossips[0].NodeID.Get())
if err := mtc.nodeLivenesses[0].Heartbeat(context.Background(), liveness.Liveness); err != nil {
t.Fatal(err)
}
// Verify that node liveness receives the change.
livenesses = mtc.nodeLivenesses[0].GetLivenesses()
actualLMapNodes = make(map[roachpb.NodeID]struct{})
for _, l := range livenesses {
if a, e := l.Epoch, int64(1); a != e {
t.Errorf("liveness record had epoch %d, wanted %d", a, e)
}
expectedExpiration := originalExpiration
if l.NodeID == 1 {
expectedExpiration += mtc.nodeLivenesses[0].GetLivenessThreshold().Nanoseconds() + 1
}
if a, e := l.Expiration.WallTime, expectedExpiration; a != e {
t.Errorf("liveness record had expiration %d, wanted %d", a, e)
}
actualLMapNodes[l.NodeID] = struct{}{}
}
if !reflect.DeepEqual(actualLMapNodes, expectedLMapNodes) {
t.Errorf("got liveness map nodes %+v; wanted %+v", actualLMapNodes, expectedLMapNodes)
}
}
// TestNodeLivenessConcurrentHeartbeats verifies that concurrent attempts
// to heartbeat all succeed.
func TestNodeLivenessConcurrentHeartbeats(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
mtc := &multiTestContext{}
defer mtc.Stop()
mtc.Start(t, 1)
verifyLiveness(t, mtc)
pauseNodeLivenessHeartbeatLoops(mtc)
const concurrency = 10
// Advance clock past the liveness threshold & concurrently heartbeat node.
nl := mtc.nodeLivenesses[0]
mtc.manualClock.Increment(nl.GetLivenessThreshold().Nanoseconds() + 1)
l, err := nl.Self()
if err != nil {
t.Fatal(err)
}
errCh := make(chan error, concurrency)
for i := 0; i < concurrency; i++ {
go func() {
errCh <- nl.Heartbeat(context.Background(), l)
}()
}
for i := 0; i < concurrency; i++ {
if err := <-errCh; err != nil {
t.Fatalf("concurrent heartbeat %d failed: %+v", i, err)
}
}
}
// TestNodeLivenessConcurrentIncrementEpochs verifies concurrent
// attempts to increment liveness of another node all succeed.
func TestNodeLivenessConcurrentIncrementEpochs(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
mtc := &multiTestContext{}
defer mtc.Stop()
mtc.Start(t, 2)
verifyLiveness(t, mtc)
pauseNodeLivenessHeartbeatLoops(mtc)
const concurrency = 10
// Advance the clock and this time increment epoch concurrently for node 1.
nl := mtc.nodeLivenesses[0]
mtc.manualClock.Increment(nl.GetLivenessThreshold().Nanoseconds() + 1)
l, err := nl.GetLiveness(mtc.gossips[1].NodeID.Get())
if err != nil {
t.Fatal(err)
}
errCh := make(chan error, concurrency)
for i := 0; i < concurrency; i++ {
go func() {
errCh <- nl.IncrementEpoch(context.Background(), l.Liveness)
}()
}
for i := 0; i < concurrency; i++ {
if err := <-errCh; err != nil && !errors.Is(err, kvserver.ErrEpochAlreadyIncremented) {
t.Fatalf("concurrent increment epoch %d failed: %+v", i, err)
}
}
}
// TestNodeLivenessSetDraining verifies that when draining, a node's liveness
// record is updated and the node will not be present in the store list of other
// nodes once they are aware of its draining state.
func TestNodeLivenessSetDraining(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
mtc := &multiTestContext{}
defer mtc.Stop()
mtc.Start(t, 3)
mtc.initGossipNetwork()
verifyLiveness(t, mtc)
ctx := context.Background()
drainingNodeIdx := 0
drainingNodeID := mtc.gossips[drainingNodeIdx].NodeID.Get()
nodeIDAppearsInStoreList := func(id roachpb.NodeID, sl kvserver.StoreList) bool {
for _, store := range sl.Stores() {
if store.Node.NodeID == id {
return true
}
}
return false
}
// Verify success on failed update of a liveness record that already has the
// given draining setting.
if err := mtc.nodeLivenesses[drainingNodeIdx].SetDrainingInternal(
ctx, kvserver.LivenessRecord{}, false,
); err != nil {
t.Fatal(err)
}
mtc.nodeLivenesses[drainingNodeIdx].SetDraining(ctx, true /* drain */, nil /* reporter */)
// Draining node disappears from store lists.
{
const expectedLive = 2
// Executed in a retry loop to wait until the new liveness record has
// been gossiped to the rest of the cluster.
testutils.SucceedsSoon(t, func() error {
for i, sp := range mtc.storePools {
curNodeID := mtc.gossips[i].NodeID.Get()
sl, alive, _ := sp.GetStoreList()
if alive != expectedLive {
return errors.Errorf(
"expected %d live stores but got %d from node %d",
expectedLive,
alive,
curNodeID,
)
}
if nodeIDAppearsInStoreList(drainingNodeID, sl) {
return errors.Errorf(
"expected node %d not to appear in node %d's store list",
drainingNodeID,
curNodeID,
)
}
}
return nil
})
}
// Stop and restart the store to verify that a restarted server clears the
// draining field on the liveness record.
mtc.stopStore(drainingNodeIdx)
mtc.restartStore(drainingNodeIdx)
// Restarted node appears once again in the store list.
{
const expectedLive = 3
// Executed in a retry loop to wait until the new liveness record has
// been gossiped to the rest of the cluster.
testutils.SucceedsSoon(t, func() error {
for i, sp := range mtc.storePools {
curNodeID := mtc.gossips[i].NodeID.Get()
sl, alive, _ := sp.GetStoreList()
if alive != expectedLive {
return errors.Errorf(
"expected %d live stores but got %d from node %d",
expectedLive,
alive,
curNodeID,
)
}
if !nodeIDAppearsInStoreList(drainingNodeID, sl) {
return errors.Errorf(
"expected node %d to appear in node %d's store list: %+v",
drainingNodeID,
curNodeID,
sl.Stores(),
)
}
}
return nil
})
}
}
func TestNodeLivenessRetryAmbiguousResultError(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
var injectError atomic.Value
var injectedErrorCount int32
injectError.Store(true)
storeCfg := kvserver.TestStoreConfig(nil)
storeCfg.TestingKnobs.EvalKnobs.TestingEvalFilter = func(args kvserverbase.FilterArgs) *roachpb.Error {
if _, ok := args.Req.(*roachpb.ConditionalPutRequest); !ok {
return nil
}
if val := injectError.Load(); val != nil && val.(bool) {
atomic.AddInt32(&injectedErrorCount, 1)
injectError.Store(false)
return roachpb.NewError(roachpb.NewAmbiguousResultError("test"))
}
return nil
}
mtc := &multiTestContext{
storeConfig: &storeCfg,
}
mtc.Start(t, 1)
defer mtc.Stop()
// Verify retry of the ambiguous result for heartbeat loop.
verifyLiveness(t, mtc)
nl := mtc.nodeLivenesses[0]
l, err := nl.Self()
if err != nil {
t.Fatal(err)
}
// And again on manual heartbeat.
injectError.Store(true)
if err := nl.Heartbeat(context.Background(), l); err != nil {
t.Fatal(err)
}
if count := atomic.LoadInt32(&injectedErrorCount); count != 2 {
t.Errorf("expected injected error count of 2; got %d", count)
}
}
func verifyNodeIsDecommissioning(t *testing.T, mtc *multiTestContext, nodeID roachpb.NodeID) {
testutils.SucceedsSoon(t, func() error {
for _, nl := range mtc.nodeLivenesses {
livenesses := nl.GetLivenesses()
for _, liveness := range livenesses {
if liveness.NodeID != nodeID {
continue
}
if !liveness.Membership.Decommissioning() {
return errors.Errorf("unexpected Membership value of %v for node %v", liveness.Membership, liveness.NodeID)
}
}
}
return nil
})
}
func TestNodeLivenessStatusMap(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
skip.UnderShort(t)
serverArgs := base.TestServerArgs{
Knobs: base.TestingKnobs{
Store: &kvserver.StoreTestingKnobs{
// Disable replica rebalancing to ensure that the liveness range
// does not get out of the first node (we'll be shutting down nodes).
DisableReplicaRebalancing: true,
// Disable LBS because when the scan is happening at the rate it's happening
// below, it's possible that one of the system ranges trigger a split.
DisableLoadBasedSplitting: true,
},
},
RaftConfig: base.RaftConfig{
// Make everything tick faster to ensure dead nodes are
// recognized dead faster.
RaftTickInterval: 100 * time.Millisecond,
},
// Scan like a bat out of hell to ensure replication and replica GC
// happen in a timely manner.
ScanInterval: 50 * time.Millisecond,
}
tc := testcluster.StartTestCluster(t, 1, base.TestClusterArgs{
ServerArgs: serverArgs,
// Disable full replication otherwise StartTestCluster with just 1
// node will wait forever.
ReplicationMode: base.ReplicationManual,
})
ctx := context.Background()
defer tc.Stopper().Stop(ctx)
ctx = logtags.AddTag(ctx, "in test", nil)
log.Infof(ctx, "setting zone config to disable replication")
// Allow for inserting zone configs without having to go through (or
// duplicate the logic from) the CLI.
config.TestingSetupZoneConfigHook(tc.Stopper())
zoneConfig := zonepb.DefaultZoneConfig()
// Force just one replica per range to ensure that we can shut down
// nodes without endangering the liveness range.
zoneConfig.NumReplicas = proto.Int32(1)
config.TestingSetZoneConfig(keys.MetaRangesID, zoneConfig)
log.Infof(ctx, "starting 3 more nodes")
tc.AddAndStartServer(t, serverArgs)
tc.AddAndStartServer(t, serverArgs)
tc.AddAndStartServer(t, serverArgs)
log.Infof(ctx, "waiting for node statuses")
tc.WaitForNodeStatuses(t)
tc.WaitForNodeLiveness(t)
log.Infof(ctx, "waiting done")
firstServer := tc.Server(0).(*server.TestServer)
liveNodeID := firstServer.NodeID()
deadNodeID := tc.Server(1).NodeID()
log.Infof(ctx, "shutting down node %d", deadNodeID)
tc.StopServer(1)
log.Infof(ctx, "done shutting down node %d", deadNodeID)
decommissioningNodeID := tc.Server(2).NodeID()
log.Infof(ctx, "marking node %d as decommissioning", decommissioningNodeID)
if err := firstServer.Decommission(ctx, kvserverpb.MembershipStatus_DECOMMISSIONING, []roachpb.NodeID{decommissioningNodeID}); err != nil {
t.Fatal(err)
}
log.Infof(ctx, "marked node %d as decommissioning", decommissioningNodeID)
removedNodeID := tc.Server(3).NodeID()
log.Infof(ctx, "marking node %d as decommissioning and shutting it down", removedNodeID)
if err := firstServer.Decommission(ctx, kvserverpb.MembershipStatus_DECOMMISSIONING, []roachpb.NodeID{removedNodeID}); err != nil {