-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathclient_raft_test.go
1920 lines (1697 loc) · 60.1 KB
/
client_raft_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2015 The Cockroach Authors.
//
// 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: Ben Darnell
package storage_test
import (
"bytes"
"fmt"
"reflect"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/coreos/etcd/raft"
"github.com/coreos/etcd/raft/raftpb"
"github.com/pkg/errors"
"golang.org/x/net/context"
"github.com/cockroachdb/cockroach/base"
"github.com/cockroachdb/cockroach/internal/client"
"github.com/cockroachdb/cockroach/keys"
"github.com/cockroachdb/cockroach/roachpb"
"github.com/cockroachdb/cockroach/storage"
"github.com/cockroachdb/cockroach/storage/engine"
"github.com/cockroachdb/cockroach/storage/storagebase"
"github.com/cockroachdb/cockroach/testutils"
"github.com/cockroachdb/cockroach/testutils/gossiputil"
"github.com/cockroachdb/cockroach/util"
"github.com/cockroachdb/cockroach/util/grpcutil"
"github.com/cockroachdb/cockroach/util/hlc"
"github.com/cockroachdb/cockroach/util/leaktest"
"github.com/cockroachdb/cockroach/util/stop"
"github.com/cockroachdb/cockroach/util/timeutil"
)
// mustGetInt decodes an int64 value from the bytes field of the receiver
// and panics if the bytes field is not 0 or 8 bytes in length.
func mustGetInt(v *roachpb.Value) int64 {
if v == nil {
return 0
}
i, err := v.GetInt()
if err != nil {
panic(err)
}
return i
}
// TestStoreRecoverFromEngine verifies that the store recovers all ranges and their contents
// after being stopped and recreated.
func TestStoreRecoverFromEngine(t *testing.T) {
defer leaktest.AfterTest(t)()
sCtx := storage.TestStoreContext()
sCtx.TestingKnobs.DisableSplitQueue = true
rangeID := roachpb.RangeID(1)
splitKey := roachpb.Key("m")
key1 := roachpb.Key("a")
key2 := roachpb.Key("z")
manual := hlc.NewManualClock(0)
clock := hlc.NewClock(manual.UnixNano)
engineStopper := stop.NewStopper()
defer engineStopper.Stop()
eng := engine.NewInMem(roachpb.Attributes{}, 1<<20, engineStopper)
var rangeID2 roachpb.RangeID
get := func(store *storage.Store, rangeID roachpb.RangeID, key roachpb.Key) int64 {
args := getArgs(key)
resp, err := client.SendWrappedWith(rg1(store), nil, roachpb.Header{
RangeID: rangeID,
}, &args)
if err != nil {
t.Fatal(err)
}
return mustGetInt(resp.(*roachpb.GetResponse).Value)
}
validate := func(store *storage.Store) {
if val := get(store, rangeID, key1); val != 13 {
t.Errorf("key %q: expected 13 but got %v", key1, val)
}
if val := get(store, rangeID2, key2); val != 28 {
t.Errorf("key %q: expected 28 but got %v", key2, val)
}
}
// First, populate the store with data across two ranges. Each range contains commands
// that both predate and postdate the split.
func() {
stopper := stop.NewStopper()
defer stopper.Stop()
store := createTestStoreWithEngine(t, eng, clock, true, sCtx, stopper)
increment := func(rangeID roachpb.RangeID, key roachpb.Key, value int64) (*roachpb.IncrementResponse, *roachpb.Error) {
args := incrementArgs(key, value)
resp, err := client.SendWrappedWith(rg1(store), nil, roachpb.Header{
RangeID: rangeID,
}, &args)
incResp, _ := resp.(*roachpb.IncrementResponse)
return incResp, err
}
if _, err := increment(rangeID, key1, 2); err != nil {
t.Fatal(err)
}
if _, err := increment(rangeID, key2, 5); err != nil {
t.Fatal(err)
}
splitArgs := adminSplitArgs(roachpb.KeyMin, splitKey)
if _, err := client.SendWrapped(rg1(store), nil, &splitArgs); err != nil {
t.Fatal(err)
}
rangeID2 = store.LookupReplica(roachpb.RKey(key2), nil).RangeID
if rangeID2 == rangeID {
t.Errorf("got same range id after split")
}
if _, err := increment(rangeID, key1, 11); err != nil {
t.Fatal(err)
}
if _, err := increment(rangeID2, key2, 23); err != nil {
t.Fatal(err)
}
validate(store)
}()
// Now create a new store with the same engine and make sure the expected data is present.
// We must use the same clock because a newly-created manual clock will be behind the one
// we wrote with and so will see stale MVCC data.
store := createTestStoreWithEngine(t, eng, clock, false, sCtx, engineStopper)
// Raft processing is initialized lazily; issue a no-op write request on each key to
// ensure that is has been started.
incArgs := incrementArgs(key1, 0)
if _, err := client.SendWrapped(rg1(store), nil, &incArgs); err != nil {
t.Fatal(err)
}
incArgs = incrementArgs(key2, 0)
if _, err := client.SendWrappedWith(rg1(store), nil, roachpb.Header{
RangeID: rangeID2,
}, &incArgs); err != nil {
t.Fatal(err)
}
validate(store)
}
// TestStoreRecoverWithErrors verifies that even commands that fail are marked as
// applied so they are not retried after recovery.
func TestStoreRecoverWithErrors(t *testing.T) {
defer leaktest.AfterTest(t)()
manual := hlc.NewManualClock(0)
clock := hlc.NewClock(manual.UnixNano)
engineStopper := stop.NewStopper()
defer engineStopper.Stop()
eng := engine.NewInMem(roachpb.Attributes{}, 1<<20, engineStopper)
numIncrements := 0
func() {
stopper := stop.NewStopper()
defer stopper.Stop()
sCtx := storage.TestStoreContext()
sCtx.TestingKnobs.TestingCommandFilter =
func(filterArgs storagebase.FilterArgs) *roachpb.Error {
_, ok := filterArgs.Req.(*roachpb.IncrementRequest)
if ok && filterArgs.Req.Header().Key.Equal(roachpb.Key("a")) {
numIncrements++
}
return nil
}
store := createTestStoreWithEngine(t, eng, clock, true, sCtx, stopper)
// Write a bytes value so the increment will fail.
putArgs := putArgs(roachpb.Key("a"), []byte("asdf"))
if _, err := client.SendWrapped(rg1(store), nil, &putArgs); err != nil {
t.Fatal(err)
}
// Try and fail to increment the key. It is important for this test that the
// failure be the last thing in the raft log when the store is stopped.
incArgs := incrementArgs(roachpb.Key("a"), 42)
if _, err := client.SendWrapped(rg1(store), nil, &incArgs); err == nil {
t.Fatal("did not get expected error")
}
}()
if numIncrements != 1 {
t.Fatalf("expected 1 increments; was %d", numIncrements)
}
// Recover from the engine.
store := createTestStoreWithEngine(
t, eng, clock, false, storage.TestStoreContext(), engineStopper)
// Issue a no-op write to lazily initialize raft on the range.
incArgs := incrementArgs(roachpb.Key("b"), 0)
if _, err := client.SendWrapped(rg1(store), nil, &incArgs); err != nil {
t.Fatal(err)
}
// No additional increments were performed on key A during recovery.
if numIncrements != 1 {
t.Fatalf("expected 1 increments; was %d", numIncrements)
}
}
// TestReplicateRange verifies basic replication functionality by creating two stores
// and a range, replicating the range to the second store, and reading its data there.
func TestReplicateRange(t *testing.T) {
defer leaktest.AfterTest(t)()
mtc := startMultiTestContext(t, 2)
defer mtc.Stop()
// Issue a command on the first node before replicating.
incArgs := incrementArgs([]byte("a"), 5)
if _, err := client.SendWrapped(rg1(mtc.stores[0]), nil, &incArgs); err != nil {
t.Fatal(err)
}
rng, err := mtc.stores[0].GetReplica(1)
if err != nil {
t.Fatal(err)
}
if err := rng.ChangeReplicas(
context.Background(),
roachpb.ADD_REPLICA,
roachpb.ReplicaDescriptor{
NodeID: mtc.stores[1].Ident.NodeID,
StoreID: mtc.stores[1].Ident.StoreID,
},
rng.Desc(),
); err != nil {
t.Fatal(err)
}
// Verify no intent remains on range descriptor key.
key := keys.RangeDescriptorKey(rng.Desc().StartKey)
desc := roachpb.RangeDescriptor{}
if ok, err := engine.MVCCGetProto(context.Background(), mtc.stores[0].Engine(), key, mtc.stores[0].Clock().Now(), true, nil, &desc); err != nil {
t.Fatal(err)
} else if !ok {
t.Fatalf("range descriptor key %s was not found", key)
}
// Verify that in time, no intents remain on meta addressing
// keys, and that range descriptor on the meta records is correct.
util.SucceedsSoon(t, func() error {
meta2, err := keys.Addr(keys.RangeMetaKey(roachpb.RKeyMax))
if err != nil {
t.Fatal(err)
}
meta1, err := keys.Addr(keys.RangeMetaKey(meta2))
if err != nil {
t.Fatal(err)
}
for _, key := range []roachpb.RKey{meta2, meta1} {
metaDesc := roachpb.RangeDescriptor{}
if ok, err := engine.MVCCGetProto(context.Background(), mtc.stores[0].Engine(), key.AsRawKey(), mtc.stores[0].Clock().Now(), true, nil, &metaDesc); err != nil {
return err
} else if !ok {
return errors.Errorf("failed to resolve %s", key.AsRawKey())
}
if !reflect.DeepEqual(metaDesc, desc) {
return errors.Errorf("descs not equal: %+v != %+v", metaDesc, desc)
}
}
return nil
})
// Verify that the same data is available on the replica.
util.SucceedsSoon(t, func() error {
getArgs := getArgs([]byte("a"))
if reply, err := client.SendWrappedWith(rg1(mtc.stores[1]), nil, roachpb.Header{
ReadConsistency: roachpb.INCONSISTENT,
}, &getArgs); err != nil {
return errors.Errorf("failed to read data: %s", err)
} else if e, v := int64(5), mustGetInt(reply.(*roachpb.GetResponse).Value); v != e {
return errors.Errorf("failed to read correct data: expected %d, got %d", e, v)
}
return nil
})
}
// TestRestoreReplicas ensures that consensus group membership is properly
// persisted to disk and restored when a node is stopped and restarted.
func TestRestoreReplicas(t *testing.T) {
defer leaktest.AfterTest(t)()
mtc := startMultiTestContext(t, 2)
defer mtc.Stop()
firstRng, err := mtc.stores[0].GetReplica(1)
if err != nil {
t.Fatal(err)
}
// Perform an increment before replication to ensure that commands are not
// repeated on restarts.
incArgs := incrementArgs([]byte("a"), 23)
if _, err := client.SendWrapped(rg1(mtc.stores[0]), nil, &incArgs); err != nil {
t.Fatal(err)
}
if err := firstRng.ChangeReplicas(
context.Background(),
roachpb.ADD_REPLICA,
roachpb.ReplicaDescriptor{
NodeID: mtc.stores[1].Ident.NodeID,
StoreID: mtc.stores[1].Ident.StoreID,
},
firstRng.Desc(),
); err != nil {
t.Fatal(err)
}
// TODO(bdarnell): use the stopper.Quiesce() method. The problem
// right now is that raft isn't creating a task for high-level work
// it's creating while snapshotting and catching up. Ideally we'll
// be able to capture that and then can just invoke
// mtc.stopper.Quiesce() here.
// TODO(bdarnell): initial creation and replication needs to be atomic;
// cutting off the process too soon currently results in a corrupted range.
time.Sleep(500 * time.Millisecond)
mtc.restart()
// Send a command on each store. The original store (the lease holder still)
// will succeed.
incArgs = incrementArgs([]byte("a"), 5)
if _, err := client.SendWrapped(rg1(mtc.stores[0]), nil, &incArgs); err != nil {
t.Fatal(err)
}
// The follower will return a not lease holder error, indicating the command
// should be forwarded to the lease holder.
incArgs = incrementArgs([]byte("a"), 11)
{
_, pErr := client.SendWrapped(rg1(mtc.stores[1]), nil, &incArgs)
if _, ok := pErr.GetDetail().(*roachpb.NotLeaseHolderError); !ok {
t.Fatalf("expected not lease holder error; got %s", pErr)
}
}
// Send again, this time to first store.
if _, pErr := client.SendWrapped(rg1(mtc.stores[0]), nil, &incArgs); pErr != nil {
t.Fatal(pErr)
}
util.SucceedsSoon(t, func() error {
getArgs := getArgs([]byte("a"))
if reply, err := client.SendWrappedWith(rg1(mtc.stores[1]), nil, roachpb.Header{
ReadConsistency: roachpb.INCONSISTENT,
}, &getArgs); err != nil {
return errors.Errorf("failed to read data: %s", err)
} else if e, v := int64(39), mustGetInt(reply.(*roachpb.GetResponse).Value); v != e {
return errors.Errorf("failed to read correct data: expected %d, got %d", e, v)
}
return nil
})
// Both replicas have a complete list in Desc.Replicas
for i, store := range mtc.stores {
rng, err := store.GetReplica(1)
if err != nil {
t.Fatal(err)
}
desc := rng.Desc()
if len(desc.Replicas) != 2 {
t.Fatalf("store %d: expected 2 replicas, found %d", i, len(desc.Replicas))
}
if desc.Replicas[0].NodeID != mtc.stores[0].Ident.NodeID {
t.Errorf("store %d: expected replica[0].NodeID == %d, was %d",
i, mtc.stores[0].Ident.NodeID, desc.Replicas[0].NodeID)
}
}
}
func TestFailedReplicaChange(t *testing.T) {
defer leaktest.AfterTest(t)()
var runFilter atomic.Value
runFilter.Store(true)
ctx := storage.TestStoreContext()
mtc := &multiTestContext{}
mtc.storeContext = &ctx
mtc.storeContext.TestingKnobs.TestingCommandFilter =
func(filterArgs storagebase.FilterArgs) *roachpb.Error {
if runFilter.Load().(bool) {
if et, ok := filterArgs.Req.(*roachpb.EndTransactionRequest); ok && et.Commit {
return roachpb.NewErrorWithTxn(errors.Errorf("boom"), filterArgs.Hdr.Txn)
}
}
return nil
}
mtc.Start(t, 2)
defer mtc.Stop()
rng, err := mtc.stores[0].GetReplica(1)
if err != nil {
t.Fatal(err)
}
if err := rng.ChangeReplicas(
context.Background(),
roachpb.ADD_REPLICA,
roachpb.ReplicaDescriptor{
NodeID: mtc.stores[1].Ident.NodeID,
StoreID: mtc.stores[1].Ident.StoreID,
},
rng.Desc(),
); !testutils.IsError(err, "boom") {
t.Fatalf("did not get expected error: %v", err)
}
// After the aborted transaction, r.Desc was not updated.
// TODO(bdarnell): expose and inspect raft's internal state.
if len(rng.Desc().Replicas) != 1 {
t.Fatalf("expected 1 replica, found %d", len(rng.Desc().Replicas))
}
// The pending config change flag was cleared, so a subsequent attempt
// can succeed.
runFilter.Store(false)
// The first failed replica change has laid down intents. Make sure those
// are pushable by making the transaction abandoned.
mtc.manualClock.Increment(10 * base.DefaultHeartbeatInterval.Nanoseconds())
if err := rng.ChangeReplicas(
context.Background(),
roachpb.ADD_REPLICA,
roachpb.ReplicaDescriptor{
NodeID: mtc.stores[1].Ident.NodeID,
StoreID: mtc.stores[1].Ident.StoreID,
},
rng.Desc(),
); err != nil {
t.Fatal(err)
}
// Wait for the range to sync to both replicas (mainly so leaktest doesn't
// complain about goroutines involved in the process).
util.SucceedsSoon(t, func() error {
for _, store := range mtc.stores {
rang, err := store.GetReplica(1)
if err != nil {
return err
}
if lr := len(rang.Desc().Replicas); lr <= 1 {
return errors.Errorf("expected > 1 replicas; got %d", lr)
}
}
return nil
})
}
// We can truncate the old log entries and a new replica will be brought up from a snapshot.
func TestReplicateAfterTruncation(t *testing.T) {
defer leaktest.AfterTest(t)()
mtc := startMultiTestContext(t, 2)
defer mtc.Stop()
rng, err := mtc.stores[0].GetReplica(1)
if err != nil {
t.Fatal(err)
}
// Issue a command on the first node before replicating.
incArgs := incrementArgs([]byte("a"), 5)
if _, err := client.SendWrapped(rg1(mtc.stores[0]), nil, &incArgs); err != nil {
t.Fatal(err)
}
// Get that command's log index.
index, err := rng.GetLastIndex()
if err != nil {
t.Fatal(err)
}
// Truncate the log at index+1 (log entries < N are removed, so this includes
// the increment).
truncArgs := truncateLogArgs(index + 1)
if _, err := client.SendWrapped(rg1(mtc.stores[0]), nil, &truncArgs); err != nil {
t.Fatal(err)
}
// Issue a second command post-truncation.
incArgs = incrementArgs([]byte("a"), 11)
if _, err := client.SendWrapped(rg1(mtc.stores[0]), nil, &incArgs); err != nil {
t.Fatal(err)
}
// Now add the second replica.
if err := rng.ChangeReplicas(
context.Background(),
roachpb.ADD_REPLICA,
roachpb.ReplicaDescriptor{
NodeID: mtc.stores[1].Ident.NodeID,
StoreID: mtc.stores[1].Ident.StoreID,
},
rng.Desc(),
); err != nil {
t.Fatal(err)
}
// Once it catches up, the effects of both commands can be seen.
util.SucceedsSoon(t, func() error {
getArgs := getArgs([]byte("a"))
if reply, err := client.SendWrappedWith(rg1(mtc.stores[1]), nil, roachpb.Header{
ReadConsistency: roachpb.INCONSISTENT,
}, &getArgs); err != nil {
return errors.Errorf("failed to read data: %s", err)
} else if e, v := int64(16), mustGetInt(reply.(*roachpb.GetResponse).Value); v != e {
return errors.Errorf("failed to read correct data: expected %d, got %d", e, v)
}
return nil
})
rng2, err := mtc.stores[1].GetReplica(1)
if err != nil {
t.Fatal(err)
}
util.SucceedsSoon(t, func() error {
if mvcc, mvcc2 := rng.GetMVCCStats(), rng2.GetMVCCStats(); mvcc2 != mvcc {
return errors.Errorf("expected stats on new range:\n%+v\not equal old:\n%+v", mvcc2, mvcc)
}
return nil
})
// Send a third command to verify that the log states are synced up so the
// new node can accept new commands.
incArgs = incrementArgs([]byte("a"), 23)
if _, err := client.SendWrapped(rg1(mtc.stores[0]), nil, &incArgs); err != nil {
t.Fatal(err)
}
util.SucceedsSoon(t, func() error {
getArgs := getArgs([]byte("a"))
if reply, err := client.SendWrappedWith(rg1(mtc.stores[1]), nil, roachpb.Header{
ReadConsistency: roachpb.INCONSISTENT,
}, &getArgs); err != nil {
return errors.Errorf("failed to read data: %s", err)
} else if e, v := int64(39), mustGetInt(reply.(*roachpb.GetResponse).Value); v != e {
return errors.Errorf("failed to read correct data: expected %d, got %d", e, v)
}
return nil
})
}
// TestStoreRangeUpReplicate verifies that the replication queue will notice
// under-replicated ranges and replicate them.
func TestStoreRangeUpReplicate(t *testing.T) {
defer leaktest.AfterTest(t)()
mtc := startMultiTestContext(t, 3)
defer mtc.Stop()
// Initialize the gossip network.
storeDescs := make([]*roachpb.StoreDescriptor, 0, len(mtc.stores))
for _, s := range mtc.stores {
desc, err := s.Descriptor()
if err != nil {
t.Fatal(err)
}
storeDescs = append(storeDescs, desc)
}
for _, g := range mtc.gossips {
gossiputil.NewStoreGossiper(g).GossipStores(storeDescs, t)
}
// Once we know our peers, trigger a scan.
mtc.stores[0].ForceReplicationScanAndProcess()
// The range should become available on every node.
util.SucceedsSoon(t, func() error {
for _, s := range mtc.stores {
r := s.LookupReplica(roachpb.RKey("a"), roachpb.RKey("b"))
if r == nil {
return errors.Errorf("expected replica for keys \"a\" - \"b\"")
}
}
return nil
})
}
// getRangeMetadata retrieves the current range descriptor for the target
// range.
func getRangeMetadata(key roachpb.RKey, mtc *multiTestContext, t *testing.T) roachpb.RangeDescriptor {
// Calls to RangeLookup typically use inconsistent reads, but we
// want to do a consistent read here. This is important when we are
// considering one of the metadata ranges: we must not do an
// inconsistent lookup in our own copy of the range.
b := &client.Batch{}
b.AddRawRequest(&roachpb.RangeLookupRequest{
Span: roachpb.Span{
Key: keys.RangeMetaKey(key),
},
MaxRanges: 1,
})
var reply *roachpb.RangeLookupResponse
if err := mtc.dbs[0].Run(b); err != nil {
t.Fatalf("error getting range metadata: %s", err)
} else {
reply = b.RawResponse().Responses[0].GetInner().(*roachpb.RangeLookupResponse)
}
if a, e := len(reply.Ranges), 1; a != e {
t.Fatalf("expected %d range descriptor, got %d", e, a)
}
return reply.Ranges[0]
}
// TestUnreplicateFirstRange verifies that multiTestContext still functions in
// the case where the first range (which contains range metadata) is
// unreplicated from the first store. This situation can arise occasionally in
// tests, as can a similar situation where the first store is no longer the lease holder of
// the first range; this verifies that those tests will not be affected.
func TestUnreplicateFirstRange(t *testing.T) {
defer leaktest.AfterTest(t)()
mtc := startMultiTestContext(t, 3)
defer mtc.Stop()
rangeID := roachpb.RangeID(1)
// Replicate the range to store 1.
mtc.replicateRange(rangeID, 1)
// Unreplicate the from from store 0.
mtc.unreplicateRange(rangeID, 0)
// Replicate the range to store 2. The first range is no longer available on
// store 1, and this command will fail if that situation is not properly
// supported.
mtc.replicateRange(rangeID, 2)
}
// TestStoreRangeDownReplicate verifies that the replication queue will notice
// over-replicated ranges and remove replicas from them.
func TestStoreRangeDownReplicate(t *testing.T) {
defer leaktest.AfterTest(t)()
mtc := startMultiTestContext(t, 5)
defer mtc.Stop()
store0 := mtc.stores[0]
// Split off a range from the initial range for testing; there are
// complications if the metadata ranges are removed from store 1, this
// simplifies the test.
splitKey := roachpb.Key("m")
rightKey := roachpb.Key("z")
{
replica := store0.LookupReplica(roachpb.RKeyMin, nil)
mtc.replicateRange(replica.RangeID, 1, 2)
desc := replica.Desc()
splitArgs := adminSplitArgs(splitKey, splitKey)
if _, err := replica.AdminSplit(context.Background(), splitArgs, desc); err != nil {
t.Fatal(err)
}
}
// Replicate the new range to all five stores.
rightKeyAddr, err := keys.Addr(rightKey)
if err != nil {
t.Fatal(err)
}
replica := store0.LookupReplica(rightKeyAddr, nil)
desc := replica.Desc()
mtc.replicateRange(desc.RangeID, 3, 4)
// Initialize the gossip network.
storeDescs := make([]*roachpb.StoreDescriptor, 0, len(mtc.stores))
for _, s := range mtc.stores {
desc, err := s.Descriptor()
if err != nil {
t.Fatal(err)
}
storeDescs = append(storeDescs, desc)
}
for _, g := range mtc.gossips {
gossiputil.NewStoreGossiper(g).GossipStores(storeDescs, t)
}
maxTimeout := time.After(10 * time.Second)
succeeded := false
i := 0
for !succeeded {
select {
case <-maxTimeout:
t.Fatalf("Failed to achieve proper replication within 10 seconds")
case <-time.After(10 * time.Millisecond):
rangeDesc := getRangeMetadata(rightKeyAddr, mtc, t)
if count := len(rangeDesc.Replicas); count < 3 {
t.Fatalf("Removed too many replicas; expected at least 3 replicas, found %d", count)
} else if count == 3 {
succeeded = true
break
}
// Cycle the lease to the next replica (on the next store) if that
// replica still exists. This avoids the condition in which we try
// to continuously remove the replica on a store when
// down-replicating while it also still holds the lease.
for {
i++
if i >= len(mtc.stores) {
i = 0
}
rep := mtc.stores[i].LookupReplica(rightKeyAddr, nil)
if rep != nil {
mtc.expireLeases()
// Force the read command request a new lease.
getArgs := getArgs(rightKey)
if _, err := client.SendWrapped(mtc.distSenders[i], nil, &getArgs); err != nil {
t.Fatal(err)
}
mtc.stores[i].ForceReplicationScanAndProcess()
break
}
}
}
}
// Expire range leases one more time, so that any remaining resolutions can
// get a range lease.
// TODO(bdarnell): understand why some tests need this.
mtc.expireLeases()
}
// TestChangeReplicasDuplicateError tests that a replica change aborts if
// another change has been made to the RangeDescriptor since it was initiated.
func TestChangeReplicasDescriptorInvariant(t *testing.T) {
defer leaktest.AfterTest(t)()
mtc := startMultiTestContext(t, 3)
defer mtc.Stop()
repl, err := mtc.stores[0].GetReplica(1)
if err != nil {
t.Fatal(err)
}
addReplica := func(storeNum int, desc *roachpb.RangeDescriptor) error {
return repl.ChangeReplicas(
context.Background(),
roachpb.ADD_REPLICA,
roachpb.ReplicaDescriptor{
NodeID: mtc.stores[storeNum].Ident.NodeID,
StoreID: mtc.stores[storeNum].Ident.StoreID,
},
desc,
)
}
// Retain the descriptor for the range at this point.
origDesc := repl.Desc()
// Add replica to the second store, which should succeed.
if err := addReplica(1, origDesc); err != nil {
t.Fatal(err)
}
util.SucceedsSoon(t, func() error {
r := mtc.stores[1].LookupReplica(roachpb.RKey("a"), roachpb.RKey("b"))
if r == nil {
return errors.Errorf("expected replica for keys \"a\" - \"b\"")
}
return nil
})
// Attempt to add replica to the third store with the original descriptor.
// This should fail because the descriptor is stale.
if err := addReplica(2, origDesc); !testutils.IsError(err, `change replicas of range \d+ failed`) {
t.Fatalf("got unexpected error: %v", err)
}
// Both addReplica calls attempted to use origDesc.NextReplicaID.
// The failed second call should not have overwritten the cached
// replica descriptor from the successful first call.
if rd, err := mtc.stores[0].ReplicaDescriptor(origDesc.RangeID, origDesc.NextReplicaID); err != nil {
t.Fatalf("failed to look up replica %s", origDesc.NextReplicaID)
} else if a, e := rd.StoreID, mtc.stores[1].Ident.StoreID; a != e {
t.Fatalf("expected replica %s to point to store %s, but got %s", origDesc.NextReplicaID, a, e)
}
// Add to third store with fresh descriptor.
if err := addReplica(2, repl.Desc()); err != nil {
t.Fatal(err)
}
util.SucceedsSoon(t, func() error {
r := mtc.stores[2].LookupReplica(roachpb.RKey("a"), roachpb.RKey("b"))
if r == nil {
return errors.Errorf("expected replica for keys \"a\" - \"b\"")
}
return nil
})
}
// TestProgressWithDownNode verifies that a surviving quorum can make progress
// with a downed node.
func TestProgressWithDownNode(t *testing.T) {
defer leaktest.AfterTest(t)()
mtc := startMultiTestContext(t, 3)
defer mtc.Stop()
rangeID := roachpb.RangeID(1)
mtc.replicateRange(rangeID, 1, 2)
incArgs := incrementArgs([]byte("a"), 5)
if _, err := client.SendWrapped(rg1(mtc.stores[0]), nil, &incArgs); err != nil {
t.Fatal(err)
}
// Verify that the first increment propagates to all the engines.
verify := func(expected []int64) {
util.SucceedsSoon(t, func() error {
values := []int64{}
for _, eng := range mtc.engines {
val, _, err := engine.MVCCGet(context.Background(), eng, roachpb.Key("a"), mtc.clock.Now(), true, nil)
if err != nil {
return err
}
values = append(values, mustGetInt(val))
}
if !reflect.DeepEqual(expected, values) {
return errors.Errorf("expected %v, got %v", expected, values)
}
return nil
})
}
verify([]int64{5, 5, 5})
// Stop one of the replicas and issue a new increment.
mtc.stopStore(1)
incArgs = incrementArgs([]byte("a"), 11)
if _, err := client.SendWrapped(rg1(mtc.stores[0]), nil, &incArgs); err != nil {
t.Fatal(err)
}
// The new increment can be seen on both live replicas.
verify([]int64{16, 5, 16})
// Once the downed node is restarted, it will catch up.
mtc.restartStore(1)
verify([]int64{16, 16, 16})
}
func TestReplicateAddAndRemove(t *testing.T) {
defer leaktest.AfterTest(t)()
testFunc := func(addFirst bool) {
mtc := startMultiTestContext(t, 4)
defer mtc.Stop()
// Replicate the initial range to three of the four nodes.
rangeID := roachpb.RangeID(1)
mtc.replicateRange(rangeID, 3, 1)
incArgs := incrementArgs([]byte("a"), 5)
if _, err := client.SendWrapped(rg1(mtc.stores[0]), nil, &incArgs); err != nil {
t.Fatal(err)
}
verify := func(expected []int64) {
util.SucceedsSoon(t, func() error {
values := []int64{}
for _, eng := range mtc.engines {
val, _, err := engine.MVCCGet(context.Background(), eng, roachpb.Key("a"), mtc.clock.Now(), true, nil)
if err != nil {
return err
}
values = append(values, mustGetInt(val))
}
if !reflect.DeepEqual(expected, values) {
return errors.Errorf("addFirst: %t, expected %v, got %v", addFirst, expected, values)
}
return nil
})
}
// The first increment is visible on all three replicas.
verify([]int64{5, 5, 0, 5})
// Stop a store and replace it.
mtc.stopStore(1)
if addFirst {
mtc.replicateRange(rangeID, 2)
mtc.unreplicateRange(rangeID, 1)
} else {
mtc.unreplicateRange(rangeID, 1)
mtc.replicateRange(rangeID, 2)
}
verify([]int64{5, 5, 5, 5})
// Ensure that the rest of the group can make progress.
incArgs = incrementArgs([]byte("a"), 11)
if _, err := client.SendWrapped(rg1(mtc.stores[0]), nil, &incArgs); err != nil {
t.Fatal(err)
}
verify([]int64{16, 5, 16, 16})
// Bring the downed store back up (required for a clean shutdown).
mtc.restartStore(1)
// Node 1 never sees the increment that was added while it was
// down. Perform another increment on the live nodes to verify.
incArgs = incrementArgs([]byte("a"), 23)
if _, err := client.SendWrapped(rg1(mtc.stores[0]), nil, &incArgs); err != nil {
t.Fatal(err)
}
verify([]int64{39, 5, 39, 39})
// Wait out the range lease and the unleased duration to make the replica GC'able.
mtc.expireLeases()
mtc.manualClock.Increment(int64(
storage.ReplicaGCQueueInactivityThreshold + 1))
mtc.stores[1].ForceReplicaGCScanAndProcess()
// The removed store no longer has any of the data from the range.
verify([]int64{39, 0, 39, 39})
desc := mtc.stores[0].LookupReplica(roachpb.RKeyMin, nil).Desc()
replicaIDsByStore := map[roachpb.StoreID]roachpb.ReplicaID{}
for _, rep := range desc.Replicas {
replicaIDsByStore[rep.StoreID] = rep.ReplicaID
}
expected := map[roachpb.StoreID]roachpb.ReplicaID{1: 1, 4: 2, 3: 4}
if !reflect.DeepEqual(expected, replicaIDsByStore) {
t.Fatalf("expected replica IDs to be %v but got %v", expected, replicaIDsByStore)
}
}
// Run the test twice, once adding the replacement before removing
// the downed node, and once removing the downed node first.
testFunc(true)
testFunc(false)
}
// TestRaftHeartbeats verifies that coalesced heartbeats are correctly
// suppressing elections in an idle cluster.
func TestRaftHeartbeats(t *testing.T) {
defer leaktest.AfterTest(t)()
mtc := startMultiTestContext(t, 3)
defer mtc.Stop()
mtc.replicateRange(1, 1, 2)
// Capture the initial term and state.
status := mtc.stores[0].RaftStatus(1)
initialTerm := status.Term
if status.SoftState.RaftState != raft.StateLeader {
t.Errorf("expected node 0 to initially be leader but was %s", status.SoftState.RaftState)
}
// Wait for several ticks to elapse.
time.Sleep(5 * mtc.makeContext(0).RaftTickInterval)
status = mtc.stores[0].RaftStatus(1)
if status.SoftState.RaftState != raft.StateLeader {
t.Errorf("expected node 0 to be leader after sleeping but was %s", status.SoftState.RaftState)
}
if status.Term != initialTerm {
t.Errorf("while sleeping, term changed from %d to %d", initialTerm, status.Term)
}
}
// TestReplicateAfterSplit verifies that a new replica whose start key
// is not KeyMin replicating to a fresh store can apply snapshots correctly.
func TestReplicateAfterSplit(t *testing.T) {
defer leaktest.AfterTest(t)()
mtc := startMultiTestContext(t, 2)
defer mtc.Stop()
rangeID := roachpb.RangeID(1)
splitKey := roachpb.Key("m")
key := roachpb.Key("z")
store0 := mtc.stores[0]
// Make the split
splitArgs := adminSplitArgs(roachpb.KeyMin, splitKey)
if _, err := client.SendWrapped(rg1(store0), nil, &splitArgs); err != nil {
t.Fatal(err)
}
rangeID2 := store0.LookupReplica(roachpb.RKey(key), nil).RangeID
if rangeID2 == rangeID {
t.Errorf("got same range id after split")
}
// Issue an increment for later check.
incArgs := incrementArgs(key, 11)
if _, err := client.SendWrappedWith(rg1(store0), nil, roachpb.Header{
RangeID: rangeID2,
}, &incArgs); err != nil {
t.Fatal(err)
}
// Now add the second replica.
mtc.replicateRange(rangeID2, 1)