-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
client_replica_test.go
2285 lines (2087 loc) · 77.4 KB
/
client_replica_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 2015 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 storage_test
import (
"bytes"
"context"
"fmt"
"math"
"math/rand"
"reflect"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/config"
"github.com/cockroachdb/cockroach/pkg/internal/client"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/server"
"github.com/cockroachdb/cockroach/pkg/storage"
"github.com/cockroachdb/cockroach/pkg/storage/batcheval"
"github.com/cockroachdb/cockroach/pkg/storage/engine"
"github.com/cockroachdb/cockroach/pkg/storage/storagebase"
"github.com/cockroachdb/cockroach/pkg/storage/storagepb"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"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/caller"
"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/randutil"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestRangeCommandClockUpdate verifies that followers update their
// clocks when executing a command, even if the lease holder's clock is far
// in the future.
func TestRangeCommandClockUpdate(t *testing.T) {
defer leaktest.AfterTest(t)()
const numNodes = 3
var manuals []*hlc.ManualClock
var clocks []*hlc.Clock
for i := 0; i < numNodes; i++ {
manuals = append(manuals, hlc.NewManualClock(1))
clocks = append(clocks, hlc.NewClock(manuals[i].UnixNano, 100*time.Millisecond))
}
mtc := &multiTestContext{
clocks: clocks,
// This test was written before the multiTestContext started creating many
// system ranges at startup, and hasn't been update to take that into
// account.
startWithSingleRange: true,
}
defer mtc.Stop()
mtc.Start(t, numNodes)
mtc.replicateRange(1, 1, 2)
// Advance the lease holder's clock ahead of the followers (by more than
// MaxOffset but less than the range lease) and execute a command.
manuals[0].Increment(int64(500 * time.Millisecond))
incArgs := incrementArgs([]byte("a"), 5)
ts := clocks[0].Now()
if _, err := client.SendWrappedWith(context.Background(), mtc.stores[0].TestSender(), roachpb.Header{Timestamp: ts}, incArgs); err != nil {
t.Fatal(err)
}
// Wait for that command to execute on all the followers.
testutils.SucceedsSoon(t, func() error {
values := []int64{}
for _, eng := range mtc.engines {
val, _, err := engine.MVCCGet(context.Background(), eng, roachpb.Key("a"), clocks[0].Now(),
engine.MVCCGetOptions{})
if err != nil {
return err
}
values = append(values, mustGetInt(val))
}
if !reflect.DeepEqual(values, []int64{5, 5, 5}) {
return errors.Errorf("expected (5, 5, 5), got %v", values)
}
return nil
})
// Verify that all the followers have accepted the clock update from
// node 0 even though it comes from outside the usual max offset.
now := clocks[0].Now()
for i, clock := range clocks {
// Only compare the WallTimes: it's normal for clock 0 to be a few logical ticks ahead.
if clock.Now().WallTime < now.WallTime {
t.Errorf("clock %d is behind clock 0: %s vs %s", i, clock.Now(), now)
}
}
}
// TestRejectFutureCommand verifies that lease holders reject commands that
// would cause a large time jump.
func TestRejectFutureCommand(t *testing.T) {
defer leaktest.AfterTest(t)()
manual := hlc.NewManualClock(123)
clock := hlc.NewClock(manual.UnixNano, 100*time.Millisecond)
mtc := &multiTestContext{clock: clock}
defer mtc.Stop()
mtc.Start(t, 1)
ts1 := clock.Now()
key := roachpb.Key("a")
incArgs := incrementArgs(key, 5)
// Commands with a future timestamp that is within the MaxOffset
// bound will be accepted and will cause the clock to advance.
const numCmds = 3
clockOffset := clock.MaxOffset() / numCmds
for i := int64(1); i <= numCmds; i++ {
ts := ts1.Add(i*clockOffset.Nanoseconds(), 0)
if _, err := client.SendWrappedWith(context.Background(), mtc.stores[0].TestSender(), roachpb.Header{Timestamp: ts}, incArgs); err != nil {
t.Fatal(err)
}
}
ts2 := clock.Now()
if expAdvance, advance := ts2.GoTime().Sub(ts1.GoTime()), numCmds*clockOffset; advance != expAdvance {
t.Fatalf("expected clock to advance %s; got %s", expAdvance, advance)
}
// Once the accumulated offset reaches MaxOffset, commands will be rejected.
_, pErr := client.SendWrappedWith(context.Background(), mtc.stores[0].TestSender(), roachpb.Header{Timestamp: ts1.Add(clock.MaxOffset().Nanoseconds()+1, 0)}, incArgs)
if !testutils.IsPError(pErr, "remote wall time is too far ahead") {
t.Fatalf("unexpected error %v", pErr)
}
// The clock did not advance and the final command was not executed.
ts3 := clock.Now()
if advance := ts3.GoTime().Sub(ts2.GoTime()); advance != 0 {
t.Fatalf("expected clock not to advance, but it advanced by %s", advance)
}
// Raft entry application is asynchronous, so we may not see the update to
// the key immediately.
testutils.SucceedsSoon(t, func() error {
val, _, err := engine.MVCCGet(context.Background(), mtc.engines[0], key, ts3,
engine.MVCCGetOptions{})
if err != nil {
t.Fatal(err)
}
if a, e := mustGetInt(val), incArgs.Increment*numCmds; a != e {
return errors.Errorf("expected %d, got %d", e, a)
}
return nil
})
}
// TestTxnPutOutOfOrder tests a case where a put operation of an older
// timestamp comes after a put operation of a newer timestamp in a
// txn. The test ensures such an out-of-order put succeeds and
// overrides an old value. The test uses a "Writer" and a "Reader"
// to reproduce an out-of-order put.
//
// 1) The Writer executes a cput operation and writes a write intent with
// time T in a txn.
// 2) Before the Writer's txn is committed, the Reader sends a high priority
// get operation with time T+100. This pushes the Writer txn timestamp to
// T+100. The Reader also writes to the same key the Writer did a cput to
// in order to trigger the restart of the Writer's txn. The original
// write intent timestamp is also updated to T+100.
// 3) The Writer starts a new epoch of the txn, but before it writes, the
// Reader sends another high priority get operation with time T+200. This
// pushes the Writer txn timestamp to T+200 to trigger a restart of the
// Writer txn. The Writer will not actually restart until it tries to commit
// the current epoch of the transaction. The Reader updates the timestamp of
// the write intent to T+200. The test deliberately fails the Reader get
// operation, and cockroach doesn't update its read timestamp cache.
// 4) The Writer executes the put operation again. This put operation comes
// out-of-order since its timestamp is T+100, while the intent timestamp
// updated at Step 3 is T+200.
// 5) The put operation overrides the old value using timestamp T+100.
// 6) When the Writer attempts to commit its txn, the txn will be restarted
// again at a new epoch timestamp T+200, which will finally succeed.
func TestTxnPutOutOfOrder(t *testing.T) {
defer leaktest.AfterTest(t)()
// key is selected to fall within the meta range in order for the later
// routing of requests to range 1 to work properly. Removing the routing
// of all requests to range 1 would allow us to make the key more normal.
const (
key = "key"
restartKey = "restart"
)
// Set up a filter to so that the get operation at Step 3 will return an error.
var numGets int32
stopper := stop.NewStopper()
defer stopper.Stop(context.TODO())
manual := hlc.NewManualClock(123)
cfg := storage.TestStoreConfig(hlc.NewClock(manual.UnixNano, time.Nanosecond))
// Splits can cause our chosen key to end up on a range other than range 1,
// and trying to handle that complicates the test without providing any
// added benefit.
cfg.TestingKnobs.DisableSplitQueue = true
cfg.TestingKnobs.EvalKnobs.TestingEvalFilter =
func(filterArgs storagebase.FilterArgs) *roachpb.Error {
if _, ok := filterArgs.Req.(*roachpb.GetRequest); ok &&
filterArgs.Req.Header().Key.Equal(roachpb.Key(key)) &&
filterArgs.Hdr.Txn == nil {
// The Reader executes two get operations, each of which triggers two get requests
// (the first request fails and triggers txn push, and then the second request
// succeeds). Returns an error for the fourth get request to avoid timestamp cache
// update after the third get operation pushes the txn timestamp.
if atomic.AddInt32(&numGets, 1) == 4 {
return roachpb.NewErrorWithTxn(errors.Errorf("Test"), filterArgs.Hdr.Txn)
}
}
return nil
}
eng := engine.NewInMem(roachpb.Attributes{}, 10<<20)
stopper.AddCloser(eng)
store := createTestStoreWithOpts(t,
testStoreOpts{eng: eng, cfg: &cfg},
stopper,
)
// Put an initial value.
initVal := []byte("initVal")
err := store.DB().Put(context.TODO(), key, initVal)
if err != nil {
t.Fatalf("failed to put: %+v", err)
}
waitPut := make(chan struct{})
waitFirstGet := make(chan struct{})
waitTxnRestart := make(chan struct{})
waitSecondGet := make(chan struct{})
errChan := make(chan error)
// Start the Writer.
go func() {
epoch := -1
// Start a txn that does read-after-write.
// The txn will be restarted twice, and the out-of-order put
// will happen in the second epoch.
errChan <- store.DB().Txn(context.TODO(), func(ctx context.Context, txn *client.Txn) error {
epoch++
if epoch == 1 {
// Wait until the second get operation is issued.
close(waitTxnRestart)
<-waitSecondGet
}
// Get a key which we can write to from the Reader in order to force a restart.
if _, err := txn.Get(ctx, restartKey); err != nil {
return err
}
updatedVal := []byte("updatedVal")
if err := txn.CPut(ctx, key, updatedVal, "initVal"); err != nil {
log.Errorf(context.TODO(), "failed put value: %+v", err)
return err
}
// Make sure a get will return the value that was just written.
actual, err := txn.Get(ctx, key)
if err != nil {
return err
}
if !bytes.Equal(actual.ValueBytes(), updatedVal) {
return errors.Errorf("unexpected get result: %s", actual)
}
if epoch == 0 {
// Wait until the first get operation will push the txn timestamp.
close(waitPut)
<-waitFirstGet
}
b := txn.NewBatch()
return txn.CommitInBatch(ctx, b)
})
if epoch != 2 {
file, line, _ := caller.Lookup(0)
errChan <- errors.Errorf("%s:%d unexpected number of txn retries. "+
"Expected epoch 2, got: %d.", file, line, epoch)
} else {
errChan <- nil
}
}()
<-waitPut
// Start the Reader.
// Advance the clock and send a get operation with higher
// priority to trigger the txn restart.
manual.Increment(100)
priority := roachpb.UserPriority(-math.MaxInt32)
requestHeader := roachpb.RequestHeader{
Key: roachpb.Key(key),
}
h := roachpb.Header{
Timestamp: cfg.Clock.Now(),
UserPriority: priority,
}
if _, err := client.SendWrappedWith(
context.Background(), store.TestSender(), h, &roachpb.GetRequest{RequestHeader: requestHeader},
); err != nil {
t.Fatalf("failed to get: %+v", err)
}
// Write to the restart key so that the Writer's txn must restart.
putReq := &roachpb.PutRequest{
RequestHeader: roachpb.RequestHeader{Key: roachpb.Key(restartKey)},
Value: roachpb.MakeValueFromBytes([]byte("restart-value")),
}
if _, err := client.SendWrappedWith(context.Background(), store.TestSender(), h, putReq); err != nil {
t.Fatalf("failed to put: %+v", err)
}
// Wait until the writer restarts the txn.
close(waitFirstGet)
<-waitTxnRestart
// Advance the clock and send a get operation again. This time
// we use TestingCommandFilter so that a get operation is not
// processed after the write intent is resolved (to prevent the
// timestamp cache from being updated).
manual.Increment(100)
h.Timestamp = cfg.Clock.Now()
if _, err := client.SendWrappedWith(
context.Background(), store.TestSender(), h, &roachpb.GetRequest{RequestHeader: requestHeader},
); err == nil {
t.Fatal("unexpected success of get")
}
if _, err := client.SendWrappedWith(context.Background(), store.TestSender(), h, putReq); err != nil {
t.Fatalf("failed to put: %+v", err)
}
close(waitSecondGet)
for i := 0; i < 2; i++ {
if err := <-errChan; err != nil {
t.Fatal(err)
}
}
}
// TestRangeLookupUseReverse tests whether the results and the results count
// are correct when scanning in reverse order.
func TestRangeLookupUseReverse(t *testing.T) {
defer leaktest.AfterTest(t)()
storeCfg := storage.TestStoreConfig(nil)
storeCfg.TestingKnobs.DisableSplitQueue = true
storeCfg.TestingKnobs.DisableMergeQueue = true
stopper := stop.NewStopper()
defer stopper.Stop(context.TODO())
store := createTestStoreWithOpts(
t,
testStoreOpts{
// This test was written before the test stores were able to start with
// more than one range and is not prepared to handle many ranges.
dontCreateSystemRanges: true,
cfg: &storeCfg,
},
stopper)
// Init test ranges:
// ["","a"), ["a","c"), ["c","e"), ["e","g") and ["g","\xff\xff").
splits := []*roachpb.AdminSplitRequest{
adminSplitArgs(roachpb.Key("g")),
adminSplitArgs(roachpb.Key("e")),
adminSplitArgs(roachpb.Key("c")),
adminSplitArgs(roachpb.Key("a")),
}
for _, split := range splits {
_, pErr := client.SendWrapped(context.Background(), store.TestSender(), split)
if pErr != nil {
t.Fatalf("%q: split unexpected error: %s", split.SplitKey, pErr)
}
}
// Resolve the intents.
scanArgs := roachpb.ScanRequest{
RequestHeader: roachpb.RequestHeader{
Key: keys.RangeMetaKey(roachpb.RKeyMin.Next()).AsRawKey(),
EndKey: keys.RangeMetaKey(roachpb.RKeyMax).AsRawKey(),
},
}
testutils.SucceedsSoon(t, func() error {
_, pErr := client.SendWrapped(context.Background(), store.TestSender(), &scanArgs)
return pErr.GoError()
})
testCases := []struct {
key roachpb.RKey
maxResults int64
expected []roachpb.RangeDescriptor
expectedPre []roachpb.RangeDescriptor
}{
// Test key in the middle of the range.
{
key: roachpb.RKey("f"),
maxResults: 2,
// ["e","g") and ["c","e").
expected: []roachpb.RangeDescriptor{
{StartKey: roachpb.RKey("e"), EndKey: roachpb.RKey("g")},
},
expectedPre: []roachpb.RangeDescriptor{
{StartKey: roachpb.RKey("c"), EndKey: roachpb.RKey("e")},
},
},
// Test key in the end key of the range.
{
key: roachpb.RKey("g"),
maxResults: 3,
// ["e","g"), ["c","e") and ["a","c").
expected: []roachpb.RangeDescriptor{
{StartKey: roachpb.RKey("e"), EndKey: roachpb.RKey("g")},
},
expectedPre: []roachpb.RangeDescriptor{
{StartKey: roachpb.RKey("c"), EndKey: roachpb.RKey("e")},
{StartKey: roachpb.RKey("a"), EndKey: roachpb.RKey("c")},
},
},
{
key: roachpb.RKey("e"),
maxResults: 2,
// ["c","e") and ["a","c").
expected: []roachpb.RangeDescriptor{
{StartKey: roachpb.RKey("c"), EndKey: roachpb.RKey("e")},
},
expectedPre: []roachpb.RangeDescriptor{
{StartKey: roachpb.RKey("a"), EndKey: roachpb.RKey("c")},
},
},
// Test RKeyMax.
{
key: roachpb.RKeyMax,
maxResults: 2,
// ["e","g") and ["g","\xff\xff")
expected: []roachpb.RangeDescriptor{
{StartKey: roachpb.RKey("g"), EndKey: roachpb.RKey("\xff\xff")},
},
expectedPre: []roachpb.RangeDescriptor{
{StartKey: roachpb.RKey("e"), EndKey: roachpb.RKey("g")},
},
},
// Test Meta2KeyMax.
{
key: roachpb.RKey(keys.Meta2KeyMax),
maxResults: 1,
// ["","a")
expected: []roachpb.RangeDescriptor{
{StartKey: roachpb.RKeyMin, EndKey: roachpb.RKey("a")},
},
},
}
for _, test := range testCases {
t.Run(fmt.Sprintf("key=%s", test.key), func(t *testing.T) {
rs, preRs, err := client.RangeLookup(context.Background(), store.TestSender(),
test.key.AsRawKey(), roachpb.READ_UNCOMMITTED, test.maxResults-1, true /* prefetchReverse */)
if err != nil {
t.Fatalf("LookupRange error: %+v", err)
}
// Checks the results count.
if rsLen, preRsLen := len(rs), len(preRs); int64(rsLen+preRsLen) != test.maxResults {
t.Fatalf("returned results count, expected %d, but got %d+%d", test.maxResults, rsLen, preRsLen)
}
// Checks the range descriptors.
for _, rngSlice := range []struct {
expect, reply []roachpb.RangeDescriptor
}{
{test.expected, rs},
{test.expectedPre, preRs},
} {
for i, rng := range rngSlice.expect {
if !(rng.StartKey.Equal(rngSlice.reply[i].StartKey) && rng.EndKey.Equal(rngSlice.reply[i].EndKey)) {
t.Fatalf("returned range is not correct, expected %v, but got %v", rng, rngSlice.reply[i])
}
}
}
})
}
}
type leaseTransferTest struct {
mtc *multiTestContext
replica0, replica1 *storage.Replica
replica0Desc, replica1Desc roachpb.ReplicaDescriptor
leftKey roachpb.Key
filterMu syncutil.Mutex
filter func(filterArgs storagebase.FilterArgs) *roachpb.Error
waitForTransferBlocked atomic.Value
transferBlocked chan struct{}
}
func setupLeaseTransferTest(t *testing.T) *leaseTransferTest {
l := &leaseTransferTest{
leftKey: roachpb.Key("a"),
}
cfg := storage.TestStoreConfig(nil)
// Ensure the node liveness duration isn't too short. By default it is 900ms
// for TestStoreConfig().
cfg.RangeLeaseRaftElectionTimeoutMultiplier =
float64((9 * time.Second) / cfg.RaftElectionTimeout())
cfg.TestingKnobs.EvalKnobs.TestingEvalFilter =
func(filterArgs storagebase.FilterArgs) *roachpb.Error {
l.filterMu.Lock()
filterCopy := l.filter
l.filterMu.Unlock()
if filterCopy != nil {
return filterCopy(filterArgs)
}
return nil
}
l.waitForTransferBlocked.Store(false)
l.transferBlocked = make(chan struct{})
cfg.TestingKnobs.LeaseTransferBlockedOnExtensionEvent = func(
_ roachpb.ReplicaDescriptor) {
if l.waitForTransferBlocked.Load().(bool) {
l.transferBlocked <- struct{}{}
l.waitForTransferBlocked.Store(false)
}
}
l.mtc = &multiTestContext{}
// This test was written before the multiTestContext started creating many
// system ranges at startup, and hasn't been update to take that into account.
l.mtc.startWithSingleRange = true
l.mtc.storeConfig = &cfg
l.mtc.Start(t, 2)
l.mtc.initGossipNetwork()
// First, do a write; we'll use it to determine when the dust has settled.
l.leftKey = roachpb.Key("a")
incArgs := incrementArgs(l.leftKey, 1)
if _, pErr := client.SendWrapped(context.Background(), l.mtc.distSenders[0], incArgs); pErr != nil {
t.Fatal(pErr)
}
// Get the left range's ID.
rangeID := l.mtc.stores[0].LookupReplica(keys.MustAddr(l.leftKey)).RangeID
// Replicate the left range onto node 1.
l.mtc.replicateRange(rangeID, 1)
l.replica0 = l.mtc.stores[0].LookupReplica(roachpb.RKey("a"))
l.replica1 = l.mtc.stores[1].LookupReplica(roachpb.RKey("a"))
{
var err error
if l.replica0Desc, err = l.replica0.GetReplicaDescriptor(); err != nil {
t.Fatal(err)
}
if l.replica1Desc, err = l.replica1.GetReplicaDescriptor(); err != nil {
t.Fatal(err)
}
}
// Check that replica0 can serve reads OK.
if pErr := l.sendRead(0); pErr != nil {
t.Fatal(pErr)
}
return l
}
func (l *leaseTransferTest) sendRead(storeIdx int) *roachpb.Error {
desc := l.mtc.stores[storeIdx].LookupReplica(keys.MustAddr(l.leftKey))
replicaDesc, err := desc.GetReplicaDescriptor()
if err != nil {
return roachpb.NewError(err)
}
_, pErr := client.SendWrappedWith(
context.Background(),
l.mtc.senders[storeIdx],
roachpb.Header{RangeID: desc.RangeID, Replica: replicaDesc},
getArgs(l.leftKey),
)
if pErr != nil {
log.Warning(context.TODO(), pErr)
}
return pErr
}
// checkHasLease checks that a lease for the left range is owned by a
// replica. The check is executed in a retry loop because the lease may not
// have been applied yet.
func (l *leaseTransferTest) checkHasLease(t *testing.T, storeIdx int) {
t.Helper()
testutils.SucceedsSoon(t, func() error {
return l.sendRead(storeIdx).GoError()
})
}
// setFilter is a helper function to enable/disable the blocking of
// RequestLeaseRequests on replica1. This function will notify that an
// extension is blocked on the passed in channel and will wait on the same
// channel to unblock the extension. Note that once an extension is blocked,
// the filter is cleared.
func (l *leaseTransferTest) setFilter(setTo bool, extensionSem chan struct{}) {
l.filterMu.Lock()
defer l.filterMu.Unlock()
if !setTo {
l.filter = nil
return
}
l.filter = func(filterArgs storagebase.FilterArgs) *roachpb.Error {
if filterArgs.Sid != l.mtc.stores[1].Ident.StoreID {
return nil
}
llReq, ok := filterArgs.Req.(*roachpb.RequestLeaseRequest)
if !ok {
return nil
}
if llReq.Lease.Replica == l.replica1Desc {
// Notify the main thread that the extension is in progress and wait for
// the signal to proceed.
l.filterMu.Lock()
l.filter = nil
l.filterMu.Unlock()
extensionSem <- struct{}{}
<-extensionSem
}
return nil
}
}
func (l *leaseTransferTest) forceLeaseExtension(storeIdx int, lease roachpb.Lease) error {
shouldRenewTS := lease.Expiration.Add(-1, 0)
l.mtc.manualClock.Set(shouldRenewTS.WallTime + 1)
err := l.sendRead(storeIdx).GoError()
// We can sometimes receive an error from our renewal attempt because the
// lease transfer ends up causing the renewal to re-propose and second
// attempt fails because it's already been renewed. This used to work
// before we compared the proposer's lease with the actual lease because
// the renewed lease still encompassed the previous request.
if _, ok := err.(*roachpb.NotLeaseHolderError); ok {
err = nil
}
return err
}
// ensureLeaderAndRaftState is a helper function that blocks until leader is
// the raft leader and follower is up to date.
func (l *leaseTransferTest) ensureLeaderAndRaftState(
t *testing.T, leader *storage.Replica, follower roachpb.ReplicaDescriptor,
) {
t.Helper()
leaderDesc, err := leader.GetReplicaDescriptor()
if err != nil {
t.Fatal(err)
}
testutils.SucceedsSoon(t, func() error {
r := l.mtc.getRaftLeader(l.replica0.RangeID)
if r == nil {
return errors.Errorf("could not find raft leader replica for range %d", l.replica0.RangeID)
}
desc, err := r.GetReplicaDescriptor()
if err != nil {
return errors.Wrap(err, "could not get replica descriptor")
}
if desc != leaderDesc {
return errors.Errorf(
"expected replica with id %v to be raft leader, instead got id %v",
leaderDesc.ReplicaID,
desc.ReplicaID,
)
}
return nil
})
testutils.SucceedsSoon(t, func() error {
status := leader.RaftStatus()
progress, ok := status.Progress[uint64(follower.ReplicaID)]
if !ok {
return errors.Errorf(
"replica %v progress not found in progress map: %v",
follower.ReplicaID,
status.Progress,
)
}
if progress.Match < status.Commit {
return errors.Errorf("replica %v failed to catch up", follower.ReplicaID)
}
return nil
})
}
func TestRangeTransferLeaseExpirationBased(t *testing.T) {
defer leaktest.AfterTest(t)()
t.Run("Transfer", func(t *testing.T) {
l := setupLeaseTransferTest(t)
defer l.mtc.Stop()
origLease, _ := l.replica0.GetLease()
{
// Transferring the lease to ourself should be a no-op.
if err := l.replica0.AdminTransferLease(context.Background(), l.replica0Desc.StoreID); err != nil {
t.Fatal(err)
}
newLease, _ := l.replica0.GetLease()
if !origLease.Equivalent(newLease) {
t.Fatalf("original lease %v and new lease %v not equivalent", origLease, newLease)
}
}
{
// An invalid target should result in an error.
const expected = "unable to find store .* in range"
if err := l.replica0.AdminTransferLease(context.Background(), 1000); !testutils.IsError(err, expected) {
t.Fatalf("expected %s, but found %v", expected, err)
}
}
if err := l.replica0.AdminTransferLease(context.Background(), l.replica1Desc.StoreID); err != nil {
t.Fatal(err)
}
// Check that replica0 doesn't serve reads any more.
pErr := l.sendRead(0)
nlhe, ok := pErr.GetDetail().(*roachpb.NotLeaseHolderError)
if !ok {
t.Fatalf("expected %T, got %s", &roachpb.NotLeaseHolderError{}, pErr)
}
if *(nlhe.LeaseHolder) != l.replica1Desc {
t.Fatalf("expected lease holder %+v, got %+v",
l.replica1Desc, nlhe.LeaseHolder)
}
// Check that replica1 now has the lease.
l.checkHasLease(t, 1)
replica1Lease, _ := l.replica1.GetLease()
// We'd like to verify the timestamp cache's low water mark, but this is
// impossible to determine precisely in all cases because it may have
// been subsumed by future tscache accesses. So instead of checking the
// low water mark, we make sure that the high water mark is equal to or
// greater than the new lease start time, which is less than the
// previous lease's expiration time.
if highWater := l.replica1.GetTSCacheHighWater(); highWater.Less(replica1Lease.Start) {
t.Fatalf("expected timestamp cache high water %s, but found %s",
replica1Lease.Start, highWater)
}
})
// Make replica1 extend its lease and transfer the lease immediately after
// that. Test that the transfer still happens (it'll wait until the extension
// is done).
t.Run("TransferWithExtension", func(t *testing.T) {
l := setupLeaseTransferTest(t)
defer l.mtc.Stop()
// Ensure that replica1 has the lease.
if err := l.replica0.AdminTransferLease(context.Background(), l.replica1Desc.StoreID); err != nil {
t.Fatal(err)
}
l.checkHasLease(t, 1)
extensionSem := make(chan struct{})
l.setFilter(true, extensionSem)
// Initiate an extension.
renewalErrCh := make(chan error)
go func() {
lease, _ := l.replica1.GetLease()
renewalErrCh <- l.forceLeaseExtension(1, lease)
}()
// Wait for extension to be blocked.
<-extensionSem
l.waitForTransferBlocked.Store(true)
// Initiate a transfer.
transferErrCh := make(chan error)
go func() {
// Transfer back from replica1 to replica0.
err := l.replica1.AdminTransferLease(context.Background(), l.replica0Desc.StoreID)
// Ignore not leaseholder errors which can arise due to re-proposals.
if _, ok := err.(*roachpb.NotLeaseHolderError); ok {
err = nil
}
transferErrCh <- err
}()
// Wait for the transfer to be blocked by the extension.
<-l.transferBlocked
// Now unblock the extension.
extensionSem <- struct{}{}
l.checkHasLease(t, 0)
l.setFilter(false, nil)
if err := <-renewalErrCh; err != nil {
t.Errorf("unexpected error from lease renewal: %+v", err)
}
if err := <-transferErrCh; err != nil {
t.Errorf("unexpected error from lease transfer: %+v", err)
}
})
// DrainTransfer verifies that a draining store attempts to transfer away
// range leases owned by its replicas.
t.Run("DrainTransfer", func(t *testing.T) {
l := setupLeaseTransferTest(t)
defer l.mtc.Stop()
// We have to ensure that replica0 is the raft leader and that replica1 has
// caught up to replica0 as draining code doesn't transfer leases to
// behind replicas.
l.ensureLeaderAndRaftState(t, l.replica0, l.replica1Desc)
l.mtc.stores[0].SetDraining(true)
// Check that replica0 doesn't serve reads any more.
pErr := l.sendRead(0)
nlhe, ok := pErr.GetDetail().(*roachpb.NotLeaseHolderError)
if !ok {
t.Fatalf("expected %T, got %s", &roachpb.NotLeaseHolderError{}, pErr)
}
if nlhe.LeaseHolder == nil || *nlhe.LeaseHolder != l.replica1Desc {
t.Fatalf("expected lease holder %+v, got %+v",
l.replica1Desc, nlhe.LeaseHolder)
}
// Check that replica1 now has the lease.
l.checkHasLease(t, 1)
l.mtc.stores[0].SetDraining(false)
})
// DrainTransferWithExtension verifies that a draining store waits for any
// in-progress lease requests to complete before transferring away the new
// lease.
t.Run("DrainTransferWithExtension", func(t *testing.T) {
l := setupLeaseTransferTest(t)
defer l.mtc.Stop()
// Ensure that replica1 has the lease.
if err := l.replica0.AdminTransferLease(context.Background(), l.replica1Desc.StoreID); err != nil {
t.Fatal(err)
}
l.checkHasLease(t, 1)
extensionSem := make(chan struct{})
l.setFilter(true, extensionSem)
// Initiate an extension.
renewalErrCh := make(chan error)
go func() {
lease, _ := l.replica1.GetLease()
renewalErrCh <- l.forceLeaseExtension(1, lease)
}()
// Wait for extension to be blocked.
<-extensionSem
// Make sure that replica 0 is up to date enough to receive the lease.
l.ensureLeaderAndRaftState(t, l.replica1, l.replica0Desc)
// Drain node 1 with an extension in progress.
go func() {
l.mtc.stores[1].SetDraining(true)
}()
// Now unblock the extension.
extensionSem <- struct{}{}
l.checkHasLease(t, 0)
l.setFilter(false, nil)
if err := <-renewalErrCh; err != nil {
t.Errorf("unexpected error from lease renewal: %+v", err)
}
})
}
// TestRangeLimitTxnMaxTimestamp verifies that on lease transfer, the
// normal limiting of a txn's max timestamp to the first observed
// timestamp on a node is extended to include the lease start
// timestamp. This disallows the possibility that a write to another
// replica of the range (on node n1) happened at a later timestamp
// than the originally observed timestamp for the node which now owns
// the lease (n2). This can happen if the replication of the write
// doesn't make it from n1 to n2 before the transaction observes n2's
// clock time.
func TestRangeLimitTxnMaxTimestamp(t *testing.T) {
defer leaktest.AfterTest(t)()
cfg := storage.TestStoreConfig(nil)
cfg.RangeLeaseRaftElectionTimeoutMultiplier =
float64((9 * time.Second) / cfg.RaftElectionTimeout())
mtc := &multiTestContext{}
mtc.storeConfig = &cfg
keyA := roachpb.Key("a")
// Create a new clock for node2 to allow drift between the two wall clocks.
manual1 := hlc.NewManualClock(100) // node1 clock is @t=100
clock1 := hlc.NewClock(manual1.UnixNano, 250*time.Nanosecond)
manual2 := hlc.NewManualClock(98) // node2 clock is @t=98
clock2 := hlc.NewClock(manual2.UnixNano, 250*time.Nanosecond)
mtc.clocks = []*hlc.Clock{clock1, clock2}
// Start a transaction using node2 as a gateway.
txn := roachpb.MakeTransaction("test", keyA, 1, clock2.Now(), 250 /* maxOffsetNs */)
// Simulate a read to another range on node2 by setting the observed timestamp.
txn.UpdateObservedTimestamp(2, clock2.Now())
defer mtc.Stop()
mtc.Start(t, 2)
// Do a write on node1 to establish a key with its timestamp @t=100.
if _, pErr := client.SendWrapped(
context.Background(), mtc.distSenders[0], putArgs(keyA, []byte("value")),
); pErr != nil {
t.Fatal(pErr)
}
// Up-replicate the data in the range to node2.
replica1 := mtc.stores[0].LookupReplica(roachpb.RKey(keyA))
mtc.replicateRange(replica1.RangeID, 1)
// Transfer the lease from node1 to node2.
replica2 := mtc.stores[1].LookupReplica(roachpb.RKey(keyA))
replica2Desc, err := replica2.GetReplicaDescriptor()
if err != nil {
t.Fatal(err)
}
testutils.SucceedsSoon(t, func() error {
if err := replica1.AdminTransferLease(context.Background(), replica2Desc.StoreID); err != nil {
t.Fatal(err)
}
lease, _ := replica2.GetLease()
if lease.Replica.NodeID != replica2.NodeID() {
return errors.Errorf("expected lease transfer to node2: %s", lease)
}
return nil
})
// Verify that after the lease transfer, node2's clock has advanced to at least 100.
if now1, now2 := clock1.Now(), clock2.Now(); now2.WallTime < now1.WallTime {
t.Fatalf("expected node2's clock walltime to be >= %d; got %d", now1.WallTime, now2.WallTime)
}
// Send a get request for keyA to node2, which is now the
// leaseholder. If the max timestamp were not being properly limited,
// we would end up incorrectly reading nothing for keyA. Instead we
// expect to see an uncertainty interval error.
h := roachpb.Header{Txn: &txn}
if _, pErr := client.SendWrappedWith(
context.Background(), mtc.distSenders[0], h, getArgs(keyA),
); !testutils.IsPError(pErr, "uncertainty") {
t.Fatalf("expected an uncertainty interval error; got %v", pErr)
}
}
// TestLeaseMetricsOnSplitAndTransfer verifies that lease-related metrics
// are updated after splitting a range and then initiating one successful
// and one failing lease transfer.
func TestLeaseMetricsOnSplitAndTransfer(t *testing.T) {
defer leaktest.AfterTest(t)()
var injectLeaseTransferError atomic.Value
sc := storage.TestStoreConfig(nil)
sc.TestingKnobs.DisableSplitQueue = true
sc.TestingKnobs.DisableMergeQueue = true
sc.TestingKnobs.EvalKnobs.TestingEvalFilter =
func(filterArgs storagebase.FilterArgs) *roachpb.Error {
if args, ok := filterArgs.Req.(*roachpb.TransferLeaseRequest); ok {
if val := injectLeaseTransferError.Load(); val != nil && val.(bool) {
// Note that we can't just return an error here as we only
// end up counting failures in the metrics if the command
// makes it through to being executed. So use a fake store ID.
args.Lease.Replica.StoreID = roachpb.StoreID(1000)
}
}
return nil
}
mtc := &multiTestContext{
storeConfig: &sc,
// This test was written before the multiTestContext started creating many
// system ranges at startup, and hasn't been update to take that into
// account.
startWithSingleRange: true,
}
defer mtc.Stop()
mtc.Start(t, 2)
// Up-replicate to two replicas.
keyMinReplica0 := mtc.stores[0].LookupReplica(roachpb.RKeyMin)