-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
client_raft_test.go
5966 lines (5329 loc) · 202 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.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package kvserver_test
import (
"bytes"
"context"
"fmt"
"math"
"math/rand"
"reflect"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/gossip"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvserverbase"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvserverpb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/liveness/livenesspb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/rditer"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/stateloader"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/rpc"
"github.com/cockroachdb/cockroach/pkg/rpc/nodedialer"
"github.com/cockroachdb/cockroach/pkg/server"
"github.com/cockroachdb/cockroach/pkg/server/serverpb"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/spanconfig"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/bootstrap"
"github.com/cockroachdb/cockroach/pkg/storage"
"github.com/cockroachdb/cockroach/pkg/storage/enginepb"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/skip"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/testutils/storageutils"
"github.com/cockroachdb/cockroach/pkg/testutils/testcluster"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/ctxgroup"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/humanizeutil"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/randutil"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
raft "go.etcd.io/etcd/raft/v3"
"go.etcd.io/etcd/raft/v3/raftpb"
"google.golang.org/grpc"
)
// 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
}
func TestXXX(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
stickyEngineRegistry := server.NewStickyInMemEnginesRegistry()
defer stickyEngineRegistry.CloseAllStickyInMemEngines()
ctx := context.Background()
tc := testcluster.StartTestCluster(t, 1,
base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgs: base.TestServerArgs{
StoreSpecs: []base.StoreSpec{
{
InMemory: true,
StickyInMemoryEngineID: "1",
},
},
Knobs: base.TestingKnobs{
Server: &server.TestingKnobs{
StickyEngineRegistry: stickyEngineRegistry,
},
Store: &kvserver.StoreTestingKnobs{
GlobalMVCCRangeTombstone: true,
},
},
},
})
defer tc.Stopper().Stop(ctx)
time.Sleep(5 * time.Second)
}
// 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)()
defer log.Scope(t).Close(t)
stickyEngineRegistry := server.NewStickyInMemEnginesRegistry()
defer stickyEngineRegistry.CloseAllStickyInMemEngines()
ctx := context.Background()
tc := testcluster.StartTestCluster(t, 1,
base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgs: base.TestServerArgs{
StoreSpecs: []base.StoreSpec{
{
InMemory: true,
StickyInMemoryEngineID: "1",
},
},
Knobs: base.TestingKnobs{
Server: &server.TestingKnobs{
StickyEngineRegistry: stickyEngineRegistry,
},
},
},
})
defer tc.Stopper().Stop(ctx)
splitKey := roachpb.Key("m")
key1 := roachpb.Key("a")
key2 := roachpb.Key("z")
get := func(store *kvserver.Store, key roachpb.Key) int64 {
args := getArgs(key)
resp, err := kv.SendWrappedWith(ctx, store.TestSender(), roachpb.Header{}, args)
if err != nil {
t.Fatal(err)
}
return mustGetInt(resp.(*roachpb.GetResponse).Value)
}
validate := func(store *kvserver.Store) {
if val := get(store, key1); val != 13 {
t.Errorf("key %q: expected 13 but got %v", key1, val)
}
if val := get(store, 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() {
store := tc.GetFirstStoreFromServer(t, 0)
increment := func(key roachpb.Key, value int64) (*roachpb.IncrementResponse, *roachpb.Error) {
args := incrementArgs(key, value)
resp, err := kv.SendWrappedWith(ctx, store.TestSender(), roachpb.Header{}, args)
incResp, _ := resp.(*roachpb.IncrementResponse)
return incResp, err
}
if _, err := increment(key1, 2); err != nil {
t.Fatal(err)
}
if _, err := increment(key2, 5); err != nil {
t.Fatal(err)
}
splitArgs := adminSplitArgs(splitKey)
if _, err := kv.SendWrapped(ctx, store.TestSender(), splitArgs); err != nil {
t.Fatal(err)
}
lhsRepl := store.LookupReplica(roachpb.RKey(key1))
rhsRepl := store.LookupReplica(roachpb.RKey(key2))
if lhsRepl.RangeID == rhsRepl.RangeID {
t.Fatal("got same range id after split")
}
if _, err := increment(key1, 11); err != nil {
t.Fatal(err)
}
if _, err := increment(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.
tc.StopServer(0)
require.NoError(t, tc.RestartServer(0))
store := tc.GetFirstStoreFromServer(t, 0)
// 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 := kv.SendWrapped(ctx, store.TestSender(), incArgs); err != nil {
t.Fatal(err)
}
incArgs = incrementArgs(key2, 0)
if _, err := kv.SendWrappedWith(ctx, store.TestSender(), roachpb.Header{}, 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)()
defer log.Scope(t).Close(t)
stickyEngineRegistry := server.NewStickyInMemEnginesRegistry()
defer stickyEngineRegistry.CloseAllStickyInMemEngines()
numIncrements := 0
keyA := roachpb.Key("a")
ctx := context.Background()
tc := testcluster.StartTestCluster(t, 1,
base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgs: base.TestServerArgs{
Knobs: base.TestingKnobs{
Server: &server.TestingKnobs{
StickyEngineRegistry: stickyEngineRegistry,
},
Store: &kvserver.StoreTestingKnobs{
EvalKnobs: kvserverbase.BatchEvalTestingKnobs{
TestingEvalFilter: func(filterArgs kvserverbase.FilterArgs) *roachpb.Error {
_, ok := filterArgs.Req.(*roachpb.IncrementRequest)
if ok && filterArgs.Req.Header().Key.Equal(keyA) {
numIncrements++
}
return nil
},
},
},
},
StoreSpecs: []base.StoreSpec{
{
InMemory: true,
StickyInMemoryEngineID: "1",
},
},
},
})
defer tc.Stopper().Stop(ctx)
store := tc.GetFirstStoreFromServer(t, 0)
// Write a bytes value so the increment will fail.
putArgs := putArgs(keyA, []byte("asdf"))
if _, err := kv.SendWrapped(ctx, store.TestSender(), 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(keyA, 42)
if _, err := kv.SendWrapped(ctx, store.TestSender(), 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.
tc.StopServer(0)
require.NoError(t, tc.RestartServer(0))
recoveredStore := tc.GetFirstStoreFromServer(t, 0)
// Issue a no-op write to lazily initialize raft on the range.
keyB := roachpb.Key("b")
incArgs = incrementArgs(keyB, 0)
if _, err := kv.SendWrapped(ctx, recoveredStore.TestSender(), 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)()
defer log.Scope(t).Close(t)
ctx := context.Background()
tc := testcluster.StartTestCluster(t, 2,
base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
})
defer tc.Stopper().Stop(ctx)
store := tc.GetFirstStoreFromServer(t, 0)
keyA := []byte("a")
_, rhsDesc := tc.SplitRangeOrFatal(t, keyA)
// Issue a command on the first node before replicating.
incArgs := incrementArgs(keyA, 5)
if _, err := kv.SendWrapped(ctx, store.TestSender(), incArgs); err != nil {
t.Fatal(err)
}
tc.AddVotersOrFatal(t, keyA, tc.Target(1))
// Verify no intent remains on range descriptor key.
key := keys.RangeDescriptorKey(rhsDesc.StartKey)
desc := roachpb.RangeDescriptor{}
if ok, err := storage.MVCCGetProto(ctx, store.Engine(), key,
store.Clock().Now(), &desc, storage.MVCCGetOptions{}); 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.
testutils.SucceedsSoon(t, func() error {
meta2 := keys.RangeMetaKey(roachpb.RKeyMax)
meta1 := keys.RangeMetaKey(meta2)
for _, key := range []roachpb.RKey{meta2, meta1} {
metaDesc := roachpb.RangeDescriptor{}
if ok, err := storage.MVCCGetProto(ctx, store.Engine(), key.AsRawKey(),
store.Clock().Now(), &metaDesc, storage.MVCCGetOptions{}); err != nil {
return err
} else if !ok {
return errors.Errorf("failed to resolve %s", key.AsRawKey())
}
}
return nil
})
// Verify that the same data is available on the replica.
testutils.SucceedsSoon(t, func() error {
getArgs := getArgs(keyA)
if reply, err := kv.SendWrappedWith(ctx, tc.GetFirstStoreFromServer(t, 1).TestSender(), 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)()
defer log.Scope(t).Close(t)
stickyEngineRegistry := server.NewStickyInMemEnginesRegistry()
defer stickyEngineRegistry.CloseAllStickyInMemEngines()
const numServers int = 2
stickyServerArgs := make(map[int]base.TestServerArgs)
for i := 0; i < numServers; i++ {
stickyServerArgs[i] = base.TestServerArgs{
StoreSpecs: []base.StoreSpec{
{
InMemory: true,
StickyInMemoryEngineID: strconv.FormatInt(int64(i), 10),
},
},
Knobs: base.TestingKnobs{
Server: &server.TestingKnobs{
StickyEngineRegistry: stickyEngineRegistry,
},
},
}
}
ctx := context.Background()
tc := testcluster.StartTestCluster(t, 2,
base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgsPerNode: stickyServerArgs,
})
defer tc.Stopper().Stop(ctx)
store := tc.GetFirstStoreFromServer(t, 0)
key := []byte("a")
tc.SplitRangeOrFatal(t, key)
// Perform an increment before replication to ensure that commands are not
// repeated on restarts.
incArgs := incrementArgs([]byte("a"), 23)
if _, err := kv.SendWrapped(ctx,
store.TestSender(), incArgs); err != nil {
t.Fatal(err)
}
tc.AddVotersOrFatal(t, key, tc.Target(1))
require.NoError(t, tc.Restart())
incArgs = incrementArgs([]byte("a"), 5)
failures := 0
successes := 0
// Send a command on each store. It should only succeed on the lease holder.
var followerStore *kvserver.Store
for i := 0; i < len(tc.Servers); i++ {
if _, pErr := kv.SendWrapped(ctx, tc.GetFirstStoreFromServer(t, i).TestSender(), incArgs); pErr != nil {
failures++
if _, ok := pErr.GetDetail().(*roachpb.NotLeaseHolderError); !ok {
t.Fatalf("expected not lease holder error; got %s", pErr)
}
followerStore = tc.GetFirstStoreFromServer(t, i)
} else {
successes++
}
}
require.Equal(t, failures, 1)
require.Equal(t, successes, 1)
testutils.SucceedsSoon(t, func() error {
getArgs := getArgs([]byte("a"))
if reply, err := kv.SendWrappedWith(ctx, followerStore.TestSender(), roachpb.Header{
ReadConsistency: roachpb.INCONSISTENT,
}, getArgs); err != nil {
return errors.Errorf("failed to read data: %s", err)
} else if e, v := int64(28), mustGetInt(reply.(*roachpb.GetResponse).Value); v != e {
return errors.Errorf("failed to read correct data: expected %d, got %d", e, v)
}
return nil
})
validate := func(s *kvserver.Store) {
repl := s.LookupReplica(key)
desc := repl.Desc()
if len(desc.InternalReplicas) != 2 {
t.Fatalf("store %d: expected 2 replicas, found %d", s.Ident.StoreID, len(desc.InternalReplicas))
}
if desc.InternalReplicas[0].NodeID != store.Ident.NodeID {
t.Errorf("store %d: expected replica[0].NodeID == %d, was %d",
store.Ident.StoreID, store.Ident.NodeID, desc.InternalReplicas[0].NodeID)
}
}
// Both replicas have a complete list in Desc.Replicas
validate(tc.GetFirstStoreFromServer(t, 0))
validate(tc.GetFirstStoreFromServer(t, 1))
}
// TODO(bdarnell): more aggressive testing here; especially with
// proposer-evaluated KV, what this test does is much less as it doesn't
// exercise the path in which the replica change fails at *apply* time (we only
// test the failfast path), in which case the replica change isn't even
// proposed.
func TestFailedReplicaChange(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
var runFilter atomic.Value
runFilter.Store(true)
testingEvalFilter := func(filterArgs kvserverbase.FilterArgs) *roachpb.Error {
if runFilter.Load().(bool) {
if et, ok := filterArgs.Req.(*roachpb.EndTxnRequest); ok && et.Commit &&
et.InternalCommitTrigger != nil && et.InternalCommitTrigger.ChangeReplicasTrigger != nil {
return roachpb.NewErrorWithTxn(errors.Errorf("boom"), filterArgs.Hdr.Txn)
}
}
return nil
}
ctx := context.Background()
manualClock := hlc.NewHybridManualClock()
tc := testcluster.StartTestCluster(t, 2,
base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgs: base.TestServerArgs{
Knobs: base.TestingKnobs{
Server: &server.TestingKnobs{
WallClock: manualClock,
},
Store: &kvserver.StoreTestingKnobs{
EvalKnobs: kvserverbase.BatchEvalTestingKnobs{
TestingEvalFilter: testingEvalFilter,
},
},
},
},
})
defer tc.Stopper().Stop(ctx)
store := tc.GetFirstStoreFromServer(t, 0)
key := tc.ScratchRange(t)
repl := store.LookupReplica(roachpb.RKey(key))
if _, err := tc.AddVoters(key, tc.Target(1)); !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 := repl.Desc().InternalReplicas; 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.
manualClock.Increment(10 * base.DefaultTxnHeartbeatInterval.Nanoseconds())
tc.AddVotersOrFatal(t, key, tc.Target(1))
// Wait for the range to sync to both replicas (mainly so leaktest doesn't
// complain about goroutines involved in the process).
require.NoError(t, tc.WaitForVoters(key, tc.Targets(0, 1)...))
}
// 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)()
defer log.Scope(t).Close(t)
ctx := context.Background()
tc := testcluster.StartTestCluster(t, 2,
base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
})
defer tc.Stopper().Stop(ctx)
store := tc.GetFirstStoreFromServer(t, 0)
key := []byte("a")
tc.SplitRangeOrFatal(t, key)
// Issue a command on the first node before replicating.
incArgs := incrementArgs(key, 5)
if _, err := kv.SendWrapped(ctx, store.TestSender(), incArgs); err != nil {
t.Fatal(err)
}
repl := store.LookupReplica(key)
// Get that command's log index.
index := repl.GetLastIndex()
// Truncate the log at index+1 (log entries < N are removed, so this includes
// the increment).
truncArgs := truncateLogArgs(index+1, repl.GetRangeID())
if _, err := kv.SendWrapped(ctx, store.TestSender(), truncArgs); err != nil {
t.Fatal(err)
}
// Issue a second command post-truncation.
incArgs = incrementArgs([]byte("a"), 11)
if _, err := kv.SendWrapped(ctx, store.TestSender(), incArgs); err != nil {
t.Fatal(err)
}
// Now add the second replica.
tc.AddVotersOrFatal(t, key, tc.Target(1))
// Once it catches up, the effects of both commands can be seen.
testutils.SucceedsSoon(t, func() error {
getArgs := getArgs([]byte("a"))
if reply, err := kv.SendWrappedWith(ctx, tc.GetFirstStoreFromServer(t, 1).TestSender(), 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
})
repl2 := tc.GetFirstStoreFromServer(t, 1).LookupReplica(key)
testutils.SucceedsSoon(t, func() error {
if mvcc, mvcc2 := repl.GetMVCCStats(), repl2.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 := kv.SendWrapped(ctx, store.TestSender(), incArgs); err != nil {
t.Fatal(err)
}
testutils.SucceedsSoon(t, func() error {
getArgs := getArgs([]byte("a"))
if reply, err := kv.SendWrappedWith(ctx, tc.GetFirstStoreFromServer(t, 1).TestSender(), 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
})
}
func TestRaftLogSizeAfterTruncation(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
tc := testcluster.StartTestCluster(t, 1,
base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
})
defer tc.Stopper().Stop(ctx)
store := tc.GetFirstStoreFromServer(t, 0)
key := []byte("a")
tc.SplitRangeOrFatal(t, key)
incArgs := incrementArgs(key, 5)
if _, err := kv.SendWrapped(ctx, store.TestSender(), incArgs); err != nil {
t.Fatal(err)
}
repl := store.LookupReplica(key)
require.NotNil(t, repl)
index := repl.GetLastIndex()
// Verifies the recomputed log size against what we track in `r.mu.raftLogSize`.
assertCorrectRaftLogSize := func() error {
// Recompute under raft lock so that the log doesn't change while we
// compute its size.
repl.RaftLock()
realSize, err := kvserver.ComputeRaftLogSize(
ctx, repl.RangeID, repl.Engine(), repl.SideloadedRaftMuLocked(),
)
size, _ := repl.GetRaftLogSize()
repl.RaftUnlock()
if err != nil {
t.Fatal(err)
}
// If the size isn't trusted, it won't have to match (and in fact
// likely won't). In this test, this is because the upreplication
// elides old Raft log entries in the snapshot it uses.
if size != realSize {
return fmt.Errorf("%s: raft log claims size %d, but is in fact %d", repl, size, realSize)
}
return nil
}
assert.NoError(t, assertCorrectRaftLogSize())
truncArgs := truncateLogArgs(index+1, repl.GetRangeID())
if _, err := kv.SendWrapped(ctx, store.TestSender(), truncArgs); err != nil {
t.Fatal(err)
}
// Note that if there were multiple nodes, the Raft log sizes would not
// be correct for the followers as they would have received a shorter
// Raft log than the leader.
assert.NoError(t, assertCorrectRaftLogSize())
}
// TestSnapshotAfterTruncation tests that Raft will properly send a snapshot
// when a node is brought up and the log has been truncated.
func TestSnapshotAfterTruncation(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
for _, changeTerm := range []bool{false, true} {
name := "sameTerm"
if changeTerm {
name = "differentTerm"
}
t.Run(name, func(t *testing.T) {
stickyEngineRegistry := server.NewStickyInMemEnginesRegistry()
defer stickyEngineRegistry.CloseAllStickyInMemEngines()
const numServers int = 3
stickyServerArgs := make(map[int]base.TestServerArgs)
for i := 0; i < numServers; i++ {
stickyServerArgs[i] = base.TestServerArgs{
StoreSpecs: []base.StoreSpec{
{
InMemory: true,
StickyInMemoryEngineID: strconv.FormatInt(int64(i), 10),
},
},
Knobs: base.TestingKnobs{
Server: &server.TestingKnobs{
StickyEngineRegistry: stickyEngineRegistry,
},
},
}
}
ctx := context.Background()
tc := testcluster.StartTestCluster(t, numServers,
base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgsPerNode: stickyServerArgs,
})
defer tc.Stopper().Stop(ctx)
store := tc.GetFirstStoreFromServer(t, 0)
var stoppedStore = 1
var otherStore1 = 0
var otherStore2 = 2
key := []byte("a")
tc.SplitRangeOrFatal(t, key)
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 := kv.SendWrapped(ctx, store.TestSender(), incArgs); err != nil {
t.Fatal(err)
}
tc.AddVotersOrFatal(t, key, tc.Targets(1, 2)...)
tc.WaitForValues(t, key, []int64{incA, incA, incA})
// Now kill one store, 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 snapshot from Raft.
tc.StopServer(stoppedStore)
incArgs = incrementArgs(key, incB)
if _, err := kv.SendWrapped(ctx, store.TestSender(), incArgs); err != nil {
t.Fatal(err)
}
tc.WaitForValues(t, key, []int64{incAB, incA, incAB})
repl0 := store.LookupReplica(key)
index := repl0.GetLastIndex()
// Truncate the log at index+1 (log entries < N are removed, so this
// includes the increment).
truncArgs := truncateLogArgs(index+1, repl0.GetRangeID())
if _, err := kv.SendWrapped(ctx, store.TestSender(), truncArgs); err != nil {
t.Fatal(err)
}
stopServer := func(i int) {
// Stop and restart all the live stores, which guarantees that
// we won't be in the same term we started with.
tc.StopServer(i)
require.NoError(t, tc.RestartServer(i))
// Disable the snapshot queue on the live stores so that
// stoppedStore won't get a snapshot as soon as it starts
// back up.
tc.GetFirstStoreFromServer(t, i).SetRaftSnapshotQueueActive(false)
}
if changeTerm {
stopServer(otherStore2)
stopServer(otherStore1)
// Restart the stopped store and wait for raft
// election/heartbeat traffic to settle down. Specifically, we
// need stoppedStore to know about the new term number before
// the snapshot is sent to reproduce #13506. If the snapshot
// happened before it learned the term, it would accept the
// snapshot no matter what term it contained.
//
// We do not wait for the store to successfully heartbeat
// because it is not expected to succeed in cases where the
// other two stores have already completed their leader
// election. In this case, a successful heartbeat won't be
// possible until we re-enable snapshots.
require.NoError(t, tc.RestartServer(stoppedStore))
testutils.SucceedsSoon(t, func() error {
hasLeader := false
term := uint64(0)
for i := 0; i < len(tc.Servers); i++ {
repl := tc.GetFirstStoreFromServer(t, i).LookupReplica(key)
require.NotNil(t, repl)
status := repl.RaftStatus()
if status == nil {
return errors.New("raft status not initialized")
}
if status.RaftState == raft.StateLeader {
hasLeader = true
}
if term == 0 {
term = status.Term
} else if status.Term != term {
return errors.Errorf("terms do not agree: %d vs %d", status.Term, term)
}
}
if !hasLeader {
return errors.New("no leader")
}
return nil
})
// Turn the queues back on and wait for the snapshot to be sent and processed.
for i := 0; i < len(tc.Servers)-1; i++ {
tc.GetFirstStoreFromServer(t, i).SetRaftSnapshotQueueActive(true)
if err := tc.GetFirstStoreFromServer(t, i).ForceRaftSnapshotQueueProcess(); err != nil {
t.Fatal(err)
}
}
} else { // !changeTerm
require.NoError(t, tc.RestartServer(stoppedStore))
}
tc.WaitForValues(t, key, []int64{incAB, incAB, incAB})
testutils.SucceedsSoon(t, func() error {
// Verify that the cached index and term (Replica.mu.last{Index,Term}))
// on all of the replicas is the same. #18327 fixed an issue where the
// cached term was left unchanged after applying a snapshot leading to a
// persistently unavailable range.
repl0 = tc.GetFirstStoreFromServer(t, otherStore1).LookupReplica(key)
require.NotNil(t, repl0)
expectedLastIndex := repl0.GetLastIndex()
expectedLastTerm := repl0.GetCachedLastTerm()
verifyIndexAndTerm := func(i int) error {
repl1 := tc.GetFirstStoreFromServer(t, i).LookupReplica(key)
require.NotNil(t, repl1)
if lastIndex := repl1.GetLastIndex(); expectedLastIndex != lastIndex {
return fmt.Errorf("%d: expected last index %d, but found %d", i, expectedLastIndex, lastIndex)
}
if lastTerm := repl1.GetCachedLastTerm(); expectedLastTerm != lastTerm {
return fmt.Errorf("%d: expected last term %d, but found %d", i, expectedLastTerm, lastTerm)
}
return nil
}
if err := verifyIndexAndTerm(otherStore2); err != nil {
return err
}
if err := verifyIndexAndTerm(stoppedStore); err != nil {
return err
}
return nil
})
})
}
}
func waitForTruncationForTesting(t *testing.T, r *kvserver.Replica, newFirstIndex uint64) {
testutils.SucceedsSoon(t, func() error {
// Flush the engine to advance durability, which triggers truncation.
require.NoError(t, r.Engine().Flush())
// FirstIndex has changed.
firstIndex := r.GetFirstIndex()
if firstIndex != newFirstIndex {
return errors.Errorf("expected firstIndex == %d, got %d", newFirstIndex, firstIndex)
}
return nil
})
}
// TestSnapshotAfterTruncationWithUncommittedTail is similar in spirit to
// TestSnapshotAfterTruncation/differentTerm. However, it differs in that we
// take care to ensure that the partitioned Replica has a long uncommitted tail
// of Raft entries that is not entirely overwritten by the snapshot it receives
// after the partition heals. If the recipient of the snapshot did not purge its
// Raft entry cache when receiving the snapshot, it could get stuck repeatedly
// rejecting attempts to catch it up. This serves as a regression test for the
// bug seen in #37056.
func TestSnapshotAfterTruncationWithUncommittedTail(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
ctx := context.Background()
manualClock := hlc.NewHybridManualClock()
tc := testcluster.StartTestCluster(t, 3,
base.TestClusterArgs{
ReplicationMode: base.ReplicationManual,
ServerArgs: base.TestServerArgs{
Knobs: base.TestingKnobs{
Server: &server.TestingKnobs{
WallClock: manualClock,
},
},
},
})
defer tc.Stopper().Stop(ctx)
store := tc.GetFirstStoreFromServer(t, 0)
key := tc.ScratchRangeWithExpirationLease(t)
incA := int64(5)
incB := int64(7)
incC := int64(9)
incAB := incA + incB
incABC := incAB + incC
// 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 partitioning one
// of the nodes to check that it gets the new value after it reconnects.
// We're then going to continue modifying this key to make sure that the
// temporarily partitioned node can continue to receive updates.
incArgs := incrementArgs(key, incA)
if _, pErr := kv.SendWrapped(ctx, store.TestSender(), incArgs); pErr != nil {
t.Fatal(pErr)
}
tc.AddVotersOrFatal(t, key, tc.Targets(1, 2)...)
require.NoError(t, tc.WaitForVoters(key, tc.Targets(1, 2)...))
tc.WaitForValues(t, key, []int64{incA, incA, incA})
// We partition the original leader from the other two replicas. This allows
// us to build up a large uncommitted Raft log on the partitioned node.
const partStore = 0
partRepl := tc.GetFirstStoreFromServer(t, partStore).LookupReplica(roachpb.RKey(key))
partReplDesc, err := partRepl.GetReplicaDescriptor()
if err != nil {
t.Fatal(err)
}
partReplSender := tc.GetFirstStoreFromServer(t, partStore).TestSender()
// Partition the original leader from its followers. We do this by installing
// unreliableRaftHandler listeners on all three Stores. The handler on the
// partitioned store filters out all messages while the handler on the other
// two stores only filters out messages from the partitioned store. The
// configuration looks like:
//
// [0]
// x x
// / \
// x x
// [1]<---->[2]
//
log.Infof(ctx, "test: installing unreliable Raft transports")
for _, s := range []int{0, 1, 2} {
h := &unreliableRaftHandler{
rangeID: partRepl.RangeID,
RaftMessageHandler: tc.GetFirstStoreFromServer(t, s),
}
if s != partStore {
// Only filter messages from the partitioned store on the other
// two stores.
h.dropReq = func(req *kvserverpb.RaftMessageRequest) bool {
return req.FromReplica.StoreID == partRepl.StoreID()
}
h.dropHB = func(hb *kvserverpb.RaftHeartbeat) bool {
return hb.FromReplicaID == partReplDesc.ReplicaID
}
}
tc.Servers[s].RaftTransport().Listen(tc.Target(s).StoreID, h)
}
// Perform a series of writes on the partitioned replica. The writes will
// not succeed before their context is canceled, but they will be appended
// to the partitioned replica's Raft log because it is currently the Raft
// leader.
log.Infof(ctx, "test: sending writes to partitioned replica")
g := ctxgroup.WithContext(ctx)
otherKeys := make([]roachpb.Key, 32)
otherKeys[0] = key.Next()
for i := 1; i < 32; i++ {
otherKeys[i] = otherKeys[i-1].Next()
}
for i := range otherKeys {
// This makes the race detector happy.
otherKey := otherKeys[i]
g.GoCtx(func(ctx context.Context) error {
cCtx, cancel := context.WithTimeout(ctx, 50*time.Millisecond)
defer cancel()
incArgsOther := incrementArgs(otherKey, 1)
if _, pErr := kv.SendWrapped(cCtx, partReplSender, incArgsOther); pErr == nil {
return errors.New("unexpected success")
} else if !testutils.IsPError(pErr, "context deadline exceeded") {
return pErr.GoError()
}
return nil
})
}
if err := g.Wait(); err != nil {
t.Fatal(err)
}
// Transfer the lease to one of the followers and perform a write. The
// partition ensures that this will require a Raft leadership change. It's
// unpredictable which one of the followers will become leader. Only the
// leader will be allowed to acquire the lease (see
// TestSnapshotAfterTruncationWithUncommittedTail), so it's also unpredictable
// who will get the lease. We try repeatedly sending requests to both
// candidates until one of them succeeds.