-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
client_lease_test.go
1677 lines (1520 loc) · 58 KB
/
client_lease_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"
"math"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"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"
"github.com/cockroachdb/cockroach/pkg/kv/kvpb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvserverbase"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/liveness"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/liveness/livenesspb"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/server"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/bootstrap"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"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/stretchr/testify/require"
raft "go.etcd.io/raft/v3"
"go.etcd.io/raft/v3/tracker"
)
// TestStoreRangeLease verifies that regular ranges (not some special ones at
// the start of the key space) get epoch-based range leases if enabled and
// expiration-based otherwise.
func TestStoreRangeLease(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
st := cluster.MakeTestingClusterSettings()
kvserver.ExpirationLeasesOnly.Override(ctx, &st.SV, false) // override metamorphism
tc := testcluster.StartTestCluster(t, 1,
base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgs: base.TestServerArgs{
Settings: st,
Knobs: base.TestingKnobs{
Store: &kvserver.StoreTestingKnobs{
DisableMergeQueue: true,
},
},
},
},
)
defer tc.Stopper().Stop(ctx)
store := tc.GetFirstStoreFromServer(t, 0)
// NodeLivenessKeyMax is a static split point, so this is always
// the start key of the first range that uses epoch-based
// leases. Splitting on it here is redundant, but we want to include
// it in our tests of lease types below.
splitKeys := []roachpb.Key{
keys.NodeLivenessKeyMax, roachpb.Key("a"), roachpb.Key("b"), roachpb.Key("c"),
}
for _, splitKey := range splitKeys {
tc.SplitRangeOrFatal(t, splitKey)
}
rLeft := store.LookupReplica(roachpb.RKeyMin)
lease, _ := rLeft.GetLease()
if lt := lease.Type(); lt != roachpb.LeaseExpiration {
t.Fatalf("expected lease type expiration; got %d", lt)
}
// After the expiration, expect an epoch lease for all the ranges if
// we've enabled epoch based range leases.
for _, key := range splitKeys {
repl := store.LookupReplica(roachpb.RKey(key))
lease, _ = repl.GetLease()
if lt := lease.Type(); lt != roachpb.LeaseEpoch {
t.Fatalf("expected lease type epoch; got %d", lt)
}
}
}
func TestGossipNodeLivenessOnLeaseChange(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
const numStores = 3
tc := testcluster.StartTestCluster(t, numStores,
base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
},
)
defer tc.Stopper().Stop(context.Background())
key := roachpb.RKey(keys.NodeLivenessSpan.Key)
tc.AddVotersOrFatal(t, key.AsRawKey(), tc.Target(1), tc.Target(2))
if pErr := tc.WaitForVoters(key.AsRawKey(), tc.Target(1), tc.Target(2)); pErr != nil {
t.Fatal(pErr)
}
desc := tc.LookupRangeOrFatal(t, key.AsRawKey())
// Turn off liveness heartbeats on all nodes to ensure that updates to node
// liveness are not triggering gossiping.
for _, s := range tc.Servers {
pErr := s.Stores().VisitStores(func(store *kvserver.Store) error {
store.GetStoreConfig().NodeLiveness.PauseHeartbeatLoopForTest()
return nil
})
if pErr != nil {
t.Fatal(pErr)
}
}
nodeLivenessKey := gossip.MakeNodeLivenessKey(1)
initialServerId := -1
for i, s := range tc.Servers {
pErr := s.Stores().VisitStores(func(store *kvserver.Store) error {
if store.Gossip().InfoOriginatedHere(nodeLivenessKey) {
initialServerId = i
}
return nil
})
if pErr != nil {
t.Fatal(pErr)
}
}
if initialServerId == -1 {
t.Fatalf("no store has gossiped %s; gossip contents: %+v",
nodeLivenessKey, tc.GetFirstStoreFromServer(t, 0).Gossip().GetInfoStatus())
}
log.Infof(context.Background(), "%s gossiped from s%d",
nodeLivenessKey, initialServerId)
newServerIdx := (initialServerId + 1) % numStores
if pErr := tc.TransferRangeLease(desc, tc.Target(newServerIdx)); pErr != nil {
t.Fatal(pErr)
}
testutils.SucceedsSoon(t, func() error {
if tc.GetFirstStoreFromServer(t, initialServerId).Gossip().InfoOriginatedHere(nodeLivenessKey) {
return fmt.Errorf("%s still most recently gossiped by original leaseholder", nodeLivenessKey)
}
if !tc.GetFirstStoreFromServer(t, newServerIdx).Gossip().InfoOriginatedHere(nodeLivenessKey) {
return fmt.Errorf("%s not most recently gossiped by new leaseholder", nodeLivenessKey)
}
return nil
})
}
// TestCannotTransferLeaseToVoterOutgoing ensures that the evaluation of lease
// requests for nodes which are already in the VOTER_DEMOTING_LEARNER state will fail
// (in this test, there is no VOTER_INCOMING node).
func TestCannotTransferLeaseToVoterDemoting(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
knobs, ltk := makeReplicationTestKnobs()
// Add a testing knob to allow us to block the change replicas command
// while it is being proposed. When we detect that the change replicas
// command to move n3 to VOTER_DEMOTING_LEARNER has been evaluated, we'll
// send the request to transfer the lease to n3. The hope is that it will
// get past the sanity check above latch acquisition prior to the change
// replicas command committing.
var scratchRangeID int64
changeReplicasChan := make(chan chan struct{}, 1)
shouldBlock := func(args kvserverbase.ProposalFilterArgs) bool {
// Block if a ChangeReplicas command is removing a node from our range.
return args.Req.RangeID == roachpb.RangeID(atomic.LoadInt64(&scratchRangeID)) &&
args.Cmd.ReplicatedEvalResult.ChangeReplicas != nil &&
len(args.Cmd.ReplicatedEvalResult.ChangeReplicas.Removed()) > 0
}
blockIfShould := func(args kvserverbase.ProposalFilterArgs) {
if shouldBlock(args) {
ch := make(chan struct{})
changeReplicasChan <- ch
<-ch
}
}
knobs.Store.(*kvserver.StoreTestingKnobs).TestingProposalFilter = func(args kvserverbase.ProposalFilterArgs) *kvpb.Error {
blockIfShould(args)
return nil
}
tc := testcluster.StartTestCluster(t, 4, base.TestClusterArgs{
ServerArgs: base.TestServerArgs{Knobs: knobs},
ReplicationMode: base.ReplicationManual,
})
defer tc.Stopper().Stop(ctx)
scratchStartKey := tc.ScratchRange(t)
desc := tc.AddVotersOrFatal(t, scratchStartKey, tc.Targets(1, 2)...)
atomic.StoreInt64(&scratchRangeID, int64(desc.RangeID))
// Make sure n1 has the lease to start with.
err := tc.Server(0).DB().AdminTransferLease(context.Background(),
scratchStartKey, tc.Target(0).StoreID)
require.NoError(t, err)
// The test proceeds as follows:
//
// - Send an AdminChangeReplicasRequest to remove n3 and add n4
// - Block the step that moves n3 to VOTER_DEMOTING_LEARNER on changeReplicasChan
// - Send an AdminLeaseTransfer to make n3 the leaseholder
// - Try really hard to make sure that the lease transfer at least gets to
// latch acquisition before unblocking the ChangeReplicas.
// - Unblock the ChangeReplicas.
// - Make sure the lease transfer fails.
ltk.withStopAfterJointConfig(func() {
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
_, err = tc.Server(0).DB().AdminChangeReplicas(ctx,
scratchStartKey, desc, []kvpb.ReplicationChange{
{ChangeType: roachpb.REMOVE_VOTER, Target: tc.Target(2)},
})
require.NoError(t, err)
}()
ch := <-changeReplicasChan
wg.Add(1)
go func() {
defer wg.Done()
err := tc.Server(0).DB().AdminTransferLease(ctx,
scratchStartKey, tc.Target(2).StoreID)
require.Error(t, err)
require.True(t, errors.Is(err, roachpb.ErrReplicaCannotHoldLease))
}()
// Try really hard to make sure that our request makes it past the
// sanity check error to the evaluation error.
for i := 0; i < 100; i++ {
runtime.Gosched()
time.Sleep(time.Microsecond)
}
close(ch)
wg.Wait()
})
}
// TestTransferLeaseToVoterDemotingFails ensures that the evaluation of lease
// requests for nodes which are already in the VOTER_DEMOTING_LEARNER state fails
// if they weren't previously holding the lease, even if there is a VOTER_INCOMING..
func TestTransferLeaseToVoterDemotingFails(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
knobs, ltk := makeReplicationTestKnobs()
// Add a testing knob to allow us to block the change replicas command
// while it is being proposed. When we detect that the change replicas
// command to move n3 to VOTER_DEMOTING_LEARNER has been evaluated, we'll
// send the request to transfer the lease to n3. The hope is that it will
// get past the sanity check above latch acquisition prior to the change
// replicas command committing.
var scratchRangeID int64
changeReplicasChan := make(chan chan struct{}, 1)
shouldBlock := func(args kvserverbase.ProposalFilterArgs) bool {
// Block if a ChangeReplicas command is removing a node from our range.
return args.Req.RangeID == roachpb.RangeID(atomic.LoadInt64(&scratchRangeID)) &&
args.Cmd.ReplicatedEvalResult.ChangeReplicas != nil &&
len(args.Cmd.ReplicatedEvalResult.ChangeReplicas.Removed()) > 0
}
blockIfShould := func(args kvserverbase.ProposalFilterArgs) {
if shouldBlock(args) {
ch := make(chan struct{})
changeReplicasChan <- ch
<-ch
}
}
knobs.Store.(*kvserver.StoreTestingKnobs).TestingProposalFilter = func(args kvserverbase.ProposalFilterArgs) *kvpb.Error {
blockIfShould(args)
return nil
}
tc := testcluster.StartTestCluster(t, 4, base.TestClusterArgs{
ServerArgs: base.TestServerArgs{Knobs: knobs},
ReplicationMode: base.ReplicationManual,
})
defer tc.Stopper().Stop(ctx)
scratchStartKey := tc.ScratchRange(t)
desc := tc.AddVotersOrFatal(t, scratchStartKey, tc.Targets(1, 2)...)
atomic.StoreInt64(&scratchRangeID, int64(desc.RangeID))
// Make sure n1 has the lease to start with.
err := tc.Server(0).DB().AdminTransferLease(context.Background(),
scratchStartKey, tc.Target(0).StoreID)
require.NoError(t, err)
// The test proceeds as follows:
//
// - Send an AdminChangeReplicasRequest to remove n3 and add n4
// - Block the step that moves n3 to VOTER_DEMOTING_LEARNER on changeReplicasChan
// - Send an AdminLeaseTransfer to make n3 the leaseholder
// - Make sure that this request fails (since n3 is VOTER_DEMOTING_LEARNER and
// wasn't previously leaseholder)
// - Unblock the ChangeReplicas.
// - Make sure the lease transfer succeeds.
ltk.withStopAfterJointConfig(func() {
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
_, err = tc.Server(0).DB().AdminChangeReplicas(ctx,
scratchStartKey, desc, []kvpb.ReplicationChange{
{ChangeType: roachpb.REMOVE_VOTER, Target: tc.Target(2)},
{ChangeType: roachpb.ADD_VOTER, Target: tc.Target(3)},
})
require.NoError(t, err)
}()
ch := <-changeReplicasChan
wg.Add(1)
go func() {
defer wg.Done()
// Make sure the lease is currently on n1.
desc, err := tc.LookupRange(scratchStartKey)
require.NoError(t, err)
leaseHolder, err := tc.FindRangeLeaseHolder(desc, nil)
require.NoError(t, err)
require.Equal(t, tc.Target(0), leaseHolder,
errors.Errorf("Leaseholder supposed to be on n1."))
// Try to move the lease to n3, the VOTER_DEMOTING_LEARNER.
// This should fail since the last leaseholder wasn't n3
// (wasLastLeaseholder = false in CheckCanReceiveLease).
err = tc.Server(0).DB().AdminTransferLease(context.Background(),
scratchStartKey, tc.Target(2).StoreID)
require.Error(t, err)
require.True(t, errors.Is(err, roachpb.ErrReplicaCannotHoldLease))
// Make sure the lease is still on n1.
leaseHolder, err = tc.FindRangeLeaseHolder(desc, nil)
require.NoError(t, err)
require.Equal(t, tc.Target(0), leaseHolder,
errors.Errorf("Leaseholder supposed to be on n1."))
}()
// Try really hard to make sure that our request makes it past the
// sanity check error to the evaluation error.
for i := 0; i < 100; i++ {
runtime.Gosched()
time.Sleep(time.Microsecond)
}
close(ch)
wg.Wait()
})
}
// TestTransferLeaseDuringJointConfigWithDeadIncomingVoter ensures that the
// lease transfer performed during a joint config replication change that is
// replacing the existing leaseholder does not get stuck even if the existing
// leaseholder cannot prove that the incoming leaseholder is caught up on its
// log. It does so by killing the incoming leaseholder before it receives the
// lease and ensuring that the range is able to exit the joint configuration.
//
// Currently, the range exits by bypassing safety checks during the lease
// transfer, sending the lease to the dead incoming voter, letting the lease
// expire, acquiring the lease on one of the non-demoting voters, and exiting.
// The details here may change in the future, but the goal of this test will
// not.
func TestTransferLeaseDuringJointConfigWithDeadIncomingVoter(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
// The lease request timeout depends on the Raft election timeout, so we set
// it low to get faster lease expiration (800 ms) and speed up the test.
var raftCfg base.RaftConfig
raftCfg.SetDefaults()
raftCfg.RaftHeartbeatIntervalTicks = 1
raftCfg.RaftElectionTimeoutTicks = 2
knobs, ltk := makeReplicationTestKnobs()
tc := testcluster.StartTestCluster(t, 4, base.TestClusterArgs{
ServerArgs: base.TestServerArgs{
RaftConfig: raftCfg,
Knobs: knobs,
},
ReplicationMode: base.ReplicationManual,
})
defer tc.Stopper().Stop(ctx)
key := tc.ScratchRange(t)
desc := tc.AddVotersOrFatal(t, key, tc.Targets(1, 2)...)
// Make sure n1 has the lease to start with.
err := tc.Server(0).DB().AdminTransferLease(ctx, key, tc.Target(0).StoreID)
require.NoError(t, err)
store0, repl0 := getFirstStoreReplica(t, tc.Server(0), key)
// The test proceeds as follows:
//
// - Send an AdminChangeReplicasRequest to remove n1 (leaseholder) and add n4
// - Stop the replication change after entering the joint configuration
// - Kill n4 and wait until n1 notices
// - Complete the replication change
// Enter joint config.
ltk.withStopAfterJointConfig(func() {
tc.RebalanceVoterOrFatal(ctx, t, key, tc.Target(0), tc.Target(3))
})
desc = tc.LookupRangeOrFatal(t, key)
require.Len(t, desc.Replicas().Descriptors(), 4)
require.True(t, desc.Replicas().InAtomicReplicationChange(), desc)
// Kill n4.
tc.StopServer(3)
// Wait for n1 to notice.
testutils.SucceedsSoon(t, func() error {
// Manually report n4 as unreachable to speed up the test.
require.NoError(t, repl0.RaftReportUnreachable(4))
// Check the Raft progress.
s := repl0.RaftStatus()
require.Equal(t, raft.StateLeader, s.RaftState)
p := s.Progress
require.Len(t, p, 4)
require.Contains(t, p, uint64(4))
if p[4].State != tracker.StateProbe {
return errors.Errorf("dead replica not state probe")
}
return nil
})
// Run the range through the replicate queue on n1.
trace, processErr, err := store0.Enqueue(
ctx, "replicate", repl0, true /* skipShouldQueue */, false /* async */)
require.NoError(t, err)
require.NoError(t, processErr)
formattedTrace := trace.String()
expectedMessages := []string{
`transitioning out of joint configuration`,
`leaseholder .* is being removed through an atomic replication change, transferring lease to`,
`lease transfer to .* complete`,
}
require.NoError(t, testutils.MatchInOrder(formattedTrace, expectedMessages...))
// Verify that the joint configuration has completed.
desc = tc.LookupRangeOrFatal(t, key)
require.Len(t, desc.Replicas().VoterDescriptors(), 3)
require.False(t, desc.Replicas().InAtomicReplicationChange(), desc)
}
// internalTransferLeaseFailureDuringJointConfig reproduces
// https://github.com/cockroachdb/cockroach/issues/83687
// and makes sure that if lease transfer fails during a joint configuration
// the previous leaseholder will successfully re-aquire the lease.
// The test proceeds as follows:
// - Creates a range with 3 replicas n1, n2, n3, and makes sure the lease is on n1
// - Makes sure lease transfers on this range fail from now on
// - Invokes AdminChangeReplicas to remove n1 and add n4
// - This causes the range to go into a joint configuration. A lease transfer
// is attempted to move the lease from n1 to n4 before exiting the joint config,
// but that fails, causing us to remain in the joint configuration with the original
// leaseholder having revoked its lease, but everyone else thinking it's still
// the leaseholder. In this situation, only n1 can re-aquire the lease as long as it is live.
// - We re-enable lease transfers on this range.
// - n1 is able to re-aquire the lease, due to the fix in #83686 which enables a
// VOTER_DEMOTING_LEARNER (n1) replica to get the lease if there's also a VOTER_INCOMING
// which is the case here (n4) and since n1 was the last leaseholder.
// - n1 transfers the lease away and the range leaves the joint configuration.
func internalTransferLeaseFailureDuringJointConfig(t *testing.T, isManual bool) {
defer log.Scope(t).Close(t)
ctx := context.Background()
knobs := base.TestingKnobs{Store: &kvserver.StoreTestingKnobs{}}
// Add a testing knob to allow us to fail all lease transfer commands on this
// range when they are being proposed.
var scratchRangeID int64
shouldFailProposal := func(args kvserverbase.ProposalFilterArgs) bool {
return args.Req.RangeID == roachpb.RangeID(atomic.LoadInt64(&scratchRangeID)) &&
args.Req.IsSingleTransferLeaseRequest()
}
const failureMsg = "injected lease transfer"
knobs.Store.(*kvserver.StoreTestingKnobs).TestingProposalFilter = func(args kvserverbase.ProposalFilterArgs) *kvpb.Error {
if shouldFailProposal(args) {
// The lease transfer should be configured to bypass safety checks.
// See maybeTransferLeaseDuringLeaveJoint for an explanation.
require.True(t, args.Req.Requests[0].GetTransferLease().BypassSafetyChecks)
return kvpb.NewErrorf(failureMsg)
}
return nil
}
tc := testcluster.StartTestCluster(t, 4, base.TestClusterArgs{
ServerArgs: base.TestServerArgs{Knobs: knobs},
ReplicationMode: base.ReplicationManual,
})
defer tc.Stopper().Stop(ctx)
scratchStartKey := tc.ScratchRange(t)
desc := tc.AddVotersOrFatal(t, scratchStartKey, tc.Targets(1, 2)...)
// Make sure n1 has the lease to start with.
err := tc.Server(0).DB().AdminTransferLease(context.Background(),
scratchStartKey, tc.Target(0).StoreID)
require.NoError(t, err)
// The next lease transfer should fail.
atomic.StoreInt64(&scratchRangeID, int64(desc.RangeID))
_, err = tc.Server(0).DB().AdminChangeReplicas(ctx,
scratchStartKey, desc, []kvpb.ReplicationChange{
{ChangeType: roachpb.REMOVE_VOTER, Target: tc.Target(0)},
{ChangeType: roachpb.ADD_VOTER, Target: tc.Target(3)},
})
require.Error(t, err)
require.Regexp(t, failureMsg, err)
// We're now in a joint configuration, n1 already revoked its lease but all
// other replicas think n1 is the leaseholder. As long as n1 is alive, it is
// the only one that can get the lease. It will retry and be able to do that
// thanks to the fix in #83686.
desc, err = tc.LookupRange(scratchStartKey)
require.NoError(t, err)
require.True(t, desc.Replicas().InAtomicReplicationChange())
// Allow further lease transfers to succeed.
atomic.StoreInt64(&scratchRangeID, 0)
if isManual {
// Manually transfer the lease to n1 (VOTER_DEMOTING_LEARNER).
err = tc.Server(0).DB().AdminTransferLease(context.Background(),
scratchStartKey, tc.Target(0).StoreID)
require.NoError(t, err)
// Make sure n1 has the lease
leaseHolder, err := tc.FindRangeLeaseHolder(desc, nil)
require.NoError(t, err)
require.Equal(t, tc.Target(0), leaseHolder,
errors.Errorf("Leaseholder supposed to be on n1."))
}
// Complete the replication change.
atomic.StoreInt64(&scratchRangeID, 0)
store := tc.GetFirstStoreFromServer(t, 0)
repl := store.LookupReplica(roachpb.RKey(scratchStartKey))
_, _, err = store.Enqueue(
ctx, "replicate", repl, true /* skipShouldQueue */, false, /* async */
)
require.NoError(t, err)
desc, err = tc.LookupRange(scratchStartKey)
require.NoError(t, err)
require.False(t, desc.Replicas().InAtomicReplicationChange())
}
// TestTransferLeaseFailureDuringJointConfig is using
// internalTransferLeaseFailureDuringJointConfig and
// completes the lease transfer to n1 “automatically”
// by relying on replicate queue.
func TestTransferLeaseFailureDuringJointConfigAuto(t *testing.T) {
defer leaktest.AfterTest(t)()
internalTransferLeaseFailureDuringJointConfig(t, false)
}
// TestTransferLeaseFailureDuringJointConfigManual is using
// internalTransferLeaseFailureDuringJointConfig and
// completes the lease transfer to n1 “manually” using
// AdminTransferLease.
func TestTransferLeaseFailureDuringJointConfigManual(t *testing.T) {
defer leaktest.AfterTest(t)()
internalTransferLeaseFailureDuringJointConfig(t, true)
}
// TestStoreLeaseTransferTimestampCacheRead verifies that the timestamp cache on
// the new leaseholder is properly updated after a lease transfer to prevent new
// writes from invalidating previously served reads.
func TestStoreLeaseTransferTimestampCacheRead(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
testutils.RunTrueAndFalse(t, "future-read", func(t *testing.T, futureRead bool) {
manualClock := hlc.NewHybridManualClock()
ctx := context.Background()
tc := testcluster.StartTestCluster(t, 3, base.TestClusterArgs{
ServerArgs: base.TestServerArgs{
Knobs: base.TestingKnobs{
Server: &server.TestingKnobs{
WallClock: manualClock,
},
},
},
})
defer tc.Stopper().Stop(ctx)
key := []byte("a")
rangeDesc, err := tc.LookupRange(key)
require.NoError(t, err)
// Transfer the lease to Servers[0] so we start in a known state. Otherwise,
// there might be already a lease owned by a random node.
require.NoError(t, tc.TransferRangeLease(rangeDesc, tc.Target(0)))
// Pause the cluster's clock. This ensures that if we perform a read at
// a future timestamp, the read time remains in the future, regardless
// of the passage of real time.
manualClock.Pause()
// Write a key.
_, pErr := kv.SendWrapped(ctx, tc.Servers[0].DistSender(), incrementArgs(key, 1))
require.Nil(t, pErr)
// Determine when to read.
readTS := tc.Servers[0].Clock().Now()
if futureRead {
readTS = readTS.Add(500*time.Millisecond.Nanoseconds(), 0).WithSynthetic(true)
}
// Read the key at readTS.
// NB: don't use SendWrapped because we want access to br.Timestamp.
ba := &kvpb.BatchRequest{}
ba.Timestamp = readTS
ba.Add(getArgs(key))
br, pErr := tc.Servers[0].DistSender().Send(ctx, ba)
require.Nil(t, pErr)
require.Equal(t, readTS, br.Timestamp)
v, err := br.Responses[0].GetGet().Value.GetInt()
require.NoError(t, err)
require.Equal(t, int64(1), v)
// Transfer the lease. This should carry over a summary of the old
// leaseholder's timestamp cache to prevent any writes on the new
// leaseholder from writing under the previous read.
require.NoError(t, tc.TransferRangeLease(rangeDesc, tc.Target(1)))
// Attempt to write under the read on the new leaseholder. The batch
// should get forwarded to a timestamp after the read.
// NB: don't use SendWrapped because we want access to br.Timestamp.
ba = &kvpb.BatchRequest{}
ba.Timestamp = readTS
ba.Add(incrementArgs(key, 1))
br, pErr = tc.Servers[0].DistSender().Send(ctx, ba)
require.Nil(t, pErr)
require.NotEqual(t, readTS, br.Timestamp)
require.True(t, readTS.Less(br.Timestamp))
require.Equal(t, readTS.Synthetic, br.Timestamp.Synthetic)
})
}
// TestStoreLeaseTransferTimestampCacheTxnRecord checks the error returned by
// attempts to create a txn record after a lease transfer.
func TestStoreLeaseTransferTimestampCacheTxnRecord(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)
key := []byte("a")
rangeDesc, err := tc.LookupRange(key)
require.NoError(t, err)
// Transfer the lease to Servers[0] so we start in a known state. Otherwise,
// there might be already a lease owned by a random node.
require.NoError(t, tc.TransferRangeLease(rangeDesc, tc.Target(0)))
// Start a txn and perform a write, so that a txn record has to be created by
// the EndTxn.
txn := tc.Servers[0].DB().NewTxn(ctx, "test")
require.NoError(t, txn.Put(ctx, "a", "val"))
// After starting the transaction, transfer the lease. This will wipe the
// timestamp cache, which means that the txn record will not be able to be
// created (because someone might have already aborted the txn).
require.NoError(t, tc.TransferRangeLease(rangeDesc, tc.Target(1)))
err = txn.Commit(ctx)
require.Regexp(t, `TransactionAbortedError\(ABORT_REASON_NEW_LEASE_PREVENTS_TXN\)`, err)
}
// This test verifies that when a lease is moved to a node that does not match the
// lease preferences the replication queue moves it eagerly back, without considering the
// kv.allocator.min_lease_transfer_interval.
func TestLeasePreferencesRebalance(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
settings := cluster.MakeTestingClusterSettings()
sv := &settings.SV
// set min lease transfer high, so we know it does affect the lease movement.
kvserver.MinLeaseTransferInterval.Override(ctx, sv, 24*time.Hour)
// Place all the leases in us-west.
zcfg := zonepb.DefaultZoneConfig()
zcfg.LeasePreferences = []zonepb.LeasePreference{
{
Constraints: []zonepb.Constraint{
{Type: zonepb.Constraint_REQUIRED, Key: "region", Value: "us-west"},
},
},
}
numNodes := 3
serverArgs := make(map[int]base.TestServerArgs)
locality := func(region string) roachpb.Locality {
return roachpb.Locality{
Tiers: []roachpb.Tier{
{Key: "region", Value: region},
},
}
}
localities := []roachpb.Locality{
locality("us-west"),
locality("us-east"),
locality("eu"),
}
for i := 0; i < numNodes; i++ {
serverArgs[i] = base.TestServerArgs{
Locality: localities[i],
Knobs: base.TestingKnobs{
Server: &server.TestingKnobs{
DefaultZoneConfigOverride: &zcfg,
},
},
Settings: settings,
}
}
tc := testcluster.StartTestCluster(t, numNodes,
base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgsPerNode: serverArgs,
})
defer tc.Stopper().Stop(ctx)
key := bootstrap.TestingUserTableDataMin()
tc.SplitRangeOrFatal(t, key)
tc.AddVotersOrFatal(t, key, tc.Targets(1, 2)...)
require.NoError(t, tc.WaitForVoters(key, tc.Targets(1, 2)...))
desc := tc.LookupRangeOrFatal(t, key)
leaseHolder, err := tc.FindRangeLeaseHolder(desc, nil)
require.NoError(t, err)
require.Equal(t, tc.Target(0), leaseHolder)
// Manually move lease out of preference.
tc.TransferRangeLeaseOrFatal(t, desc, tc.Target(1))
testutils.SucceedsSoon(t, func() error {
lh, err := tc.FindRangeLeaseHolder(desc, nil)
if err != nil {
return err
}
if !lh.Equal(tc.Target(1)) {
return errors.Errorf("Expected leaseholder to be %s but was %s", tc.Target(1), lh)
}
return nil
})
tc.GetFirstStoreFromServer(t, 1).SetReplicateQueueActive(true)
require.NoError(t, tc.GetFirstStoreFromServer(t, 1).ForceReplicationScanAndProcess())
// The lease should be moved back by the rebalance queue to us-west.
testutils.SucceedsSoon(t, func() error {
lh, err := tc.FindRangeLeaseHolder(desc, nil)
if err != nil {
return err
}
if !lh.Equal(tc.Target(0)) {
return errors.Errorf("Expected leaseholder to be %s but was %s", tc.Target(0), lh)
}
return nil
})
}
// Tests that when leaseholder is relocated, the lease can be transferred directly to new node
func TestLeaseholderRelocate(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
stickyRegistry := server.NewStickyInMemEnginesRegistry()
defer stickyRegistry.CloseAllStickyInMemEngines()
ctx := context.Background()
manualClock := hlc.NewHybridManualClock()
serverArgs := make(map[int]base.TestServerArgs)
locality := func(region string) roachpb.Locality {
return roachpb.Locality{
Tiers: []roachpb.Tier{
{Key: "region", Value: region},
},
}
}
localities := []roachpb.Locality{
locality("eu"),
locality("eu"),
locality("us"),
locality("us"),
}
const numNodes = 4
for i := 0; i < numNodes; i++ {
serverArgs[i] = base.TestServerArgs{
Locality: localities[i],
Knobs: base.TestingKnobs{
Server: &server.TestingKnobs{
WallClock: manualClock,
StickyEngineRegistry: stickyRegistry,
},
},
StoreSpecs: []base.StoreSpec{
{
InMemory: true,
StickyInMemoryEngineID: strconv.FormatInt(int64(i), 10),
},
},
}
}
tc := testcluster.StartTestCluster(t, numNodes,
base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgsPerNode: serverArgs,
})
defer tc.Stopper().Stop(ctx)
_, rhsDesc := tc.SplitRangeOrFatal(t, bootstrap.TestingUserTableDataMin())
// We start with having the range under test on (1,2,3).
tc.AddVotersOrFatal(t, rhsDesc.StartKey.AsRawKey(), tc.Targets(1, 2)...)
// Make sure the lease is on 3 and is fully upgraded.
tc.TransferRangeLeaseOrFatal(t, rhsDesc, tc.Target(2))
// Check that the lease moved to 3.
leaseHolder, err := tc.FindRangeLeaseHolder(rhsDesc, nil)
require.NoError(t, err)
require.Equal(t, tc.Target(2), leaseHolder)
gossipLiveness(t, tc)
testutils.SucceedsSoon(t, func() error {
// Relocate range 3 -> 4.
err = tc.Servers[2].DB().
AdminRelocateRange(
context.Background(), rhsDesc.StartKey.AsRawKey(),
tc.Targets(0, 1, 3), nil, false)
if err != nil {
return err
}
leaseHolder, err = tc.FindRangeLeaseHolder(rhsDesc, nil)
if err != nil {
return err
}
if leaseHolder.Equal(tc.Target(2)) {
return errors.Errorf("Leaseholder didn't move.")
}
return nil
})
// Make sure lease moved to the preferred region.
leaseHolder, err = tc.FindRangeLeaseHolder(rhsDesc, nil)
require.NoError(t, err)
require.Equal(t, tc.Target(3), leaseHolder)
// Double check that lease moved directly. The tail of the lease history
// should all be on leaseHolder.NodeID. We may metamorphically enable
// kv.expiration_leases_only.enabled, in which case there will be a single
// expiration lease, but otherwise we'll have transferred an expiration lease
// and then upgraded to an epoch lease.
repl := tc.GetFirstStoreFromServer(t, 3).
LookupReplica(roachpb.RKey(rhsDesc.StartKey.AsRawKey()))
history := repl.GetLeaseHistory()
require.Equal(t, leaseHolder.NodeID, history[len(history)-1].Replica.NodeID)
var prevLeaseHolder roachpb.NodeID
for i := len(history) - 1; i >= 0; i-- {
if id := history[i].Replica.NodeID; id != leaseHolder.NodeID {
prevLeaseHolder = id
break
}
}
require.Equal(t, tc.Target(2).NodeID, prevLeaseHolder)
}
func gossipLiveness(t *testing.T, tc *testcluster.TestCluster) {
for i := range tc.Servers {
testutils.SucceedsSoon(t, tc.Servers[i].HeartbeatNodeLiveness)
}
// Make sure that all store pools have seen liveness heartbeats from everyone.
testutils.SucceedsSoon(t, func() error {
for i := range tc.Servers {
for j := range tc.Servers {
live, err := tc.GetFirstStoreFromServer(t, i).GetStoreConfig().
StorePool.IsLive(tc.Target(j).StoreID)
if err != nil {
return err
}
if !live {
return errors.Errorf("Server %d is suspect on server %d", j, i)
}
}
}
return nil
})
}
// This test replicates the behavior observed in
// https://github.com/cockroachdb/cockroach/issues/62485. We verify that
// when a dc with the leaseholder is lost, a node in a dc that does not have the
// lease preference can steal the lease, upreplicate the range and then give up the
// lease in a single cycle of the replicate_queue.
func TestLeasePreferencesDuringOutage(t *testing.T) {
defer leaktest.AfterTest(t)()
skip.WithIssue(t, 88769, "flaky test")
defer log.Scope(t).Close(t)
stickyRegistry := server.NewStickyInMemEnginesRegistry()
defer stickyRegistry.CloseAllStickyInMemEngines()
ctx := context.Background()
manualClock := hlc.NewHybridManualClock()
// Place all the leases in the us.
zcfg := zonepb.DefaultZoneConfig()
zcfg.LeasePreferences = []zonepb.LeasePreference{
{
Constraints: []zonepb.Constraint{
{Type: zonepb.Constraint_REQUIRED, Key: "region", Value: "us"},
},
},
}
numNodes := 5
serverArgs := make(map[int]base.TestServerArgs)
locality := func(region string, dc string) roachpb.Locality {
return roachpb.Locality{
Tiers: []roachpb.Tier{
{Key: "region", Value: region},
{Key: "dc", Value: dc},
},
}
}
localities := []roachpb.Locality{
locality("eu", "tr"),
locality("us", "sf"),
locality("us", "sf"),
locality("us", "mi"),
locality("us", "mi"),
}
for i := 0; i < numNodes; i++ {
serverArgs[i] = base.TestServerArgs{
Locality: localities[i],
Knobs: base.TestingKnobs{
Server: &server.TestingKnobs{
WallClock: manualClock,
DefaultZoneConfigOverride: &zcfg,
StickyEngineRegistry: stickyRegistry,
},
Store: &kvserver.StoreTestingKnobs{
// The Raft leadership may not end up on the eu node, but it needs to
// be able to acquire the lease anyway.
AllowLeaseRequestProposalsWhenNotLeader: true,
},
},
StoreSpecs: []base.StoreSpec{
{
InMemory: true,
StickyInMemoryEngineID: strconv.FormatInt(int64(i), 10),
},
},
}
}
tc := testcluster.StartTestCluster(t, numNodes,
base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgsPerNode: serverArgs,
})
defer tc.Stopper().Stop(ctx)
key := bootstrap.TestingUserTableDataMin()
tc.SplitRangeOrFatal(t, key)
tc.AddVotersOrFatal(t, key, tc.Targets(1, 3)...)
repl := tc.GetFirstStoreFromServer(t, 0).LookupReplica(roachpb.RKey(key))
require.NoError(t, tc.WaitForVoters(key, tc.Targets(1, 3)...))
tc.TransferRangeLeaseOrFatal(t, *repl.Desc(), tc.Target(1))
// Shutdown the sf datacenter, which is going to kill the node with the lease.
tc.StopServer(1)
tc.StopServer(2)
wait := func(duration time.Duration) {
manualClock.Increment(duration.Nanoseconds())
// Gossip and heartbeat all the live stores, we do this manually otherwise the
// allocator on server 0 may see everyone as temporarily dead due to the
// clock move above.
for _, i := range []int{0, 3, 4} {
require.NoError(t, tc.Servers[i].HeartbeatNodeLiveness())