-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
store_test.go
3377 lines (3073 loc) · 111 KB
/
store_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"
"sort"
"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/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
"github.com/cockroachdb/cockroach/pkg/storage/abortspan"
"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/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/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/uuid"
"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"
"golang.org/x/time/rate"
)
var testIdent = roachpb.StoreIdent{
ClusterID: uuid.MakeV4(),
NodeID: 1,
StoreID: 1,
}
func (s *Store) TestSender() client.Sender {
return client.Wrap(s, func(ba roachpb.BatchRequest) roachpb.BatchRequest {
if ba.RangeID != 0 {
return ba
}
// If the client hasn't set ba.Range, we do it a favor and figure out the
// range to which the request needs to go.
//
// NOTE: We don't use keys.Range(ba.Requests) here because that does some
// validation on the batch, and some tests using this sender don't like
// that.
key, err := keys.Addr(ba.Requests[0].GetInner().Header().Key)
if err != nil {
log.Fatal(context.TODO(), err)
}
ba.RangeID = roachpb.RangeID(1)
if repl := s.LookupReplica(key); repl != nil {
ba.RangeID = repl.RangeID
// Attempt to assign a Replica descriptor to the batch if
// necessary, but don't throw an error if this fails.
if ba.Replica == (roachpb.ReplicaDescriptor{}) {
if desc, err := repl.GetReplicaDescriptor(); err == nil {
ba.Replica = desc
}
}
}
return ba
})
}
// testSenderFactory is an implementation of the
// client.TxnSenderFactory interface.
type testSenderFactory struct {
store *Store
nonTxnSender *testSender
}
func (f *testSenderFactory) TransactionalSender(
typ client.TxnType, coordMeta roachpb.TxnCoordMeta,
) client.TxnSender {
return client.NewMockTransactionalSender(
func(
ctx context.Context, _ *roachpb.Transaction, ba roachpb.BatchRequest,
) (*roachpb.BatchResponse, *roachpb.Error) {
return f.store.Send(ctx, ba)
},
&coordMeta.Txn)
}
func (f *testSenderFactory) NonTransactionalSender() client.Sender {
if f.nonTxnSender != nil {
return f.nonTxnSender
}
f.nonTxnSender = &testSender{store: f.store}
return f.nonTxnSender
}
func (f *testSenderFactory) setStore(s *Store) {
f.store = s
if f.nonTxnSender != nil {
// monkey-patch an already created Sender, helping with test bootstrapping.
f.nonTxnSender.store = s
}
}
// testSender is an implementation of the client.TxnSender interface
// which passes all requests through to a single store.
type testSender struct {
store *Store
}
// Send forwards the call to the single store. This is a poor man's
// version of kv.TxnCoordSender, but it serves the purposes of
// supporting tests in this package. Transactions are not supported.
// Since kv/ depends on storage/, we can't get access to a
// TxnCoordSender from here.
// TODO(tschottdorf): {kv->storage}.LocalSender
func (db *testSender) Send(
ctx context.Context, ba roachpb.BatchRequest,
) (*roachpb.BatchResponse, *roachpb.Error) {
if et, ok := ba.GetArg(roachpb.EndTransaction); ok {
return nil, roachpb.NewErrorf("%s method not supported", et.Method())
}
// Lookup range and direct request.
rs, err := keys.Range(ba.Requests)
if err != nil {
return nil, roachpb.NewError(err)
}
repl := db.store.LookupReplica(rs.Key)
if repl == nil || !repl.Desc().ContainsKeyRange(rs.Key, rs.EndKey) {
return nil, roachpb.NewError(roachpb.NewRangeKeyMismatchError(rs.Key.AsRawKey(), rs.EndKey.AsRawKey(), nil))
}
ba.RangeID = repl.RangeID
repDesc, err := repl.GetReplicaDescriptor()
if err != nil {
return nil, roachpb.NewError(err)
}
ba.Replica = repDesc
br, pErr := db.store.Send(ctx, ba)
if br != nil && br.Error != nil {
panic(roachpb.ErrorUnexpectedlySet(db.store, br))
}
if pErr != nil {
return nil, pErr
}
return br, nil
}
// testStoreOpts affords control over aspects of store creation.
type testStoreOpts struct {
// If createSystemRanges is not set, the store will have a single range. If
// set, the store will have all the system ranges that are generally created
// for a cluster at boostrap.
createSystemRanges bool
}
// createTestStoreWithoutStart creates a test store using an in-memory
// engine without starting the store. It returns the store, the store
// clock's manual unix nanos time and a stopper. The caller is
// responsible for stopping the stopper upon completion.
// Some fields of ctx are populated by this function.
func createTestStoreWithoutStart(
t testing.TB, stopper *stop.Stopper, opts testStoreOpts, cfg *StoreConfig,
) *Store {
// Setup fake zone config handler.
config.TestingSetupZoneConfigHook(stopper)
rpcContext := rpc.NewContext(
cfg.AmbientCtx, &base.Config{Insecure: true}, cfg.Clock,
stopper, &cfg.Settings.Version)
server := rpc.NewServer(rpcContext) // never started
cfg.Gossip = gossip.NewTest(1, rpcContext, server, stopper, metric.NewRegistry(), cfg.DefaultZoneConfig)
cfg.StorePool = NewTestStorePool(*cfg)
// Many tests using this test harness (as opposed to higher-level
// ones like multiTestContext or TestServer) want to micro-manage
// replicas and the background queues just get in the way. The
// scanner doesn't run frequently enough to expose races reliably,
// so just disable the scanner for all tests that use this function
// instead of figuring out exactly which tests need it.
cfg.TestingKnobs.DisableScanner = true
// The scanner affects background operations; we must also disable the split
// and merge queues separately to cover event-driven splits and merges.
cfg.TestingKnobs.DisableSplitQueue = true
cfg.TestingKnobs.DisableMergeQueue = true
eng := engine.NewInMem(roachpb.Attributes{}, 10<<20)
stopper.AddCloser(eng)
cfg.Transport = NewDummyRaftTransport(cfg.Settings)
factory := &testSenderFactory{}
cfg.DB = client.NewDB(cfg.AmbientCtx, factory, cfg.Clock)
store := NewStore(context.TODO(), *cfg, eng, &roachpb.NodeDescriptor{NodeID: 1})
factory.setStore(store)
if err := InitEngine(
context.TODO(), eng, roachpb.StoreIdent{NodeID: 1, StoreID: 1}, cfg.Settings.Version.BootstrapVersion(),
); err != nil {
t.Fatal(err)
}
var splits []roachpb.RKey
kvs, tableSplits := sqlbase.MakeMetadataSchema(cfg.DefaultZoneConfig, cfg.DefaultSystemZoneConfig).GetInitialValues()
if opts.createSystemRanges {
splits = config.StaticSplits()
splits = append(splits, tableSplits...)
sort.Slice(splits, func(i, j int) bool {
return splits[i].Less(splits[j])
})
}
if err := WriteInitialClusterData(
context.TODO(), eng, kvs /* initialValues */, cfg.Settings.Version.BootstrapVersion().Version,
1 /* numStores */, splits, cfg.Clock.PhysicalNow(),
); err != nil {
t.Fatal(err)
}
return store
}
func createTestStore(
t testing.TB, opts testStoreOpts, stopper *stop.Stopper,
) (*Store, *hlc.ManualClock) {
manual := hlc.NewManualClock(123)
cfg := TestStoreConfig(hlc.NewClock(manual.UnixNano, time.Nanosecond))
store := createTestStoreWithConfig(t, stopper, opts, &cfg)
return store, manual
}
// createTestStore creates a test store using an in-memory
// engine. It returns the store, the store clock's manual unix nanos time
// and a stopper. The caller is responsible for stopping the stopper
// upon completion.
func createTestStoreWithConfig(
t testing.TB, stopper *stop.Stopper, opts testStoreOpts, cfg *StoreConfig,
) *Store {
store := createTestStoreWithoutStart(t, stopper, opts, cfg)
// Put an empty system config into gossip.
if err := store.Gossip().AddInfoProto(gossip.KeySystemConfig,
&config.SystemConfigEntries{}, 0); err != nil {
t.Fatal(err)
}
if err := store.Start(context.Background(), stopper); err != nil {
t.Fatal(err)
}
store.WaitForInit()
return store
}
// TestIterateIDPrefixKeys lays down a number of tombstones (at keys.RaftTombstoneKey) interspersed
// with other irrelevant keys (both chosen randomly). It then verifies that IterateIDPrefixKeys
// correctly returns only the relevant keys and values.
func TestIterateIDPrefixKeys(t *testing.T) {
defer leaktest.AfterTest(t)()
ctx := context.Background()
stopper := stop.NewStopper()
defer stopper.Stop(ctx)
eng := engine.NewInMem(roachpb.Attributes{}, 1<<20)
stopper.AddCloser(eng)
seed := randutil.NewPseudoSeed()
//const seed = -1666367124291055473
t.Logf("seed is %d", seed)
rng := rand.New(rand.NewSource(seed))
ops := []func(rangeID roachpb.RangeID) roachpb.Key{
keys.RaftAppliedIndexLegacyKey, // replicated; sorts before tombstone
keys.RaftHardStateKey, // unreplicated; sorts after tombstone
// Replicated key-anchored local key (i.e. not one we should care about).
// Will be written at zero timestamp, but that's ok.
func(rangeID roachpb.RangeID) roachpb.Key {
return keys.RangeDescriptorKey([]byte(fmt.Sprintf("fakerange%d", rangeID)))
},
func(rangeID roachpb.RangeID) roachpb.Key {
return roachpb.Key(fmt.Sprintf("fakeuserkey%d", rangeID))
},
}
const rangeCount = 10
rangeIDFn := func() roachpb.RangeID {
return 1 + roachpb.RangeID(rng.Intn(10*rangeCount)) // spread rangeIDs out
}
// Write a number of keys that should be irrelevant to the iteration in this test.
for i := 0; i < rangeCount; i++ {
rangeID := rangeIDFn()
// Grab between one and all ops, randomly.
for _, opIdx := range rng.Perm(len(ops))[:rng.Intn(1+len(ops))] {
key := ops[opIdx](rangeID)
t.Logf("writing op=%d rangeID=%d", opIdx, rangeID)
if err := engine.MVCCPut(
ctx,
eng,
nil, /* ms */
key,
hlc.Timestamp{},
roachpb.MakeValueFromString("fake value for "+key.String()),
nil, /* txn */
); err != nil {
t.Fatal(err)
}
}
}
type seenT struct {
rangeID roachpb.RangeID
tombstone roachpb.RaftTombstone
}
// Next, write the keys we're planning to see again.
var wanted []seenT
{
used := make(map[roachpb.RangeID]struct{})
for {
rangeID := rangeIDFn()
if _, ok := used[rangeID]; ok {
// We already wrote this key, so roll the dice again.
continue
}
tombstone := roachpb.RaftTombstone{
NextReplicaID: roachpb.ReplicaID(rng.Int31n(100)),
}
used[rangeID] = struct{}{}
wanted = append(wanted, seenT{rangeID: rangeID, tombstone: tombstone})
t.Logf("writing tombstone at rangeID=%d", rangeID)
if err := engine.MVCCPutProto(
ctx, eng, nil /* ms */, keys.RaftTombstoneKey(rangeID), hlc.Timestamp{}, nil /* txn */, &tombstone,
); err != nil {
t.Fatal(err)
}
if len(wanted) >= rangeCount {
break
}
}
}
sort.Slice(wanted, func(i, j int) bool {
return wanted[i].rangeID < wanted[j].rangeID
})
var seen []seenT
var tombstone roachpb.RaftTombstone
handleTombstone := func(rangeID roachpb.RangeID) (more bool, _ error) {
seen = append(seen, seenT{rangeID: rangeID, tombstone: tombstone})
return true, nil
}
if err := IterateIDPrefixKeys(ctx, eng, keys.RaftTombstoneKey, &tombstone, handleTombstone); err != nil {
t.Fatal(err)
}
placeholder := seenT{
rangeID: roachpb.RangeID(9999),
}
if len(wanted) != len(seen) {
t.Errorf("wanted %d results, got %d", len(wanted), len(seen))
}
for len(wanted) < len(seen) {
wanted = append(wanted, placeholder)
}
for len(seen) < len(wanted) {
seen = append(seen, placeholder)
}
if diff := pretty.Diff(wanted, seen); len(diff) > 0 {
pretty.Ldiff(t, wanted, seen)
t.Fatal("diff(wanted, seen) is nonempty")
}
}
// TestStoreInitAndBootstrap verifies store initialization and bootstrap.
func TestStoreInitAndBootstrap(t *testing.T) {
defer leaktest.AfterTest(t)()
// We need a fixed clock to avoid LastUpdateNanos drifting on us.
cfg := TestStoreConfig(hlc.NewClock(func() int64 { return 123 }, time.Nanosecond))
stopper := stop.NewStopper()
ctx := context.TODO()
defer stopper.Stop(ctx)
eng := engine.NewInMem(roachpb.Attributes{}, 1<<20)
stopper.AddCloser(eng)
cfg.Transport = NewDummyRaftTransport(cfg.Settings)
factory := &testSenderFactory{}
cfg.DB = client.NewDB(cfg.AmbientCtx, factory, cfg.Clock)
{
store := NewStore(ctx, cfg, eng, &roachpb.NodeDescriptor{NodeID: 1})
// Can't start as haven't bootstrapped.
if err := store.Start(ctx, stopper); err == nil {
t.Error("expected failure starting un-bootstrapped store")
}
// Bootstrap with a fake ident.
if err := InitEngine(ctx, eng, testIdent, cfg.Settings.Version.BootstrapVersion()); err != nil {
t.Errorf("error bootstrapping store: %+v", err)
}
// Verify we can read the store ident after a flush.
if err := eng.Flush(); err != nil {
t.Fatal(err)
}
if _, err := ReadStoreIdent(ctx, eng); err != nil {
t.Fatalf("unable to read store ident: %+v", err)
}
// Bootstrap the system ranges.
var splits []roachpb.RKey
kvs, tableSplits := sqlbase.MakeMetadataSchema(cfg.DefaultZoneConfig, cfg.DefaultSystemZoneConfig).GetInitialValues()
splits = config.StaticSplits()
splits = append(splits, tableSplits...)
sort.Slice(splits, func(i, j int) bool {
return splits[i].Less(splits[j])
})
if err := WriteInitialClusterData(
ctx, eng, kvs /* initialValues */, cfg.Settings.Version.BootstrapVersion().Version,
1 /* numStores */, splits, cfg.Clock.PhysicalNow(),
); err != nil {
t.Errorf("failure to create first range: %+v", err)
}
}
// Now, attempt to initialize a store with a now-bootstrapped range.
store := NewStore(ctx, cfg, eng, &roachpb.NodeDescriptor{NodeID: 1})
if err := store.Start(ctx, stopper); err != nil {
t.Fatalf("failure initializing bootstrapped store: %+v", err)
}
for i := 1; i <= store.ReplicaCount(); i++ {
r, err := store.GetReplica(roachpb.RangeID(i))
if err != nil {
t.Fatalf("failure fetching range %d: %+v", i, err)
}
rs := r.GetMVCCStats()
// Stats should agree with a recomputation.
now := r.store.Clock().Now()
if ms, err := rditer.ComputeStatsForRange(r.Desc(), eng, now.WallTime); err != nil {
t.Errorf("failure computing range's stats: %+v", err)
} else if ms != rs {
t.Errorf("expected range's stats to agree with recomputation: %s", pretty.Diff(ms, rs))
}
}
}
// TestBootstrapOfNonEmptyStore verifies bootstrap failure if engine
// is not empty.
func TestBootstrapOfNonEmptyStore(t *testing.T) {
defer leaktest.AfterTest(t)()
stopper := stop.NewStopper()
ctx := context.TODO()
defer stopper.Stop(ctx)
eng := engine.NewInMem(roachpb.Attributes{}, 1<<20)
stopper.AddCloser(eng)
// Put some random garbage into the engine.
if err := eng.Put(engine.MakeMVCCMetadataKey(roachpb.Key("foo")), []byte("bar")); err != nil {
t.Errorf("failure putting key foo into engine: %+v", err)
}
cfg := TestStoreConfig(nil)
cfg.Transport = NewDummyRaftTransport(cfg.Settings)
store := NewStore(ctx, cfg, eng, &roachpb.NodeDescriptor{NodeID: 1})
// Can't init as haven't bootstrapped.
switch err := errors.Cause(store.Start(ctx, stopper)); err.(type) {
case *NotBootstrappedError:
default:
t.Errorf("unexpected error initializing un-bootstrapped store: %+v", err)
}
// Bootstrap should fail on non-empty engine.
switch err := errors.Cause(InitEngine(ctx, eng, testIdent, cfg.Settings.Version.BootstrapVersion())); err.(type) {
case *NotBootstrappedError:
default:
t.Errorf("unexpected error bootstrapping non-empty store: %+v", err)
}
}
// create a Replica and add it to the store. Note that replicas
// created in this way do not have their raft groups fully initialized
// so most KV operations will not work on them. This function is
// deprecated; new tests should create replicas by splitting from a
// properly-bootstrapped initial range.
func createReplica(s *Store, rangeID roachpb.RangeID, start, end roachpb.RKey) *Replica {
desc := &roachpb.RangeDescriptor{
RangeID: rangeID,
StartKey: start,
EndKey: end,
InternalReplicas: []roachpb.ReplicaDescriptor{{
NodeID: 1,
StoreID: 1,
ReplicaID: 1,
}},
NextReplicaID: 2,
}
r, err := NewReplica(desc, s, 0)
if err != nil {
log.Fatal(context.Background(), err)
}
return r
}
func TestStoreAddRemoveRanges(t *testing.T) {
defer leaktest.AfterTest(t)()
stopper := stop.NewStopper()
defer stopper.Stop(context.TODO())
store, _ := createTestStore(t,
testStoreOpts{
// This test was written before test stores could start with more than one
// range and was not adapted.
createSystemRanges: false,
},
stopper)
if _, err := store.GetReplica(0); err == nil {
t.Error("expected GetRange to fail on missing range")
}
// Range 1 already exists. Make sure we can fetch it.
repl1, err := store.GetReplica(1)
if err != nil {
t.Error(err)
}
// Remove range 1.
if err := store.RemoveReplica(context.Background(), repl1, repl1.Desc().NextReplicaID, RemoveOptions{
DestroyData: true,
}); err != nil {
t.Error(err)
}
// Create a new range (id=2).
repl2 := createReplica(store, 2, roachpb.RKey("a"), roachpb.RKey("b"))
if err := store.AddReplica(repl2); err != nil {
t.Fatal(err)
}
// Try to add the same range twice
err = store.AddReplica(repl2)
if err == nil {
t.Fatal("expected error re-adding same range")
}
// Try to remove range 1 again.
if err := store.RemoveReplica(context.Background(), repl1, repl1.Desc().NextReplicaID, RemoveOptions{
DestroyData: true,
}); err != nil {
t.Fatalf("didn't expected error re-removing same range: %v", err)
}
// Try to add a range with previously-used (but now removed) ID.
repl2Dup := createReplica(store, 1, roachpb.RKey("a"), roachpb.RKey("b"))
if err := store.AddReplica(repl2Dup); err == nil {
t.Fatal("expected error inserting a duplicated range")
}
// Add another range with different key range and then test lookup.
repl3 := createReplica(store, 3, roachpb.RKey("c"), roachpb.RKey("d"))
if err := store.AddReplica(repl3); err != nil {
t.Fatal(err)
}
testCases := []struct {
key roachpb.RKey
expRng *Replica
}{
{roachpb.RKey("a"), repl2},
{roachpb.RKey("a\xff\xff"), repl2},
{roachpb.RKey("c"), repl3},
{roachpb.RKey("c\xff\xff"), repl3},
{roachpb.RKey("x60\xff\xff"), nil},
{roachpb.RKey("x60\xff\xff"), nil},
{roachpb.RKey("d"), nil},
}
for i, test := range testCases {
if r := store.LookupReplica(test.key); r != test.expRng {
t.Errorf("%d: expected range %v; got %v", i, test.expRng, r)
}
}
}
// TestReplicasByKey tests that operations that depend on the
// store.replicasByKey map function correctly when the underlying replicas'
// start and end keys are manipulated in place. This mutation happens when a
// snapshot is applied that advances a replica past a split.
func TestReplicasByKey(t *testing.T) {
defer leaktest.AfterTest(t)()
stopper := stop.NewStopper()
defer stopper.Stop(context.TODO())
store, _ := createTestStore(t,
testStoreOpts{
// This test was written before test stores could start with more than one
// range and was not adapted.
createSystemRanges: false,
},
stopper)
// Shrink the main replica.
rep, err := store.GetReplica(1)
if err != nil {
t.Fatal(err)
}
rep.mu.Lock()
desc := *rep.mu.state.Desc // shallow copy to replace desc wholesale
desc.EndKey = roachpb.RKey("e")
rep.mu.state.Desc = &desc
rep.mu.Unlock()
// Ensure that this shrinkage is recognized by future additions to replicasByKey.
reps := []*struct {
replica *Replica
id int
start, end roachpb.RKey
expectedErrorOnAdd string
}{
// [a,c) is contained in [KeyMin, e)
{nil, 2, roachpb.RKey("a"), roachpb.RKey("c"), ".*has overlapping range"},
// [c,f) partially overlaps with [KeyMin, e)
{nil, 3, roachpb.RKey("c"), roachpb.RKey("f"), ".*has overlapping range"},
// [e, f) is disjoint from [KeyMin, e)
{nil, 4, roachpb.RKey("e"), roachpb.RKey("f"), ""},
}
for i, desc := range reps {
desc.replica = createReplica(store, roachpb.RangeID(desc.id), desc.start, desc.end)
err := store.AddReplica(desc.replica)
if !testutils.IsError(err, desc.expectedErrorOnAdd) {
t.Fatalf("adding replica %d: expected err %q, but encountered %v", i, desc.expectedErrorOnAdd, err)
}
}
}
func TestStoreRemoveReplicaOldDescriptor(t *testing.T) {
defer leaktest.AfterTest(t)()
ctx := context.Background()
stopper := stop.NewStopper()
defer stopper.Stop(ctx)
store, _ := createTestStore(t, testStoreOpts{createSystemRanges: true}, stopper)
rep, err := store.GetReplica(1)
if err != nil {
t.Fatal(err)
}
// First try and fail with a stale descriptor.
origDesc := rep.Desc()
newDesc := protoutil.Clone(origDesc).(*roachpb.RangeDescriptor)
for i := range newDesc.InternalReplicas {
if newDesc.InternalReplicas[i].StoreID == store.StoreID() {
newDesc.InternalReplicas[i].ReplicaID++
newDesc.NextReplicaID++
break
}
}
rep.setDesc(ctx, newDesc)
expectedErr := "replica descriptor's ID has changed"
if err := store.RemoveReplica(ctx, rep, origDesc.NextReplicaID, RemoveOptions{
DestroyData: true,
}); !testutils.IsError(err, expectedErr) {
t.Fatalf("expected error %q but got %v", expectedErr, err)
}
// Now try a fresh descriptor and succeed.
if err := store.RemoveReplica(ctx, rep, rep.Desc().NextReplicaID, RemoveOptions{
DestroyData: true,
}); err != nil {
t.Fatal(err)
}
}
func TestStoreRemoveReplicaDestroy(t *testing.T) {
defer leaktest.AfterTest(t)()
stopper := stop.NewStopper()
defer stopper.Stop(context.TODO())
store, _ := createTestStore(t, testStoreOpts{createSystemRanges: true}, stopper)
repl1, err := store.GetReplica(1)
if err != nil {
t.Fatal(err)
}
if err := store.RemoveReplica(context.Background(), repl1, repl1.Desc().NextReplicaID, RemoveOptions{
DestroyData: true,
}); err != nil {
t.Fatal(err)
}
// Verify that removal of a replica marks it as destroyed so that future raft
// commands on the Replica will silently be dropped.
if err := repl1.withRaftGroup(true, func(r *raft.RawNode) (bool, error) {
return true, errors.Errorf("unexpectedly created a raft group")
}); err != nil {
t.Fatal(err)
}
repl1.mu.Lock()
expErr := roachpb.NewError(repl1.mu.destroyStatus.err)
lease := *repl1.mu.state.Lease
repl1.mu.Unlock()
if expErr == nil {
t.Fatal("replica was not marked as destroyed")
}
if _, _, _, pErr := repl1.evalAndPropose(
context.Background(), lease, &roachpb.BatchRequest{}, &allSpans, endCmds{},
); !pErr.Equal(expErr) {
t.Fatalf("expected error %s, but got %v", expErr, pErr)
}
}
func TestStoreReplicaVisitor(t *testing.T) {
defer leaktest.AfterTest(t)()
stopper := stop.NewStopper()
defer stopper.Stop(context.TODO())
store, _ := createTestStore(t,
testStoreOpts{
// This test was written before test stores could start with more than one
// range and was not adapted.
createSystemRanges: false,
},
stopper)
// Remove range 1.
repl1, err := store.GetReplica(1)
if err != nil {
t.Error(err)
}
if err := store.RemoveReplica(context.Background(), repl1, repl1.Desc().NextReplicaID, RemoveOptions{
DestroyData: true,
}); err != nil {
t.Error(err)
}
// Add 10 new ranges.
const newCount = 10
for i := 0; i < newCount; i++ {
repl := createReplica(store, roachpb.RangeID(i+1), roachpb.RKey(fmt.Sprintf("a%02d", i)), roachpb.RKey(fmt.Sprintf("a%02d", i+1)))
if err := store.AddReplica(repl); err != nil {
t.Fatal(err)
}
}
// Verify two passes of the visit, the second one in-order.
visitor := newStoreReplicaVisitor(store)
exp := make(map[roachpb.RangeID]struct{})
for i := 0; i < newCount; i++ {
exp[roachpb.RangeID(i+1)] = struct{}{}
}
for pass := 0; pass < 2; pass++ {
if ec := visitor.EstimatedCount(); ec != 10 {
t.Fatalf("expected 10 remaining; got %d", ec)
}
i := 1
seen := make(map[roachpb.RangeID]struct{})
// Ensure that our next pass is done in-order.
if pass == 1 {
_ = visitor.InOrder()
}
var lastRangeID roachpb.RangeID
visitor.Visit(func(repl *Replica) bool {
if pass == 1 {
if repl.RangeID <= lastRangeID {
t.Fatalf("on second pass, expect ranges to be visited in ascending range ID order; %d !> %d", repl.RangeID, lastRangeID)
}
lastRangeID = repl.RangeID
}
_, ok := seen[repl.RangeID]
if ok {
t.Fatalf("already saw %d", repl.RangeID)
}
seen[repl.RangeID] = struct{}{}
if ec := visitor.EstimatedCount(); ec != 10-i {
t.Fatalf(
"expected %d remaining; got %d after seeing %+v",
10-i, ec, seen,
)
}
i++
return true
})
if ec := visitor.EstimatedCount(); ec != 10 {
t.Fatalf("expected 10 remaining; got %d", ec)
}
if !reflect.DeepEqual(exp, seen) {
t.Fatalf("got %v, expected %v", seen, exp)
}
}
}
func TestHasOverlappingReplica(t *testing.T) {
defer leaktest.AfterTest(t)()
stopper := stop.NewStopper()
defer stopper.Stop(context.TODO())
store, _ := createTestStore(t,
testStoreOpts{
// This test was written before test stores could start with more than one
// range and was not adapted.
createSystemRanges: false,
},
stopper)
if _, err := store.GetReplica(0); err == nil {
t.Error("expected GetRange to fail on missing range")
}
// Range 1 already exists. Make sure we can fetch it.
repl1, err := store.GetReplica(1)
if err != nil {
t.Error(err)
}
// Remove range 1.
if err := store.RemoveReplica(context.Background(), repl1, repl1.Desc().NextReplicaID, RemoveOptions{
DestroyData: true,
}); err != nil {
t.Error(err)
}
// Create ranges.
rngDescs := []struct {
id int
start, end roachpb.RKey
}{
{2, roachpb.RKey("b"), roachpb.RKey("c")},
{3, roachpb.RKey("c"), roachpb.RKey("d")},
{4, roachpb.RKey("d"), roachpb.RKey("f")},
}
for _, desc := range rngDescs {
repl := createReplica(store, roachpb.RangeID(desc.id), desc.start, desc.end)
if err := store.AddReplica(repl); err != nil {
t.Fatal(err)
}
}
testCases := []struct {
start, end roachpb.RKey
exp bool
}{
{roachpb.RKey("a"), roachpb.RKey("c"), true},
{roachpb.RKey("b"), roachpb.RKey("c"), true},
{roachpb.RKey("b"), roachpb.RKey("d"), true},
{roachpb.RKey("d"), roachpb.RKey("e"), true},
{roachpb.RKey("d"), roachpb.RKey("g"), true},
{roachpb.RKey("e"), roachpb.RKey("e\x00"), true},
{roachpb.RKey("f"), roachpb.RKey("g"), false},
{roachpb.RKey("a"), roachpb.RKey("b"), false},
}
for i, test := range testCases {
rngDesc := &roachpb.RangeDescriptor{StartKey: test.start, EndKey: test.end}
if r := store.getOverlappingKeyRangeLocked(rngDesc) != nil; r != test.exp {
t.Errorf("%d: expected range %v; got %v", i, test.exp, r)
}
}
}
func TestLookupPrecedingReplica(t *testing.T) {
defer leaktest.AfterTest(t)()
ctx := context.Background()
stopper := stop.NewStopper()
defer stopper.Stop(ctx)
store, _ := createTestStore(t,
testStoreOpts{
// This test was written before test stores could start with more than one
// range and was not adapted.
createSystemRanges: false,
},
stopper)
// Clobber the existing range so we can test ranges that aren't KeyMin or
// KeyMax.
repl1, err := store.GetReplica(1)
if err != nil {
t.Fatal(err)
}
if err := store.RemoveReplica(ctx, repl1, repl1.Desc().NextReplicaID, RemoveOptions{
DestroyData: true,
}); err != nil {
t.Fatal(err)
}
repl2 := createReplica(store, 2, roachpb.RKey("a"), roachpb.RKey("b"))
if err := store.AddReplica(repl2); err != nil {
t.Fatal(err)
}
repl3 := createReplica(store, 3, roachpb.RKey("b"), roachpb.RKey("c"))
if err := store.AddReplica(repl3); err != nil {
t.Fatal(err)
}
if err := store.addPlaceholder(&ReplicaPlaceholder{rangeDesc: roachpb.RangeDescriptor{
RangeID: 4, StartKey: roachpb.RKey("c"), EndKey: roachpb.RKey("d"),
}}); err != nil {
t.Fatal(err)
}
repl5 := createReplica(store, 5, roachpb.RKey("e"), roachpb.RKey("f"))
if err := store.AddReplica(repl5); err != nil {
t.Fatal(err)
}
for i, tc := range []struct {
key roachpb.RKey
expRepl *Replica
}{
{roachpb.RKeyMin, nil},
{roachpb.RKey("a"), nil},
{roachpb.RKey("aa"), nil},
{roachpb.RKey("b"), repl2},
{roachpb.RKey("bb"), repl2},
{roachpb.RKey("c"), repl3},
{roachpb.RKey("cc"), repl3},
{roachpb.RKey("d"), repl3},
{roachpb.RKey("dd"), repl3},
{roachpb.RKey("e"), repl3},
{roachpb.RKey("ee"), repl3},
{roachpb.RKey("f"), repl5},
{roachpb.RKeyMax, repl5},
} {
if repl := store.lookupPrecedingReplica(tc.key); repl != tc.expRepl {
t.Errorf("%d: expected replica %v; got %v", i, tc.expRepl, repl)
}
}
}
func TestMaybeMarkReplicaInitialized(t *testing.T) {
defer leaktest.AfterTest(t)()
stopper := stop.NewStopper()
defer stopper.Stop(context.TODO())
store, _ := createTestStore(t,
testStoreOpts{
// This test was written before test stores could start with more than one
// range and was not adapted.
createSystemRanges: false,
},
stopper)
// Clobber the existing range so we can test overlaps that aren't KeyMin or KeyMax.
repl1, err := store.GetReplica(1)
if err != nil {
t.Error(err)
}
if err := store.RemoveReplica(context.Background(), repl1, repl1.Desc().NextReplicaID, RemoveOptions{
DestroyData: true,
}); err != nil {
t.Error(err)
}
repl := createReplica(store, roachpb.RangeID(2), roachpb.RKey("a"), roachpb.RKey("c"))
if err := store.AddReplica(repl); err != nil {
t.Fatal(err)
}
newRangeID := roachpb.RangeID(3)
desc := &roachpb.RangeDescriptor{
RangeID: newRangeID,
InternalReplicas: []roachpb.ReplicaDescriptor{{
NodeID: 1,
StoreID: 1,
ReplicaID: 1,
}},
NextReplicaID: 2,
}
r := &Replica{
RangeID: desc.RangeID,
store: store,
abortSpan: abortspan.New(desc.RangeID),
}
if err := r.init(desc, store.Clock(), 0); err != nil {
t.Fatal(err)
}