-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
testserver.go
2554 lines (2248 loc) · 84.4 KB
/
testserver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 The Cockroach Authors.
//
// 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 server
import (
"bytes"
"context"
gosql "database/sql"
"fmt"
"net"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/cenkalti/backoff"
circuit "github.com/cockroachdb/circuitbreaker"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/base/serverident"
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"github.com/cockroachdb/cockroach/pkg/config"
"github.com/cockroachdb/cockroach/pkg/config/zonepb"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/rangefeed"
"github.com/cockroachdb/cockroach/pkg/kv/kvpb"
"github.com/cockroachdb/cockroach/pkg/kv/kvprober"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/allocator/plan"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/liveness"
"github.com/cockroachdb/cockroach/pkg/multitenant/mtinfopb"
"github.com/cockroachdb/cockroach/pkg/multitenant/tenantcapabilities"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/rpc"
"github.com/cockroachdb/cockroach/pkg/security/certnames"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/server/authserver"
"github.com/cockroachdb/cockroach/pkg/server/serverpb"
"github.com/cockroachdb/cockroach/pkg/server/status"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/bootstrap"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/deprecatedshowranges"
"github.com/cockroachdb/cockroach/pkg/sql/isql"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire"
"github.com/cockroachdb/cockroach/pkg/sql/physicalplan"
"github.com/cockroachdb/cockroach/pkg/sql/sem/catconstants"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/storage"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/upgrade/upgradebase"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/admission"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/metric"
"github.com/cockroachdb/cockroach/pkg/util/netutil"
addrutil "github.com/cockroachdb/cockroach/pkg/util/netutil/addr"
"github.com/cockroachdb/cockroach/pkg/util/retry"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/logtags"
"github.com/gogo/protobuf/proto"
"google.golang.org/grpc"
)
// makeTestConfig returns a config for testing. It overrides the
// Certs with the test certs directory.
// We need to override the certs loader.
func makeTestConfig(st *cluster.Settings, tr *tracing.Tracer) Config {
if tr == nil {
panic("nil Tracer")
}
return Config{
BaseConfig: makeTestBaseConfig(st, tr),
KVConfig: makeTestKVConfig(),
SQLConfig: makeTestSQLConfig(st, roachpb.SystemTenantID),
}
}
func makeTestBaseConfig(st *cluster.Settings, tr *tracing.Tracer) BaseConfig {
if tr == nil {
panic("nil Tracer")
}
baseCfg := MakeBaseConfig(st, tr, base.DefaultTestStoreSpec)
// Test servers start in secure mode by default.
baseCfg.Insecure = false
// Configure test storage engine.
baseCfg.StorageEngine = storage.DefaultStorageEngine
// Load test certs. In addition, the tests requiring certs
// need to call securityassets.SetLoader(securitytest.EmbeddedAssets)
// in their init to mock out the file system calls for calls to AssetFS,
// which has the test certs compiled in. Typically this is done
// once per package, in main_test.go.
baseCfg.SSLCertsDir = certnames.EmbeddedCertsDir
// Addr defaults to localhost with port set at time of call to
// Start() to an available port. May be overridden later (as in
// makeTestConfigFromParams). Call testServer.AdvRPCAddr() and
// .AdvSQLAddr() for the full address (including bound port).
baseCfg.Addr = util.TestAddr.String()
baseCfg.AdvertiseAddr = util.TestAddr.String()
baseCfg.SQLAddr = util.TestAddr.String()
baseCfg.SQLAdvertiseAddr = util.TestAddr.String()
baseCfg.SplitListenSQL = true
baseCfg.HTTPAddr = util.TestAddr.String()
// Set standard user for intra-cluster traffic.
baseCfg.User = username.NodeUserName()
return baseCfg
}
func makeTestKVConfig() KVConfig {
kvCfg := MakeKVConfig()
return kvCfg
}
func makeTestSQLConfig(st *cluster.Settings, tenID roachpb.TenantID) SQLConfig {
return MakeSQLConfig(tenID, base.DefaultTestTempStorageConfig(st))
}
func initTraceDir(dir string) error {
if dir == "" {
return nil
}
if err := os.MkdirAll(dir, 0755); err != nil {
return errors.Wrap(err, "cannot create trace dir; traces will not be dumped")
}
return nil
}
// makeTestConfigFromParams creates a Config from a TestServerParams.
func makeTestConfigFromParams(params base.TestServerArgs) Config {
st := params.Settings
if params.Settings == nil {
st = cluster.MakeClusterSettings()
}
// Needed for backward-compat on crdb_internal.ranges{_no_leases}.
// Remove in v23.2.
deprecatedshowranges.ShowRangesDeprecatedBehaviorSetting.Override(
context.TODO(), &st.SV,
// In unit tests, we exercise the new behavior.
false)
st.ExternalIODir = params.ExternalIODir
tr := params.Tracer
if params.Tracer == nil {
tr = tracing.NewTracerWithOpt(context.TODO(), tracing.WithClusterSettings(&st.SV), tracing.WithTracingMode(params.TracingDefault))
}
cfg := makeTestConfig(st, tr)
cfg.TestingKnobs = params.Knobs
cfg.RaftConfig = params.RaftConfig
cfg.RaftConfig.SetDefaults()
if params.JoinAddr != "" {
cfg.JoinList = []string{params.JoinAddr}
}
cfg.ClusterName = params.ClusterName
cfg.ExternalIODirConfig = params.ExternalIODirConfig
cfg.Insecure = params.Insecure
cfg.AutoInitializeCluster = !params.NoAutoInitializeCluster
cfg.SocketFile = params.SocketFile
cfg.RetryOptions = params.RetryOptions
cfg.Locality = params.Locality
cfg.StartDiagnosticsReporting = params.StartDiagnosticsReporting
if params.TraceDir != "" {
if err := initTraceDir(params.TraceDir); err == nil {
cfg.InflightTraceDirName = params.TraceDir
}
}
if knobs := params.Knobs.Store; knobs != nil {
if mo := knobs.(*kvserver.StoreTestingKnobs).MaxOffset; mo != 0 {
cfg.MaxOffset = MaxOffsetType(mo)
}
}
if params.Knobs.Server != nil {
if zoneConfig := params.Knobs.Server.(*TestingKnobs).DefaultZoneConfigOverride; zoneConfig != nil {
cfg.DefaultZoneConfig = *zoneConfig
}
if systemZoneConfig := params.Knobs.Server.(*TestingKnobs).DefaultSystemZoneConfigOverride; systemZoneConfig != nil {
cfg.DefaultSystemZoneConfig = *systemZoneConfig
}
}
if params.ScanInterval != 0 {
cfg.ScanInterval = params.ScanInterval
}
if params.ScanMinIdleTime != 0 {
cfg.ScanMinIdleTime = params.ScanMinIdleTime
}
if params.ScanMaxIdleTime != 0 {
cfg.ScanMaxIdleTime = params.ScanMaxIdleTime
}
if params.SSLCertsDir != "" {
cfg.SSLCertsDir = params.SSLCertsDir
}
if params.TimeSeriesQueryWorkerMax != 0 {
cfg.TimeSeriesServerConfig.QueryWorkerMax = params.TimeSeriesQueryWorkerMax
}
if params.TimeSeriesQueryMemoryBudget != 0 {
cfg.TimeSeriesServerConfig.QueryMemoryMax = params.TimeSeriesQueryMemoryBudget
}
if params.DisableEventLog {
cfg.EventLogEnabled = false
}
if params.SQLMemoryPoolSize != 0 {
cfg.MemoryPoolSize = params.SQLMemoryPoolSize
}
if params.CacheSize != 0 {
cfg.CacheSize = params.CacheSize
}
if params.JoinAddr != "" {
cfg.JoinList = []string{params.JoinAddr}
}
if cfg.Insecure {
// Whenever we can (i.e. in insecure mode), use IsolatedTestAddr
// to prevent issues that can occur when running a test under
// stress.
cfg.Addr = util.IsolatedTestAddr.String()
cfg.AdvertiseAddr = util.IsolatedTestAddr.String()
cfg.SQLAddr = util.IsolatedTestAddr.String()
cfg.SQLAdvertiseAddr = util.IsolatedTestAddr.String()
cfg.HTTPAddr = util.IsolatedTestAddr.String()
}
if params.SecondaryTenantPortOffset != 0 {
cfg.SecondaryTenantPortOffset = params.SecondaryTenantPortOffset
}
if params.Addr != "" {
cfg.Addr = params.Addr
cfg.AdvertiseAddr = params.Addr
}
if params.SQLAddr != "" {
cfg.SQLAddr = params.SQLAddr
cfg.SQLAdvertiseAddr = params.SQLAddr
cfg.SplitListenSQL = true
}
if params.HTTPAddr != "" {
cfg.HTTPAddr = params.HTTPAddr
}
cfg.DisableTLSForHTTP = params.DisableTLSForHTTP
cfg.TestingInsecureWebAccess = params.InsecureWebAccess
if params.EnableDemoLoginEndpoint {
cfg.EnableDemoLoginEndpoint = true
}
if params.DisableSpanConfigs {
cfg.SpanConfigsDisabled = true
}
if params.SnapshotApplyLimit != 0 {
cfg.SnapshotApplyLimit = params.SnapshotApplyLimit
}
if params.SnapshotSendLimit != 0 {
cfg.SnapshotSendLimit = params.SnapshotSendLimit
}
if params.AutoConfigProvider != nil {
cfg.AutoConfigProvider = params.AutoConfigProvider
}
// Ensure we have the correct number of engines. Add in-memory ones where
// needed. There must be at least one store/engine.
if len(params.StoreSpecs) == 0 {
params.StoreSpecs = []base.StoreSpec{base.DefaultTestStoreSpec}
}
// Validate the store specs.
for _, storeSpec := range params.StoreSpecs {
if storeSpec.InMemory {
if storeSpec.Size.Percent > 0 {
panic(fmt.Sprintf("test server does not yet support in memory stores based on percentage of total memory: %s", storeSpec))
}
} else {
// The default store spec is in-memory, so if this one is on-disk then
// one specific test must have requested it. A failure is returned if
// the Path field is empty, which means the test is then forced to pick
// the dir (and the test is then responsible for cleaning it up, not
// testServer).
// HeapProfileDirName and GoroutineDumpDirName are normally set by the
// cli, once, to the path of the first store.
if cfg.HeapProfileDirName == "" {
cfg.HeapProfileDirName = filepath.Join(storeSpec.Path, "logs", base.HeapProfileDir)
}
if cfg.GoroutineDumpDirName == "" {
cfg.GoroutineDumpDirName = filepath.Join(storeSpec.Path, "logs", base.GoroutineDumpDir)
}
if cfg.InflightTraceDirName == "" {
cfg.InflightTraceDirName = filepath.Join(storeSpec.Path, "logs", base.InflightTraceDir)
}
if cfg.CPUProfileDirName == "" {
cfg.CPUProfileDirName = filepath.Join(storeSpec.Path, "logs", base.CPUProfileDir)
}
}
}
cfg.Stores = base.StoreSpecList{Specs: params.StoreSpecs}
if params.TempStorageConfig.InMemory || params.TempStorageConfig.Path != "" {
cfg.TempStorageConfig = params.TempStorageConfig
cfg.TempStorageConfig.Settings = st
}
if cfg.TestingKnobs.Store == nil {
cfg.TestingKnobs.Store = &kvserver.StoreTestingKnobs{}
}
cfg.TestingKnobs.Store.(*kvserver.StoreTestingKnobs).SkipMinSizeCheck = true
if params.Knobs.SQLExecutor == nil {
cfg.TestingKnobs.SQLExecutor = &sql.ExecutorTestingKnobs{}
}
if params.Knobs.AdmissionControlOptions == nil {
cfg.TestingKnobs.AdmissionControlOptions = &admission.Options{}
}
cfg.ObsServiceAddr = params.ObsServiceAddr
return cfg
}
// A testServer encapsulates an in-memory instantiation of a cockroach node with
// a single store. It provides tests with access to Server internals.
// Where possible, it should be used through the
// serverutils.TestServerInterface.
//
// Example usage of a testServer:
//
// s, db, kvDB := serverutils.StartServer(t, base.TestServerArgs{})
// defer s.Stopper().Stop()
type testServer struct {
Cfg *Config
params base.TestServerArgs
// server is the embedded Cockroach server struct.
*topLevelServer
// httpTestServer provides the HTTP APIs of the
// serverutils.ApplicationLayerInterface.
*httpTestServer
// The test tenants associated with this server, and used for probabilistic
// testing within tenants. Currently, there is only one test tenant created
// by default, but longer term we may allow for the creation of multiple
// test tenants for more advanced testing.
testTenants []serverutils.ApplicationLayerInterface
// disableStartTenantError is set to an error if the test server should
// prevent starting any tenants manually. This is used to prevent tests that
// have not explicitly disabled probabilistic testing, or opted in to it, from
// starting a tenant to avoid unexpected behavior.
disableStartTenantError error
}
var _ serverutils.TestServerInterfaceRaw = &testServer{}
// Node returns the Node as an interface{}.
func (ts *testServer) Node() interface{} {
return ts.node
}
// NodeID returns the ID of this node within its cluster.
func (ts *testServer) NodeID() roachpb.NodeID {
return ts.rpcContext.NodeID.Get()
}
// Stopper returns the embedded server's Stopper.
func (ts *testServer) Stopper() *stop.Stopper {
return ts.stopper
}
// AppStopper is part of serverutils.ApplicationLayerInterface.
func (ts *testServer) AppStopper() *stop.Stopper {
return ts.stopper
}
// GossipI is part of the serverutils.StorageLayerInterface.
func (ts *testServer) GossipI() interface{} {
return ts.topLevelServer.gossip
}
// RangeFeedFactory is part of serverutils.ApplicationLayerInterface.
func (ts *testServer) RangeFeedFactory() interface{} {
if ts != nil {
return ts.sqlServer.execCfg.RangeFeedFactory
}
return (*rangefeed.Factory)(nil)
}
// Clock returns the clock used by the testServer.
func (ts *testServer) Clock() *hlc.Clock {
if ts != nil {
return ts.clock
}
return nil
}
// SQLLivenessProvider returns the sqlliveness.Provider as an interface{}.
func (ts *testServer) SQLLivenessProvider() interface{} {
if ts != nil {
return ts.sqlServer.execCfg.SQLLiveness
}
return nil
}
// JobRegistry returns the *jobs.Registry as an interface{}.
func (ts *testServer) JobRegistry() interface{} {
if ts != nil {
return ts.sqlServer.jobRegistry
}
return nil
}
// NodeLiveness exposes the NodeLiveness instance used by the testServer as an
// interface{}.
func (ts *testServer) NodeLiveness() interface{} {
if ts != nil {
return ts.nodeLiveness
}
return nil
}
// NodeDialer returns the NodeDialer used by the testServer.
func (ts *testServer) NodeDialer() interface{} {
return ts.kvNodeDialer
}
// HeartbeatNodeLiveness heartbeats the server's NodeLiveness record.
func (ts *testServer) HeartbeatNodeLiveness() error {
if ts == nil {
return errors.New("no node liveness instance")
}
nl := ts.nodeLiveness
l, ok := nl.Self()
if !ok {
return errors.New("liveness not found")
}
var err error
ctx := context.Background()
for r := retry.StartWithCtx(ctx, retry.Options{MaxRetries: 5}); r.Next(); {
if err = nl.Heartbeat(ctx, l); !errors.Is(err, liveness.ErrEpochIncremented) {
break
}
}
return err
}
// SQLInstanceID is part of the serverutils.ApplicationLayerInterface.
func (ts *testServer) SQLInstanceID() base.SQLInstanceID {
return ts.sqlServer.sqlIDContainer.SQLInstanceID()
}
// StatusServer is part of the serverutils.ApplicationLayerInterface.
func (ts *testServer) StatusServer() interface{} {
return ts.status
}
// RPCContext returns the rpc context used by the testServer.
func (ts *testServer) RPCContext() *rpc.Context {
if ts != nil {
return ts.rpcContext
}
return nil
}
// TsDB returns the ts.DB instance used by the testServer.
func (ts *testServer) TsDB() interface{} {
return ts.tsDB
}
// SQLConn is part of the serverutils.ApplicationLayerInterface.
func (ts *testServer) SQLConn(test serverutils.TestFataler, dbName string) *gosql.DB {
return ts.SQLConnForUser(test, username.RootUser, dbName)
}
// SQLConnForUser is part of the serverutils.ApplicationLayerInterface.
func (ts *testServer) SQLConnForUser(
test serverutils.TestFataler, userName, dbName string,
) *gosql.DB {
db, err := ts.SQLConnForUserE(userName, dbName)
if err != nil {
test.Fatal(err)
}
return db
}
// SQLConnE is part of the serverutils.ApplicationLayerInterface.
func (ts *testServer) SQLConnE(dbName string) (*gosql.DB, error) {
return ts.SQLConnForUserE(username.RootUser, dbName)
}
// SQLConnForUserE is part of the serverutils.ApplicationLayerInterface.
func (ts *testServer) SQLConnForUserE(userName string, dbName string) (*gosql.DB, error) {
return openTestSQLConn(
userName, dbName, catconstants.SystemTenantName,
ts.Stopper(),
ts.topLevelServer.loopbackPgL,
ts.cfg.SQLAdvertiseAddr,
ts.cfg.Insecure,
)
}
// DB returns the client.DB instance used by the testServer.
func (ts *testServer) DB() *kv.DB {
if ts != nil {
return ts.db
}
return nil
}
// PGServer exposes the pgwire.Server instance used by the testServer as an
// interface{}.
func (ts *testServer) PGServer() interface{} {
if ts != nil {
return ts.sqlServer.pgServer
}
return nil
}
// PGPreServer exposes the pgwire.PreServeConnHandler instance used by
// the testServer.
func (ts *testServer) PGPreServer() interface{} {
if ts != nil {
return ts.pgPreServer
}
return nil
}
// RaftTransport is part of the serverutils.StorageLayerInterface.
func (ts *testServer) RaftTransport() interface{} {
if ts != nil {
return ts.raftTransport
}
return nil
}
// AmbientCtx implements serverutils.ApplicationLayerInterface. This
// retrieves the ambient context for this server. This is intended for
// exclusive use by test code.
func (ts *testServer) AmbientCtx() log.AmbientContext {
return ts.Cfg.AmbientCtx
}
// TestingKnobs returns the TestingKnobs used by the testServer.
func (ts *testServer) TestingKnobs() *base.TestingKnobs {
if ts != nil {
return &ts.Cfg.TestingKnobs
}
return nil
}
// SQLServerInternal is part of the serverutils.ApplicationLayerInterface.
func (ts *testServer) SQLServerInternal() interface{} {
return ts.sqlServer
}
// TenantStatusServer returns the TenantStatusServer used by the testServer.
func (ts *testServer) TenantStatusServer() interface{} {
return ts.status
}
// TestTenant is part of serverutils.TenantControlInterface.
func (ts *testServer) TestTenant() serverutils.ApplicationLayerInterface {
return ts.testTenants[0]
}
// maybeStartDefaultTestTenant might start a test tenant. This can then be used
// for multi-tenant testing, where the default SQL connection will be made to
// this tenant instead of to the system tenant. Note that we will
// currently only attempt to start a test tenant if we're running in an
// enterprise enabled build. This is due to licensing restrictions on the MT
// capabilities.
func (ts *testServer) maybeStartDefaultTestTenant(ctx context.Context) error {
if !(ts.params.DefaultTestTenant.TestTenantAlwaysDisabled() ||
ts.params.DefaultTestTenant.TestTenantAlwaysEnabled()) {
return errors.WithHint(
errors.AssertionFailedf("programming error: no decision taken about the default test tenant"),
"Maybe add the missing call to serverutils.ShouldStartDefaultTestTenant()?")
}
// If the flag has been set to disable the default test tenant, don't start
// it here.
if ts.params.DefaultTestTenant.TestTenantAlwaysDisabled() {
return nil
}
tenantSettings := cluster.MakeTestingClusterSettings()
if st := ts.params.Settings; st != nil {
// Copy overrides and other test-specific configuration,
// as a convenience for test writers that do the following:
// - create a new Settings
// - add some overrides
// - call serverutils.StartServer
// - expect the overrides to propagate to the application layer.
tenantSettings.SV.TestingCopyForVirtualCluster(&st.SV)
}
var tempStorageConfig base.TempStorageConfig
if tsc := ts.params.TempStorageConfig; tsc.Settings != nil {
tempStorageConfig = base.InheritTestTempStorageConfig(tenantSettings, tsc)
} else {
tempStorageConfig = base.DefaultTestTempStorageConfig(tenantSettings)
}
params := base.TestTenantArgs{
// Currently, all the servers leverage the same tenant ID. We may
// want to change this down the road, for more elaborate testing.
TenantID: serverutils.TestTenantID(),
MemoryPoolSize: ts.params.SQLMemoryPoolSize,
TempStorageConfig: &tempStorageConfig,
Locality: ts.params.Locality,
ExternalIODir: ts.params.ExternalIODir,
ExternalIODirConfig: ts.params.ExternalIODirConfig,
ForceInsecure: ts.Insecure(),
UseDatabase: ts.params.UseDatabase,
SSLCertsDir: ts.params.SSLCertsDir,
TestingKnobs: ts.params.Knobs,
StartDiagnosticsReporting: ts.params.StartDiagnosticsReporting,
Settings: tenantSettings,
}
// Since we're creating a tenant, it doesn't make sense to pass through the
// Server testing knobs, since the bulk of them only apply to the system
// tenant. Any remaining knobs which are required by the tenant should be
// passed through here.
params.TestingKnobs.Server = &TestingKnobs{}
if ts.params.Knobs.Server != nil {
params.TestingKnobs.Server.(*TestingKnobs).DiagnosticsTestingKnobs = ts.params.Knobs.Server.(*TestingKnobs).DiagnosticsTestingKnobs
}
// Temporarily disable the error that is returned if a tenant should not be started manually,
// so that we can start the default test tenant internally here.
disableStartTenantError := ts.disableStartTenantError
if ts.disableStartTenantError != nil {
ts.disableStartTenantError = nil
}
defer func() {
if disableStartTenantError != nil {
ts.disableStartTenantError = disableStartTenantError
}
}()
tenant, err := ts.StartTenant(ctx, params)
if err != nil {
return err
}
if len(ts.testTenants) == 0 {
ts.testTenants = make([]serverutils.ApplicationLayerInterface, 1)
ts.testTenants[0] = tenant
} else {
// We restrict the creation of multiple default tenants because if
// we allow for more than one to be created, it's not clear what we
// should return in AdvSQLAddr() as the default SQL address. Panic
// here to prevent more than one from being added. If you're hitting
// this panic it's likely that you're trying to expose multiple default
// test tenants, in which case, you should evaluate what to do about
// returning a default SQL address in AdvSQLAddr().
return errors.AssertionFailedf("invalid number of test SQL servers %d", len(ts.testTenants))
}
return nil
}
// PreStart calls the PreStart() method on the underlying server.
// Call this before calling Start().
// The caller is responsible for calling .Stopper().Stop() even
// when PreStart() returns an error.
func (ts *testServer) PreStart(ctx context.Context) error {
return ts.topLevelServer.PreStart(ctx)
}
// Activate runs post-init server initialization and enables
// clients to connect.
// The caller is responsible for calling .Stopper().Stop() even
// when PreStart() returns an error.
func (ts *testServer) Activate(ctx context.Context) error {
if err := ts.topLevelServer.AcceptInternalClients(ctx); err != nil {
return err
}
// In tests we need some, but not all of RunInitialSQL functionality.
if err := ts.topLevelServer.RunInitialSQL(
ctx, !ts.params.PartOfCluster, "" /* adminUser */, "", /* adminPassword */
); err != nil {
return err
}
maybeRunVersionUpgrade := func(layer serverutils.ApplicationLayerInterface) error {
if v := ts.BinaryVersionOverride(); v != (roachpb.Version{}) {
ie := layer.InternalExecutor().(isql.Executor)
if _, err := ie.Exec(context.Background(), "set-cluster-version", nil, /* txn */
`SET CLUSTER SETTING version = $1`, v.String()); err != nil {
return err
}
}
return nil
}
if err := maybeRunVersionUpgrade(ts); err != nil {
return err
}
// Let clients connect.
if err := ts.topLevelServer.AcceptClients(ctx); err != nil {
return err
}
if err := ts.maybeStartDefaultTestTenant(ctx); err != nil {
return err
}
if ts.StartedDefaultTestTenant() {
if err := maybeRunVersionUpgrade(ts.TestTenant()); err != nil {
return err
}
}
go func() {
// If the server requests a shutdown, do that simply by stopping the
// stopper.
select {
case req := <-ts.topLevelServer.ShutdownRequested():
shutdownCtx := ts.topLevelServer.AnnotateCtx(context.Background())
log.Infof(shutdownCtx, "server requesting spontaneous shutdown: %v", req.ShutdownCause())
// TODO(knz): evaluate whether there is value in shutting down
// test servers using a graceful drain when
// req.TerminateUsingGracefulDrain() is true.
ts.Stopper().Stop(shutdownCtx)
case <-ts.Stopper().ShouldQuiesce():
}
}()
return nil
}
// Start calls PreStart() and Activate().
// For convenience, it also ensures .Stopper().Stop() has been
// called if an error is returned.
func (ts *testServer) Start(ctx context.Context) (retErr error) {
defer func() {
if retErr != nil {
// Use a separate context to avoid using an already-cancelled
// context in closers.
ts.Stopper().Stop(context.Background())
}
}()
if err := ts.PreStart(ctx); err != nil {
return err
}
return ts.Activate(ctx)
}
// Stop is part of the serverutils.TestServerInterface.
func (ts *testServer) Stop(ctx context.Context) {
ctx = ts.topLevelServer.AnnotateCtx(ctx)
ts.topLevelServer.stopper.Stop(ctx)
}
// testTenant is an in-memory instantiation of the SQL-only process created for
// each active Cockroach tenant. testTenant provides tests with access to
// internal methods and state on SQLServer. It is typically started in tests by
// calling the TestServerInterface.StartTenant method or by calling the wrapper
// serverutils.StartTenant method.
type testTenant struct {
sql *SQLServer
Cfg *BaseConfig
SQLCfg *SQLConfig
*httpTestServer
drain *drainServer
http *httpServer
pgL *netutil.LoopbackListener
// pgPreServer handles SQL connections prior to routing them to a
// specific tenant.
pgPreServer *pgwire.PreServeConnHandler
}
var _ serverutils.ApplicationLayerInterface = &testTenant{}
// AnnotateCtx is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) AnnotateCtx(ctx context.Context) context.Context {
return t.sql.AnnotateCtx(ctx)
}
// SQLInstanceID is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) SQLInstanceID() base.SQLInstanceID {
return t.sql.SQLInstanceID()
}
// AdvRPCAddr is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) AdvRPCAddr() string {
return t.Cfg.AdvertiseAddr
}
// AdvSQLAddr is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) AdvSQLAddr() string {
return t.Cfg.SQLAdvertiseAddr
}
// SQLAddr is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) SQLAddr() string {
return t.Cfg.SQLAddr
}
// HTTPAddr is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) HTTPAddr() string {
return t.Cfg.HTTPAddr
}
// RPCAddr is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) RPCAddr() string {
return t.Cfg.Addr
}
// SQLConn is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) SQLConn(test serverutils.TestFataler, dbName string) *gosql.DB {
return t.SQLConnForUser(test, username.RootUser, dbName)
}
// SQLConnForUser is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) SQLConnForUser(
test serverutils.TestFataler, userName, dbName string,
) *gosql.DB {
db, err := t.SQLConnForUserE(userName, dbName)
if err != nil {
test.Fatal(err)
}
return db
}
// SQLConnE is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) SQLConnE(dbName string) (*gosql.DB, error) {
return t.SQLConnForUserE(username.RootUser, dbName)
}
// SQLConnForUserE is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) SQLConnForUserE(userName string, dbName string) (*gosql.DB, error) {
tenantName := t.t.tenantName
if !t.Cfg.DisableSQLListener {
// This tenant server has its own SQL listener. It will not accept
// a "cluster" connection parameter.
tenantName = ""
}
return openTestSQLConn(
userName, dbName, tenantName,
t.AppStopper(),
t.pgL,
t.Cfg.SQLAdvertiseAddr,
t.Cfg.Insecure,
)
}
// DB is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) DB() *kv.DB {
return t.sql.execCfg.DB
}
// PGServer is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) PGServer() interface{} {
return t.sql.pgServer
}
// PGPreServer exposes the pgwire.PreServeConnHandler instance used by
// the testServer.
func (ts *testTenant) PGPreServer() interface{} {
if ts != nil {
return ts.pgPreServer
}
return nil
}
// DiagnosticsReporter is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) DiagnosticsReporter() interface{} {
return t.sql.diagnosticsReporter
}
// StatusServer is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) StatusServer() interface{} {
return t.t.status
}
// TenantStatusServer is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) TenantStatusServer() interface{} {
return t.t.status
}
// SQLServer is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) SQLServer() interface{} {
return t.sql.pgServer.SQLServer
}
// DistSQLServer is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) DistSQLServer() interface{} {
return t.sql.distSQLServer
}
// SetDistSQLSpanResolver is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) SetDistSQLSpanResolver(spanResolver interface{}) {
t.sql.execCfg.DistSQLPlanner.SetSpanResolver(spanResolver.(physicalplan.SpanResolver))
}
// DistSenderI is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) DistSenderI() interface{} {
return t.sql.execCfg.DistSender
}
// NodeDescStoreI is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) NodeDescStoreI() interface{} {
return t.sql.execCfg.DistSQLPlanner.NodeDescStore()
}
// InternalDB is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) InternalDB() interface{} {
return t.sql.internalDB
}
// Locality is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) Locality() roachpb.Locality {
return t.Cfg.Locality
}
// DistSQLPlanningNodeID is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) DistSQLPlanningNodeID() roachpb.NodeID {
// See comments on replicaoracle.Config.
return 0
}
// LeaseManager is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) LeaseManager() interface{} {
return t.sql.leaseMgr
}
// InternalExecutor is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) InternalExecutor() interface{} {
return t.sql.internalExecutor
}
// RPCContext is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) RPCContext() *rpc.Context {
return t.sql.execCfg.RPCContext
}
// JobRegistry is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) JobRegistry() interface{} {
return t.sql.jobRegistry
}
// NodeDialer returns the NodeDialer used by the testServer.
func (t *testTenant) NodeDialer() interface{} {
return t.sql.sqlInstanceDialer
}
// ExecutorConfig is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) ExecutorConfig() interface{} {
return *t.sql.execCfg
}
// RangeFeedFactory is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) RangeFeedFactory() interface{} {
return t.sql.execCfg.RangeFeedFactory
}
// ClusterSettings is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) ClusterSettings() *cluster.Settings {
return t.Cfg.Settings
}
// AppStopper is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) AppStopper() *stop.Stopper {
return t.sql.stopper
}
// Clock is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) Clock() *hlc.Clock {
return t.sql.execCfg.Clock
}
// AmbientCtx implements serverutils.ApplicationLayerInterface. This
// retrieves the ambient context for this server. This is intended for
// exclusive use by test code.
func (t *testTenant) AmbientCtx() log.AmbientContext {
return t.Cfg.AmbientCtx
}
// TestingKnobs is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) TestingKnobs() *base.TestingKnobs {
return &t.Cfg.TestingKnobs
}
// SQLServerInternal is part of the serverutils.ApplicationLayerInterface.
func (t *testTenant) SQLServerInternal() interface{} {
return t.sql
}
// SpanConfigKVAccessor is part of the serverutils.ApplicationLayerInterface.