-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
replica_test.go
11549 lines (10629 loc) · 381 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.
//
// 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
import (
"bytes"
"context"
"fmt"
"math"
"math/rand"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"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/storage/batcheval"
"github.com/cockroachdb/cockroach/pkg/storage/engine"
"github.com/cockroachdb/cockroach/pkg/storage/engine/enginepb"
"github.com/cockroachdb/cockroach/pkg/storage/intentresolver"
"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/storage/txnwait"
"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/metric"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/randutil"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/logtags"
"github.com/gogo/protobuf/proto"
"github.com/kr/pretty"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.etcd.io/etcd/raft"
"go.etcd.io/etcd/raft/raftpb"
)
// 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,
InternalReplicas: []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.WriteInitialData, 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
}
// Create a Raft status that shows everyone fully up to date.
func upToDateRaftStatus(repls []roachpb.ReplicaDescriptor) *raft.Status {
prs := make(map[uint64]raft.Progress)
for _, repl := range repls {
prs[uint64(repl.ReplicaID)] = raft.Progress{
State: raft.ProgressStateReplicate,
Match: 100,
}
}
return &raft.Status{
HardState: raftpb.HardState{Commit: 100},
SoftState: raft.SoftState{Lead: 1, RaftState: raft.StateLeader},
Progress: prs,
}
}
// 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(), cfg.DefaultZoneConfig)
}
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()
bootstrapVersion := cfg.Settings.Version.BootstrapVersion()
if ver := cfg.TestingKnobs.BootstrapVersion; ver != nil {
bootstrapVersion = *ver
}
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 := InitEngine(ctx, tc.engine, roachpb.StoreIdent{
ClusterID: uuid.MakeV4(),
NodeID: 1,
StoreID: 1,
}, bootstrapVersion); err != nil {
t.Fatal(err)
}
tc.store = NewStore(ctx, 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 := WriteInitialClusterData(
ctx, tc.store.Engine(),
nil, /* initialValues */
bootstrapVersion.Version,
1 /* numStores */, nil /* splits */, cfg.Clock.PhysicalNow(),
); 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.Engine(),
enginepb.MVCCStats{},
*testDesc,
roachpb.BootstrapLease(),
hlc.Timestamp{},
bootstrapVersion.Version,
stateloader.TruncatedStateUnreplicated,
); 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)
}
}
tc.Clock().Update(ba.Timestamp)
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.InternalReplicas = append(newDesc.InternalReplicas, secondReplica)
newDesc.NextReplicaID = 3
dbDescKV, err := tc.store.DB().Get(ctx, keys.RangeDescriptorKey(oldDesc.StartKey))
if err != nil {
return roachpb.ReplicaDescriptor{}, err
}
var dbDesc roachpb.RangeDescriptor
if err := dbDescKV.Value.GetProto(&dbDesc); err != nil {
return roachpb.ReplicaDescriptor{}, err
}
if !oldDesc.Equal(&dbDesc) {
return roachpb.ReplicaDescriptor{}, errors.Errorf(`descs didn't match: %v vs %v`, oldDesc, dbDesc)
}
// 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, dbDescKV.Value, &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, 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, 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
}
// TestMaybeStripInFlightWrites verifies that in-flight writes declared
// on an EndTransaction request are stripped if the corresponding write
// or query intent is in the same batch as the EndTransaction.
func TestMaybeStripInFlightWrites(t *testing.T) {
defer leaktest.AfterTest(t)()
keyA, keyB, keyC := roachpb.Key("a"), roachpb.Key("b"), roachpb.Key("c")
qi1 := &roachpb.QueryIntentRequest{RequestHeader: roachpb.RequestHeader{Key: keyA}}
qi1.Txn.Sequence = 1
put2 := &roachpb.PutRequest{RequestHeader: roachpb.RequestHeader{Key: keyB}}
put2.Sequence = 2
put3 := &roachpb.PutRequest{RequestHeader: roachpb.RequestHeader{Key: keyC}}
put3.Sequence = 3
delRng3 := &roachpb.DeleteRangeRequest{RequestHeader: roachpb.RequestHeader{Key: keyC}}
delRng3.Sequence = 3
scan3 := &roachpb.ScanRequest{RequestHeader: roachpb.RequestHeader{Key: keyC}}
scan3.Sequence = 3
et := &roachpb.EndTransactionRequest{RequestHeader: roachpb.RequestHeader{Key: keyA}, Commit: true}
et.Sequence = 4
et.IntentSpans = []roachpb.Span{{Key: keyC}}
et.InFlightWrites = []roachpb.SequencedWrite{{Key: keyA, Sequence: 1}, {Key: keyB, Sequence: 2}}
testCases := []struct {
reqs []roachpb.Request
expIFW []roachpb.SequencedWrite
expIntentSpans []roachpb.Span
expErr string
}{
{
reqs: []roachpb.Request{et},
expIFW: []roachpb.SequencedWrite{{Key: keyA, Sequence: 1}, {Key: keyB, Sequence: 2}},
expIntentSpans: []roachpb.Span{{Key: keyC}},
},
// QueryIntents aren't stripped from the in-flight writes set on the
// slow-path of maybeStripInFlightWrites. This is intentional.
{
reqs: []roachpb.Request{qi1, et},
expIFW: []roachpb.SequencedWrite{{Key: keyA, Sequence: 1}, {Key: keyB, Sequence: 2}},
expIntentSpans: []roachpb.Span{{Key: keyC}},
},
{
reqs: []roachpb.Request{put2, et},
expIFW: []roachpb.SequencedWrite{{Key: keyA, Sequence: 1}},
expIntentSpans: []roachpb.Span{{Key: keyB}, {Key: keyC}},
},
{
reqs: []roachpb.Request{put3, et},
expErr: "write in batch with EndTransaction missing from in-flight writes",
},
{
reqs: []roachpb.Request{qi1, put2, et},
expIFW: nil,
expIntentSpans: []roachpb.Span{{Key: keyA}, {Key: keyB}, {Key: keyC}},
},
{
reqs: []roachpb.Request{qi1, put2, delRng3, et},
expIFW: nil,
expIntentSpans: []roachpb.Span{{Key: keyA}, {Key: keyB}, {Key: keyC}},
},
{
reqs: []roachpb.Request{qi1, put2, scan3, et},
expIFW: nil,
expIntentSpans: []roachpb.Span{{Key: keyA}, {Key: keyB}, {Key: keyC}},
},
{
reqs: []roachpb.Request{qi1, put2, delRng3, scan3, et},
expIFW: nil,
expIntentSpans: []roachpb.Span{{Key: keyA}, {Key: keyB}, {Key: keyC}},
},
}
for _, c := range testCases {
var ba roachpb.BatchRequest
ba.Add(c.reqs...)
t.Run(fmt.Sprint(ba), func(t *testing.T) {
resBa, err := maybeStripInFlightWrites(&ba)
if c.expErr == "" {
if err != nil {
t.Errorf("expected no error, got %v", err)
}
resArgs, _ := resBa.GetArg(roachpb.EndTransaction)
resEt := resArgs.(*roachpb.EndTransactionRequest)
if !reflect.DeepEqual(resEt.InFlightWrites, c.expIFW) {
t.Errorf("expected in-flight writes %v, got %v", c.expIFW, resEt.InFlightWrites)
}
if !reflect.DeepEqual(resEt.IntentSpans, c.expIntentSpans) {
t.Errorf("expected intent spans %v, got %v", c.expIntentSpans, resEt.IntentSpans)
}
} else {
if !testutils.IsError(err, c.expErr) {
t.Errorf("expected error %q, got %v", c.expErr, err)
}
}
})
}
}
// 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{Commit: true})
txnReqsNoRefresh := make([]roachpb.RequestUnion, 3)
txnReqsNoRefresh[0].MustSetInner(&roachpb.BeginTransactionRequest{})
txnReqsNoRefresh[1].MustSetInner(&roachpb.PutRequest{})
txnReqsNoRefresh[2].MustSetInner(&roachpb.EndTransactionRequest{Commit: true, NoRefreshSpans: true})
testCases := []struct {
bu []roachpb.RequestUnion
isTxn bool
isWTO bool
isTSOff bool
exp1PC bool
}{
{[]roachpb.RequestUnion{}, false, false, false, false},
{[]roachpb.RequestUnion{}, true, false, false, false},
{[]roachpb.RequestUnion{{Value: &roachpb.RequestUnion_Get{Get: &roachpb.GetRequest{}}}}, true, false, false, false},
{[]roachpb.RequestUnion{{Value: &roachpb.RequestUnion_Put{Put: &roachpb.PutRequest{}}}}, true, false, false, false},
{txnReqs[0 : len(txnReqs)-1], true, false, false, false},
{txnReqs[1:], true, false, false, false},
{txnReqs, true, false, false, true},
{txnReqs, true, true, false, false},
{txnReqs, true, false, true, false},
{txnReqs, true, true, true, false},
{txnReqsNoRefresh, true, false, false, true},
{txnReqsNoRefresh, true, true, false, true},
{txnReqsNoRefresh, true, false, true, true},
{txnReqsNoRefresh, true, true, true, true},
}
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, clock)
if c.isWTO {
ba.Txn.WriteTooOld = true
}
if c.isTSOff {
ba.Txn.Timestamp = ba.Txn.OrigTimestamp.Add(1, 0)
}
}
if is1PC := isOnePhaseCommit(&ba, &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.evalAndPropose(context.TODO(), exLease, &ba, &allSpans, endCmds{})
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: %+v", err)
}
// Try a read commmitted read and an inconsistent read, both within a
// transaction.
txn := newTransaction("test", roachpb.Key("a"), 1, 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 := checkForcedErr(
context.Background(), makeIDKey(), &raftCmd, nil /* proposal */, false, /* proposedLocally */
&tc.repl.mu.state,
)
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())
var filterErr atomic.Value
applyFilter := func(args storagebase.ApplyFilterArgs) (int, *roachpb.Error) {
if pErr := filterErr.Load(); pErr != nil {
return 0, pErr.(*roachpb.Error)
}
return 0, nil
}
tc.manualClock = hlc.NewManualClock(123)
tsc := TestStoreConfig(hlc.NewClock(tc.manualClock.UnixNano, time.Nanosecond))
tsc.TestingKnobs.DisableAutomaticLeaseRenewal = true
tsc.TestingKnobs.TestingApplyFilter = applyFilter
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),