-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathreplicate_queue_test.go
1918 lines (1757 loc) · 64.5 KB
/
replicate_queue_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"
gosql "database/sql"
"encoding/json"
"fmt"
"math"
"math/rand"
"regexp"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/cockroachdb/cockroach-go/v2/crdb"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/config/zonepb"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvserverpb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/liveness/livenesspb"
"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/spanconfig"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/bootstrap"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/skip"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/testutils/testcluster"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/errors"
"github.com/gogo/protobuf/proto"
"github.com/stretchr/testify/require"
"go.etcd.io/etcd/raft/v3/tracker"
)
func TestReplicateQueueRebalance(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
// This test was seen taking north of 20m under race.
skip.UnderRace(t)
skip.UnderShort(t)
const numNodes = 5
ctx := context.Background()
tc := testcluster.StartTestCluster(t, numNodes,
base.TestClusterArgs{
ReplicationMode: base.ReplicationAuto,
ServerArgs: base.TestServerArgs{
ScanMinIdleTime: time.Millisecond,
ScanMaxIdleTime: time.Millisecond,
},
},
)
defer tc.Stopper().Stop(context.Background())
for _, server := range tc.Servers {
st := server.ClusterSettings()
st.Manual.Store(true)
kvserver.LoadBasedRebalancingMode.Override(ctx, &st.SV, int64(kvserver.LBRebalancingOff))
}
const newRanges = 10
trackedRanges := map[roachpb.RangeID]struct{}{}
for i := uint32(0); i < newRanges; i++ {
tableID := bootstrap.TestingUserDescID(i)
splitKey := keys.SystemSQLCodec.TablePrefix(tableID)
// Retry the splits on descriptor errors which are likely as the replicate
// queue is already hard at work.
testutils.SucceedsSoon(t, func() error {
desc := tc.LookupRangeOrFatal(t, splitKey)
if i > 0 && len(desc.Replicas().VoterDescriptors()) > 3 {
// Some system ranges have five replicas but user ranges only three,
// so we'll see downreplications early in the startup process which
// we want to ignore. Delay the splits so that we don't create
// more over-replicated ranges.
// We don't do this for i=0 since that range stays at five replicas.
return errors.Errorf("still downreplicating: %s", &desc)
}
_, rightDesc, err := tc.SplitRange(splitKey)
if err != nil {
return err
}
t.Logf("split off %s", &rightDesc)
if i > 0 {
trackedRanges[rightDesc.RangeID] = struct{}{}
}
return nil
})
}
countReplicas := func() []int {
counts := make([]int, len(tc.Servers))
for _, s := range tc.Servers {
err := s.Stores().VisitStores(func(s *kvserver.Store) error {
counts[s.StoreID()-1] += s.ReplicaCount()
return nil
})
if err != nil {
t.Fatal(err)
}
}
return counts
}
initialRanges, err := server.ExpectedInitialRangeCount(
keys.SystemSQLCodec,
zonepb.DefaultZoneConfigRef(),
zonepb.DefaultSystemZoneConfigRef(),
)
if err != nil {
t.Fatal(err)
}
numRanges := newRanges + initialRanges
numReplicas := numRanges * 3
const minThreshold = 0.9
minReplicas := int(math.Floor(minThreshold * (float64(numReplicas) / numNodes)))
testutils.SucceedsSoon(t, func() error {
counts := countReplicas()
for _, c := range counts {
if c < minReplicas {
err := errors.Errorf(
"not balanced (want at least %d replicas on all stores): %d", minReplicas, counts)
log.Infof(ctx, "%v", err)
return err
}
}
return nil
})
// Query the range log to see if anything unexpected happened. Concretely,
// we'll make sure that our tracked ranges never had >3 replicas.
infos, err := queryRangeLog(tc.Conns[0], `SELECT info FROM system.rangelog ORDER BY timestamp DESC`)
require.NoError(t, err)
for _, info := range infos {
if _, ok := trackedRanges[info.UpdatedDesc.RangeID]; !ok || len(info.UpdatedDesc.Replicas().VoterDescriptors()) <= 3 {
continue
}
// If we have atomic changes enabled, we expect to never see four replicas
// on our tracked ranges. If we don't have atomic changes, we can't avoid
// it.
t.Error(info)
}
}
// TestReplicateQueueUpReplicateOddVoters tests that up-replication only
// proceeds if there are a good number of candidates to up-replicate to.
// Specifically, we won't up-replicate to an even number of replicas unless
// there is an additional candidate that will allow a subsequent up-replication
// to an odd number.
func TestReplicateQueueUpReplicateOddVoters(t *testing.T) {
defer leaktest.AfterTest(t)()
skip.UnderRaceWithIssue(t, 57144, "flaky under race")
defer log.Scope(t).Close(t)
const replicaCount = 3
tc := testcluster.StartTestCluster(t, 1,
base.TestClusterArgs{ReplicationMode: base.ReplicationAuto},
)
defer tc.Stopper().Stop(context.Background())
testKey := keys.MetaMin
desc, err := tc.LookupRange(testKey)
if err != nil {
t.Fatal(err)
}
if len(desc.InternalReplicas) != 1 {
t.Fatalf("replica count, want 1, current %d", len(desc.InternalReplicas))
}
tc.AddAndStartServer(t, base.TestServerArgs{})
if err := tc.Servers[0].Stores().VisitStores(func(s *kvserver.Store) error {
return s.ForceReplicationScanAndProcess()
}); err != nil {
t.Fatal(err)
}
// After the initial splits have been performed, all of the resulting ranges
// should be present in replicate queue purgatory (because we only have a
// single store in the test and thus replication cannot succeed).
expected, err := tc.Servers[0].ExpectedInitialRangeCount()
if err != nil {
t.Fatal(err)
}
var store *kvserver.Store
_ = tc.Servers[0].Stores().VisitStores(func(s *kvserver.Store) error {
store = s
return nil
})
if n := store.ReplicateQueuePurgatoryLength(); expected != n {
t.Fatalf("expected %d replicas in purgatory, but found %d", expected, n)
}
tc.AddAndStartServer(t, base.TestServerArgs{})
// Now wait until the replicas have been up-replicated to the
// desired number.
testutils.SucceedsSoon(t, func() error {
descriptor, err := tc.LookupRange(testKey)
if err != nil {
t.Fatal(err)
}
if len(descriptor.InternalReplicas) != replicaCount {
return errors.Errorf("replica count, want %d, current %d", replicaCount, len(desc.InternalReplicas))
}
return nil
})
infos, err := filterRangeLog(
tc.Conns[0], desc.RangeID, kvserverpb.RangeLogEventType_add_voter, kvserverpb.ReasonRangeUnderReplicated,
)
if err != nil {
t.Fatal(err)
}
if len(infos) < 1 {
t.Fatalf("found no upreplication due to underreplication in the range logs")
}
}
// TestReplicateQueueDownReplicate verifies that the replication queue will
// notice over-replicated ranges and remove replicas from them.
func TestReplicateQueueDownReplicate(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
skip.UnderRace(t, "takes >1min under race")
ctx := context.Background()
// The goal of this test is to ensure that down replication occurs
// correctly using the replicate queue, and to ensure that's the case,
// the test cluster needs to be kept in auto replication mode.
tc := testcluster.StartTestCluster(t, 3,
base.TestClusterArgs{
ReplicationMode: base.ReplicationAuto,
ServerArgs: base.TestServerArgs{
ScanMinIdleTime: 10 * time.Millisecond,
ScanMaxIdleTime: 10 * time.Millisecond,
Knobs: base.TestingKnobs{
SpanConfig: &spanconfig.TestingKnobs{
ConfigureScratchRange: true,
},
},
},
},
)
defer tc.Stopper().Stop(ctx)
testKey := tc.ScratchRange(t)
testutils.SucceedsSoon(t, func() error {
desc := tc.LookupRangeOrFatal(t, testKey)
if got := len(desc.Replicas().Descriptors()); got != 3 {
return errors.Newf("expected 3 replicas for scratch range, found %d", got)
}
return nil
})
_, err := tc.ServerConn(0).Exec(
`ALTER RANGE DEFAULT CONFIGURE ZONE USING num_replicas = 1`,
)
require.NoError(t, err)
for _, s := range tc.Servers {
require.NoError(t, s.Stores().VisitStores(func(s *kvserver.Store) error {
require.NoError(t, s.ForceReplicationScanAndProcess())
return nil
}))
}
// Now wait until the replicas have been down-replicated back to the
// desired number.
testutils.SucceedsSoon(t, func() error {
desc := tc.LookupRangeOrFatal(t, testKey)
if got := len(desc.Replicas().Descriptors()); got != 1 {
return errors.Errorf("expected 1 replica, found %d", got)
}
return nil
})
desc := tc.LookupRangeOrFatal(t, testKey)
infos, err := filterRangeLog(
tc.Conns[0], desc.RangeID, kvserverpb.RangeLogEventType_remove_voter, kvserverpb.ReasonRangeOverReplicated,
)
require.NoError(t, err)
require.Truef(t, len(infos) >= 1, "found no down replication due to over-replication in the range logs")
}
func scanAndGetNumNonVoters(
t *testing.T, tc *testcluster.TestCluster, scratchKey roachpb.Key,
) (numNonVoters int) {
for _, s := range tc.Servers {
// Nudge internal queues to up/down-replicate our scratch range.
require.NoError(t, s.Stores().VisitStores(func(s *kvserver.Store) error {
require.NoError(t, s.ForceSplitScanAndProcess())
require.NoError(t, s.ForceReplicationScanAndProcess())
require.NoError(t, s.ForceRaftSnapshotQueueProcess())
return nil
}))
}
scratchRange := tc.LookupRangeOrFatal(t, scratchKey)
row := tc.ServerConn(0).QueryRow(
`SELECT coalesce(max(array_length(non_voting_replicas, 1)),0) FROM crdb_internal.ranges_no_leases WHERE range_id=$1`,
scratchRange.GetRangeID())
require.NoError(t, row.Scan(&numNonVoters))
return numNonVoters
}
// TestReplicateQueueUpAndDownReplicateNonVoters is an end-to-end test ensuring
// that the replicateQueue will add or remove non-voter(s) to a range based on
// updates to its zone configuration.
func TestReplicateQueueUpAndDownReplicateNonVoters(t *testing.T) {
defer leaktest.AfterTest(t)()
skip.UnderRace(t)
defer log.Scope(t).Close(t)
tc := testcluster.StartTestCluster(t, 1,
base.TestClusterArgs{
ReplicationMode: base.ReplicationAuto,
ServerArgs: base.TestServerArgs{
// Test fails with the default tenant. Disabling and
// tracking with #76378.
DisableDefaultTestTenant: true,
Knobs: base.TestingKnobs{
SpanConfig: &spanconfig.TestingKnobs{
ConfigureScratchRange: true,
},
},
},
},
)
defer tc.Stopper().Stop(context.Background())
scratchKey := tc.ScratchRange(t)
scratchRange := tc.LookupRangeOrFatal(t, scratchKey)
// Since we started the TestCluster with 1 node, that first node should have
// 1 voting replica.
require.Len(t, scratchRange.Replicas().VoterDescriptors(), 1)
// Set up the default zone configs such that every range should have 1 voting
// replica and 2 non-voting replicas.
_, err := tc.ServerConn(0).Exec(
`ALTER RANGE DEFAULT CONFIGURE ZONE USING num_replicas = 3, num_voters = 1`,
)
require.NoError(t, err)
// Add two new servers and expect that 2 non-voters are added to the range.
tc.AddAndStartServer(t, base.TestServerArgs{})
tc.AddAndStartServer(t, base.TestServerArgs{})
var expectedNonVoterCount = 2
testutils.SucceedsSoon(t, func() error {
if found := scanAndGetNumNonVoters(t, tc, scratchKey); found != expectedNonVoterCount {
return errors.Errorf("expected upreplication to %d non-voters; found %d",
expectedNonVoterCount, found)
}
return nil
})
// Now remove all non-voting replicas and expect that the range will
// down-replicate to having just 1 voting replica.
_, err = tc.ServerConn(0).Exec(`ALTER RANGE DEFAULT CONFIGURE ZONE USING num_replicas = 1`)
require.NoError(t, err)
expectedNonVoterCount = 0
testutils.SucceedsSoon(t, func() error {
if found := scanAndGetNumNonVoters(t, tc, scratchKey); found != expectedNonVoterCount {
return errors.Errorf("expected downreplication to %d non-voters; found %d",
expectedNonVoterCount, found)
}
return nil
})
}
func checkReplicaCount(
ctx context.Context,
tc *testcluster.TestCluster,
rangeDesc *roachpb.RangeDescriptor,
voterCount, nonVoterCount int,
) (bool, error) {
err := forceScanOnAllReplicationQueues(tc)
if err != nil {
log.Infof(ctx, "store.ForceReplicationScanAndProcess() failed with: %s", err)
return false, err
}
*rangeDesc, err = tc.LookupRange(rangeDesc.StartKey.AsRawKey())
if err != nil {
return false, err
}
if len(rangeDesc.Replicas().VoterDescriptors()) != voterCount {
return false, nil
}
if len(rangeDesc.Replicas().NonVoterDescriptors()) != nonVoterCount {
return false, nil
}
return true, nil
}
// TestReplicateQueueDecommissioningNonVoters is an end-to-end test ensuring
// that the replicateQueue will replace or remove non-voter(s) on
// decommissioning nodes.
func TestReplicateQueueDecommissioningNonVoters(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
skip.UnderRace(t, "takes a long time or times out under race")
ctx := context.Background()
// Setup a scratch range on a test cluster with 2 non-voters and 1 voter.
setupFn := func(t *testing.T) (*testcluster.TestCluster, roachpb.RangeDescriptor) {
tc := testcluster.StartTestCluster(t, 5,
base.TestClusterArgs{
ReplicationMode: base.ReplicationAuto,
ServerArgs: base.TestServerArgs{
Knobs: base.TestingKnobs{
Store: &kvserver.StoreTestingKnobs{
DisableReplicaRebalancing: true,
},
SpanConfig: &spanconfig.TestingKnobs{
ConfigureScratchRange: true,
},
},
},
},
)
_, err := tc.ServerConn(0).Exec(
`SET CLUSTER SETTING server.failed_reservation_timeout='1ms'`)
require.NoError(t, err)
scratchKey := tc.ScratchRange(t)
scratchRange := tc.LookupRangeOrFatal(t, scratchKey)
_, err = tc.ServerConn(0).Exec(
`ALTER RANGE DEFAULT CONFIGURE ZONE USING num_replicas = 3, num_voters = 1`,
)
require.NoError(t, err)
require.Eventually(t, func() bool {
ok, err := checkReplicaCount(ctx, tc, &scratchRange, 1 /* voterCount */, 2 /* nonVoterCount */)
if err != nil {
log.Errorf(ctx, "error checking replica count: %s", err)
return false
}
return ok
}, testutils.DefaultSucceedsSoonDuration, 100*time.Millisecond)
return tc, scratchRange
}
// Check that non-voters on decommissioning nodes are replaced by
// upreplicating elsewhere. This test is supposed to tickle the
// `AllocatorReplaceDecommissioningNonVoter` code path.
t.Run("replace", func(t *testing.T) {
tc, scratchRange := setupFn(t)
defer tc.Stopper().Stop(ctx)
// Do a fresh look up on the range descriptor.
scratchRange = tc.LookupRangeOrFatal(t, scratchRange.StartKey.AsRawKey())
beforeNodeIDs := getNonVoterNodeIDs(scratchRange)
store, err := getLeaseholderStore(tc, scratchRange)
if err != nil {
t.Fatal(err)
}
// Check the value of metrics prior to replacement.
previousAddCount := store.ReplicateQueueMetrics().AddNonVoterReplicaCount.Count()
previousRemovalCount := store.ReplicateQueueMetrics().RemoveNonVoterReplicaCount.Count()
previousDecommRemovals :=
store.ReplicateQueueMetrics().RemoveDecommissioningNonVoterReplicaCount.Count()
previousDecommReplacementSuccesses :=
store.ReplicateQueueMetrics().ReplaceDecommissioningReplicaSuccessCount.Count()
// Decommission each of the two nodes that have the non-voters and make sure
// that those non-voters are upreplicated elsewhere.
require.NoError(t,
tc.Server(0).Decommission(ctx, livenesspb.MembershipStatus_DECOMMISSIONING, beforeNodeIDs))
require.Eventually(t, func() bool {
ok, err := checkReplicaCount(ctx, tc, &scratchRange, 1 /* voterCount */, 2 /* nonVoterCount */)
if err != nil {
log.Errorf(ctx, "error checking replica count: %s", err)
return false
}
if !ok {
return false
}
// Ensure that the non-voters have actually been removed from the dead
// nodes and moved to others.
scratchRange = tc.LookupRangeOrFatal(t, scratchRange.StartKey.AsRawKey())
afterNodeIDs := getNonVoterNodeIDs(scratchRange)
for _, before := range beforeNodeIDs {
for _, after := range afterNodeIDs {
if after == before {
return false
}
}
}
return true
}, testutils.DefaultSucceedsSoonDuration, 100*time.Millisecond)
// replica replacements update the addition/removal metrics as replicas
// are being removed on two decommissioning stores added to other stores.
currentAddCount := store.ReplicateQueueMetrics().AddNonVoterReplicaCount.Count()
currentRemoveCount := store.ReplicateQueueMetrics().RemoveNonVoterReplicaCount.Count()
currentDecommRemovals :=
store.ReplicateQueueMetrics().RemoveDecommissioningNonVoterReplicaCount.Count()
currentDecommReplacementSuccesses :=
store.ReplicateQueueMetrics().ReplaceDecommissioningReplicaSuccessCount.Count()
require.GreaterOrEqualf(
t, currentAddCount, previousAddCount+2,
"expected replica additions to increase by at least 2",
)
require.GreaterOrEqualf(
t, currentRemoveCount, previousRemovalCount+2,
"expected total replica removals to increase by at least 2",
)
require.GreaterOrEqualf(
t, currentDecommRemovals, previousDecommRemovals+2,
"expected decommissioning replica removals to increase by at least 2",
)
require.GreaterOrEqualf(t, currentDecommReplacementSuccesses, previousDecommReplacementSuccesses+2,
"expected decommissioning replica replacement successes to increase by at least 2",
)
})
// Check that when we have more non-voters than needed and some of those
// non-voters are on decommissioning nodes, that we simply remove those
// non-voters. This test is supposed to tickle the
// `AllocatorRemoveDecommissioningNonVoter` code path.
t.Run("remove", func(t *testing.T) {
tc, scratchRange := setupFn(t)
defer tc.Stopper().Stop(ctx)
// Turn off the replicateQueue and update the zone configs to remove all
// non-voters. At the same time, also mark all the nodes that have
// non-voters as decommissioning.
tc.ToggleReplicateQueues(false)
_, err := tc.ServerConn(0).Exec(
`ALTER RANGE DEFAULT CONFIGURE ZONE USING num_replicas = 1`,
)
require.NoError(t, err)
// Do a fresh look up on the range descriptor.
scratchRange = tc.LookupRangeOrFatal(t, scratchRange.StartKey.AsRawKey())
var nonVoterNodeIDs []roachpb.NodeID
for _, repl := range scratchRange.Replicas().NonVoterDescriptors() {
nonVoterNodeIDs = append(nonVoterNodeIDs, repl.NodeID)
}
// Check metrics of leaseholder store prior to removal.
store, err := getLeaseholderStore(tc, scratchRange)
if err != nil {
t.Fatal(err)
}
// Ensure leaseholder has updated span config with 0 non-voters.
require.Eventually(t, func() bool {
repl, err := store.GetReplica(scratchRange.RangeID)
if err != nil {
t.Fatal(err)
}
_, conf := repl.DescAndSpanConfig()
return conf.GetNumNonVoters() == 0
}, testutils.DefaultSucceedsSoonDuration, 100*time.Millisecond)
previousRemovalCount := store.ReplicateQueueMetrics().RemoveNonVoterReplicaCount.Count()
previousDecommRemovals :=
store.ReplicateQueueMetrics().RemoveDecommissioningNonVoterReplicaCount.Count()
previousDecommRemovalSuccesses :=
store.ReplicateQueueMetrics().RemoveDecommissioningReplicaSuccessCount.Count()
require.NoError(t,
tc.Server(0).Decommission(ctx, livenesspb.MembershipStatus_DECOMMISSIONING, nonVoterNodeIDs))
// At this point, we know that we have an over-replicated range with
// non-voters on nodes that are marked as decommissioning. So turn the
// replicateQueue on and ensure that these redundant non-voters are removed.
tc.ToggleReplicateQueues(true)
require.Eventually(t, func() bool {
ok, err := checkReplicaCount(ctx, tc, &scratchRange, 1 /* voterCount */, 0 /* nonVoterCount */)
if err != nil {
log.Errorf(ctx, "error checking replica count: %s", err)
return false
}
return ok
}, testutils.DefaultSucceedsSoonDuration, 100*time.Millisecond)
currentRemoveCount := store.ReplicateQueueMetrics().RemoveNonVoterReplicaCount.Count()
currentDecommRemovals :=
store.ReplicateQueueMetrics().RemoveDecommissioningNonVoterReplicaCount.Count()
currentDecommRemovalSuccesses :=
store.ReplicateQueueMetrics().RemoveDecommissioningReplicaSuccessCount.Count()
require.GreaterOrEqualf(
t, currentRemoveCount, previousRemovalCount+2,
"expected replica removals to increase by at least 2",
)
require.GreaterOrEqualf(
t, currentDecommRemovals, previousDecommRemovals+2,
"expected replica removals to increase by at least 2",
)
require.GreaterOrEqualf(t, currentDecommRemovalSuccesses, previousDecommRemovalSuccesses+2,
"expected decommissioning replica removal successes to increase by at least 2",
)
})
}
// TestReplicateQueueTracingOnError tests that an error or slowdown in
// processing a replica results in traces being logged.
func TestReplicateQueueTracingOnError(t *testing.T) {
defer leaktest.AfterTest(t)()
s := log.ScopeWithoutShowLogs(t)
defer s.Close(t)
// NB: This test injects a fake failure during replica rebalancing, and we use
// this `rejectSnapshots` variable as a flag to activate or deactivate that
// injected failure.
var rejectSnapshots int64
ctx := context.Background()
tc := testcluster.StartTestCluster(
t, 4, base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgs: base.TestServerArgs{Knobs: base.TestingKnobs{Store: &kvserver.StoreTestingKnobs{
ReceiveSnapshot: func(_ *kvserverpb.SnapshotRequest_Header) error {
if atomic.LoadInt64(&rejectSnapshots) == 1 {
return errors.Newf("boom")
}
return nil
},
}}},
},
)
defer tc.Stopper().Stop(ctx)
// Add a replica to the second and third nodes, and then decommission the
// second node. Since there are only 4 nodes in the cluster, the
// decommissioning replica must be rebalanced to the fourth node.
const decomNodeIdx = 1
const decomNodeID = 2
scratchKey := tc.ScratchRange(t)
tc.AddVotersOrFatal(t, scratchKey, tc.Target(decomNodeIdx))
tc.AddVotersOrFatal(t, scratchKey, tc.Target(decomNodeIdx+1))
adminSrv := tc.Server(decomNodeIdx)
conn, err := adminSrv.RPCContext().GRPCDialNode(
adminSrv.RPCAddr(), adminSrv.NodeID(), rpc.DefaultClass).Connect(ctx)
require.NoError(t, err)
adminClient := serverpb.NewAdminClient(conn)
_, err = adminClient.Decommission(
ctx, &serverpb.DecommissionRequest{
NodeIDs: []roachpb.NodeID{decomNodeID},
TargetMembership: livenesspb.MembershipStatus_DECOMMISSIONING,
},
)
require.NoError(t, err)
// Activate the above testing knob to start rejecting future rebalances and
// then attempt to rebalance the decommissioning replica away. We expect a
// purgatory error to be returned here.
atomic.StoreInt64(&rejectSnapshots, 1)
store := tc.GetFirstStoreFromServer(t, 0)
repl, err := store.GetReplica(tc.LookupRangeOrFatal(t, scratchKey).RangeID)
require.NoError(t, err)
recording, processErr, enqueueErr := tc.GetFirstStoreFromServer(t, 0).Enqueue(
ctx, "replicate", repl, true /* skipShouldQueue */, false, /* async */
)
require.NoError(t, enqueueErr)
require.Error(t, processErr, "expected processing error")
processRecSpan, foundSpan := recording.FindSpan("process replica")
require.True(t, foundSpan)
foundParent := false
foundErr := false
foundTrace := false
for _, recSpan := range recording {
if recSpan.SpanID == processRecSpan.ParentSpanID {
foundParent = true
for _, logMsg := range recSpan.Logs {
if matched, matchErr := regexp.MatchString(`error processing replica:.*boom`, logMsg.Msg().StripMarkers()); matchErr == nil && matched {
foundErr = true
}
if matched, matchErr := regexp.MatchString(`trace:.*`, logMsg.Msg().StripMarkers()); matchErr == nil && matched {
foundTrace = true
}
}
break
}
}
require.True(t, foundParent && foundErr && foundTrace)
}
// TestReplicateQueueDecommissionPurgatoryError tests that failure to move a
// decommissioning replica puts it in the replicate queue purgatory.
func TestReplicateQueueDecommissionPurgatoryError(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
// NB: This test injects a fake failure during replica rebalancing, and we use
// this `rejectSnapshots` variable as a flag to activate or deactivate that
// injected failure.
var rejectSnapshots int64
ctx := context.Background()
tc := testcluster.StartTestCluster(
t, 4, base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgs: base.TestServerArgs{Knobs: base.TestingKnobs{Store: &kvserver.StoreTestingKnobs{
ReceiveSnapshot: func(_ *kvserverpb.SnapshotRequest_Header) error {
if atomic.LoadInt64(&rejectSnapshots) == 1 {
return errors.Newf("boom")
}
return nil
},
}}},
},
)
defer tc.Stopper().Stop(ctx)
// Add a replica to the second and third nodes, and then decommission the
// second node. Since there are only 4 nodes in the cluster, the
// decommissioning replica must be rebalanced to the fourth node.
const decomNodeIdx = 1
const decomNodeID = 2
scratchKey := tc.ScratchRange(t)
tc.AddVotersOrFatal(t, scratchKey, tc.Target(decomNodeIdx))
tc.AddVotersOrFatal(t, scratchKey, tc.Target(decomNodeIdx+1))
adminSrv := tc.Server(decomNodeIdx)
conn, err := adminSrv.RPCContext().GRPCDialNode(
adminSrv.RPCAddr(), adminSrv.NodeID(), rpc.DefaultClass).Connect(ctx)
require.NoError(t, err)
adminClient := serverpb.NewAdminClient(conn)
_, err = adminClient.Decommission(
ctx, &serverpb.DecommissionRequest{
NodeIDs: []roachpb.NodeID{decomNodeID},
TargetMembership: livenesspb.MembershipStatus_DECOMMISSIONING,
},
)
require.NoError(t, err)
// Activate the above testing knob to start rejecting future rebalances and
// then attempt to rebalance the decommissioning replica away. We expect a
// purgatory error to be returned here.
atomic.StoreInt64(&rejectSnapshots, 1)
store := tc.GetFirstStoreFromServer(t, 0)
repl, err := store.GetReplica(tc.LookupRangeOrFatal(t, scratchKey).RangeID)
require.NoError(t, err)
_, processErr, enqueueErr := tc.GetFirstStoreFromServer(t, 0).Enqueue(
ctx, "replicate", repl, true /* skipShouldQueue */, false, /* async */
)
require.NoError(t, enqueueErr)
_, isPurgErr := kvserver.IsPurgatoryError(processErr)
if !isPurgErr {
t.Fatalf("expected to receive a purgatory error, got %v", processErr)
}
}
// getLeaseholderStore returns the leaseholder store for the given scratchRange.
func getLeaseholderStore(
tc *testcluster.TestCluster, scratchRange roachpb.RangeDescriptor,
) (*kvserver.Store, error) {
leaseHolder, err := tc.FindRangeLeaseHolder(scratchRange, nil)
if err != nil {
return nil, err
}
leaseHolderSrv := tc.Servers[leaseHolder.NodeID-1]
store, err := leaseHolderSrv.Stores().GetStore(leaseHolder.StoreID)
if err != nil {
return nil, err
}
return store, nil
}
// TestReplicateQueueDeadNonVoters is an end to end test ensuring that
// non-voting replicas on dead nodes are replaced or removed.
func TestReplicateQueueDeadNonVoters(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
skip.WithIssue(t, 76996)
skip.UnderRace(t, "takes a long time or times out under race")
ctx := context.Background()
var livenessTrap atomic.Value
setupFn := func(t *testing.T) (*testcluster.TestCluster, roachpb.RangeDescriptor) {
tc := testcluster.StartTestCluster(t, 5,
base.TestClusterArgs{
ReplicationMode: base.ReplicationAuto,
ServerArgs: base.TestServerArgs{
ScanMinIdleTime: time.Millisecond,
ScanMaxIdleTime: time.Millisecond,
Knobs: base.TestingKnobs{
Store: &kvserver.StoreTestingKnobs{
DisableReplicaRebalancing: true,
},
SpanConfig: &spanconfig.TestingKnobs{
ConfigureScratchRange: true,
},
NodeLiveness: kvserver.NodeLivenessTestingKnobs{
StorePoolNodeLivenessFn: func(
id roachpb.NodeID, now time.Time, duration time.Duration,
) livenesspb.NodeLivenessStatus {
val := livenessTrap.Load()
if val == nil {
return livenesspb.NodeLivenessStatus_LIVE
}
return val.(func(nodeID roachpb.NodeID) livenesspb.NodeLivenessStatus)(id)
},
},
},
},
},
)
_, err := tc.ServerConn(0).Exec(
`SET CLUSTER SETTING server.failed_reservation_timeout='1ms'`)
require.NoError(t, err)
// Setup a scratch range on a test cluster with 2 non-voters and 1 voter.
scratchKey := tc.ScratchRange(t)
scratchRange := tc.LookupRangeOrFatal(t, scratchKey)
_, err = tc.ServerConn(0).Exec(
`ALTER RANGE DEFAULT CONFIGURE ZONE USING num_replicas = 3, num_voters = 1`,
)
require.NoError(t, err)
require.Eventually(t, func() bool {
ok, err := checkReplicaCount(ctx, tc, &scratchRange, 1 /* voterCount */, 2 /* nonVoterCount */)
if err != nil {
log.Errorf(ctx, "error checking replica count: %s", err)
return false
}
return ok
}, testutils.DefaultSucceedsSoonDuration, 100*time.Millisecond)
return tc, scratchRange
}
markDead := func(nodeIDs []roachpb.NodeID) {
livenessTrap.Store(func(id roachpb.NodeID) livenesspb.NodeLivenessStatus {
for _, dead := range nodeIDs {
if dead == id {
return livenesspb.NodeLivenessStatus_DEAD
}
}
return livenesspb.NodeLivenessStatus_LIVE
})
}
// This subtest checks that non-voters on dead nodes are replaced by
// upreplicating elsewhere. This test is supposed to tickle the
// `AllocatorReplaceDeadNonVoter` code path. It does the following:
//
// 1. On a 5 node cluster, instantiate a range with 1 voter and 2 non-voters.
// 2. Kill the 2 nodes that have the non-voters.
// 3. Check that those non-voters are replaced.
t.Run("replace", func(t *testing.T) {
tc, scratchRange := setupFn(t)
defer tc.Stopper().Stop(ctx)
// Check the value of non-voter metrics from leaseholder store prior to removals.
store, err := getLeaseholderStore(tc, scratchRange)
if err != nil {
t.Fatal(err)
}
prevAdditions := store.ReplicateQueueMetrics().AddNonVoterReplicaCount.Count()
prevRemovals := store.ReplicateQueueMetrics().RemoveNonVoterReplicaCount.Count()
prevDeadRemovals := store.ReplicateQueueMetrics().RemoveDeadNonVoterReplicaCount.Count()
prevDeadReplacementSuccesses := store.ReplicateQueueMetrics().ReplaceDeadReplicaSuccessCount.Count()
beforeNodeIDs := getNonVoterNodeIDs(scratchRange)
markDead(beforeNodeIDs)
require.Eventually(t, func() bool {
ok, err := checkReplicaCount(ctx, tc, &scratchRange, 1 /* voterCount */, 2 /* nonVoterCount */)
if err != nil {
log.Errorf(ctx, "error checking replica count: %s", err)
return false
}
if !ok {
return false
}
// Ensure that the non-voters have actually been removed from the dead
// nodes and moved to others.
scratchRange = tc.LookupRangeOrFatal(t, scratchRange.StartKey.AsRawKey())
afterNodeIDs := getNonVoterNodeIDs(scratchRange)
for _, before := range beforeNodeIDs {
for _, after := range afterNodeIDs {
if after == before {
return false
}
}
}
return true
}, testutils.DefaultSucceedsSoonDuration, 100*time.Millisecond)
addCount := store.ReplicateQueueMetrics().AddNonVoterReplicaCount.Count()
removeNonVoterCount := store.ReplicateQueueMetrics().RemoveNonVoterReplicaCount.Count()
removeDeadNonVoterCount := store.ReplicateQueueMetrics().RemoveDeadNonVoterReplicaCount.Count()
replaceDeadSuccesses := store.ReplicateQueueMetrics().ReplaceDeadReplicaSuccessCount.Count()
require.GreaterOrEqualf(
t, addCount, prevAdditions+2,
"expected replica removals to increase by at least 2",
)
require.GreaterOrEqualf(
t, removeNonVoterCount, prevRemovals+2,
"expected replica removals to increase by at least 2",
)
require.GreaterOrEqualf(
t, removeDeadNonVoterCount, prevDeadRemovals+2,
"expected replica removals to increase by at least 2",
)
require.GreaterOrEqualf(
t, replaceDeadSuccesses, prevDeadReplacementSuccesses+2,
"expected dead replica replacement successes to increase by at least 2",
)
})
// This subtest checks that when we have more non-voters than needed and some
// existing non-voters are on dead nodes, we will simply remove these
// non-voters. This test is supposed to tickle the
// AllocatorRemoveDeadNonVoter` code path. The test does the following:
//
// 1. Instantiate a range with 1 voter and 2 non-voters on a 5-node cluster.
// 2. Turn off the replicateQueue
// 3. Change the zone configs such that there should be no non-voters --
// the two existing non-voters should now be considered "over-replicated"
// by the system.
// 4. Kill the nodes that have non-voters.
// 5. Turn on the replicateQueue
// 6. Make sure that the non-voters are downreplicated from the dead nodes.
t.Run("remove", func(t *testing.T) {
tc, scratchRange := setupFn(t)
defer tc.Stopper().Stop(ctx)
toggleReplicationQueues(tc, false)
_, err := tc.ServerConn(0).Exec(
// Remove all non-voters.
"ALTER RANGE default CONFIGURE ZONE USING num_replicas = 1",
)
require.NoError(t, err)
// Check the value of non-voter metrics from leaseholder store prior to removals.
store, err := getLeaseholderStore(tc, scratchRange)
if err != nil {
t.Fatal(err)
}
// Ensure leaseholder has updated span config with 0 non-voters.
require.Eventually(t, func() bool {
repl, err := store.GetReplica(scratchRange.RangeID)
if err != nil {
t.Fatal(err)
}
_, conf := repl.DescAndSpanConfig()
return conf.GetNumNonVoters() == 0
}, testutils.DefaultSucceedsSoonDuration, 100*time.Millisecond)
prevRemovals := store.ReplicateQueueMetrics().RemoveReplicaCount.Count()
prevNonVoterRemovals := store.ReplicateQueueMetrics().RemoveNonVoterReplicaCount.Count()
prevDeadRemovals := store.ReplicateQueueMetrics().RemoveDeadNonVoterReplicaCount.Count()
prevDeadRemovalSuccesses := store.ReplicateQueueMetrics().RemoveDeadReplicaSuccessCount.Count()
beforeNodeIDs := getNonVoterNodeIDs(scratchRange)
markDead(beforeNodeIDs)
toggleReplicationQueues(tc, true)
require.Eventually(t, func() bool {
ok, err := checkReplicaCount(ctx, tc, &scratchRange, 1 /* voterCount */, 0 /* nonVoterCount */)
if err != nil {
log.Errorf(ctx, "error checking replica count: %s", err)
return false
}
return ok
}, testutils.DefaultSucceedsSoonDuration, 100*time.Millisecond)
removeCount := store.ReplicateQueueMetrics().RemoveReplicaCount.Count()
removeNonVoterCount := store.ReplicateQueueMetrics().RemoveNonVoterReplicaCount.Count()
removeDeadNonVoterCount := store.ReplicateQueueMetrics().RemoveDeadNonVoterReplicaCount.Count()
removeDeadSuccesses := store.ReplicateQueueMetrics().RemoveDeadReplicaSuccessCount.Count()
require.GreaterOrEqualf(
t, removeCount, prevRemovals+2,
"expected replica removals to increase by at least 2",
)
require.GreaterOrEqualf(
t, removeNonVoterCount, prevNonVoterRemovals+2,
"expected replica removals to increase by at least 2",
)
require.GreaterOrEqualf(
t, removeDeadNonVoterCount, prevDeadRemovals+2,
"expected replica removals to increase by at least 2",
)
require.GreaterOrEqualf(
t, removeDeadSuccesses, prevDeadRemovalSuccesses+2,