forked from cockroachdb/cockroach
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_sql.go
More file actions
2247 lines (2003 loc) · 85.6 KB
/
server_sql.go
File metadata and controls
2247 lines (2003 loc) · 85.6 KB
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 2020 The Cockroach Authors.
//
// Use of this software is governed by the CockroachDB Software License
// included in the /LICENSE file.
package server
import (
"context"
"net"
"net/url"
"os"
"path/filepath"
"strings"
"sync/atomic"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/cloud"
"github.com/cockroachdb/cockroach/pkg/cloud/externalconn"
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"github.com/cockroachdb/cockroach/pkg/featureflag"
"github.com/cockroachdb/cockroach/pkg/gossip"
"github.com/cockroachdb/cockroach/pkg/inspectz/inspectzpb"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/jobs/jobsprotectedts"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/keyvisualizer"
"github.com/cockroachdb/cockroach/pkg/keyvisualizer/spanstatsconsumer"
"github.com/cockroachdb/cockroach/pkg/keyvisualizer/spanstatskvaccessor"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/kv/bulk"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/kvcoord"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/kvstreamer"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/kvtenant"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/rangefeed"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/rangestats"
"github.com/cockroachdb/cockroach/pkg/kv/kvpb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvserverbase"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/liveness/livenesspb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/protectedts"
"github.com/cockroachdb/cockroach/pkg/multitenant"
"github.com/cockroachdb/cockroach/pkg/multitenant/mtinfopb"
"github.com/cockroachdb/cockroach/pkg/multitenant/tenantcapabilities"
"github.com/cockroachdb/cockroach/pkg/obs/clustermetrics/cmwriter"
clustermetricutils "github.com/cockroachdb/cockroach/pkg/obs/clustermetrics/utils"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/rpc"
"github.com/cockroachdb/cockroach/pkg/rpc/nodedialer"
"github.com/cockroachdb/cockroach/pkg/scheduledjobs"
"github.com/cockroachdb/cockroach/pkg/security/clientsecopts"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/server/diagnostics"
"github.com/cockroachdb/cockroach/pkg/server/license"
"github.com/cockroachdb/cockroach/pkg/server/pgurl"
"github.com/cockroachdb/cockroach/pkg/server/serverctl"
"github.com/cockroachdb/cockroach/pkg/server/serverpb"
"github.com/cockroachdb/cockroach/pkg/server/settingswatcher"
"github.com/cockroachdb/cockroach/pkg/server/status"
"github.com/cockroachdb/cockroach/pkg/server/systemconfigwatcher"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/spanconfig"
"github.com/cockroachdb/cockroach/pkg/spanconfig/spanconfiglimiter"
"github.com/cockroachdb/cockroach/pkg/spanconfig/spanconfigmanager"
"github.com/cockroachdb/cockroach/pkg/spanconfig/spanconfigreconciler"
"github.com/cockroachdb/cockroach/pkg/spanconfig/spanconfigsplitter"
"github.com/cockroachdb/cockroach/pkg/spanconfig/spanconfigsqltranslator"
"github.com/cockroachdb/cockroach/pkg/spanconfig/spanconfigsqlwatcher"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/auditlogging"
"github.com/cockroachdb/cockroach/pkg/sql/bulkutil"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catalogkeys"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catsessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descidgen"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descs"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/hydrateddesccache"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/lease"
"github.com/cockroachdb/cockroach/pkg/sql/colexec"
"github.com/cockroachdb/cockroach/pkg/sql/consistencychecker"
"github.com/cockroachdb/cockroach/pkg/sql/contention"
"github.com/cockroachdb/cockroach/pkg/sql/distsql"
"github.com/cockroachdb/cockroach/pkg/sql/execinfra"
"github.com/cockroachdb/cockroach/pkg/sql/execinfrapb"
"github.com/cockroachdb/cockroach/pkg/sql/flowinfra"
"github.com/cockroachdb/cockroach/pkg/sql/gcjob/gcjobnotifier"
"github.com/cockroachdb/cockroach/pkg/sql/hints"
"github.com/cockroachdb/cockroach/pkg/sql/idxusage"
"github.com/cockroachdb/cockroach/pkg/sql/isql"
"github.com/cockroachdb/cockroach/pkg/sql/optionalnodeliveness"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire"
"github.com/cockroachdb/cockroach/pkg/sql/querycache"
"github.com/cockroachdb/cockroach/pkg/sql/rangeprober"
"github.com/cockroachdb/cockroach/pkg/sql/regions"
"github.com/cockroachdb/cockroach/pkg/sql/rolemembershipcache"
"github.com/cockroachdb/cockroach/pkg/sql/scheduledlogging"
"github.com/cockroachdb/cockroach/pkg/sql/schemachanger/scdeps"
"github.com/cockroachdb/cockroach/pkg/sql/schemachanger/scexec"
"github.com/cockroachdb/cockroach/pkg/sql/sem/catconstants"
"github.com/cockroachdb/cockroach/pkg/sql/sem/eval"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondatapb"
"github.com/cockroachdb/cockroach/pkg/sql/sessioninit"
"github.com/cockroachdb/cockroach/pkg/sql/sqlinstance"
"github.com/cockroachdb/cockroach/pkg/sql/sqlinstance/instancestorage"
"github.com/cockroachdb/cockroach/pkg/sql/sqlliveness"
"github.com/cockroachdb/cockroach/pkg/sql/sqlliveness/slinstance"
"github.com/cockroachdb/cockroach/pkg/sql/sqlliveness/slprovider"
"github.com/cockroachdb/cockroach/pkg/sql/sqlstats"
"github.com/cockroachdb/cockroach/pkg/sql/stats"
"github.com/cockroachdb/cockroach/pkg/sql/stmtdiagnostics"
"github.com/cockroachdb/cockroach/pkg/sql/syntheticprivilegecache"
tablemetadatacacheutil "github.com/cockroachdb/cockroach/pkg/sql/tablemetadatacache/util"
"github.com/cockroachdb/cockroach/pkg/sql/vecindex"
"github.com/cockroachdb/cockroach/pkg/storage"
"github.com/cockroachdb/cockroach/pkg/ts"
"github.com/cockroachdb/cockroach/pkg/upgrade"
"github.com/cockroachdb/cockroach/pkg/upgrade/upgradebase"
"github.com/cockroachdb/cockroach/pkg/upgrade/upgradecluster"
"github.com/cockroachdb/cockroach/pkg/upgrade/upgrademanager"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/admission"
"github.com/cockroachdb/cockroach/pkg/util/envutil"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/log/eventlog"
"github.com/cockroachdb/cockroach/pkg/util/metric"
"github.com/cockroachdb/cockroach/pkg/util/mon"
"github.com/cockroachdb/cockroach/pkg/util/netutil"
"github.com/cockroachdb/cockroach/pkg/util/netutil/addr"
"github.com/cockroachdb/cockroach/pkg/util/rangedesc"
"github.com/cockroachdb/cockroach/pkg/util/retry"
"github.com/cockroachdb/cockroach/pkg/util/startup"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing/collector"
"github.com/cockroachdb/cockroach/pkg/util/tracing/service"
"github.com/cockroachdb/cockroach/pkg/util/tracing/tracingservicepb"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/errors/oserror"
"github.com/cockroachdb/redact"
"github.com/marusama/semaphore"
"github.com/nightlyone/lockfile"
"google.golang.org/grpc"
"storj.io/drpc"
)
// SQLServer encapsulates the part of a CRDB server that is dedicated to SQL
// processing. All SQL commands are reduced to primitive operations on the
// lower-level KV layer. Multi-tenant installations of CRDB run zero or more
// standalone SQLServer instances per tenant (the KV layer is shared across all
// tenants).
type SQLServer struct {
ambientCtx log.AmbientContext
stopper *stop.Stopper
stopTrigger *stopTrigger
sqlIDContainer *base.SQLIDContainer
pgServer *pgwire.Server
distSQLServer *distsql.ServerImpl
execCfg *sql.ExecutorConfig
cfg *BaseConfig
internalExecutor *sql.InternalExecutor
internalDB descs.DB
leaseMgr *lease.Manager
tracingService *service.Service
sqlInstanceDialer *nodedialer.Dialer
tenantConnect kvtenant.Connector
// sessionRegistry can be queried for info on running SQL sessions. It is
// shared between the sql.Server and the statusServer.
sessionRegistry *sql.SessionRegistry
closedSessionCache *sql.ClosedSessionCache
jobRegistry *jobs.Registry
statsRefresher *stats.Refresher
clusterMetricsWriter *cmwriter.Writer
temporaryObjectCleaner *sql.TemporaryObjectCleaner
stmtDiagnosticsRegistry *stmtdiagnostics.Registry
txnDiagnosticsRegistry *stmtdiagnostics.TxnRegistry
sqlLivenessSessionID sqlliveness.SessionID
sqlLivenessProvider sqlliveness.Provider
sqlInstanceReader *instancestorage.Reader
sqlInstanceStorage *instancestorage.Storage
metricsRegistry *metric.Registry
diagnosticsReporter *diagnostics.Reporter
spanconfigMgr *spanconfigmanager.Manager
spanconfigSQLTranslatorFactory *spanconfigsqltranslator.Factory
spanconfigSQLWatcher *spanconfigsqlwatcher.SQLWatcher
settingsWatcher *settingswatcher.SettingsWatcher
systemConfigWatcher *systemconfigwatcher.Cache
isMeta1Leaseholder func(context.Context, hlc.ClockTimestamp) (bool, error)
// isReady is the health status of the node. When true, the node is healthy;
// load balancers and connection management tools treat the node as "ready".
// When false, the node is unhealthy or "not ready", with load balancers and
// connection management tools learning this status from health checks.
// This is set to true when the server has started accepting client conns.
isReady atomic.Bool
// gracefulDrainComplete indicates when a graceful drain has
// completed successfully. We use this to document cases where a
// graceful drain did _not_ occur.
gracefulDrainComplete atomic.Bool
// internalDBMemMonitor is the memory monitor corresponding to the
// InternalDB singleton. It only gets closed when
// Server is closed. Every Executor created via the factory
// uses this memory monitor.
internalDBMemMonitor *mon.BytesMonitor
// upgradeManager deals with cluster version upgrades on bootstrap and on
// `set cluster setting version = <v>`.
upgradeManager *upgrademanager.Manager
// Tenant migration server for use in tenant tests.
migrationServer *TenantMigrationServer
// serviceMode is the service mode this server was started with.
serviceMode mtinfopb.TenantServiceMode
}
// sqlServerOptionalKVArgs are the arguments supplied to newSQLServer which are
// only available if the SQL server runs as part of a KV node.
//
// TODO(tbg): give all of these fields a wrapper that can signal whether the
// respective object is available. When it is not, return
// UnsupportedUnderClusterVirtualization.
type sqlServerOptionalKVArgs struct {
// nodesStatusServer gives access to the NodesStatus service.
nodesStatusServer serverpb.OptionalNodesStatusServer
// Narrowed down version of *NodeLiveness. Used by jobs, DistSQLPlanner, and
// upgrade manager.
nodeLiveness optionalnodeliveness.Container
// Gossip is relied upon by distSQLCfg (execinfra.ServerConfig), the executor
// config, the DistSQL planner, the table statistics cache, the statements
// diagnostics registry, and the lease manager.
gossip gossip.OptionalGossip
// To register blob and DistSQL servers.
grpcServer *grpc.Server
drpcMux drpc.Mux
// For the temporaryObjectCleaner.
isMeta1Leaseholder func(context.Context, hlc.ClockTimestamp) (bool, error)
// DistSQL, lease management, and others want to know the node they're on.
nodeIDContainer *base.SQLIDContainer
// Used by backup/restore.
externalStorage cloud.ExternalStorageFactory
externalStorageFromURI cloud.ExternalStorageFromURIFactory
// The admission queue to use for SQLSQLResponseWork.
sqlSQLResponseAdmissionQ *admission.WorkQueue
// Used when creating and deleting tenant records.
spanConfigKVAccessor spanconfig.KVAccessor
// kvStores is used by crdb_internal builtins to access the stores on this
// node.
kvStoresIterator kvserverbase.StoresIterator
// inspectzServer is used to power various crdb_internal vtables, exposing
// the equivalent of /inspectz but through SQL.
inspectzServer inspectzpb.InspectzServer
// notifyChangeToSystemVisibleSettings is called by the settings
// watcher when one or more TenandReadOnly setting is updated via
// SET CLUSTER SETTING (i.e. updated in system.settings).
//
// The second argument must be sorted by setting key already.
notifyChangeToSystemVisibleSettings func(context.Context, []kvpb.TenantSetting)
}
// sqlServerOptionalTenantArgs are the arguments supplied to newSQLServer which
// are only available if the SQL server runs as part of a standalone SQL node.
type sqlServerOptionalTenantArgs struct {
tenantConnect kvtenant.Connector
spanLimiterFactory spanLimiterFactory
serviceMode mtinfopb.TenantServiceMode
promRuleExporter *metric.PrometheusRuleExporter
}
type sqlServerArgs struct {
sqlServerOptionalKVArgs
sqlServerOptionalTenantArgs
*SQLConfig
*BaseConfig
stopper *stop.Stopper
// stopTrigger is user by the sqlServer to signal requests to shut down the
// server. The creator of the server is supposed to listen for such requests
// and terminate the process.
stopTrigger *stopTrigger
// SQL uses the clock to assign timestamps to transactions, among many
// other things.
clock *hlc.Clock
// The RuntimeStatSampler provides metrics data to the recorder.
runtime *status.RuntimeStatSampler
// DistSQL uses rpcContext to set up flows. Less centrally, the executor
// also uses rpcContext in a number of places to learn whether the server
// is running insecure, and to read the cluster name.
rpcContext *rpc.Context
// Used by DistSQLPlanner.
nodeDescs kvclient.NodeDescStore
// Used by the executor config.
systemConfigWatcher *systemconfigwatcher.Cache
// Used by the span config reconciliation job.
spanConfigAccessor spanconfig.KVAccessor
spanConfigReporter spanconfig.Reporter
// Used by the Key Visualizer job.
keyVisServerAccessor *spanstatskvaccessor.SpanStatsKVAccessor
// Used by DistSQLPlanner to dial KV nodes.
kvNodeDialer *nodedialer.Dialer
// Used by DistSQLPlanner to dial other SQL instances.
sqlInstanceDialer *nodedialer.Dialer
// SQL mostly uses the DistSender "wrapped" under a *kv.DB, but SQL also
// uses range descriptors and leaseholders, which DistSender maintains,
// for debugging and DistSQL planning purposes.
distSender *kvcoord.DistSender
// SQL uses KV, both for non-DistSQL and DistSQL execution.
db *kv.DB
// Various components want to register themselves with metrics.
registry *metric.Registry
sysRegistry *metric.Registry
clusterMetricsRegistry metric.RegistryReader
// Recorder exposes metrics to the prometheus endpoint.
recorder *status.MetricsRecorder
// Used for SHOW/CANCEL QUERIE(S)/SESSION(S).
sessionRegistry *sql.SessionRegistry
// Used to store closed sessions.
closedSessionCache *sql.ClosedSessionCache
// Used to track the DistSQL flows currently running on this node but
// initiated on behalf of other nodes.
remoteFlowRunner *flowinfra.RemoteFlowRunner
// KV depends on the internal executor, so we pass a pointer to an empty
// struct in this configuration, which newSQLServer fills.
//
// TODO(tbg): make this less hacky.
// TODO(ajwerner): Replace this entirely with the internalDB which follows.
// it is no less hacky, but at least it removes some redundancy. In some ways
// the internalDB is worse: the Executor() method cannot be used during server
// startup while the internalDB is partially initialized.
circularInternalExecutor *sql.InternalExecutor // empty initially
// internalDB is to initialize an internal executor.
internalDB *sql.InternalDB
// Stores and deletes expired liveness sessions.
sqlLivenessProvider sqlliveness.Provider
// Stores and manages sql instance information.
sqlInstanceReader *instancestorage.Reader
// Low-level access to the system.sql_instances table, used for allocating
// this server's instance ID.
sqlInstanceStorage *instancestorage.Storage
// The protected timestamps KV subsystem depends on this, so we pass a
// pointer to an empty struct in this configuration, which newSQLServer
// fills.
circularJobRegistry *jobs.Registry
// The executorConfig uses the provider.
protectedtsProvider protectedts.Provider
// Used to list activity (sessions, queries, contention, DistSQL flows) on
// the node/cluster and cancel sessions/queries.
sqlStatusServer serverpb.SQLStatusServer
// Used to construct rangefeeds.
rangeFeedFactory *rangefeed.Factory
// Used to query status information useful for debugging on the server.
tenantStatusServer serverpb.TenantStatusServer
// Used for multi-tenant cost control (on the storage cluster side).
tenantUsageServer multitenant.TenantUsageServer
// Used for multi-tenant cost control (on the tenant side).
costController multitenant.TenantSideCostController
// monitorAndMetrics contains the return value of newRootSQLMemoryMonitor.
monitorAndMetrics monitorAndMetrics
// settingsStorage is an optional interface to drive storing of settings
// data on disk to provide a fresh source of settings upon next startup.
settingsStorage settingswatcher.Storage
// grpc is the RPC service.
grpc *grpcServer
drpc *drpcServer
// externalStorageBuilder is the constructor for accesses to external
// storage.
externalStorageBuilder *externalStorageBuilder
// admissionPacerFactory is used for elastic CPU control when performing
// CPU intensive operations, such as CDC event encoding/decoding.
admissionPacerFactory admission.PacerFactory
// sqlCPUProvider is used to report CPU usage and foreground (non-elastic)
// SQL CPU admission control.
sqlCPUProvider admission.SQLCPUProvider
// rangeDescIteratorFactory is used to construct iterators over range
// descriptors.
rangeDescIteratorFactory rangedesc.IteratorFactory
// tenantTimeSeriesServer is used to make TSDB queries by the DB Console.
tenantTimeSeriesServer *ts.TenantServer
tenantCapabilitiesReader sql.SystemTenantOnly[tenantcapabilities.Reader]
}
type monitorAndMetrics struct {
rootSQLMemoryMonitor *mon.BytesMonitor
rootSQLMetrics sql.BaseMemoryMetrics
}
type monitorAndMetricsOptions struct {
memoryPoolSize int64
histogramWindowInterval time.Duration
settings *cluster.Settings
}
var vmoduleSetting = settings.RegisterStringSetting(
settings.ApplicationLevel,
"server.debug.default_vmodule",
"vmodule string (ignored by any server with an explicit one provided at start)",
"",
)
// newRootSQLMemoryMonitor returns a started BytesMonitor and corresponding
// metrics.
func newRootSQLMemoryMonitor(opts monitorAndMetricsOptions) monitorAndMetrics {
rootSQLMetrics := sql.MakeBaseMemMetrics("root", opts.histogramWindowInterval)
rootSQLMemoryMonitor := mon.NewMonitor(mon.Options{
Name: mon.MakeName("root"),
CurCount: rootSQLMetrics.CurBytesCount,
MaxHist: rootSQLMetrics.MaxBytesHist,
Settings: opts.settings,
})
rootSQLMemoryMonitor.MarkAsRootSQLMonitor()
// Set the limit to the memoryPoolSize. Note that this memory monitor also
// serves as a parent for a memory monitor that accounts for memory used in
// the KV layer at the same node.
rootSQLMemoryMonitor.Start(
context.Background(), nil, mon.NewStandaloneBudget(opts.memoryPoolSize))
return monitorAndMetrics{
rootSQLMemoryMonitor: rootSQLMemoryMonitor,
rootSQLMetrics: rootSQLMetrics,
}
}
// stopperSessionEventListener implements slinstance.SessionEventListener and
// turns a session deletion event into a request to stop the server.
type stopperSessionEventListener struct {
trigger *stopTrigger
}
var _ slinstance.SessionEventListener = &stopperSessionEventListener{}
// OnSessionDeleted implements the slinstance.SessionEventListener interface.
func (s *stopperSessionEventListener) OnSessionDeleted(
ctx context.Context,
) (createAnotherSession bool) {
s.trigger.signalStop(ctx,
serverctl.MakeShutdownRequest(serverctl.ShutdownReasonFatalError, errors.New("sql liveness session deleted")))
// Return false in order to prevent the sqlliveness loop from creating a new
// session. We're shutting down the server and creating a new session would
// only cause confusion.
return false
}
type refreshInstanceSessionListener struct {
cfg *sqlServerArgs
}
var _ slinstance.SessionEventListener = &stopperSessionEventListener{}
// OnSessionDeleted implements the slinstance.SessionEventListener interface.
func (r *refreshInstanceSessionListener) OnSessionDeleted(
ctx context.Context,
) (createAnotherSession bool) {
if err := r.cfg.stopper.RunAsyncTask(ctx, "refresh-instance-session", func(ctx context.Context) {
for i := retry.StartWithCtx(ctx, retry.Options{MaxBackoff: time.Second * 5}); i.Next(); {
select {
case <-r.cfg.stopper.ShouldQuiesce():
return
case <-ctx.Done():
return
default:
}
nodeID, _ := r.cfg.nodeIDContainer.OptionalNodeID()
s, err := r.cfg.sqlLivenessProvider.Session(ctx)
if err != nil {
log.Dev.Warningf(ctx, "failed to get new liveness session ID: %v", err)
continue
}
if _, err := r.cfg.sqlInstanceStorage.CreateNodeInstance(
ctx,
s,
r.cfg.AdvertiseAddr,
r.cfg.SQLAdvertiseAddr,
r.cfg.Locality,
r.cfg.Settings.Version.LatestVersion(),
nodeID,
); err != nil {
log.Dev.Warningf(ctx, "failed to update instance with new session ID: %v", err)
continue
}
return
}
}); err != nil {
log.Dev.Errorf(ctx, "failed to run update of instance with new session ID: %v", err)
}
return true
}
// newSQLServer constructs a new SQLServer. The caller is responsible for
// listening to the server's serverctl.ShutdownRequested() channel (which is the same as
// cfg.stopTrigger.C()) and stopping cfg.stopper when signaled.
func newSQLServer(ctx context.Context, cfg sqlServerArgs) (*SQLServer, error) {
// NB: ValidateAddrs also fills in defaults.
if err := cfg.Config.ValidateAddrs(ctx); err != nil {
return nil, err
}
execCfg := &sql.ExecutorConfig{}
codec := keys.MakeSQLCodec(cfg.SQLConfig.TenantID)
if knobs := cfg.TestingKnobs.TenantTestingKnobs; knobs != nil {
override := knobs.(*sql.TenantTestingKnobs).TenantIDCodecOverride
if override != (roachpb.TenantID{}) {
codec = keys.MakeSQLCodec(override)
}
}
var jobAdoptionStopFile string
for _, spec := range cfg.Stores.Specs {
if !spec.InMemory && spec.Path != "" {
jobAdoptionStopFile = filepath.Join(spec.Path, jobs.PreventAdoptionFile)
break
}
}
if err := cfg.stopper.RunAsyncTask(ctx, "tracer-snapshots", func(context.Context) {
cfg.Tracer.PeriodicSnapshotsLoop(&cfg.Settings.SV, cfg.stopper.ShouldQuiesce())
}); err != nil {
return nil, err
}
// Create trace service for inter-node sharing of inflight trace spans.
tracingService := service.New(cfg.Tracer)
tracingservicepb.RegisterTracingServer(cfg.grpcServer, tracingService)
if err := tracingservicepb.DRPCRegisterTracing(cfg.drpcMux, tracingService); err != nil {
return nil, err
}
// If the node id is already populated, we only need to create a placeholder
// instance provider without initializing the instance, since this is not a
// SQL pod server.
_, isMixedSQLAndKVNode := cfg.nodeIDContainer.OptionalNodeID()
var settingsWatcher *settingswatcher.SettingsWatcher
if codec.ForSystemTenant() {
settingsWatcher = settingswatcher.NewWithNotifier(ctx,
cfg.clock, codec, cfg.Settings, cfg.rangeFeedFactory, cfg.stopper, cfg.notifyChangeToSystemVisibleSettings, cfg.settingsStorage,
)
} else {
// Create the tenant settings watcher, using the tenant connector as the
// overrides monitor.
settingsWatcher = settingswatcher.NewWithOverrides(
cfg.clock, codec, cfg.Settings, cfg.rangeFeedFactory, cfg.stopper, cfg.tenantConnect, cfg.settingsStorage,
)
}
sqllivenessKnobs, _ := cfg.TestingKnobs.SQLLivenessKnobs.(*sqlliveness.TestingKnobs)
var sessionEventsConsumer slinstance.SessionEventListener
if !isMixedSQLAndKVNode {
// For SQL pods, we want the process to shutdown when the session liveness
// record is found to be deleted. This is because, if the session is
// deleted, the instance ID used by this server may have been stolen by
// another server, or it may be stolen in the future. This server shouldn't
// use the instance ID anymore, and there's no mechanism for allocating a
// new one after startup.
sessionEventsConsumer = &stopperSessionEventListener{trigger: cfg.stopTrigger}
} else {
sessionEventsConsumer = &refreshInstanceSessionListener{cfg: &cfg}
}
cfg.sqlLivenessProvider = slprovider.New(
cfg.AmbientCtx,
cfg.stopper, cfg.clock, cfg.db, codec, cfg.Settings, settingsWatcher, sqllivenessKnobs, sessionEventsConsumer,
)
cfg.sqlInstanceStorage = instancestorage.NewStorage(
cfg.db, codec, cfg.sqlLivenessProvider.CachedReader(), cfg.Settings,
cfg.clock, cfg.rangeFeedFactory, settingsWatcher)
cfg.sqlInstanceReader = instancestorage.NewReader(
cfg.sqlInstanceStorage, cfg.sqlLivenessProvider.CachedReader(),
cfg.stopper,
cfg.db,
)
// We can't use the nodeDialer as the sqlInstanceDialer unless we
// are serving the system tenant despite the fact that we've
// arranged for pod IDs and instance IDs to match since the
// secondary tenant gRPC servers currently live on a different
// port.
canUseNodeDialerAsSQLInstanceDialer := isMixedSQLAndKVNode && codec.ForSystemTenant()
if canUseNodeDialerAsSQLInstanceDialer {
cfg.sqlInstanceDialer = cfg.kvNodeDialer
} else {
// In a multi-tenant environment, use the sqlInstanceReader to resolve
// SQL pod addresses.
addressResolver := func(nodeID roachpb.NodeID) (net.Addr, roachpb.Locality, error) {
info, err := cfg.sqlInstanceReader.GetInstance(cfg.rpcContext.MasterCtx, base.SQLInstanceID(nodeID))
if err != nil {
return nil, roachpb.Locality{}, errors.Wrapf(err, "unable to look up descriptor for n%d", nodeID)
}
return &util.UnresolvedAddr{AddressField: info.InstanceRPCAddr}, info.Locality, nil
}
cfg.sqlInstanceDialer = nodedialer.New(cfg.rpcContext, addressResolver)
}
jobRegistry := cfg.circularJobRegistry
{
cfg.registry.AddMetricStruct(cfg.sqlLivenessProvider.Metrics())
var jobsKnobs *jobs.TestingKnobs
if cfg.TestingKnobs.JobsTestingKnobs != nil {
jobsKnobs = cfg.TestingKnobs.JobsTestingKnobs.(*jobs.TestingKnobs)
}
*jobRegistry = *jobs.MakeRegistry(
ctx,
cfg.AmbientCtx,
cfg.stopper,
cfg.clock,
cfg.rpcContext.LogicalClusterID,
cfg.nodeIDContainer,
cfg.sqlLivenessProvider,
cfg.Settings,
cfg.HistogramWindowInterval(),
func(ctx context.Context, opName redact.SafeString, user username.SQLUsername) (interface{}, func()) {
// This is a hack to get around a Go package dependency cycle. See comment
// in sql/jobs/registry.go on planHookMaker.
return sql.MakeJobExecContext(ctx, opName, user, &sql.MemoryMetrics{}, execCfg)
},
jobAdoptionStopFile,
jobsKnobs,
cfg.CidrLookup,
)
}
cfg.registry.AddMetricStruct(jobRegistry.MetricsStruct())
// Set up Lease Manager
var lmKnobs lease.ManagerTestingKnobs
if leaseManagerTestingKnobs := cfg.TestingKnobs.SQLLeaseManager; leaseManagerTestingKnobs != nil {
lmKnobs = *leaseManagerTestingKnobs.(*lease.ManagerTestingKnobs)
}
leaseMgr := lease.NewLeaseManager(
ctx,
cfg.AmbientCtx,
cfg.nodeIDContainer,
cfg.internalDB,
cfg.clock,
cfg.Settings,
settingsWatcher,
cfg.sqlLivenessProvider,
codec,
lmKnobs,
cfg.stopper,
cfg.rangeFeedFactory,
cfg.monitorAndMetrics.rootSQLMemoryMonitor,
)
cfg.registry.AddMetricStruct(leaseMgr.MetricsStruct())
rootSQLMetrics := cfg.monitorAndMetrics.rootSQLMetrics
cfg.registry.AddMetricStruct(rootSQLMetrics)
// Set up internal memory metrics for use by internal SQL executors.
internalMemMetrics := sql.MakeMemMetrics("internal", cfg.HistogramWindowInterval())
cfg.registry.AddMetricStruct(internalMemMetrics)
rootSQLMemoryMonitor := cfg.monitorAndMetrics.rootSQLMemoryMonitor
// bulkMemoryMonitor is the parent to all child SQL monitors tracking bulk
// operations (IMPORT, index backfill). It is itself a child of the
// ParentMemoryMonitor.
bulkMemoryMonitor := mon.NewMonitorInheritWithLimit(
mon.MakeName("bulk-mon"), 0 /* limit */, rootSQLMemoryMonitor, true, /* longLiving */
)
bulkMetrics := bulk.MakeBulkMetrics(cfg.HistogramWindowInterval())
cfg.registry.AddMetricStruct(bulkMetrics)
bulkMemoryMonitor.SetMetrics(bulkMetrics.CurBytesCount, bulkMetrics.MaxBytesHist)
bulkMemoryMonitor.StartNoReserved(ctx, rootSQLMemoryMonitor)
bulkMergeMetrics := execinfra.MakeBulkMergeMetrics(cfg.HistogramWindowInterval())
cfg.registry.AddMetricStruct(bulkMergeMetrics)
backfillMemoryMonitor := execinfra.NewMonitor(ctx, bulkMemoryMonitor, mon.MakeName("backfill-mon"))
backfillMemoryMonitor.MarkLongLiving()
backupMemoryMonitor := execinfra.NewMonitor(ctx, bulkMemoryMonitor, mon.MakeName("backup-mon"))
backupMemoryMonitor.MarkLongLiving()
changefeedMemoryMonitor := mon.NewMonitorInheritWithLimit(
mon.MakeName("changefeed-mon"), 0 /* limit */, rootSQLMemoryMonitor, true, /* longLiving */
)
if jobs.MakeChangefeedMemoryMetricsHook != nil {
changefeedCurCount, changefeedMaxHist := jobs.MakeChangefeedMemoryMetricsHook(cfg.HistogramWindowInterval())
changefeedMemoryMonitor.SetMetrics(changefeedCurCount, changefeedMaxHist)
}
changefeedMemoryMonitor.StartNoReserved(ctx, rootSQLMemoryMonitor)
serverCacheMemoryMonitor := mon.NewMonitorInheritWithLimit(
mon.MakeName("server-cache-mon"), 0 /* limit */, rootSQLMemoryMonitor, true, /* longLiving */
)
serverCacheMemoryMonitor.StartNoReserved(ctx, rootSQLMemoryMonitor)
// Set up the DistSQL temp engine.
tempEngine, tempFS, err := storage.NewTempEngine(ctx, cfg.TempStorageConfig, cfg.DiskWriteStats)
if err != nil {
return nil, errors.Wrap(err, "creating temp storage")
}
cfg.stopper.AddCloser(tempEngine)
distSQLMetrics := execinfra.MakeDistSQLMetrics(cfg.HistogramWindowInterval())
cfg.registry.AddMetricStruct(distSQLMetrics)
rowMetrics := sql.NewRowMetrics(false /* internal */)
cfg.registry.AddMetricStruct(rowMetrics)
internalRowMetrics := sql.NewRowMetrics(true /* internal */)
cfg.registry.AddMetricStruct(internalRowMetrics)
kvStreamerMetrics := kvstreamer.MakeMetrics()
cfg.registry.AddMetricStruct(kvStreamerMetrics)
virtualSchemas, err := sql.NewVirtualSchemaHolder(ctx, cfg.Settings)
if err != nil {
return nil, errors.Wrap(err, "creating virtual schema holder")
}
hydratedDescCache := hydrateddesccache.NewCache(cfg.Settings)
cfg.registry.AddMetricStruct(hydratedDescCache.Metrics())
gcJobNotifier := gcjobnotifier.New(cfg.Settings, cfg.systemConfigWatcher, codec, cfg.stopper)
spanConfig := struct {
manager *spanconfigmanager.Manager
sqlTranslatorFactory *spanconfigsqltranslator.Factory
sqlWatcher *spanconfigsqlwatcher.SQLWatcher
splitter spanconfig.Splitter
limiter spanconfig.Limiter
}{}
spanConfigKnobs, _ := cfg.TestingKnobs.SpanConfig.(*spanconfig.TestingKnobs)
if codec.ForSystemTenant() {
spanConfig.splitter = spanconfigsplitter.NoopSplitter{}
} else {
spanConfig.splitter = spanconfigsplitter.New(codec, spanConfigKnobs)
}
if cfg.spanLimiterFactory == nil {
spanConfig.limiter = spanconfiglimiter.NoopLimiter{}
} else {
spanConfig.limiter = cfg.spanLimiterFactory(
cfg.circularInternalExecutor,
cfg.Settings,
spanConfigKnobs,
)
}
collectionFactory := descs.NewCollectionFactory(
ctx,
cfg.Settings,
leaseMgr,
virtualSchemas,
hydratedDescCache,
spanConfig.splitter,
spanConfig.limiter,
catsessiondata.DefaultDescriptorSessionDataProvider,
)
clusterIDForSQL := cfg.rpcContext.LogicalClusterID
bulkSenderLimiter := bulk.MakeAndRegisterConcurrencyLimiter(&cfg.Settings.SV)
rangeStatsFetcher := rangestats.NewFetcher(cfg.db)
vecIndexManager := vecindex.NewManager(ctx, cfg.stopper, &cfg.Settings.SV, codec, cfg.internalDB)
if vecIndexKnobs, ok := cfg.TestingKnobs.VecIndexTestingKnobs.(*vecindex.VecIndexTestingKnobs); ok && vecIndexKnobs != nil {
vecIndexManager.SetTestingKnobs(vecIndexKnobs)
}
cfg.registry.AddMetricStruct(vecIndexManager.Metrics())
// Set up the DistSQL server.
distSQLCfg := execinfra.ServerConfig{
AmbientContext: cfg.AmbientCtx,
Settings: cfg.Settings,
RuntimeStats: cfg.runtime,
LogicalClusterID: clusterIDForSQL,
ClusterName: cfg.ClusterName,
NodeID: cfg.nodeIDContainer,
Locality: cfg.Locality,
Codec: codec,
DB: cfg.internalDB,
RPCContext: cfg.rpcContext,
Stopper: cfg.stopper,
TempStorage: tempEngine,
TempStoragePath: cfg.TempStorageConfig.Path,
TempFS: tempFS,
// COCKROACH_VEC_MAX_OPEN_FDS specifies the maximum number of open file
// descriptors that the vectorized execution engine may have open at any
// one time. This limit is implemented as a weighted semaphore acquired
// before opening files.
VecFDSemaphore: semaphore.New(envutil.EnvOrDefaultInt("COCKROACH_VEC_MAX_OPEN_FDS", colexec.VecMaxOpenFDsLimit)),
ParentDiskMonitor: cfg.TempStorageConfig.Mon,
BackfillerMonitor: backfillMemoryMonitor,
BackupMonitor: backupMemoryMonitor,
BulkMonitor: bulkMemoryMonitor,
ChangefeedMonitor: changefeedMemoryMonitor,
BulkSenderLimiter: bulkSenderLimiter,
BulkMergeMetrics: &bulkMergeMetrics,
ParentMemoryMonitor: rootSQLMemoryMonitor,
BulkAdder: func(
ctx context.Context, db *kv.DB, ts hlc.Timestamp, opts kvserverbase.BulkAdderOptions,
) (kvserverbase.BulkAdder, error) {
// Attach a child memory monitor to enable control over the BulkAdder's
// memory usage.
bulkMon := execinfra.NewMonitor(ctx, bulkMemoryMonitor, mon.MakeName("bulk-adder-monitor"))
return bulk.MakeBulkAdder(ctx, db, cfg.distSender.RangeDescriptorCache(), cfg.Settings, ts, opts, bulkMon, bulkSenderLimiter)
},
Metrics: &distSQLMetrics,
RowMetrics: &rowMetrics,
InternalRowMetrics: &internalRowMetrics,
KVStreamerMetrics: &kvStreamerMetrics,
SQLLivenessReader: cfg.sqlLivenessProvider.CachedReader(),
BlockingSQLLivenessReader: cfg.sqlLivenessProvider.BlockingReader(),
JobRegistry: jobRegistry,
Gossip: cfg.gossip,
SQLInstanceDialer: cfg.sqlInstanceDialer,
LeaseManager: leaseMgr,
ExternalStorage: cfg.externalStorage,
ExternalStorageFromURI: cfg.externalStorageFromURI,
DistSender: cfg.distSender,
RangeCache: cfg.distSender.RangeDescriptorCache(),
SQLSQLResponseAdmissionQ: cfg.sqlSQLResponseAdmissionQ,
CollectionFactory: collectionFactory,
ExternalIORecorder: cfg.costController,
TenantCostController: cfg.costController,
RangeStatsFetcher: rangeStatsFetcher,
AdmissionPacerFactory: cfg.admissionPacerFactory,
SQLCPUProvider: cfg.sqlCPUProvider,
ExecutorConfig: execCfg,
RootSQLMemoryPoolSize: cfg.MemoryPoolSize,
VecIndexManager: vecIndexManager,
}
cfg.TempStorageConfig.Mon.SetMetrics(distSQLMetrics.CurDiskBytesCount, distSQLMetrics.MaxDiskBytesHist)
if codec.ForSystemTenant() {
// Stop the temp storage disk monitor to enforce (in test builds) that
// all short-living descendants are stopped too.
//
// Note that we don't do this for SQL servers of tenants since there we
// can have ungraceful shutdown whenever the node is quiescing, so we
// have some short-living monitors that aren't stopped.
cfg.stopper.AddCloser(stop.CloserFn(func() {
cfg.TempStorageConfig.Mon.EmergencyStop(ctx)
}))
}
if distSQLTestingKnobs := cfg.TestingKnobs.DistSQL; distSQLTestingKnobs != nil {
distSQLCfg.TestingKnobs = *distSQLTestingKnobs.(*execinfra.TestingKnobs)
}
if cfg.TestingKnobs.JobsTestingKnobs != nil {
distSQLCfg.TestingKnobs.JobsTestingKnobs = cfg.TestingKnobs.JobsTestingKnobs
}
distSQLServer := distsql.NewServer(ctx, distSQLCfg, cfg.remoteFlowRunner)
execinfrapb.RegisterDistSQLServer(cfg.grpcServer, distSQLServer)
if err := execinfrapb.DRPCRegisterDistSQL(cfg.drpcMux, distSQLServer.AsDRPCServer()); err != nil {
return nil, err
}
// Set up Executor
var sqlExecutorTestingKnobs sql.ExecutorTestingKnobs
if k := cfg.TestingKnobs.SQLExecutor; k != nil {
sqlExecutorTestingKnobs = *k.(*sql.ExecutorTestingKnobs)
} else {
sqlExecutorTestingKnobs = sql.ExecutorTestingKnobs{}
}
nodeInfo := sql.NodeInfo{
AdminURL: cfg.AdminURL,
PGURL: func(user *url.Userinfo) (*pgurl.URL, error) {
if cfg.Config.SQLAdvertiseAddr == "" {
log.Dev.Fatal(ctx, "programming error: usage of advertised addr before listeners have started")
}
ccopts := clientsecopts.ClientSecurityOptions{
Insecure: cfg.Config.Insecure,
CertsDir: cfg.Config.SSLCertsDir,
}
sparams := clientsecopts.ServerParameters{
ServerAddr: cfg.Config.SQLAdvertiseAddr,
DefaultPort: base.DefaultPort,
DefaultDatabase: catalogkeys.DefaultDatabaseName,
}
return clientsecopts.MakeURLForServer(ccopts, sparams, user)
},
LogicalClusterID: cfg.rpcContext.LogicalClusterID.Get,
NodeID: cfg.nodeIDContainer,
}
var isAvailable func(sqlInstanceID base.SQLInstanceID) bool
nodeLiveness, hasNodeLiveness := cfg.nodeLiveness.Optional()
if hasNodeLiveness {
isAvailable = func(sqlInstanceID base.SQLInstanceID) bool {
return nodeLiveness.GetNodeVitalityFromCache(roachpb.NodeID(sqlInstanceID)).IsLive(livenesspb.DistSQL)
}
} else {
// We're on a SQL tenant, so this is the only node DistSQL will ever
// schedule on - always returning true is fine.
isAvailable = func(sqlInstanceID base.SQLInstanceID) bool {
return true
}
}
// Setup the trace collector that is used to fetch inflight trace spans from
// all nodes in the cluster.
traceCollector := collector.New(cfg.Tracer, cfg.sqlInstanceReader.GetAllInstances, cfg.sqlInstanceDialer)
contentionMetrics := contention.NewMetrics()
cfg.registry.AddMetricStruct(contentionMetrics)
contentionRegistry := contention.NewRegistry(
cfg.Settings,
cfg.sqlStatusServer.TxnIDResolution,
&contentionMetrics,
)
if !cfg.Insecure {
certMgr, err := cfg.rpcContext.SecurityContext.GetCertificateManager()
if err != nil {
return nil, errors.Wrap(err, "initializing certificate manager")
}
err = certMgr.RegisterExpirationCache(
ctx, cfg.stopper, &timeutil.DefaultTimeSource{}, rootSQLMemoryMonitor, cfg.Settings,
)
if err != nil {
return nil, errors.Wrap(err, "adding clientcert cache")
}
}
storageEngineClient := kvserver.NewStorageEngineClient(cfg.kvNodeDialer)
*execCfg = sql.ExecutorConfig{
Settings: cfg.Settings,
// TODO(yuzefovich): I think cfg.stopper doesn't use the Tracer option.
// Investigate whether it's important (it's probably created in
// setupAndInitializeLoggingAndProfiling).
Stopper: cfg.stopper,
NodeInfo: nodeInfo,
Codec: codec,
DefaultZoneConfig: &cfg.DefaultZoneConfig,
Locality: cfg.Locality,
AmbientCtx: cfg.AmbientCtx,
DB: cfg.db,
Gossip: cfg.gossip,
NodeLiveness: cfg.nodeLiveness,
SystemConfig: cfg.systemConfigWatcher,
MetricsRecorder: cfg.recorder,
DistSender: cfg.distSender,
RPCContext: cfg.rpcContext,
LeaseManager: leaseMgr,
TenantStatusServer: cfg.tenantStatusServer,