-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
store_test.go
2631 lines (2385 loc) · 85.2 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.
//
// 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.
//
// Author: Spencer Kimball ([email protected])
// Author: Matthew O'Connor ([email protected])
// Author: Zach Brock ([email protected])
package storage
import (
"bytes"
"fmt"
"math"
"reflect"
"sync/atomic"
"testing"
"time"
"github.com/coreos/etcd/raft"
"github.com/coreos/etcd/raft/raftpb"
"github.com/kr/pretty"
"github.com/pkg/errors"
"golang.org/x/net/context"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/build"
"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/engine"
"github.com/cockroachdb/cockroach/pkg/storage/engine/enginepb"
"github.com/cockroachdb/cockroach/pkg/storage/storagebase"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/util"
"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/retry"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
)
var defaultMuLogger = syncutil.ThresholdLogger(
context.Background(),
10*time.Second,
log.Warningf,
func(time.Duration) {},
)
var testIdent = roachpb.StoreIdent{
ClusterID: uuid.MakeV4(),
NodeID: 1,
StoreID: 1,
}
// testRetryOptions returns retry options with aggressive retries and a limit
// on number of attempts so we don't get stuck behind indefinite backoff/retry
// loops.
// Using this is generally considered bad taste and legacy.
func testRetryOptions() retry.Options {
return retry.Options{
InitialBackoff: 1 * time.Millisecond,
MaxBackoff: 2 * time.Millisecond,
Multiplier: 2,
MaxRetries: 1,
}
}
// testSender is an implementation of the client.Sender interface
// which passes all requests through to a single store.
type testSender struct {
store *Store
}
func (s *Store) testSender() client.Sender {
return client.Wrap(s, func(ba roachpb.BatchRequest) roachpb.BatchRequest {
if ba.RangeID == 0 {
ba.RangeID = 1
}
return ba
})
}
// 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)
if err != nil {
return nil, roachpb.NewError(err)
}
rng := db.store.LookupReplica(rs.Key, rs.EndKey)
if rng == nil {
return nil, roachpb.NewError(roachpb.NewRangeKeyMismatchError(rs.Key.AsRawKey(), rs.EndKey.AsRawKey(), nil))
}
ba.RangeID = rng.RangeID
repDesc, err := rng.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
}
// 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, cfg *StoreConfig) (*Store, *stop.Stopper) {
stopper := stop.NewStopper()
// Setup fake zone config handler.
config.TestingSetupZoneConfigHook(stopper)
defer func() {
if t.Failed() {
stopper.Stop()
}
}()
rpcContext := rpc.NewContext(log.AmbientContext{}, &base.Config{Insecure: true}, cfg.Clock, stopper)
server := rpc.NewServer(rpcContext) // never started
cfg.Gossip = gossip.NewTest(1, rpcContext, server, nil, stopper, metric.NewRegistry())
cfg.StorePool = NewStorePool(
log.AmbientContext{},
cfg.Gossip,
cfg.Clock,
rpcContext,
TestTimeUntilStoreDeadOff,
stopper,
)
eng := engine.NewInMem(roachpb.Attributes{}, 10<<20)
stopper.AddCloser(eng)
cfg.Transport = NewDummyRaftTransport()
sender := &testSender{}
cfg.DB = client.NewDB(sender)
store := NewStore(*cfg, eng, &roachpb.NodeDescriptor{NodeID: 1})
sender.store = store
if err := store.Bootstrap(roachpb.StoreIdent{NodeID: 1, StoreID: 1}); err != nil {
t.Fatal(err)
}
if err := store.BootstrapRange(nil); err != nil {
t.Fatal(err)
}
return store, stopper
}
func createTestStore(t testing.TB) (*Store, *hlc.ManualClock, *stop.Stopper) {
manual := hlc.NewManualClock(123)
cfg := TestStoreConfig(hlc.NewClock(manual.UnixNano, time.Nanosecond))
// 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 queue separately to cover event-driven splits.
cfg.TestingKnobs.DisableSplitQueue = true
store, stopper := createTestStoreWithConfig(t, &cfg)
return store, manual, stopper
}
// 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, cfg *StoreConfig) (*Store, *stop.Stopper) {
store, stopper := createTestStoreWithoutStart(t, cfg)
// Put an empty system config into gossip.
if err := store.Gossip().AddInfoProto(gossip.KeySystemConfig,
&config.SystemConfig{}, 0); err != nil {
t.Fatal(err)
}
if err := store.Start(context.Background(), stopper); err != nil {
t.Fatal(err)
}
store.WaitForInit()
return store, stopper
}
// 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()
defer stopper.Stop()
eng := engine.NewInMem(roachpb.Attributes{}, 1<<20)
stopper.AddCloser(eng)
cfg.Transport = NewDummyRaftTransport()
store := NewStore(cfg, eng, &roachpb.NodeDescriptor{NodeID: 1})
// Can't start as haven't bootstrapped.
if err := store.Start(context.Background(), stopper); err == nil {
t.Error("expected failure starting un-bootstrapped store")
}
// Bootstrap with a fake ident.
if err := store.Bootstrap(testIdent); err != nil {
t.Errorf("error bootstrapping store: %s", err)
}
// Verify we can read the store ident after a flush.
if err := eng.Flush(); err != nil {
t.Fatal(err)
}
if _, err := ReadStoreIdent(context.Background(), eng); err != nil {
t.Fatalf("unable to read store ident: %s", err)
}
// Try to get 1st range--non-existent.
if _, err := store.GetReplica(1); err == nil {
t.Error("expected error fetching non-existent range")
}
// Bootstrap first range.
if err := store.BootstrapRange(nil); err != nil {
t.Errorf("failure to create first range: %s", err)
}
// Now, attempt to initialize a store with a now-bootstrapped range.
store = NewStore(cfg, eng, &roachpb.NodeDescriptor{NodeID: 1})
if err := store.Start(context.Background(), stopper); err != nil {
t.Errorf("failure initializing bootstrapped store: %s", err)
}
// 1st range should be available.
r, err := store.GetReplica(1)
if err != nil {
t.Errorf("failure fetching 1st range: %s", err)
}
rs := r.GetMVCCStats()
// Stats should agree with a recomputation.
now := r.store.Clock().Now()
if ms, err := ComputeStatsForRange(r.Desc(), eng, now.WallTime); err != nil {
t.Errorf("failure computing range's stats: %s", 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()
defer stopper.Stop()
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: %s", err)
}
cfg := TestStoreConfig(nil)
cfg.Transport = NewDummyRaftTransport()
store := NewStore(cfg, eng, &roachpb.NodeDescriptor{NodeID: 1})
// Can't init as haven't bootstrapped.
switch err := errors.Cause(store.Start(context.Background(), 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(store.Bootstrap(testIdent)); 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,
Replicas: []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)()
store, _, stopper := createTestStore(t)
defer stopper.Stop()
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.
rng1, err := store.GetReplica(1)
if err != nil {
t.Error(err)
}
// Remove range 1.
if err := store.RemoveReplica(rng1, *rng1.Desc(), true); err != nil {
t.Error(err)
}
// Create a new range (id=2).
rng2 := createReplica(store, 2, roachpb.RKey("a"), roachpb.RKey("b"))
if err := store.AddReplica(rng2); err != nil {
t.Fatal(err)
}
// Try to add the same range twice
err = store.AddReplica(rng2)
if err == nil {
t.Fatal("expected error re-adding same range")
}
// Try to remove range 1 again.
if err := store.RemoveReplica(rng1, *rng1.Desc(), true); err == nil {
t.Fatal("expected error re-removing same range")
}
// Try to add a range with previously-used (but now removed) ID.
rng2Dup := createReplica(store, 1, roachpb.RKey("a"), roachpb.RKey("b"))
if err := store.AddReplica(rng2Dup); err == nil {
t.Fatal("expected error inserting a duplicated range")
}
// Add another range with different key range and then test lookup.
rng3 := createReplica(store, 3, roachpb.RKey("c"), roachpb.RKey("d"))
if err := store.AddReplica(rng3); err != nil {
t.Fatal(err)
}
testCases := []struct {
start, end roachpb.RKey
expRng *Replica
}{
{roachpb.RKey("a"), roachpb.RKey("a\x00"), rng2},
{roachpb.RKey("a"), roachpb.RKey("b"), rng2},
{roachpb.RKey("a\xff\xff"), roachpb.RKey("b"), rng2},
{roachpb.RKey("c"), roachpb.RKey("c\x00"), rng3},
{roachpb.RKey("c"), roachpb.RKey("d"), rng3},
{roachpb.RKey("c\xff\xff"), roachpb.RKey("d"), rng3},
{roachpb.RKey("x60\xff\xff"), roachpb.RKey("a"), nil},
{roachpb.RKey("x60\xff\xff"), roachpb.RKey("a\x00"), nil},
{roachpb.RKey("d"), roachpb.RKey("d"), nil},
{roachpb.RKey("c\xff\xff"), roachpb.RKey("d\x00"), nil},
{roachpb.RKey("a"), nil, rng2},
{roachpb.RKey("d"), nil, nil},
}
for i, test := range testCases {
if r := store.LookupReplica(test.start, test.end); 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)()
store, _, stopper := createTestStore(t)
defer stopper.Stop()
// 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 desc.expectedErrorOnAdd == "" {
if err != nil {
t.Fatalf("adding replica %d: expected success, but encountered %s", i, err)
}
} else {
if !testutils.IsError(err, desc.expectedErrorOnAdd) {
t.Fatalf("adding replica %d: expected err %s, but encountered %v", i, desc.expectedErrorOnAdd, err)
}
}
}
}
func TestStoreRemoveReplicaOldDescriptor(t *testing.T) {
defer leaktest.AfterTest(t)()
store, _, stopper := createTestStore(t)
defer stopper.Stop()
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.Replicas {
if newDesc.Replicas[i].StoreID == store.StoreID() {
newDesc.Replicas[i].ReplicaID++
newDesc.NextReplicaID++
break
}
}
if err := rep.setDesc(newDesc); err != nil {
t.Fatal(err)
}
if err := store.RemoveReplica(rep, *origDesc, true); !testutils.IsError(err, "replica ID has changed") {
t.Fatalf("expected error 'replica ID has changed' but got %v", err)
}
// Now try a fresh descriptor and succeed.
if err := store.RemoveReplica(rep, *rep.Desc(), true); err != nil {
t.Fatal(err)
}
}
func TestStoreRemoveReplicaDestroy(t *testing.T) {
defer leaktest.AfterTest(t)()
store, _, stopper := createTestStore(t)
defer stopper.Stop()
rng1, err := store.GetReplica(1)
if err != nil {
t.Fatal(err)
}
if err := store.RemoveReplica(rng1, *rng1.Desc(), 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 := rng1.withRaftGroup(func(r *raft.RawNode) (bool, error) {
return true, errors.Errorf("unexpectedly created a raft group")
}); err != nil {
t.Fatal(err)
}
rng1.mu.Lock()
expErr := rng1.mu.destroyed
rng1.mu.Unlock()
if expErr == nil {
t.Fatal("replica was not marked as destroyed")
}
if _, _, err := rng1.propose(
context.Background(), roachpb.BatchRequest{},
); err != expErr {
t.Fatalf("expected error %s, but got %v", expErr, err)
}
}
func TestStoreReplicaVisitor(t *testing.T) {
defer leaktest.AfterTest(t)()
store, _, stopper := createTestStore(t)
defer stopper.Stop()
// Remove range 1.
rng1, err := store.GetReplica(1)
if err != nil {
t.Error(err)
}
if err := store.RemoveReplica(rng1, *rng1.Desc(), true); err != nil {
t.Error(err)
}
// Add 10 new ranges.
const newCount = 10
for i := 0; i < newCount; i++ {
rng := 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(rng); err != nil {
t.Fatal(err)
}
}
// Verify two passes of the visit.
ranges := 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 := ranges.EstimatedCount(); ec != 10 {
t.Fatalf("expected 10 remaining; got %d", ec)
}
i := 1
seen := make(map[roachpb.RangeID]struct{})
ranges.Visit(func(rng *Replica) bool {
_, ok := seen[rng.RangeID]
if ok {
t.Fatalf("already saw %d", rng.RangeID)
}
seen[rng.RangeID] = struct{}{}
if ec := ranges.EstimatedCount(); ec != 10-i {
t.Fatalf(
"expected %d remaining; got %d after seeing %+v",
10-i, ec, seen,
)
}
i++
return true
})
if ec := ranges.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)()
store, _, stopper := createTestStore(t)
defer stopper.Stop()
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.
rng1, err := store.GetReplica(1)
if err != nil {
t.Error(err)
}
// Remove range 1.
if err := store.RemoveReplica(rng1, *rng1.Desc(), 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 {
rng := createReplica(store, roachpb.RangeID(desc.id), desc.start, desc.end)
if err := store.AddReplica(rng); 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 TestProcessRangeDescriptorUpdate(t *testing.T) {
defer leaktest.AfterTest(t)()
store, _, stopper := createTestStore(t)
defer stopper.Stop()
// Clobber the existing range so we can test overlaps that aren't KeyMin or KeyMax.
rng1, err := store.GetReplica(1)
if err != nil {
t.Error(err)
}
if err := store.RemoveReplica(rng1, *rng1.Desc(), true); err != nil {
t.Error(err)
}
rng := createReplica(store, roachpb.RangeID(2), roachpb.RKey("a"), roachpb.RKey("c"))
if err := store.AddReplica(rng); err != nil {
t.Fatal(err)
}
newRangeID := roachpb.RangeID(3)
desc := &roachpb.RangeDescriptor{
RangeID: newRangeID,
Replicas: []roachpb.ReplicaDescriptor{{
NodeID: 1,
StoreID: 1,
ReplicaID: 1,
}},
NextReplicaID: 2,
}
r := &Replica{
RangeID: desc.RangeID,
store: store,
abortCache: NewAbortCache(desc.RangeID),
}
r.mu.TimedMutex = syncutil.MakeTimedMutex(defaultMuLogger)
r.cmdQMu.TimedMutex = syncutil.MakeTimedMutex(defaultMuLogger)
if err := r.init(desc, store.Clock(), 0); err != nil {
t.Fatal(err)
}
expectedResult := "attempted to process uninitialized range.*"
if err := store.processRangeDescriptorUpdate(r); !testutils.IsError(err, expectedResult) {
t.Errorf("expected processRangeDescriptorUpdate with uninitialized replica to fail, got %v", err)
}
// Initialize the range with start and end keys.
r.mu.Lock()
r.mu.state.Desc.StartKey = roachpb.RKey("b")
r.mu.state.Desc.EndKey = roachpb.RKey("d")
r.mu.Unlock()
if err := store.processRangeDescriptorUpdateLocked(r); err != nil {
t.Errorf("expected processRangeDescriptorUpdate on a replica that's not in the uninit map to silently succeed, got %v", err)
}
store.mu.Lock()
store.mu.uninitReplicas[newRangeID] = r
store.mu.Unlock()
expectedResult = ".*cannot processRangeDescriptorUpdate.*"
if err := store.processRangeDescriptorUpdate(r); !testutils.IsError(err, expectedResult) {
t.Errorf("expected processRangeDescriptorUpdate with overlapping keys to fail, got %v", err)
}
}
// TestStoreSend verifies straightforward command execution
// of both a read-only and a read-write command.
func TestStoreSend(t *testing.T) {
defer leaktest.AfterTest(t)()
store, _, stopper := createTestStore(t)
defer stopper.Stop()
gArgs := getArgs([]byte("a"))
// Try a successful get request.
if _, pErr := client.SendWrapped(context.Background(), store.testSender(), &gArgs); pErr != nil {
t.Fatal(pErr)
}
pArgs := putArgs([]byte("a"), []byte("aaa"))
if _, pErr := client.SendWrapped(context.Background(), store.testSender(), &pArgs); pErr != nil {
t.Fatal(pErr)
}
}
// TestStoreObservedTimestamp verifies that execution of a transactional
// command on a Store always returns a timestamp observation, either per the
// error's or the response's transaction, as well as an originating NodeID.
func TestStoreObservedTimestamp(t *testing.T) {
defer leaktest.AfterTest(t)()
badKey := []byte("a")
goodKey := []byte("b")
desc := roachpb.ReplicaDescriptor{
NodeID: 5,
// not relevant
StoreID: 1,
ReplicaID: 2,
}
testCases := []struct {
key roachpb.Key
check func(int64, roachpb.Response, *roachpb.Error)
}{
{badKey,
func(wallNanos int64, _ roachpb.Response, pErr *roachpb.Error) {
if pErr == nil {
t.Fatal("expected an error")
}
txn := pErr.GetTxn()
if txn == nil || txn.ID == nil {
t.Fatalf("expected nontrivial transaction in %s", pErr)
}
if ts, _ := txn.GetObservedTimestamp(desc.NodeID); ts.WallTime != wallNanos {
t.Fatalf("unexpected observed timestamps, expected %d->%d but got map %+v",
desc.NodeID, wallNanos, txn.ObservedTimestamps)
}
if pErr.OriginNode != desc.NodeID {
t.Fatalf("unexpected OriginNode %d, expected %d",
pErr.OriginNode, desc.NodeID)
}
}},
{goodKey,
func(wallNanos int64, pReply roachpb.Response, pErr *roachpb.Error) {
if pErr != nil {
t.Fatal(pErr)
}
txn := pReply.Header().Txn
if txn == nil || txn.ID == nil {
t.Fatal("expected transactional response")
}
obs, _ := txn.GetObservedTimestamp(desc.NodeID)
if act, exp := obs.WallTime, wallNanos; exp != act {
t.Fatalf("unexpected observed wall time: %d, wanted %d", act, exp)
}
}},
}
for _, test := range testCases {
func() {
manual := hlc.NewManualClock(123)
cfg := TestStoreConfig(hlc.NewClock(manual.UnixNano, time.Nanosecond))
cfg.TestingKnobs.TestingCommandFilter =
func(filterArgs storagebase.FilterArgs) *roachpb.Error {
if bytes.Equal(filterArgs.Req.Header().Key, badKey) {
return roachpb.NewError(errors.Errorf("boom"))
}
return nil
}
store, stopper := createTestStoreWithConfig(t, &cfg)
defer stopper.Stop()
txn := newTransaction("test", test.key, 1, enginepb.SERIALIZABLE, store.cfg.Clock)
txn.MaxTimestamp = hlc.MaxTimestamp
pArgs := putArgs(test.key, []byte("value"))
h := roachpb.Header{
Txn: txn,
Replica: desc,
}
pReply, pErr := client.SendWrappedWith(context.Background(), store.testSender(), h, &pArgs)
test.check(manual.UnixNano(), pReply, pErr)
}()
}
}
// TestStoreAnnotateNow verifies that the Store sets Now on the batch responses.
func TestStoreAnnotateNow(t *testing.T) {
defer leaktest.AfterTest(t)()
badKey := []byte("a")
goodKey := []byte("b")
desc := roachpb.ReplicaDescriptor{
NodeID: 5,
// not relevant
StoreID: 1,
ReplicaID: 2,
}
testCases := []struct {
key roachpb.Key
check func(*roachpb.BatchResponse, *roachpb.Error)
}{
{badKey,
func(_ *roachpb.BatchResponse, pErr *roachpb.Error) {
if pErr == nil {
t.Fatal("expected an error")
}
if pErr.Now == hlc.ZeroTimestamp {
t.Fatal("timestamp not annotated on error")
}
}},
{goodKey,
func(pReply *roachpb.BatchResponse, pErr *roachpb.Error) {
if pErr != nil {
t.Fatal(pErr)
}
if pReply.Now == hlc.ZeroTimestamp {
t.Fatal("timestamp not annotated on batch response")
}
}},
}
for _, useTxn := range []bool{false, true} {
for _, test := range testCases {
func() {
cfg := TestStoreConfig(nil)
cfg.TestingKnobs.TestingCommandFilter =
func(filterArgs storagebase.FilterArgs) *roachpb.Error {
if bytes.Equal(filterArgs.Req.Header().Key, badKey) {
return roachpb.NewErrorWithTxn(errors.Errorf("boom"), filterArgs.Hdr.Txn)
}
return nil
}
store, stopper := createTestStoreWithConfig(t, &cfg)
defer stopper.Stop()
var txn *roachpb.Transaction
if useTxn {
txn = newTransaction("test", test.key, 1, enginepb.SERIALIZABLE, store.cfg.Clock)
txn.MaxTimestamp = hlc.MaxTimestamp
}
pArgs := putArgs(test.key, []byte("value"))
ba := roachpb.BatchRequest{
Header: roachpb.Header{
Txn: txn,
Replica: desc,
},
}
ba.Add(&pArgs)
test.check(store.testSender().Send(context.Background(), ba))
}()
}
}
}
func TestStoreExecuteNoop(t *testing.T) {
defer leaktest.AfterTest(t)()
store, _, stopper := createTestStore(t)
defer stopper.Stop()
ba := roachpb.BatchRequest{}
ba.RangeID = 1
ba.Replica = roachpb.ReplicaDescriptor{StoreID: store.StoreID()}
ba.Add(&roachpb.GetRequest{Span: roachpb.Span{Key: roachpb.Key("a")}})
ba.Add(&roachpb.NoopRequest{})
br, pErr := store.Send(context.Background(), ba)
if pErr != nil {
t.Fatal(pErr)
}
reply := br.Responses[1].GetInner()
if _, ok := reply.(*roachpb.NoopResponse); !ok {
t.Errorf("expected *roachpb.NoopResponse, got %T", reply)
}
}
// TestStoreVerifyKeys checks that key length is enforced and
// that end keys must sort >= start.
func TestStoreVerifyKeys(t *testing.T) {
defer leaktest.AfterTest(t)()
store, _, stopper := createTestStore(t)
defer stopper.Stop()
// Try a start key == KeyMax.
gArgs := getArgs(roachpb.KeyMax)
if _, pErr := client.SendWrapped(context.Background(), store.testSender(), &gArgs); !testutils.IsPError(pErr, "must be less than KeyMax") {
t.Fatalf("expected error for start key == KeyMax: %v", pErr)
}
// Try a get with an end key specified (get requires only a start key and should fail).
gArgs.EndKey = roachpb.KeyMax
if _, pErr := client.SendWrapped(context.Background(), store.testSender(), &gArgs); !testutils.IsPError(pErr, "must be less than KeyMax") {
t.Fatalf("unexpected error for end key specified on a non-range-based operation: %v", pErr)
}
// Try a scan with end key < start key.
sArgs := scanArgs([]byte("b"), []byte("a"))
if _, pErr := client.SendWrapped(context.Background(), store.testSender(), &sArgs); !testutils.IsPError(pErr, "must be greater than") {
t.Fatalf("unexpected error for end key < start: %v", pErr)
}
// Try a scan with start key == end key.
sArgs.Key = []byte("a")
sArgs.EndKey = sArgs.Key
if _, pErr := client.SendWrapped(context.Background(), store.testSender(), &sArgs); !testutils.IsPError(pErr, "must be greater than") {
t.Fatalf("unexpected error for start == end key: %v", pErr)
}
// Try a scan with range-local start key, but "regular" end key.
sArgs.Key = keys.MakeRangeKey([]byte("test"), []byte("sffx"), nil)
sArgs.EndKey = []byte("z")
if _, pErr := client.SendWrapped(context.Background(), store.testSender(), &sArgs); !testutils.IsPError(pErr, "range-local") {
t.Fatalf("unexpected error for local start, non-local end key: %v", pErr)
}
// Try a put to meta2 key which would otherwise exceed maximum key
// length, but is accepted because of the meta prefix.
meta2KeyMax := testutils.MakeKey(keys.Meta2Prefix, roachpb.RKeyMax)
pArgs := putArgs(meta2KeyMax, []byte("value"))
if _, pErr := client.SendWrapped(context.Background(), store.testSender(), &pArgs); pErr != nil {
t.Fatalf("unexpected error on put to meta2 value: %s", pErr)
}
// Try to put a range descriptor record for a start key which is
// maximum length.
key := append([]byte{}, roachpb.RKeyMax...)
key[len(key)-1] = 0x01
pArgs = putArgs(keys.RangeDescriptorKey(key), []byte("value"))
if _, pErr := client.SendWrapped(context.Background(), store.testSender(), &pArgs); pErr != nil {
t.Fatalf("unexpected error on put to range descriptor for KeyMax value: %s", pErr)
}
// Try a put to txn record for a meta2 key (note that this doesn't
// actually happen in practice, as txn records are not put directly,
// but are instead manipulated only through txn methods).
pArgs = putArgs(keys.TransactionKey(meta2KeyMax, uuid.NewV4()), []byte("value"))
if _, pErr := client.SendWrapped(context.Background(), store.testSender(), &pArgs); pErr != nil {
t.Fatalf("unexpected error on put to txn meta2 value: %s", pErr)
}
}
// TestStoreSendUpdateTime verifies that the node clock is updated.
func TestStoreSendUpdateTime(t *testing.T) {
defer leaktest.AfterTest(t)()
store, _, stopper := createTestStore(t)
defer stopper.Stop()
args := getArgs([]byte("a"))
reqTS := store.cfg.Clock.Now().Add(store.cfg.Clock.MaxOffset().Nanoseconds(), 0)
_, pErr := client.SendWrappedWith(context.Background(), store.testSender(), roachpb.Header{Timestamp: reqTS}, &args)
if pErr != nil {
t.Fatal(pErr)
}
ts := store.cfg.Clock.Now()
if ts.WallTime != reqTS.WallTime || ts.Logical <= reqTS.Logical {
t.Errorf("expected store clock to advance to %s; got %s", reqTS, ts)
}
}
// TestStoreSendWithZeroTime verifies that no timestamp causes
// the command to assume the node's wall time.
func TestStoreSendWithZeroTime(t *testing.T) {
defer leaktest.AfterTest(t)()
store, _, stopper := createTestStore(t)
defer stopper.Stop()
args := getArgs([]byte("a"))
_, respH, pErr := SendWrapped(context.Background(), store.testSender(), roachpb.Header{}, &args)
if pErr != nil {
t.Fatal(pErr)
}
// The Logical time will increase over the course of the command
// execution so we can only rely on comparing the WallTime.
if respH.Timestamp.WallTime != store.cfg.Clock.Now().WallTime {
t.Errorf("expected reply to have store clock time %s; got %s",
store.cfg.Clock.Now(), respH.Timestamp)
}
}
// TestStoreSendWithClockOffset verifies that if the request
// specifies a timestamp further into the future than the node's
// maximum allowed clock offset, the cmd fails.
func TestStoreSendWithClockOffset(t *testing.T) {
defer leaktest.AfterTest(t)()
store, _, stopper := createTestStore(t)
defer stopper.Stop()
args := getArgs([]byte("a"))
// Set args timestamp to exceed max offset.
reqTS := store.cfg.Clock.Now().Add(store.cfg.Clock.MaxOffset().Nanoseconds()+1, 0)
_, pErr := client.SendWrappedWith(context.Background(), store.testSender(), roachpb.Header{Timestamp: reqTS}, &args)
if !testutils.IsPError(pErr, "rejecting command with timestamp in the future") {
t.Errorf("unexpected error: %v", pErr)
}
}