-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
client_raft_test.go
2907 lines (2543 loc) · 90.6 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"
"math/rand"
"reflect"
"sync"
"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/internal/client"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/storage"
"github.com/cockroachdb/cockroach/pkg/storage/engine"
"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/stop"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/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)()
storeCfg := storage.TestStoreConfig(nil)
storeCfg.TestingKnobs.DisableSplitQueue = true
rangeID := roachpb.RangeID(1)
splitKey := roachpb.Key("m")
key1 := roachpb.Key("a")
key2 := roachpb.Key("z")
engineStopper := stop.NewStopper()
defer engineStopper.Stop()
eng := engine.NewInMem(roachpb.Attributes{}, 1<<20)
engineStopper.AddCloser(eng)
var rangeID2 roachpb.RangeID
get := func(store *storage.Store, rangeID roachpb.RangeID, key roachpb.Key) int64 {
args := getArgs(key)
resp, err := client.SendWrappedWith(context.Background(), rg1(store), 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, true, storeCfg, stopper)
increment := func(rangeID roachpb.RangeID, key roachpb.Key, value int64) (*roachpb.IncrementResponse, *roachpb.Error) {
args := incrementArgs(key, value)
resp, err := client.SendWrappedWith(context.Background(), rg1(store), 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(context.Background(), rg1(store), &splitArgs); err != nil {
t.Fatal(err)
}
rangeID2 = store.LookupReplica(roachpb.RKey(key2), nil).RangeID
if rangeID2 == rangeID {
t.Fatal("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, false, storeCfg, 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(context.Background(), rg1(store), &incArgs); err != nil {
t.Fatal(err)
}
incArgs = incrementArgs(key2, 0)
if _, err := client.SendWrappedWith(context.Background(), rg1(store), 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)()
storeCfg := storage.TestStoreConfig(nil)
eng := engine.NewInMem(roachpb.Attributes{}, 1<<20)
defer eng.Close()
numIncrements := 0
func() {
stopper := stop.NewStopper()
defer stopper.Stop()
storeCfg := storeCfg // copy
storeCfg.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, true, storeCfg, stopper)
// Write a bytes value so the increment will fail.
putArgs := putArgs(roachpb.Key("a"), []byte("asdf"))
if _, err := client.SendWrapped(context.Background(), rg1(store), &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(context.Background(), rg1(store), &incArgs); err == nil {
t.Fatal("did not get expected error")
}
}()
if numIncrements != 1 {
t.Fatalf("expected 1 increments; was %d", numIncrements)
}
stopper := stop.NewStopper()
defer stopper.Stop()
// Recover from the engine.
store := createTestStoreWithEngine(t, eng, false, storeCfg, stopper)
// Issue a no-op write to lazily initialize raft on the range.
incArgs := incrementArgs(roachpb.Key("b"), 0)
if _, err := client.SendWrapped(context.Background(), rg1(store), &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(context.Background(), rg1(mtc.stores[0]), &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(context.Background(), rg1(mtc.stores[1]), 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)()
sc := storage.TestStoreConfig(nil)
// Disable periodic gossip activities. The periodic gossiping of the first
// range can cause spurious lease transfers which cause this test to fail.
sc.TestingKnobs.DisablePeriodicGossips = true
mtc := &multiTestContext{storeConfig: &sc}
mtc.Start(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(context.Background(), rg1(mtc.stores[0]), &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(context.Background(), rg1(mtc.stores[0]), &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(context.Background(), rg1(mtc.stores[1]), &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(context.Background(), rg1(mtc.stores[0]), &incArgs); pErr != nil {
t.Fatal(pErr)
}
util.SucceedsSoon(t, func() error {
getArgs := getArgs([]byte("a"))
if reply, err := client.SendWrappedWith(context.Background(), rg1(mtc.stores[1]), 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)
sc := storage.TestStoreConfig(nil)
sc.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 := &multiTestContext{storeConfig: &sc}
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 replicas := rng.Desc().Replicas; len(replicas) != 1 {
t.Fatalf("expected 1 replica, found %v", 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 replicas := rang.Desc().Replicas; len(replicas) <= 1 {
return errors.Errorf("expected > 1 replicas; got %v", replicas)
}
}
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(context.Background(), rg1(mtc.stores[0]), &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, 1)
if _, err := client.SendWrapped(context.Background(), rg1(mtc.stores[0]), &truncArgs); err != nil {
t.Fatal(err)
}
// Issue a second command post-truncation.
incArgs = incrementArgs([]byte("a"), 11)
if _, err := client.SendWrapped(context.Background(), rg1(mtc.stores[0]), &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(context.Background(), rg1(mtc.stores[1]), 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(context.Background(), rg1(mtc.stores[0]), &incArgs); err != nil {
t.Fatal(err)
}
util.SucceedsSoon(t, func() error {
getArgs := getArgs([]byte("a"))
if reply, err := client.SendWrappedWith(context.Background(), rg1(mtc.stores[1]), 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
})
}
// TestSnapshotAfterTruncation tests that Raft will properly send a
// non-preemptive snapshot when a node is brought up and the log has been
// truncated.
func TestSnapshotAfterTruncation(t *testing.T) {
defer leaktest.AfterTest(t)()
mtc := startMultiTestContext(t, 3)
defer mtc.Stop()
rng, err := mtc.stores[0].GetReplica(1)
if err != nil {
t.Fatal(err)
}
key := roachpb.Key("a")
incA := int64(5)
incB := int64(7)
incAB := incA + incB
// Set up a key to replicate across the cluster. We're going to modify this
// key and truncate the raft logs from that command after killing one of the
// nodes to check that it gets the new value after it comes up.
incArgs := incrementArgs(key, incA)
if _, err := client.SendWrapped(context.Background(), rg1(mtc.stores[0]), &incArgs); err != nil {
t.Fatal(err)
}
mtc.replicateRange(1, 1, 2)
mtc.waitForValues(key, []int64{incA, incA, incA})
// Now kill store 1, increment the key on the other stores and truncate
// their logs to make sure that when store 1 comes back up it will require a
// non-preemptive snapshot from Raft.
mtc.stopStore(1)
incArgs = incrementArgs(key, incB)
if _, err := client.SendWrapped(context.Background(), rg1(mtc.stores[0]), &incArgs); err != nil {
t.Fatal(err)
}
mtc.waitForValues(key, []int64{incAB, incA, incAB})
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, 1)
if _, err := client.SendWrapped(context.Background(), rg1(mtc.stores[0]), &truncArgs); err != nil {
t.Fatal(err)
}
mtc.restartStore(1)
mtc.waitForValues(key, []int64{incAB, incAB, incAB})
}
type fakeSnapshotStream struct {
nextReq *storage.SnapshotRequest
nextErr error
}
// Recv implements the SnapshotResponseStream interface.
func (c fakeSnapshotStream) Recv() (*storage.SnapshotRequest, error) {
return c.nextReq, c.nextErr
}
// Send implements the SnapshotResponseStream interface.
func (c fakeSnapshotStream) Send(request *storage.SnapshotResponse) error {
return nil
}
// Context implements the SnapshotResponseStream interface.
func (c fakeSnapshotStream) Context() context.Context {
return context.Background()
}
// TestFailedSnapshotFillsReservation tests that failing to finish applying an
// incoming snapshot still cleans up the outstanding reservation that was made.
func TestFailedSnapshotFillsReservation(t *testing.T) {
defer leaktest.AfterTest(t)()
mtc := startMultiTestContext(t, 3)
defer mtc.Stop()
rep, err := mtc.stores[0].GetReplica(1)
if err != nil {
t.Fatal(err)
}
header := storage.SnapshotRequest_Header{
CanDecline: true,
RangeSize: 100,
RangeDescriptor: *rep.Desc(),
}
// Cause this stream to return an error as soon as we ask it for something.
// This injects an error into HandleSnapshotStream when we try to send the
// "snapshot accepted" message.
expectedErr := errors.Errorf("")
stream := fakeSnapshotStream{nil, expectedErr}
if err := mtc.stores[1].HandleSnapshot(&header, stream); err != expectedErr {
t.Fatalf("expected error %s, but found %v", expectedErr, err)
}
if n := mtc.stores[1].ReservationCount(); n != 0 {
t.Fatalf("expected 0 reservations, but found %d", n)
}
}
// TestConcurrentRaftSnapshots tests that snapshots still work correctly when
// Raft requests multiple non-preemptive snapshots at the same time. This
// situation occurs when two replicas need snapshots at the same time.
func TestConcurrentRaftSnapshots(t *testing.T) {
defer leaktest.AfterTest(t)()
mtc := startMultiTestContext(t, 5)
defer mtc.Stop()
rng, err := mtc.stores[0].GetReplica(1)
if err != nil {
t.Fatal(err)
}
key := roachpb.Key("a")
incA := int64(5)
incB := int64(7)
incAB := incA + incB
// Set up a key to replicate across the cluster. We're going to modify this
// key and truncate the raft logs from that command after killing one of the
// nodes to check that it gets the new value after it comes up.
incArgs := incrementArgs(key, incA)
if _, err := client.SendWrapped(context.Background(), rg1(mtc.stores[0]), &incArgs); err != nil {
t.Fatal(err)
}
mtc.replicateRange(1, 1, 2, 3, 4)
mtc.waitForValues(key, []int64{incA, incA, incA, incA, incA})
// Now kill stores 1 + 2, increment the key on the other stores and
// truncate their logs to make sure that when store 1 + 2 comes back up
// they will require a non-preemptive snapshot from Raft.
mtc.stopStore(1)
mtc.stopStore(2)
incArgs = incrementArgs(key, incB)
if _, err := client.SendWrapped(context.Background(), rg1(mtc.stores[0]), &incArgs); err != nil {
t.Fatal(err)
}
mtc.waitForValues(key, []int64{incAB, incA, incA, incAB, incAB})
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, 1)
if _, err := client.SendWrapped(context.Background(), rg1(mtc.stores[0]), &truncArgs); err != nil {
t.Fatal(err)
}
mtc.restartStore(1)
mtc.restartStore(2)
mtc.waitForValues(key, []int64{incAB, incAB, incAB, incAB, incAB})
}
// Test a scenario where a replica is removed from a down node, the associated
// range is split, the node restarts and we try to replicate the RHS of the
// split range back to the restarted node.
func TestReplicateAfterRemoveAndSplit(t *testing.T) {
defer leaktest.AfterTest(t)()
sc := storage.TestStoreConfig(nil)
// Disable the replica GC queue so that it doesn't accidentally pick up the
// removed replica and GC it. We'll explicitly enable it later in the test.
sc.TestingKnobs.DisableReplicaGCQueue = true
mtc := &multiTestContext{storeConfig: &sc}
mtc.Start(t, 3)
defer mtc.Stop()
rep1, err := mtc.stores[0].GetReplica(1)
if err != nil {
t.Fatal(err)
}
mtc.replicateRange(1, 1, 2)
// Kill store 2.
mtc.stopStore(2)
// Remove store 2 from the range to simulate removal of a dead node.
mtc.unreplicateRange(1, 2)
// Split the range.
splitKey := roachpb.Key("m")
splitArgs := adminSplitArgs(splitKey, splitKey)
if _, err := rep1.AdminSplit(context.Background(), splitArgs, rep1.Desc()); err != nil {
t.Fatal(err)
}
mtc.expireLeases()
// Restart store 2.
mtc.restartStore(2)
replicateRHS := func() error {
// Try to up-replicate the RHS of the split to store 2. We can't use
// replicateRange because this should fail on the first attempt and then
// eventually succeed.
startKey := roachpb.RKey(splitKey)
var desc roachpb.RangeDescriptor
if err := mtc.dbs[0].GetProto(context.TODO(), keys.RangeDescriptorKey(startKey), &desc); err != nil {
t.Fatal(err)
}
rep2, err := mtc.findMemberStoreLocked(desc).GetReplica(desc.RangeID)
if err != nil {
t.Fatal(err)
}
return rep2.ChangeReplicas(
context.Background(),
roachpb.ADD_REPLICA,
roachpb.ReplicaDescriptor{
NodeID: mtc.stores[2].Ident.NodeID,
StoreID: mtc.stores[2].Ident.StoreID,
},
&desc,
)
}
expected := "snapshot intersects existing range"
if err := replicateRHS(); !testutils.IsError(err, expected) {
t.Fatalf("unexpected error %v", err)
}
// Enable the replica GC queue so that the next attempt to replicate the RHS
// to store 2 will cause the obsolete replica to be GC'd allowing a
// subsequent replication to succeed.
mtc.stores[2].SetReplicaGCQueueActive(true)
util.SucceedsSoon(t, replicateRHS)
}
// Test various mechanism for refreshing pending commands.
func TestRefreshPendingCommands(t *testing.T) {
defer leaktest.AfterTest(t)()
// In this scenario, three different mechanisms detect the need to repropose
// commands. Test that each one is sufficient individually. We have this
// redundancy because some mechanisms respond with lower latency than others,
// but each has some scenarios (not currently tested) in which it is
// insufficient on its own. In addition, there is a fourth reproposal
// mechanism (reasonNewLeaderOrConfigChange) which is not relevant to this
// scenario.
testCases := []storage.StoreTestingKnobs{
{DisableRefreshReasonNewLeader: true, DisableRefreshReasonTicks: true},
{DisableRefreshReasonSnapshotApplied: true, DisableRefreshReasonTicks: true},
{DisableRefreshReasonNewLeader: true, DisableRefreshReasonSnapshotApplied: true},
}
for _, c := range testCases {
func() {
sc := storage.TestStoreConfig(nil)
sc.TestingKnobs = c
// Disable periodic gossip tasks which can move the range 1 lease
// unexpectedly.
sc.TestingKnobs.DisablePeriodicGossips = true
mtc := &multiTestContext{storeConfig: &sc}
mtc.Start(t, 3)
defer mtc.Stop()
rangeID := roachpb.RangeID(1)
mtc.replicateRange(rangeID, 1, 2)
// Put some data in the range so we'll have something to test for.
incArgs := incrementArgs([]byte("a"), 5)
if _, err := client.SendWrapped(context.Background(), rg1(mtc.stores[0]), &incArgs); err != nil {
t.Fatal(err)
}
// Wait for all nodes to catch up.
mtc.waitForValues(roachpb.Key("a"), []int64{5, 5, 5})
// Stop node 2; while it is down write some more data.
mtc.stopStore(2)
if _, err := client.SendWrapped(context.Background(), rg1(mtc.stores[0]), &incArgs); err != nil {
t.Fatal(err)
}
// Get the last increment's log index.
rng, err := mtc.stores[0].GetReplica(1)
if err != nil {
t.Fatal(err)
}
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, rangeID)
if _, err := client.SendWrapped(context.Background(), rg1(mtc.stores[0]), &truncArgs); err != nil {
t.Fatal(err)
}
// Stop and restart node 0 in order to make sure that any in-flight Raft
// messages have been sent.
mtc.stopStore(0)
mtc.restartStore(0)
// Expire existing leases (i.e. move the clock forward). This allows node
// 3 to grab the lease later in the test.
mtc.expireLeases()
// Drain leases from nodes 0 and 1 to prevent them from grabbing any new
// leases.
for i := 0; i < 2; i++ {
if err := mtc.stores[i].DrainLeases(true); err != nil {
t.Fatal(err)
}
}
// Restart node 2 and wait for the snapshot to be applied. Note that
// waitForValues reads directly from the engine and thus isn't executing
// a Raft command.
mtc.restartStore(2)
mtc.waitForValues(roachpb.Key("a"), []int64{10, 10, 10})
// Send an increment to the restarted node. If we don't refresh pending
// commands appropriately, the range lease command will not get
// re-proposed when we discover the new leader.
if _, err := client.SendWrapped(context.Background(), rg1(mtc.stores[2]), &incArgs); err != nil {
t.Fatal(err)
}
mtc.waitForValues(roachpb.Key("a"), []int64{15, 15, 15})
}()
}
}
// 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()
mtc.initGossipNetwork()
// 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
})
}
// TestStoreRangeCorruptionChangeReplicas verifies that the replication queue
// will notice corrupted replicas and replace them.
func TestStoreRangeCorruptionChangeReplicas(t *testing.T) {
defer leaktest.AfterTest(t)()
const numReplicas = 3
const extraStores = 3
sc := storage.TestStoreConfig(nil)
var corrupt struct {
syncutil.Mutex
store *storage.Store
}
sc.TestingKnobs.TestingCommandFilter = func(filterArgs storagebase.FilterArgs) *roachpb.Error {
corrupt.Lock()
defer corrupt.Unlock()
if corrupt.store == nil || filterArgs.Sid != corrupt.store.StoreID() {
return nil
}
if filterArgs.Req.Header().Key.Equal(roachpb.Key("boom")) {
return roachpb.NewError(storage.NewReplicaCorruptionError(errors.New("test")))
}
return nil
}
// Don't timeout raft leader.
sc.RaftElectionTimeoutTicks = 1000000
mtc := &multiTestContext{
storeConfig: &sc,
}
mtc.Start(t, numReplicas+extraStores)
defer mtc.Stop()
mtc.initGossipNetwork()
store0 := mtc.stores[0]
for i := 0; i < extraStores; i++ {
util.SucceedsSoon(t, func() error {
store0.ForceReplicationScanAndProcess()
replicas := store0.LookupReplica(roachpb.RKey("a"), roachpb.RKey("b")).Desc().Replicas
if len(replicas) < numReplicas {
return errors.Errorf("initial replication: expected len(replicas) = %d, got %+v", numReplicas, replicas)
}
corrupt.Lock()
defer corrupt.Unlock()
// Pick a random replica to corrupt.
for corrupt.store = nil; corrupt.store == nil || corrupt.store == store0; {
storeID := replicas[rand.Intn(len(replicas))].StoreID
for _, store := range mtc.stores {
if store.StoreID() == storeID {
corrupt.store = store
break
}
}
}
return nil
})
var corruptRep roachpb.ReplicaDescriptor
util.SucceedsSoon(t, func() error {
r := corrupt.store.LookupReplica(roachpb.RKey("a"), roachpb.RKey("b"))
if r == nil {
return errors.New("replica is not available yet")
}
var err error
corruptRep, err = r.GetReplicaDescriptor()
return err
})