-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
replica_test.go
10886 lines (9896 loc) · 345 KB
/
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 2014 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
package storage
import (
"bytes"
"context"
"fmt"
"math"
"math/rand"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/gogo/protobuf/proto"
"github.com/kr/pretty"
"github.com/pkg/errors"
"github.com/stretchr/testify/require"
"go.etcd.io/etcd/raft"
"go.etcd.io/etcd/raft/raftpb"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/config"
"github.com/cockroachdb/cockroach/pkg/gossip"
"github.com/cockroachdb/cockroach/pkg/internal/client"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/rpc"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/storage/batcheval"
"github.com/cockroachdb/cockroach/pkg/storage/engine"
"github.com/cockroachdb/cockroach/pkg/storage/engine/enginepb"
"github.com/cockroachdb/cockroach/pkg/storage/rditer"
"github.com/cockroachdb/cockroach/pkg/storage/spanset"
"github.com/cockroachdb/cockroach/pkg/storage/stateloader"
"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/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/log/logtags"
"github.com/cockroachdb/cockroach/pkg/util/metric"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/randutil"
"github.com/cockroachdb/cockroach/pkg/util/shuffle"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
)
// allSpans is a SpanSet that covers *everything* for use in tests that don't
// care about properly declaring their spans.
var allSpans = func() spanset.SpanSet {
var ss spanset.SpanSet
ss.Add(spanset.SpanReadWrite, roachpb.Span{
Key: roachpb.KeyMin,
EndKey: roachpb.KeyMax,
})
// Local keys (see `keys.localPrefix`).
ss.Add(spanset.SpanReadWrite, roachpb.Span{
Key: append([]byte("\x01"), roachpb.KeyMin...),
EndKey: append([]byte("\x01"), roachpb.KeyMax...),
})
return ss
}()
func testRangeDescriptor() *roachpb.RangeDescriptor {
return &roachpb.RangeDescriptor{
RangeID: 1,
StartKey: roachpb.RKeyMin,
EndKey: roachpb.RKeyMax,
Replicas: []roachpb.ReplicaDescriptor{
{
ReplicaID: 1,
NodeID: 1,
StoreID: 1,
},
},
NextReplicaID: 2,
}
}
// boostrapMode controls how the first range is created in testContext.
type bootstrapMode int
const (
// Use Store.BootstrapRange, which writes the range descriptor and
// other metadata. Most tests should use this mode because it more
// closely resembles the real world.
bootstrapRangeWithMetadata bootstrapMode = iota
// Create a range with NewRange and Store.AddRangeTest. The store's data
// will be persisted but metadata will not.
//
// Tests which run in this mode play fast and loose; they want
// a Replica which doesn't have too many moving parts, but then
// may still exercise a sizable amount of code, be it by accident
// or design. We bootstrap them here with what's absolutely
// necessary to not immediately crash on a Raft command, but
// nothing more.
// If you read this and you're writing a new test, try not to
// use this mode - it's deprecated and tends to get in the way
// of new development.
bootstrapRangeOnly
)
// leaseExpiry returns a duration in nanos after which any range lease the
// Replica may hold is expired. It is more precise than LeaseExpiration
// in that it returns the minimal duration necessary.
func leaseExpiry(repl *Replica) int64 {
l, _ := repl.GetLease()
if l.Type() != roachpb.LeaseExpiration {
panic("leaseExpiry only valid for expiration-based leases")
}
return l.Expiration.WallTime + 1
}
// testContext contains all the objects necessary to test a Range.
// In most cases, simply call Start(t) (and later Stop()) on a zero-initialized
// testContext{}. Any fields which are initialized to non-nil values
// will be used as-is.
type testContext struct {
testing.TB
transport *RaftTransport
store *Store
repl *Replica
rangeID roachpb.RangeID
gossip *gossip.Gossip
engine engine.Engine
manualClock *hlc.ManualClock
bootstrapMode bootstrapMode
}
func (tc *testContext) Clock() *hlc.Clock {
return tc.store.cfg.Clock
}
// Start initializes the test context with a single range covering the
// entire keyspace.
func (tc *testContext) Start(t testing.TB, stopper *stop.Stopper) {
tc.manualClock = hlc.NewManualClock(123)
cfg := TestStoreConfig(hlc.NewClock(tc.manualClock.UnixNano, time.Nanosecond))
tc.StartWithStoreConfig(t, stopper, cfg)
}
// StartWithStoreConfig initializes the test context with a single
// range covering the entire keyspace.
func (tc *testContext) StartWithStoreConfig(t testing.TB, stopper *stop.Stopper, cfg StoreConfig) {
tc.TB = t
// Setup fake zone config handler.
config.TestingSetupZoneConfigHook(stopper)
if tc.gossip == nil {
rpcContext := rpc.NewContext(
cfg.AmbientCtx, &base.Config{Insecure: true}, cfg.Clock, stopper, &cfg.Settings.Version)
server := rpc.NewServer(rpcContext) // never started
tc.gossip = gossip.NewTest(1, rpcContext, server, stopper, metric.NewRegistry())
}
if tc.engine == nil {
tc.engine = engine.NewInMem(roachpb.Attributes{Attrs: []string{"dc1", "mem"}}, 1<<20)
stopper.AddCloser(tc.engine)
}
if tc.transport == nil {
tc.transport = NewDummyRaftTransport(cfg.Settings)
}
ctx := context.TODO()
if tc.store == nil {
cfg.Gossip = tc.gossip
cfg.Transport = tc.transport
cfg.StorePool = NewTestStorePool(cfg)
// Create a test sender without setting a store. This is to deal with the
// circular dependency between the test sender and the store. The actual
// store will be passed to the sender after it is created and bootstrapped.
factory := &testSenderFactory{}
cfg.DB = client.NewDB(cfg.AmbientCtx, factory, cfg.Clock)
if err := Bootstrap(ctx, tc.engine, roachpb.StoreIdent{
ClusterID: uuid.MakeV4(),
NodeID: 1,
StoreID: 1,
}, cfg.Settings.Version.BootstrapVersion()); err != nil {
t.Fatal(err)
}
tc.store = NewStore(cfg, tc.engine, &roachpb.NodeDescriptor{NodeID: 1})
// Now that we have our actual store, monkey patch the factory used in cfg.DB.
factory.setStore(tc.store)
// We created the store without a real KV client, so it can't perform splits
// or merges.
tc.store.splitQueue.SetDisabled(true)
tc.store.mergeQueue.SetDisabled(true)
if tc.repl == nil && tc.bootstrapMode == bootstrapRangeWithMetadata {
if err := tc.store.BootstrapRange(nil, cfg.Settings.Version.ServerVersion); err != nil {
t.Fatal(err)
}
}
if err := tc.store.Start(ctx, stopper); err != nil {
t.Fatal(err)
}
tc.store.WaitForInit()
}
realRange := tc.repl == nil
if realRange {
if tc.bootstrapMode == bootstrapRangeOnly {
testDesc := testRangeDescriptor()
if _, err := stateloader.WriteInitialState(
ctx,
tc.store.ClusterSettings(),
tc.store.Engine(),
enginepb.MVCCStats{},
*testDesc,
roachpb.BootstrapLease(),
hlc.Timestamp{},
hlc.Timestamp{},
); err != nil {
t.Fatal(err)
}
repl, err := NewReplica(testDesc, tc.store, 0)
if err != nil {
t.Fatal(err)
}
if err := tc.store.AddReplica(repl); err != nil {
t.Fatal(err)
}
}
var err error
tc.repl, err = tc.store.GetReplica(1)
if err != nil {
t.Fatal(err)
}
tc.rangeID = tc.repl.RangeID
}
if err := tc.initConfigs(realRange, t); err != nil {
t.Fatal(err)
}
}
func (tc *testContext) Sender() client.Sender {
return client.Wrap(tc.repl, func(ba roachpb.BatchRequest) roachpb.BatchRequest {
if ba.RangeID == 0 {
ba.RangeID = 1
}
if ba.Timestamp == (hlc.Timestamp{}) {
if err := ba.SetActiveTimestamp(tc.Clock().Now); err != nil {
tc.Fatal(err)
}
}
return ba
})
}
// SendWrappedWith is a convenience function which wraps the request in a batch
// and sends it
func (tc *testContext) SendWrappedWith(
h roachpb.Header, args roachpb.Request,
) (roachpb.Response, *roachpb.Error) {
return client.SendWrappedWith(context.Background(), tc.Sender(), h, args)
}
// SendWrapped is identical to SendWrappedWith with a zero header.
func (tc *testContext) SendWrapped(args roachpb.Request) (roachpb.Response, *roachpb.Error) {
return tc.SendWrappedWith(roachpb.Header{}, args)
}
// initConfigs creates default configuration entries.
func (tc *testContext) initConfigs(realRange bool, t testing.TB) error {
// Put an empty system config into gossip so that gossip callbacks get
// run. We're using a fake config, but it's hooked into SystemConfig.
if err := tc.gossip.AddInfoProto(gossip.KeySystemConfig,
&config.SystemConfigEntries{}, 0); err != nil {
return err
}
testutils.SucceedsSoon(t, func() error {
if cfg := tc.gossip.GetSystemConfig(); cfg == nil {
return errors.Errorf("expected system config to be set")
}
return nil
})
return nil
}
// addBogusReplicaToRangeDesc modifies the range descriptor to include a second
// replica. This is useful for tests that want to pretend they're transferring
// the range lease away, as the lease can only be obtained by Replicas which are
// part of the range descriptor.
// This is a workaround, but it's sufficient for the purposes of several tests.
func (tc *testContext) addBogusReplicaToRangeDesc(
ctx context.Context,
) (roachpb.ReplicaDescriptor, error) {
secondReplica := roachpb.ReplicaDescriptor{
NodeID: 2,
StoreID: 2,
ReplicaID: 2,
}
oldDesc := *tc.repl.Desc()
newDesc := oldDesc
newDesc.Replicas = append(newDesc.Replicas, secondReplica)
newDesc.NextReplicaID = 3
// Update the "on-disk" replica state, so that it doesn't diverge from what we
// have in memory. At the time of this writing, this is not actually required
// by the tests using this functionality, but it seems sane to do.
ba := client.Batch{
Header: roachpb.Header{Timestamp: tc.Clock().Now()},
}
descKey := keys.RangeDescriptorKey(oldDesc.StartKey)
if err := updateRangeDescriptor(&ba, descKey, &oldDesc, &newDesc); err != nil {
return roachpb.ReplicaDescriptor{}, err
}
if err := tc.store.DB().Run(ctx, &ba); err != nil {
return roachpb.ReplicaDescriptor{}, err
}
tc.repl.setDesc(ctx, &newDesc)
tc.repl.raftMu.Lock()
tc.repl.mu.Lock()
tc.repl.assertStateLocked(ctx, tc.engine)
tc.repl.mu.Unlock()
tc.repl.raftMu.Unlock()
return secondReplica, nil
}
func newTransaction(
name string,
baseKey roachpb.Key,
userPriority roachpb.UserPriority,
isolation enginepb.IsolationType,
clock *hlc.Clock,
) *roachpb.Transaction {
var offset int64
var now hlc.Timestamp
if clock != nil {
offset = clock.MaxOffset().Nanoseconds()
now = clock.Now()
}
txn := roachpb.MakeTransaction(name, baseKey, userPriority, isolation, now, offset)
return &txn
}
// assignSeqNumsForReqs sets sequence numbers for each of the provided requests
// given a transaction proto. It also updates the proto to reflect the incremented
// sequence number.
func assignSeqNumsForReqs(txn *roachpb.Transaction, reqs ...roachpb.Request) {
for _, ru := range reqs {
txn.Sequence++
oldHeader := ru.Header()
oldHeader.Sequence = txn.Sequence
ru.SetHeader(oldHeader)
}
}
// createReplicaSets creates new roachpb.ReplicaDescriptor protos based on an array of
// StoreIDs to aid in testing. Note that this does not actually produce any
// replicas, it just creates the descriptors.
func createReplicaSets(replicaNumbers []roachpb.StoreID) []roachpb.ReplicaDescriptor {
result := []roachpb.ReplicaDescriptor{}
for _, replicaNumber := range replicaNumbers {
result = append(result, roachpb.ReplicaDescriptor{
StoreID: replicaNumber,
})
}
return result
}
// TestIsOnePhaseCommit verifies the circumstances where a
// transactional batch can be committed as an atomic write.
func TestIsOnePhaseCommit(t *testing.T) {
defer leaktest.AfterTest(t)()
txnReqs := make([]roachpb.RequestUnion, 3)
txnReqs[0].MustSetInner(&roachpb.BeginTransactionRequest{})
txnReqs[1].MustSetInner(&roachpb.PutRequest{})
txnReqs[2].MustSetInner(&roachpb.EndTransactionRequest{})
txnReqsNoRefresh := make([]roachpb.RequestUnion, 3)
txnReqsNoRefresh[0].MustSetInner(&roachpb.BeginTransactionRequest{})
txnReqsNoRefresh[1].MustSetInner(&roachpb.PutRequest{})
txnReqsNoRefresh[2].MustSetInner(&roachpb.EndTransactionRequest{NoRefreshSpans: true})
testCases := []struct {
bu []roachpb.RequestUnion
isTxn bool
isWTO bool
isTSOff bool
iso enginepb.IsolationType
exp1PC bool
}{
{[]roachpb.RequestUnion{}, false, false, false, enginepb.SERIALIZABLE, false},
{[]roachpb.RequestUnion{}, true, false, false, enginepb.SERIALIZABLE, false},
{[]roachpb.RequestUnion{{Value: &roachpb.RequestUnion_Get{Get: &roachpb.GetRequest{}}}}, true, false, false, enginepb.SERIALIZABLE, false},
{[]roachpb.RequestUnion{{Value: &roachpb.RequestUnion_Put{Put: &roachpb.PutRequest{}}}}, true, false, false, enginepb.SERIALIZABLE, false},
{txnReqs[0 : len(txnReqs)-1], true, false, false, enginepb.SERIALIZABLE, false},
{txnReqs[1:], true, false, false, enginepb.SERIALIZABLE, false},
{txnReqs, true, false, false, enginepb.SERIALIZABLE, true},
{txnReqs, true, false, false, enginepb.SNAPSHOT, true},
{txnReqs, true, true, false, enginepb.SERIALIZABLE, false},
{txnReqs, true, true, false, enginepb.SNAPSHOT, false},
{txnReqs, true, false, true, enginepb.SERIALIZABLE, false},
{txnReqs, true, false, true, enginepb.SNAPSHOT, false},
{txnReqs, true, true, true, enginepb.SERIALIZABLE, false},
{txnReqs, true, true, true, enginepb.SNAPSHOT, false},
{txnReqsNoRefresh, true, false, false, enginepb.SERIALIZABLE, true},
{txnReqsNoRefresh, true, false, false, enginepb.SNAPSHOT, true},
{txnReqsNoRefresh, true, true, false, enginepb.SERIALIZABLE, true},
{txnReqsNoRefresh, true, true, false, enginepb.SNAPSHOT, false},
{txnReqsNoRefresh, true, false, true, enginepb.SERIALIZABLE, true},
{txnReqsNoRefresh, true, false, true, enginepb.SNAPSHOT, false},
{txnReqsNoRefresh, true, true, true, enginepb.SERIALIZABLE, true},
{txnReqsNoRefresh, true, true, true, enginepb.SNAPSHOT, false},
}
clock := hlc.NewClock(hlc.UnixNano, time.Nanosecond)
for i, c := range testCases {
ba := roachpb.BatchRequest{Requests: c.bu}
if c.isTxn {
ba.Txn = newTransaction("txn", roachpb.Key("a"), 1, c.iso, clock)
if c.isWTO {
ba.Txn.WriteTooOld = true
}
if c.isTSOff {
ba.Txn.Timestamp = ba.Txn.OrigTimestamp.Add(1, 0)
}
}
if is1PC := isOnePhaseCommit(ba, &storagebase.StoreTestingKnobs{}); is1PC != c.exp1PC {
t.Errorf("%d: expected 1pc=%t; got %t", i, c.exp1PC, is1PC)
}
}
}
// TestReplicaContains verifies that the range uses Key.Address() in
// order to properly resolve addresses for local keys.
func TestReplicaContains(t *testing.T) {
defer leaktest.AfterTest(t)()
desc := &roachpb.RangeDescriptor{
RangeID: 1,
StartKey: roachpb.RKey("a"),
EndKey: roachpb.RKey("b"),
}
// This test really only needs a hollow shell of a Replica.
r := &Replica{}
r.mu.state.Desc = desc
r.rangeStr.store(0, desc)
if statsKey := keys.RangeStatsLegacyKey(desc.RangeID); !r.ContainsKey(statsKey) {
t.Errorf("expected range to contain range stats key %q", statsKey)
}
if !r.ContainsKey(roachpb.Key("aa")) {
t.Errorf("expected range to contain key \"aa\"")
}
if !r.ContainsKey(keys.RangeDescriptorKey([]byte("aa"))) {
t.Errorf("expected range to contain range descriptor key for \"aa\"")
}
if !r.ContainsKeyRange(roachpb.Key("aa"), roachpb.Key("b")) {
t.Errorf("expected range to contain key range \"aa\"-\"b\"")
}
if !r.ContainsKeyRange(keys.RangeDescriptorKey([]byte("aa")),
keys.RangeDescriptorKey([]byte("b"))) {
t.Errorf("expected range to contain key transaction range \"aa\"-\"b\"")
}
}
func sendLeaseRequest(r *Replica, l *roachpb.Lease) error {
ba := roachpb.BatchRequest{}
ba.Timestamp = r.store.Clock().Now()
ba.Add(&roachpb.RequestLeaseRequest{Lease: *l})
exLease, _ := r.GetLease()
ch, _, _, pErr := r.propose(context.TODO(), exLease, ba, nil, &allSpans)
if pErr == nil {
// Next if the command was committed, wait for the range to apply it.
// TODO(bdarnell): refactor this to a more conventional error-handling pattern.
pErr = (<-ch).Err
}
return pErr.GoError()
}
// TestReplicaReadConsistency verifies behavior of the range under
// different read consistencies. Note that this unittest plays
// fast and loose with granting range leases.
func TestReplicaReadConsistency(t *testing.T) {
defer leaktest.AfterTest(t)()
stopper := stop.NewStopper()
defer stopper.Stop(context.TODO())
tc := testContext{manualClock: hlc.NewManualClock(123)}
cfg := TestStoreConfig(hlc.NewClock(tc.manualClock.UnixNano, time.Nanosecond))
cfg.TestingKnobs.DisableAutomaticLeaseRenewal = true
tc.StartWithStoreConfig(t, stopper, cfg)
secondReplica, err := tc.addBogusReplicaToRangeDesc(context.TODO())
if err != nil {
t.Fatal(err)
}
gArgs := getArgs(roachpb.Key("a"))
// Try consistent read and verify success.
if _, err := tc.SendWrapped(&gArgs); err != nil {
t.Errorf("expected success on consistent read: %s", err)
}
// Try a read commmitted read and an inconsistent read, both within a
// transaction.
txn := newTransaction("test", roachpb.Key("a"), 1, enginepb.SERIALIZABLE, tc.Clock())
assignSeqNumsForReqs(txn, &gArgs)
if _, err := tc.SendWrappedWith(roachpb.Header{
Txn: txn,
ReadConsistency: roachpb.READ_UNCOMMITTED,
}, &gArgs); err == nil {
t.Errorf("expected error on read uncommitted read within a txn")
}
if _, err := tc.SendWrappedWith(roachpb.Header{
Txn: txn,
ReadConsistency: roachpb.INCONSISTENT,
}, &gArgs); err == nil {
t.Errorf("expected error on inconsistent read within a txn")
}
// Lose the lease and verify CONSISTENT reads receive NotLeaseHolderError
// and INCONSISTENT reads work as expected.
tc.manualClock.Set(leaseExpiry(tc.repl))
start := tc.Clock().Now()
if err := sendLeaseRequest(tc.repl, &roachpb.Lease{
Start: start,
Expiration: start.Add(10, 0).Clone(),
Replica: secondReplica,
}); err != nil {
t.Fatal(err)
}
// Send without Txn.
_, pErr := tc.SendWrappedWith(roachpb.Header{
ReadConsistency: roachpb.CONSISTENT,
}, &gArgs)
if _, ok := pErr.GetDetail().(*roachpb.NotLeaseHolderError); !ok {
t.Errorf("expected not lease holder error; got %s", pErr)
}
_, pErr = tc.SendWrappedWith(roachpb.Header{
ReadConsistency: roachpb.READ_UNCOMMITTED,
}, &gArgs)
if _, ok := pErr.GetDetail().(*roachpb.NotLeaseHolderError); !ok {
t.Errorf("expected not lease holder error; got %s", pErr)
}
if _, pErr := tc.SendWrappedWith(roachpb.Header{
ReadConsistency: roachpb.INCONSISTENT,
}, &gArgs); pErr != nil {
t.Errorf("expected success reading with inconsistent: %s", pErr)
}
}
// Test the behavior of a replica while a range lease transfer is in progress:
// - while the transfer is in progress, reads should return errors pointing to
// the transfer target.
// - if a transfer fails, the pre-existing lease does not start being used
// again. Instead, a new lease needs to be obtained. This is because, even
// though the transfer got an error, that error is considered ambiguous as the
// transfer might still apply.
func TestBehaviorDuringLeaseTransfer(t *testing.T) {
defer leaktest.AfterTest(t)()
manual := hlc.NewManualClock(123)
clock := hlc.NewClock(manual.UnixNano, 100*time.Millisecond)
tc := testContext{manualClock: manual}
tsc := TestStoreConfig(clock)
var leaseAcquisitionTrap atomic.Value
tsc.TestingKnobs.DisableAutomaticLeaseRenewal = true
tsc.TestingKnobs.LeaseRequestEvent = func(ts hlc.Timestamp) {
val := leaseAcquisitionTrap.Load()
if val == nil {
return
}
trapCallback := val.(func(ts hlc.Timestamp))
if trapCallback != nil {
trapCallback(ts)
}
}
transferSem := make(chan struct{})
tsc.TestingKnobs.EvalKnobs.TestingEvalFilter =
func(filterArgs storagebase.FilterArgs) *roachpb.Error {
if _, ok := filterArgs.Req.(*roachpb.TransferLeaseRequest); ok {
// Notify the test that the transfer has been trapped.
transferSem <- struct{}{}
// Wait for the test to unblock the transfer.
<-transferSem
// Return an error, so that the pendingLeaseRequest considers the
// transfer failed.
return roachpb.NewErrorf("injected transfer error")
}
return nil
}
stopper := stop.NewStopper()
defer stopper.Stop(context.TODO())
tc.StartWithStoreConfig(t, stopper, tsc)
secondReplica, err := tc.addBogusReplicaToRangeDesc(context.TODO())
if err != nil {
t.Fatal(err)
}
// Do a read to acquire the lease.
gArgs := getArgs(roachpb.Key("a"))
if _, err := tc.SendWrapped(&gArgs); err != nil {
t.Fatal(err)
}
// Advance the clock so that the transfer we're going to perform sets a higher
// minLeaseProposedTS.
tc.manualClock.Increment((500 * time.Nanosecond).Nanoseconds())
// Initiate a transfer (async) and wait for it to be blocked.
transferResChan := make(chan error)
go func() {
err := tc.repl.AdminTransferLease(context.Background(), secondReplica.StoreID)
if !testutils.IsError(err, "injected") {
transferResChan <- err
} else {
transferResChan <- nil
}
}()
<-transferSem
// Check that a transfer is indeed on-going.
tc.repl.mu.Lock()
repDesc, err := tc.repl.getReplicaDescriptorRLocked()
if err != nil {
tc.repl.mu.Unlock()
t.Fatal(err)
}
_, pending := tc.repl.mu.pendingLeaseRequest.TransferInProgress(repDesc.ReplicaID)
tc.repl.mu.Unlock()
if !pending {
t.Fatalf("expected transfer to be in progress, and it wasn't")
}
// Check that, while the transfer is on-going, the replica redirects to the
// transfer target.
_, pErr := tc.SendWrapped(&gArgs)
nlhe, ok := pErr.GetDetail().(*roachpb.NotLeaseHolderError)
if !ok || nlhe.LeaseHolder.StoreID != secondReplica.StoreID {
t.Fatalf("expected not lease holder error pointing to store %d, got %v",
secondReplica.StoreID, pErr)
}
// Unblock the transfer and wait for the pendingLeaseRequest to clear the
// transfer state.
transferSem <- struct{}{}
if err := <-transferResChan; err != nil {
t.Fatal(err)
}
testutils.SucceedsSoon(t, func() error {
tc.repl.mu.Lock()
defer tc.repl.mu.Unlock()
_, pending := tc.repl.mu.pendingLeaseRequest.TransferInProgress(repDesc.ReplicaID)
if pending {
return errors.New("transfer pending")
}
return nil
})
// Check that the replica doesn't use its lease, even though there's no longer
// a transfer in progress. This is because, even though the transfer got an
// error, that error is considered ambiguous as the transfer might still
// apply.
// Concretely, we're going to check that a read triggers a new lease
// acquisition.
tc.repl.mu.Lock()
minLeaseProposedTS := tc.repl.mu.minLeaseProposedTS
leaseStartTS := tc.repl.mu.state.Lease.Start
tc.repl.mu.Unlock()
if !leaseStartTS.Less(minLeaseProposedTS) {
t.Fatalf("expected minLeaseProposedTS > lease start. minLeaseProposedTS: %s, "+
"leas start: %s", minLeaseProposedTS, leaseStartTS)
}
expectedLeaseStartTS := tc.manualClock.UnixNano()
leaseAcquisitionCh := make(chan error)
leaseAcquisitionTrap.Store(func(ts hlc.Timestamp) {
if ts.WallTime == expectedLeaseStartTS {
close(leaseAcquisitionCh)
} else {
leaseAcquisitionCh <- errors.Errorf(
"expected acquisition of lease with start: %d but got start: %s",
expectedLeaseStartTS, ts)
}
})
// We expect this call to succeed, but after acquiring a new lease.
if _, err := tc.SendWrapped(&gArgs); err != nil {
t.Fatal(err)
}
// Check that the Send above triggered a lease acquisition.
select {
case <-leaseAcquisitionCh:
case <-time.After(time.Second):
t.Fatalf("read did not acquire a new lease")
}
}
// TestApplyCmdLeaseError verifies that when during application of a Raft
// command the proposing node no longer holds the range lease, an error is
// returned. This prevents regression of #1483.
func TestApplyCmdLeaseError(t *testing.T) {
defer leaktest.AfterTest(t)()
stopper := stop.NewStopper()
defer stopper.Stop(context.TODO())
tc := testContext{manualClock: hlc.NewManualClock(123)}
cfg := TestStoreConfig(hlc.NewClock(tc.manualClock.UnixNano, time.Nanosecond))
cfg.TestingKnobs.DisableAutomaticLeaseRenewal = true
tc.StartWithStoreConfig(t, stopper, cfg)
secondReplica, err := tc.addBogusReplicaToRangeDesc(context.TODO())
if err != nil {
t.Fatal(err)
}
pArgs := putArgs(roachpb.Key("a"), []byte("asd"))
// Lose the lease.
tc.manualClock.Set(leaseExpiry(tc.repl))
start := tc.Clock().Now()
if err := sendLeaseRequest(tc.repl, &roachpb.Lease{
Start: start,
Expiration: start.Add(10, 0).Clone(),
Replica: secondReplica,
}); err != nil {
t.Fatal(err)
}
_, pErr := tc.SendWrappedWith(roachpb.Header{
Timestamp: tc.Clock().Now().Add(-100, 0),
}, &pArgs)
if _, ok := pErr.GetDetail().(*roachpb.NotLeaseHolderError); !ok {
t.Fatalf("expected not lease holder error in return, got %v", pErr)
}
}
func TestLeaseReplicaNotInDesc(t *testing.T) {
defer leaktest.AfterTest(t)()
tc := testContext{}
stopper := stop.NewStopper()
defer stopper.Stop(context.TODO())
tc.Start(t, stopper)
lease, _ := tc.repl.GetLease()
invalidLease := lease
invalidLease.Sequence++
invalidLease.Replica.StoreID += 12345
raftCmd := storagepb.RaftCommand{
ProposerLeaseSequence: lease.Sequence,
ProposerReplica: invalidLease.Replica,
ReplicatedEvalResult: storagepb.ReplicatedEvalResult{
IsLeaseRequest: true,
State: &storagepb.ReplicaState{
Lease: &invalidLease,
},
},
}
tc.repl.mu.Lock()
_, _, pErr := tc.repl.checkForcedErrLocked(
context.Background(), makeIDKey(), raftCmd, nil /* proposal */, false, /* proposedLocally */
)
tc.repl.mu.Unlock()
if _, isErr := pErr.GetDetail().(*roachpb.LeaseRejectedError); !isErr {
t.Fatal(pErr)
} else if !testutils.IsPError(pErr, "replica not part of range") {
t.Fatal(pErr)
}
}
func TestReplicaRangeBoundsChecking(t *testing.T) {
defer leaktest.AfterTest(t)()
tc := testContext{}
stopper := stop.NewStopper()
defer stopper.Stop(context.TODO())
tc.Start(t, stopper)
key := roachpb.RKey("a")
firstRepl := tc.store.LookupReplica(key)
newRepl := splitTestRange(tc.store, key, key, t)
if _, pErr := newRepl.redirectOnOrAcquireLease(context.Background()); pErr != nil {
t.Fatal(pErr)
}
gArgs := getArgs(roachpb.Key("b"))
_, pErr := tc.SendWrapped(&gArgs)
if mismatchErr, ok := pErr.GetDetail().(*roachpb.RangeKeyMismatchError); !ok {
t.Errorf("expected range key mismatch error: %s", pErr)
} else {
if mismatchedDesc := mismatchErr.MismatchedRange; mismatchedDesc == nil || mismatchedDesc.RangeID != firstRepl.RangeID {
t.Errorf("expected mismatched range to be %d, found %v", firstRepl.RangeID, mismatchedDesc)
}
if suggestedDesc := mismatchErr.SuggestedRange; suggestedDesc == nil || suggestedDesc.RangeID != newRepl.RangeID {
t.Errorf("expected suggested range to be %d, found %v", newRepl.RangeID, suggestedDesc)
}
}
}
// hasLease returns whether the most recent range lease was held by the given
// range replica and whether it's expired for the given timestamp.
func hasLease(repl *Replica, timestamp hlc.Timestamp) (owned bool, expired bool) {
repl.mu.Lock()
defer repl.mu.Unlock()
status := repl.leaseStatus(*repl.mu.state.Lease, timestamp, repl.mu.minLeaseProposedTS)
return repl.mu.state.Lease.OwnedBy(repl.store.StoreID()), status.State != storagepb.LeaseState_VALID
}
func TestReplicaLease(t *testing.T) {
defer leaktest.AfterTest(t)()
tc := testContext{}
stopper := stop.NewStopper()
defer stopper.Stop(context.TODO())
tc.manualClock = hlc.NewManualClock(123)
tsc := TestStoreConfig(hlc.NewClock(tc.manualClock.UnixNano, time.Nanosecond))
tsc.TestingKnobs.DisableAutomaticLeaseRenewal = true
tc.StartWithStoreConfig(t, stopper, tsc)
secondReplica, err := tc.addBogusReplicaToRangeDesc(context.TODO())
if err != nil {
t.Fatal(err)
}
// Test that leases with invalid times are rejected.
// Start leases at a point that avoids overlapping with the existing lease.
leaseDuration := tc.store.cfg.RangeLeaseActiveDuration()
start := hlc.Timestamp{WallTime: (time.Second + leaseDuration).Nanoseconds(), Logical: 0}
for _, lease := range []roachpb.Lease{
{Start: start, Expiration: &hlc.Timestamp{}},
} {
if _, err := batcheval.RequestLease(context.Background(), tc.store.Engine(),
batcheval.CommandArgs{
EvalCtx: NewReplicaEvalContext(tc.repl, &allSpans),
Args: &roachpb.RequestLeaseRequest{
Lease: lease,
},
}, &roachpb.RequestLeaseResponse{}); !testutils.IsError(err, "illegal lease") {
t.Fatalf("unexpected error: %v", err)
}
}
if held, _ := hasLease(tc.repl, tc.Clock().Now()); !held {
t.Errorf("expected lease on range start")
}
tc.manualClock.Set(leaseExpiry(tc.repl))
now := tc.Clock().Now()
if err := sendLeaseRequest(tc.repl, &roachpb.Lease{
Start: now.Add(10, 0),
Expiration: now.Add(20, 0).Clone(),
Replica: secondReplica,
}); err != nil {
t.Fatal(err)
}
if held, expired := hasLease(tc.repl, tc.Clock().Now().Add(15, 0)); held || expired {
t.Errorf("expected second replica to have range lease")
}
{
_, pErr := tc.repl.redirectOnOrAcquireLease(context.Background())
if lErr, ok := pErr.GetDetail().(*roachpb.NotLeaseHolderError); !ok || lErr == nil {
t.Fatalf("wanted NotLeaseHolderError, got %s", pErr)
}
}
// Advance clock past expiration and verify that another has
// range lease will not be true.
tc.manualClock.Increment(21) // 21ns have passed
if held, expired := hasLease(tc.repl, tc.Clock().Now()); held || !expired {
t.Errorf("expected another replica to have expired lease; %t, %t", held, expired)
}
// Verify that command returns NotLeaseHolderError when lease is rejected.
tc.repl.mu.Lock()
tc.repl.mu.submitProposalFn = func(*ProposalData) error {
return &roachpb.LeaseRejectedError{
Message: "replica not found",
}
}
tc.repl.mu.Unlock()
{
_, err := tc.repl.redirectOnOrAcquireLease(context.Background())
if _, ok := err.GetDetail().(*roachpb.NotLeaseHolderError); !ok {
t.Fatalf("expected %T, got %s", &roachpb.NotLeaseHolderError{}, err)
}
}
}
func TestReplicaNotLeaseHolderError(t *testing.T) {
defer leaktest.AfterTest(t)()
stopper := stop.NewStopper()
defer stopper.Stop(context.TODO())
tc := testContext{manualClock: hlc.NewManualClock(123)}
cfg := TestStoreConfig(hlc.NewClock(tc.manualClock.UnixNano, time.Nanosecond))
cfg.TestingKnobs.DisableAutomaticLeaseRenewal = true
tc.StartWithStoreConfig(t, stopper, cfg)
secondReplica, err := tc.addBogusReplicaToRangeDesc(context.TODO())
if err != nil {
t.Fatal(err)
}
tc.manualClock.Set(leaseExpiry(tc.repl))
now := tc.Clock().Now()
if err := sendLeaseRequest(tc.repl, &roachpb.Lease{
Start: now,
Expiration: now.Add(10, 0).Clone(),
Replica: secondReplica,
}); err != nil {
t.Fatal(err)
}
header := roachpb.RequestHeader{
Key: roachpb.Key("a"),
}
testCases := []roachpb.Request{
// Admin split covers admin commands.
&roachpb.AdminSplitRequest{
RequestHeader: header,
SplitKey: roachpb.Key("a"),
},
// Get covers read-only commands.
&roachpb.GetRequest{
RequestHeader: header,
},
// Put covers read-write commands.
&roachpb.PutRequest{
RequestHeader: header,
Value: roachpb.MakeValueFromString("value"),
},
}
for i, test := range testCases {
_, pErr := tc.SendWrappedWith(roachpb.Header{Timestamp: now}, test)
if _, ok := pErr.GetDetail().(*roachpb.NotLeaseHolderError); !ok {
t.Errorf("%d: expected not lease holder error: %s", i, pErr)
}
}
}
// TestReplicaLeaseCounters verifies leaseRequest metrics counters are updated
// correctly after a lease request.
func TestReplicaLeaseCounters(t *testing.T) {
defer leaktest.AfterTest(t)()
defer EnableLeaseHistory(100)()
stopper := stop.NewStopper()
defer stopper.Stop(context.TODO())
var tc testContext
cfg := TestStoreConfig(nil)
// Disable reasonNewLeader and reasonNewLeaderOrConfigChange proposal
// refreshes so that our lease proposal does not risk being rejected
// with an AmbiguousResultError.
cfg.TestingKnobs.DisableRefreshReasonNewLeader = true
cfg.TestingKnobs.DisableRefreshReasonNewLeaderOrConfigChange = true
tc.StartWithStoreConfig(t, stopper, cfg)
assert := func(actual, min, max int64) error {
if actual < min || actual > max {
return errors.Errorf(
"metrics counters actual=%d, expected=[%d,%d]",
actual, min, max,
)
}
return nil
}
metrics := tc.repl.store.metrics
if err := assert(metrics.LeaseRequestSuccessCount.Count(), 1, 1000); err != nil {
t.Fatal(err)
}
if err := assert(metrics.LeaseRequestErrorCount.Count(), 0, 0); err != nil {
t.Fatal(err)
}
if err := tc.repl.store.updateReplicationGauges(context.Background()); err != nil {
t.Fatal(err)
}