-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
testcluster.go
1561 lines (1416 loc) · 50.7 KB
/
testcluster.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 2016 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 testcluster
import (
"context"
gosql "database/sql"
"fmt"
"net"
"reflect"
"runtime"
"strings"
"sync"
"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/kvserver"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/liveness/livenesspb"
"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/storage"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/util/contextutil"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/retry"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/logtags"
"github.com/stretchr/testify/require"
"go.etcd.io/etcd/raft/v3"
)
// TestCluster represents a set of TestServers. The hope is that it can be used
// analogous to TestServer, but with control over range replication and join
// flags.
type TestCluster struct {
Servers []*server.TestServer
Conns []*gosql.DB
stopper *stop.Stopper
mu struct {
syncutil.Mutex
serverStoppers []*stop.Stopper
}
serverArgs []base.TestServerArgs
clusterArgs base.TestClusterArgs
t testing.TB
}
var _ serverutils.TestClusterInterface = &TestCluster{}
// NumServers is part of TestClusterInterface.
func (tc *TestCluster) NumServers() int {
return len(tc.Servers)
}
// Server is part of TestClusterInterface.
func (tc *TestCluster) Server(idx int) serverutils.TestServerInterface {
return tc.Servers[idx]
}
// ServerTyped is like Server, but returns the right type.
func (tc *TestCluster) ServerTyped(idx int) *server.TestServer {
return tc.Servers[idx]
}
// ServerConn is part of TestClusterInterface.
func (tc *TestCluster) ServerConn(idx int) *gosql.DB {
return tc.Conns[idx]
}
// Stopper returns the stopper for this testcluster.
func (tc *TestCluster) Stopper() *stop.Stopper {
return tc.stopper
}
// stopServers stops the stoppers for each individual server in the cluster.
// This method ensures that servers that were previously stopped explicitly are
// not double-stopped.
func (tc *TestCluster) stopServers(ctx context.Context) {
tc.mu.Lock()
defer tc.mu.Unlock()
// Quiesce the servers in parallel to avoid deadlocks. If we stop servers
// serially when we lose quorum (2 out of 3 servers have stopped) the last
// server may never finish due to waiting for a Raft command that can't
// commit due to the lack of quorum.
log.Infof(ctx, "TestCluster quiescing nodes")
var wg sync.WaitGroup
wg.Add(len(tc.mu.serverStoppers))
for i, s := range tc.mu.serverStoppers {
go func(i int, s *stop.Stopper) {
defer wg.Done()
if s != nil {
quiesceCtx := logtags.AddTag(ctx, "n", tc.Servers[i].NodeID())
s.Quiesce(quiesceCtx)
}
}(i, s)
}
wg.Wait()
for i := 0; i < tc.NumServers(); i++ {
tc.stopServerLocked(i)
}
// TODO(andrei): Instead of checking for empty tracing registries after
// shutting down each node, we're doing it after shutting down all nodes. This
// is because all the nodes might share the same cluster (in case the Tracer
// was passed in at cluster creation time). We should not allow the Tracer to
// be passed in like this, and we should then also added this registry
// draining check to individual TestServers.
for i := 0; i < tc.NumServers(); i++ {
// Wait until a server's span registry is emptied out. This helps us check
// to see that there are no un-Finish()ed spans. We need to wrap this in a
// SucceedsSoon block because it's possible for us to issue requests during
// server shut down, where the requests in turn would create (registered)
// spans. Cleaning up temporary objects created by the session[1] is one
// example of this.
//
// [1]: cleanupSessionTempObjects
tracer := tc.Servers[i].Tracer()
testutils.SucceedsSoon(tc.t, func() error {
var sps []tracing.RegistrySpan
_ = tracer.VisitSpans(func(span tracing.RegistrySpan) error {
sps = append(sps, span)
return nil
})
if len(sps) == 0 {
return nil
}
var buf strings.Builder
fmt.Fprintf(&buf, "unexpectedly found %d active spans:\n", len(sps))
for _, sp := range sps {
fmt.Fprintln(&buf, sp.GetFullRecording(tracing.RecordingVerbose))
fmt.Fprintln(&buf)
}
return errors.Newf("%s", buf.String())
})
}
// Force a GC in an attempt to run finalizers. Some finalizers run sanity
// checks that panic on failure, and ideally we'd run them all before starting
// the next test.
runtime.GC()
}
// StopServer stops an individual server in the cluster.
func (tc *TestCluster) StopServer(idx int) {
tc.mu.Lock()
defer tc.mu.Unlock()
tc.stopServerLocked(idx)
}
func (tc *TestCluster) stopServerLocked(idx int) {
if tc.mu.serverStoppers[idx] != nil {
tc.mu.serverStoppers[idx].Stop(context.TODO())
tc.mu.serverStoppers[idx] = nil
}
}
// StartTestCluster creates and starts up a TestCluster made up of `nodes`
// in-memory testing servers.
// The cluster should be stopped using TestCluster.Stopper().Stop().
func StartTestCluster(t testing.TB, nodes int, args base.TestClusterArgs) *TestCluster {
cluster := NewTestCluster(t, nodes, args)
cluster.Start(t)
return cluster
}
// NewTestCluster initializes a TestCluster made up of `nodes` in-memory testing
// servers. It needs to be started separately using the return type.
func NewTestCluster(t testing.TB, nodes int, clusterArgs base.TestClusterArgs) *TestCluster {
if nodes < 1 {
t.Fatal("invalid cluster size: ", nodes)
}
if err := checkServerArgsForCluster(
clusterArgs.ServerArgs, clusterArgs.ReplicationMode, disallowJoinAddr,
); err != nil {
t.Fatal(err)
}
for _, sargs := range clusterArgs.ServerArgsPerNode {
if err := checkServerArgsForCluster(
sargs, clusterArgs.ReplicationMode, allowJoinAddr,
); err != nil {
t.Fatal(err)
}
}
tc := &TestCluster{
stopper: stop.NewStopper(),
clusterArgs: clusterArgs,
t: t,
}
// Check if any of the args have a locality set.
noLocalities := true
for _, arg := range tc.clusterArgs.ServerArgsPerNode {
if len(arg.Locality.Tiers) > 0 {
noLocalities = false
break
}
}
if len(tc.clusterArgs.ServerArgs.Locality.Tiers) > 0 {
noLocalities = false
}
var firstListener net.Listener
for i := 0; i < nodes; i++ {
var serverArgs base.TestServerArgs
if perNodeServerArgs, ok := tc.clusterArgs.ServerArgsPerNode[i]; ok {
serverArgs = perNodeServerArgs
} else {
serverArgs = tc.clusterArgs.ServerArgs
}
if len(serverArgs.StoreSpecs) == 0 {
serverArgs.StoreSpecs = []base.StoreSpec{base.DefaultTestStoreSpec}
}
if knobs, ok := serverArgs.Knobs.Server.(*server.TestingKnobs); ok && knobs.StickyEngineRegistry != nil {
for j := range serverArgs.StoreSpecs {
if serverArgs.StoreSpecs[j].StickyInMemoryEngineID == "" {
serverArgs.StoreSpecs[j].StickyInMemoryEngineID = fmt.Sprintf("auto-node%d-store%d", i+1, j+1)
}
}
}
// If no localities are specified in the args, we'll generate some
// automatically.
if noLocalities {
tiers := []roachpb.Tier{
{Key: "region", Value: "test"},
{Key: "dc", Value: fmt.Sprintf("dc%d", i+1)},
}
serverArgs.Locality = roachpb.Locality{Tiers: tiers}
}
if i == 0 {
if serverArgs.Listener != nil {
// If the test installed a listener for us, use that.
firstListener = serverArgs.Listener
} else {
// Pre-bind a listener for node zero so the kernel can go ahead and
// assign its address for use in the other nodes' join flags.
// The Server becomes responsible for closing this.
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
tc.Stopper().Stop(context.Background())
t.Fatal(err)
}
firstListener = listener
serverArgs.Listener = listener
}
} else {
if serverArgs.JoinAddr == "" {
// Point to the first listener unless told explicitly otherwise.
serverArgs.JoinAddr = firstListener.Addr().String()
}
serverArgs.NoAutoInitializeCluster = true
}
if _, err := tc.AddServer(serverArgs); err != nil {
tc.Stopper().Stop(context.Background())
t.Fatal(err)
}
}
return tc
}
// Start is the companion method to NewTestCluster, and is responsible for
// actually starting up the cluster. Start waits for each server to be fully up
// and running.
//
// If looking to test initialization/bootstrap behavior, Start should be invoked
// in a separate thread and with ParallelStart enabled (otherwise it'll block
// on waiting for init for the first server).
func (tc *TestCluster) Start(t testing.TB) {
nodes := len(tc.Servers)
var errCh chan error
if tc.clusterArgs.ParallelStart {
errCh = make(chan error, nodes)
}
disableLBS := false
for i := 0; i < nodes; i++ {
// Disable LBS if any server has a very low scan interval.
if tc.serverArgs[i].ScanInterval > 0 && tc.serverArgs[i].ScanInterval <= 100*time.Millisecond {
disableLBS = true
}
if tc.clusterArgs.ParallelStart {
go func(i int) {
errCh <- tc.startServer(i, tc.serverArgs[i])
}(i)
} else {
if err := tc.startServer(i, tc.serverArgs[i]); err != nil {
t.Fatal(err)
}
// We want to wait for stores for each server in order to have predictable
// store IDs. Otherwise, stores can be asynchronously bootstrapped in an
// unexpected order (#22342).
tc.WaitForNStores(t, i+1, tc.Servers[0].Gossip())
}
}
if tc.clusterArgs.ParallelStart {
for i := 0; i < nodes; i++ {
if err := <-errCh; err != nil {
t.Fatal(err)
}
}
tc.WaitForNStores(t, tc.NumServers(), tc.Servers[0].Gossip())
}
if tc.clusterArgs.ReplicationMode == base.ReplicationManual {
// We've already disabled the merge queue via testing knobs above, but ALTER
// TABLE ... SPLIT AT will throw an error unless we also disable merges via
// the cluster setting.
//
// TODO(benesch): this won't be necessary once we have sticky bits for
// splits.
if _, err := tc.Conns[0].Exec(`SET CLUSTER SETTING kv.range_merge.queue_enabled = false`); err != nil {
t.Fatal(err)
}
}
if disableLBS {
if _, err := tc.Conns[0].Exec(`SET CLUSTER SETTING kv.range_split.by_load_enabled = false`); err != nil {
t.Fatal(err)
}
}
// Create a closer that will stop the individual server stoppers when the
// cluster stopper is stopped.
tc.stopper.AddCloser(stop.CloserFn(func() { tc.stopServers(context.TODO()) }))
if tc.clusterArgs.ReplicationMode == base.ReplicationAuto {
if err := tc.WaitForFullReplication(); err != nil {
t.Fatal(err)
}
}
// Wait until a NodeStatus is persisted for every node (see #25488, #25649, #31574).
tc.WaitForNodeStatuses(t)
}
type checkType bool
const (
disallowJoinAddr checkType = false
allowJoinAddr checkType = true
)
// checkServerArgsForCluster sanity-checks TestServerArgs to work for a cluster
// with a given replicationMode.
func checkServerArgsForCluster(
args base.TestServerArgs, replicationMode base.TestClusterReplicationMode, checkType checkType,
) error {
if checkType == disallowJoinAddr && args.JoinAddr != "" {
return errors.Errorf("can't specify a join addr when starting a cluster: %s",
args.JoinAddr)
}
if args.Stopper != nil {
return errors.Errorf("can't set individual server stoppers when starting a cluster")
}
if args.Knobs.Store != nil {
storeKnobs := args.Knobs.Store.(*kvserver.StoreTestingKnobs)
if storeKnobs.DisableSplitQueue || storeKnobs.DisableReplicateQueue {
return errors.Errorf("can't disable an individual server's queues when starting a cluster; " +
"the cluster controls replication")
}
}
if replicationMode != base.ReplicationAuto && replicationMode != base.ReplicationManual {
return errors.Errorf("unexpected replication mode: %s", replicationMode)
}
return nil
}
// AddAndStartServer creates a server with the specified arguments and appends it to
// the TestCluster. It also starts it.
//
// The new Server's copy of serverArgs might be changed according to the
// cluster's ReplicationMode.
func (tc *TestCluster) AddAndStartServer(t testing.TB, serverArgs base.TestServerArgs) {
if serverArgs.JoinAddr == "" && len(tc.Servers) > 0 {
serverArgs.JoinAddr = tc.Servers[0].ServingRPCAddr()
}
_, err := tc.AddServer(serverArgs)
if err != nil {
t.Fatal(err)
}
if err := tc.startServer(len(tc.Servers)-1, serverArgs); err != nil {
t.Fatal(err)
}
}
// AddServer is like AddAndStartServer, except it does not start it.
func (tc *TestCluster) AddServer(serverArgs base.TestServerArgs) (*server.TestServer, error) {
serverArgs.PartOfCluster = true
if serverArgs.JoinAddr != "" {
serverArgs.NoAutoInitializeCluster = true
}
// Check args even though they might have been checked in StartNewTestCluster;
// this method might be called for servers being added after the cluster was
// started, in which case the check has not been performed.
if err := checkServerArgsForCluster(
serverArgs,
tc.clusterArgs.ReplicationMode,
// Allow JoinAddr here; servers being added after the TestCluster has been
// started should have a JoinAddr filled in at this point.
allowJoinAddr,
); err != nil {
return nil, err
}
if tc.clusterArgs.ReplicationMode == base.ReplicationManual {
var stkCopy kvserver.StoreTestingKnobs
if stk := serverArgs.Knobs.Store; stk != nil {
stkCopy = *stk.(*kvserver.StoreTestingKnobs)
}
stkCopy.DisableSplitQueue = true
stkCopy.DisableMergeQueue = true
stkCopy.DisableReplicateQueue = true
serverArgs.Knobs.Store = &stkCopy
}
// Install listener, if non-empty.
if serverArgs.Listener != nil {
// Instantiate the server testing knobs if non-empty.
if serverArgs.Knobs.Server == nil {
serverArgs.Knobs.Server = &server.TestingKnobs{}
} else {
// Copy the knobs so the struct with the listener is not
// reused for other nodes.
knobs := *serverArgs.Knobs.Server.(*server.TestingKnobs)
serverArgs.Knobs.Server = &knobs
}
// Install the provided listener.
serverArgs.Knobs.Server.(*server.TestingKnobs).RPCListener = serverArgs.Listener
serverArgs.Addr = serverArgs.Listener.Addr().String()
}
srv, err := serverutils.NewServer(serverArgs)
if err != nil {
return nil, err
}
s := srv.(*server.TestServer)
tc.Servers = append(tc.Servers, s)
tc.serverArgs = append(tc.serverArgs, serverArgs)
tc.mu.Lock()
defer tc.mu.Unlock()
tc.mu.serverStoppers = append(tc.mu.serverStoppers, s.Stopper())
return s, nil
}
// startServer is the companion method to AddServer, and is responsible for
// actually starting the server.
func (tc *TestCluster) startServer(idx int, serverArgs base.TestServerArgs) error {
server := tc.Servers[idx]
if err := server.Start(context.Background()); err != nil {
return err
}
dbConn, err := serverutils.OpenDBConnE(
server.ServingSQLAddr(), serverArgs.UseDatabase, serverArgs.Insecure, server.Stopper())
if err != nil {
return err
}
tc.mu.Lock()
defer tc.mu.Unlock()
tc.Conns = append(tc.Conns, dbConn)
return nil
}
// WaitForNStores waits for N store descriptors to be gossiped. Servers other
// than the first "bootstrap" their stores asynchronously, but we'd like to have
// control over when stores get initialized before returning the TestCluster.
func (tc *TestCluster) WaitForNStores(t testing.TB, n int, g *gossip.Gossip) {
// Register a gossip callback for the store descriptors.
var storesMu syncutil.Mutex
stores := map[roachpb.StoreID]struct{}{}
storesDone := make(chan error)
storesDoneOnce := storesDone
unregister := g.RegisterCallback(gossip.MakePrefixPattern(gossip.KeyStorePrefix),
func(_ string, content roachpb.Value) {
storesMu.Lock()
defer storesMu.Unlock()
if storesDoneOnce == nil {
return
}
var desc roachpb.StoreDescriptor
if err := content.GetProto(&desc); err != nil {
storesDoneOnce <- err
return
}
stores[desc.StoreID] = struct{}{}
if len(stores) == n {
close(storesDoneOnce)
storesDoneOnce = nil
}
})
defer unregister()
// Wait for the store descriptors to be gossiped.
for err := range storesDone {
if err != nil {
t.Fatal(err)
}
}
}
// LookupRange is part of TestClusterInterface.
func (tc *TestCluster) LookupRange(key roachpb.Key) (roachpb.RangeDescriptor, error) {
return tc.Servers[0].LookupRange(key)
}
// LookupRangeOrFatal is part of TestClusterInterface.
func (tc *TestCluster) LookupRangeOrFatal(t testing.TB, key roachpb.Key) roachpb.RangeDescriptor {
t.Helper()
desc, err := tc.LookupRange(key)
if err != nil {
t.Fatalf(`looking up range for %s: %+v`, key, err)
}
return desc
}
// SplitRangeWithExpiration splits the range containing splitKey with a sticky
// bit expiring at expirationTime.
// The right range created by the split starts at the split key and extends to the
// original range's end key.
// Returns the new descriptors of the left and right ranges.
//
// splitKey must correspond to a SQL table key (it must end with a family ID /
// col ID).
func (tc *TestCluster) SplitRangeWithExpiration(
splitKey roachpb.Key, expirationTime hlc.Timestamp,
) (roachpb.RangeDescriptor, roachpb.RangeDescriptor, error) {
return tc.Servers[0].SplitRangeWithExpiration(splitKey, expirationTime)
}
// SplitRange splits the range containing splitKey.
// The right range created by the split starts at the split key and extends to the
// original range's end key.
// Returns the new descriptors of the left and right ranges.
//
// splitKey must correspond to a SQL table key (it must end with a family ID /
// col ID).
func (tc *TestCluster) SplitRange(
splitKey roachpb.Key,
) (roachpb.RangeDescriptor, roachpb.RangeDescriptor, error) {
return tc.Servers[0].SplitRange(splitKey)
}
// SplitRangeOrFatal is the same as SplitRange but will Fatal the test on error.
func (tc *TestCluster) SplitRangeOrFatal(
t testing.TB, splitKey roachpb.Key,
) (roachpb.RangeDescriptor, roachpb.RangeDescriptor) {
lhsDesc, rhsDesc, err := tc.Servers[0].SplitRange(splitKey)
if err != nil {
t.Fatalf(`splitting at %s: %+v`, splitKey, err)
}
return lhsDesc, rhsDesc
}
// Target returns a ReplicationTarget for the specified server.
func (tc *TestCluster) Target(serverIdx int) roachpb.ReplicationTarget {
s := tc.Servers[serverIdx]
return roachpb.ReplicationTarget{
NodeID: s.GetNode().Descriptor.NodeID,
StoreID: s.GetFirstStoreID(),
}
}
// Targets creates a slice of ReplicationTarget where each entry corresponds to
// a call to tc.Target() for serverIdx in serverIdxs.
func (tc *TestCluster) Targets(serverIdxs ...int) []roachpb.ReplicationTarget {
ret := make([]roachpb.ReplicationTarget, 0, len(serverIdxs))
for _, serverIdx := range serverIdxs {
ret = append(ret, tc.Target(serverIdx))
}
return ret
}
func (tc *TestCluster) changeReplicas(
changeType roachpb.ReplicaChangeType, startKey roachpb.RKey, targets ...roachpb.ReplicationTarget,
) (roachpb.RangeDescriptor, error) {
tc.t.Helper()
ctx := context.TODO()
var returnErr error
var desc *roachpb.RangeDescriptor
if err := testutils.SucceedsSoonError(func() error {
tc.t.Helper()
var beforeDesc roachpb.RangeDescriptor
if err := tc.Servers[0].DB().GetProto(
ctx, keys.RangeDescriptorKey(startKey), &beforeDesc,
); err != nil {
return errors.Wrap(err, "range descriptor lookup error")
}
var err error
desc, err = tc.Servers[0].DB().AdminChangeReplicas(
ctx, startKey.AsRawKey(), beforeDesc, roachpb.MakeReplicationChanges(changeType, targets...),
)
if kvserver.IsRetriableReplicationChangeError(err) {
tc.t.Logf("encountered retriable replication change error: %v", err)
return err
}
// Don't return blindly - if this isn't an error we think is related to a
// replication error that we can retry, save the error to the outer scope
// and return nil.
returnErr = err
return nil
}); err != nil {
returnErr = err
}
if returnErr != nil {
// We mark the error as Handled so that tests that wanted the error in the
// first attempt but spent a while spinning in the retry loop above will
// fail. These should invoke ChangeReplicas directly.
return roachpb.RangeDescriptor{}, errors.Handled(errors.Wrap(returnErr, "AdminChangeReplicas error"))
}
return *desc, nil
}
func (tc *TestCluster) addReplica(
startKey roachpb.Key, typ roachpb.ReplicaChangeType, targets ...roachpb.ReplicationTarget,
) (roachpb.RangeDescriptor, error) {
rKey := keys.MustAddr(startKey)
rangeDesc, err := tc.changeReplicas(
typ, rKey, targets...,
)
if err != nil {
return roachpb.RangeDescriptor{}, err
}
if err := tc.waitForNewReplicas(startKey, false /* waitForVoter */, targets...); err != nil {
return roachpb.RangeDescriptor{}, err
}
return rangeDesc, nil
}
// AddVoters is part of TestClusterInterface.
func (tc *TestCluster) AddVoters(
startKey roachpb.Key, targets ...roachpb.ReplicationTarget,
) (roachpb.RangeDescriptor, error) {
return tc.addReplica(startKey, roachpb.ADD_VOTER, targets...)
}
// AddNonVoters is part of TestClusterInterface.
func (tc *TestCluster) AddNonVoters(
startKey roachpb.Key, targets ...roachpb.ReplicationTarget,
) (roachpb.RangeDescriptor, error) {
return tc.addReplica(startKey, roachpb.ADD_NON_VOTER, targets...)
}
// AddNonVotersOrFatal is part of TestClusterInterface.
func (tc *TestCluster) AddNonVotersOrFatal(
t testing.TB, startKey roachpb.Key, targets ...roachpb.ReplicationTarget,
) roachpb.RangeDescriptor {
desc, err := tc.addReplica(startKey, roachpb.ADD_NON_VOTER, targets...)
if err != nil {
t.Fatal(err)
}
return desc
}
// AddVotersMulti is part of TestClusterInterface.
func (tc *TestCluster) AddVotersMulti(
kts ...serverutils.KeyAndTargets,
) ([]roachpb.RangeDescriptor, []error) {
var descs []roachpb.RangeDescriptor
var errs []error
for _, kt := range kts {
rKey := keys.MustAddr(kt.StartKey)
rangeDesc, err := tc.changeReplicas(
roachpb.ADD_VOTER, rKey, kt.Targets...,
)
if err != nil {
errs = append(errs, err)
continue
}
descs = append(descs, rangeDesc)
}
for _, kt := range kts {
if err := tc.waitForNewReplicas(kt.StartKey, false, kt.Targets...); err != nil {
errs = append(errs, err)
continue
}
}
return descs, errs
}
// WaitForVoters waits for the targets to be voters in the range indicated by
// startKey.
func (tc *TestCluster) WaitForVoters(
startKey roachpb.Key, targets ...roachpb.ReplicationTarget,
) error {
return tc.waitForNewReplicas(startKey, true /* waitForVoter */, targets...)
}
// waitForNewReplicas waits for each of the targets to have a fully initialized
// replica of the range indicated by startKey.
//
// startKey is start key of range.
//
// waitForVoter indicates that the method should wait until the targets are full
// voters in the range (and they also know that they're voters - i.e. the
// respective replica has caught up with the config change).
//
// targets are replication target for change replica.
func (tc *TestCluster) waitForNewReplicas(
startKey roachpb.Key, waitForVoter bool, targets ...roachpb.ReplicationTarget,
) error {
rKey := keys.MustAddr(startKey)
errRetry := errors.Errorf("target not found")
// Wait for the replication to complete on all destination nodes.
if err := retry.ForDuration(time.Second*25, func() error {
for _, target := range targets {
// Use LookupReplica(keys) instead of GetRange(rangeID) to ensure that the
// snapshot has been transferred and the descriptor initialized.
store, err := tc.findMemberStore(target.StoreID)
if err != nil {
log.Errorf(context.TODO(), "unexpected error: %s", err)
return err
}
repl := store.LookupReplica(rKey)
if repl == nil {
return errors.Wrapf(errRetry, "for target %s", target)
}
desc := repl.Desc()
if replDesc, ok := desc.GetReplicaDescriptor(target.StoreID); !ok {
return errors.Errorf("target store %d not yet in range descriptor %v", target.StoreID, desc)
} else if waitForVoter && replDesc.GetType() != roachpb.VOTER_FULL {
return errors.Errorf("target store %d not yet voter in range descriptor %v", target.StoreID, desc)
}
}
return nil
}); err != nil {
return err
}
return nil
}
// AddVotersOrFatal is part of TestClusterInterface.
func (tc *TestCluster) AddVotersOrFatal(
t testing.TB, startKey roachpb.Key, targets ...roachpb.ReplicationTarget,
) roachpb.RangeDescriptor {
t.Helper()
desc, err := tc.AddVoters(startKey, targets...)
if err != nil {
t.Fatalf(`could not add %v replicas to range containing %s: %+v`,
targets, startKey, err)
}
return desc
}
// RemoveVoters is part of the TestServerInterface.
func (tc *TestCluster) RemoveVoters(
startKey roachpb.Key, targets ...roachpb.ReplicationTarget,
) (roachpb.RangeDescriptor, error) {
return tc.changeReplicas(roachpb.REMOVE_VOTER, keys.MustAddr(startKey), targets...)
}
// RemoveVotersOrFatal is part of TestClusterInterface.
func (tc *TestCluster) RemoveVotersOrFatal(
t testing.TB, startKey roachpb.Key, targets ...roachpb.ReplicationTarget,
) roachpb.RangeDescriptor {
t.Helper()
desc, err := tc.RemoveVoters(startKey, targets...)
if err != nil {
t.Fatalf(`could not remove %v replicas from range containing %s: %+v`,
targets, startKey, err)
}
return desc
}
// RemoveNonVoters is part of TestClusterInterface.
func (tc *TestCluster) RemoveNonVoters(
startKey roachpb.Key, targets ...roachpb.ReplicationTarget,
) (roachpb.RangeDescriptor, error) {
return tc.changeReplicas(roachpb.REMOVE_NON_VOTER, keys.MustAddr(startKey), targets...)
}
// RemoveNonVotersOrFatal is part of TestClusterInterface.
func (tc *TestCluster) RemoveNonVotersOrFatal(
t testing.TB, startKey roachpb.Key, targets ...roachpb.ReplicationTarget,
) roachpb.RangeDescriptor {
desc, err := tc.RemoveNonVoters(startKey, targets...)
if err != nil {
t.Fatalf(`could not remove %v replicas from range containing %s: %+v`,
targets, startKey, err)
}
return desc
}
// SwapVoterWithNonVoter is part of TestClusterInterface.
func (tc *TestCluster) SwapVoterWithNonVoter(
startKey roachpb.Key, voterTarget, nonVoterTarget roachpb.ReplicationTarget,
) (*roachpb.RangeDescriptor, error) {
ctx := context.Background()
key := keys.MustAddr(startKey)
var beforeDesc roachpb.RangeDescriptor
if err := tc.Servers[0].DB().GetProto(
ctx, keys.RangeDescriptorKey(key), &beforeDesc,
); err != nil {
return nil, errors.Wrap(err, "range descriptor lookup error")
}
changes := []roachpb.ReplicationChange{
{ChangeType: roachpb.ADD_VOTER, Target: nonVoterTarget},
{ChangeType: roachpb.REMOVE_NON_VOTER, Target: nonVoterTarget},
{ChangeType: roachpb.ADD_NON_VOTER, Target: voterTarget},
{ChangeType: roachpb.REMOVE_VOTER, Target: voterTarget},
}
return tc.Servers[0].DB().AdminChangeReplicas(ctx, key, beforeDesc, changes)
}
// SwapVoterWithNonVoterOrFatal is part of TestClusterInterface.
func (tc *TestCluster) SwapVoterWithNonVoterOrFatal(
t *testing.T, startKey roachpb.Key, voterTarget, nonVoterTarget roachpb.ReplicationTarget,
) *roachpb.RangeDescriptor {
afterDesc, err := tc.SwapVoterWithNonVoter(startKey, voterTarget, nonVoterTarget)
// Verify that the swap actually worked.
require.NoError(t, err)
replDesc, ok := afterDesc.GetReplicaDescriptor(voterTarget.StoreID)
require.True(t, ok)
require.Equal(t, roachpb.NON_VOTER, replDesc.GetType())
replDesc, ok = afterDesc.GetReplicaDescriptor(nonVoterTarget.StoreID)
require.True(t, ok)
require.Equal(t, roachpb.VOTER_FULL, replDesc.GetType())
return afterDesc
}
// TransferRangeLease is part of the TestServerInterface.
func (tc *TestCluster) TransferRangeLease(
rangeDesc roachpb.RangeDescriptor, dest roachpb.ReplicationTarget,
) error {
err := tc.Servers[0].DB().AdminTransferLease(context.TODO(),
rangeDesc.StartKey.AsRawKey(), dest.StoreID)
if err != nil {
return errors.Wrapf(err, "%q: transfer lease unexpected error", rangeDesc.StartKey)
}
return nil
}
// TransferRangeLeaseOrFatal is a convenience version of TransferRangeLease
func (tc *TestCluster) TransferRangeLeaseOrFatal(
t testing.TB, rangeDesc roachpb.RangeDescriptor, dest roachpb.ReplicationTarget,
) {
if err := tc.TransferRangeLease(rangeDesc, dest); err != nil {
t.Fatalf(`could not transfer lease for range %s error is %+v`, rangeDesc, err)
}
}
// RemoveLeaseHolderOrFatal is a convenience wrapper around RemoveVoter
func (tc *TestCluster) RemoveLeaseHolderOrFatal(
t testing.TB, rangeDesc roachpb.RangeDescriptor, src roachpb.ReplicationTarget,
) {
testutils.SucceedsSoon(t, func() error {
if _, err := tc.RemoveVoters(rangeDesc.StartKey.AsRawKey(), src); err != nil {
if strings.Contains(err.Error(), "to remove self (leaseholder)") ||
strings.Contains(err.Error(), "leaseholder moved") ||
strings.Contains(err.Error(), "isn't the Raft leader") {
return err
} else if strings.Contains(err.Error(),
"trying to remove a replica that doesn't exist") {
// It's possible that on leaseholder initiates the removal but another one completes it.
// The first attempt throws an error because the leaseholder moves, the second attempt
// fails with the exception that the voter doesn't exist, which is expected.
return nil
}
t.Fatal(err)
}
return nil
})
}
// MoveRangeLeaseNonCooperatively is part of the TestClusterInterface.
func (tc *TestCluster) MoveRangeLeaseNonCooperatively(
ctx context.Context,
rangeDesc roachpb.RangeDescriptor,
dest roachpb.ReplicationTarget,
manual *hlc.HybridManualClock,
) (*roachpb.Lease, error) {
knobs := tc.clusterArgs.ServerArgs.Knobs.Store.(*kvserver.StoreTestingKnobs)
if !knobs.AllowLeaseRequestProposalsWhenNotLeader {
// Without this knob, we'd have to architect a Raft leadership change
// too in order to let the replica get the lease. It's easier to just
// require that callers set it.
return nil, errors.Errorf("must set StoreTestingKnobs.AllowLeaseRequestProposalsWhenNotLeader")
}
destServer, err := tc.FindMemberServer(dest.StoreID)
if err != nil {
return nil, err
}
destStore, err := destServer.Stores().GetStore(dest.StoreID)
if err != nil {
return nil, err
}
// We are going to advance the manual clock so that the current lease
// expires and then issue a request to the target in hopes that it grabs the
// lease. But it is possible that another replica grabs the lease before us
// when it's up for grabs. To handle that case, we wrap the entire operation
// in an outer retry loop.
const retryDur = testutils.DefaultSucceedsSoonDuration
var newLease *roachpb.Lease
err = retry.ForDuration(retryDur, func() error {
// Find the current lease.
prevLease, _, err := tc.FindRangeLease(rangeDesc, nil /* hint */)
if err != nil {
return err
}
if prevLease.Replica.StoreID == dest.StoreID {
newLease = &prevLease
return nil
}
// Advance the manual clock past the lease's expiration.
lhStore, err := tc.findMemberStore(prevLease.Replica.StoreID)
if err != nil {
return err
}
log.Infof(ctx, "test: advancing clock to lease expiration")
manual.Increment(lhStore.GetStoreConfig().LeaseExpiration())
// Heartbeat the destination server's liveness record so that if we are
// attempting to acquire an epoch-based lease, the server will be live.
err = destServer.HeartbeatNodeLiveness()
if err != nil {
return err
}
// Issue a request to the target replica, which should notice that the
// old lease has expired and that it can acquire the lease.
r, err := destStore.GetReplica(rangeDesc.RangeID)
if err != nil {
return err
}
ls, err := r.TestingAcquireLease(ctx)
if err != nil {
log.Infof(ctx, "TestingAcquireLease failed: %s", err)
if lErr := (*roachpb.NotLeaseHolderError)(nil); errors.As(err, &lErr) && lErr.Lease != nil {
newLease = lErr.Lease
} else {
return err
}
} else {
newLease = &ls.Lease
}
// Is the lease in the right place?
if newLease.Replica.StoreID != dest.StoreID {
return errors.Errorf("LeaseInfoRequest succeeded, "+
"but lease in wrong location, want %v, got %v", dest, newLease.Replica)
}
return nil
})
log.Infof(ctx, "MoveRangeLeaseNonCooperatively: acquired lease: %s. err: %v", newLease, err)