-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
conn_executor.go
3829 lines (3476 loc) · 144 KB
/
conn_executor.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 2017 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 sql
import (
"context"
"fmt"
"io"
"math"
"math/rand"
"strings"
"sync/atomic"
"time"
"unicode/utf8"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/multitenant"
"github.com/cockroachdb/cockroach/pkg/multitenant/multitenantcpu"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/server/serverpb"
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descidgen"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descs"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/schematelemetry/schematelemetrycontroller"
"github.com/cockroachdb/cockroach/pkg/sql/clusterunique"
"github.com/cockroachdb/cockroach/pkg/sql/contention/txnidcache"
"github.com/cockroachdb/cockroach/pkg/sql/execstats"
"github.com/cockroachdb/cockroach/pkg/sql/idxrecommendations"
"github.com/cockroachdb/cockroach/pkg/sql/idxusage"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgwirecancel"
"github.com/cockroachdb/cockroach/pkg/sql/schemachanger/scerrors"
"github.com/cockroachdb/cockroach/pkg/sql/schemachanger/scrun"
"github.com/cockroachdb/cockroach/pkg/sql/sem/asof"
"github.com/cockroachdb/cockroach/pkg/sql/sem/catconstants"
"github.com/cockroachdb/cockroach/pkg/sql/sem/eval"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondatapb"
"github.com/cockroachdb/cockroach/pkg/sql/sessionphase"
"github.com/cockroachdb/cockroach/pkg/sql/sqlerrors"
"github.com/cockroachdb/cockroach/pkg/sql/sqlstats"
"github.com/cockroachdb/cockroach/pkg/sql/sqlstats/insights"
"github.com/cockroachdb/cockroach/pkg/sql/sqlstats/persistedsqlstats"
"github.com/cockroachdb/cockroach/pkg/sql/sqlstats/sslocal"
"github.com/cockroachdb/cockroach/pkg/sql/stmtdiagnostics"
"github.com/cockroachdb/cockroach/pkg/util"
"github.com/cockroachdb/cockroach/pkg/util/buildutil"
"github.com/cockroachdb/cockroach/pkg/util/envutil"
"github.com/cockroachdb/cockroach/pkg/util/errorutil"
"github.com/cockroachdb/cockroach/pkg/util/fsm"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/log/logcrash"
"github.com/cockroachdb/cockroach/pkg/util/log/severity"
"github.com/cockroachdb/cockroach/pkg/util/metric"
"github.com/cockroachdb/cockroach/pkg/util/mon"
"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/tochar"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/logtags"
"golang.org/x/net/trace"
)
// noteworthyMemoryUsageBytes is the minimum size tracked by a
// transaction or session monitor before the monitor starts explicitly
// logging overall usage growth in the log.
var noteworthyMemoryUsageBytes = envutil.EnvOrDefaultInt64("COCKROACH_NOTEWORTHY_SESSION_MEMORY_USAGE", 1024*1024)
// A connExecutor is in charge of executing queries received on a given client
// connection. The connExecutor implements a state machine (dictated by the
// Postgres/pgwire session semantics). The state machine is supposed to run
// asynchronously wrt the client connection: it receives input statements
// through a stmtBuf and produces results through a clientComm interface. The
// connExecutor maintains a cursor over the statementBuffer and executes
// statements / produces results for one statement at a time. The cursor points
// at all times to the statement that the connExecutor is currently executing.
// Results for statements before the cursor have already been produced (but not
// necessarily delivered to the client). Statements after the cursor are queued
// for future execution. Keeping already executed statements in the buffer is
// useful in case of automatic retries (in which case statements from the
// retried transaction have to be executed again); the connExecutor is in charge
// of removing old statements that are no longer needed for retries from the
// (head of the) buffer. Separately, the implementer of the clientComm interface
// (e.g. the pgwire module) is in charge of keeping track of what results have
// been delivered to the client and what results haven't (yet).
//
// The connExecutor has two main responsibilities: to dispatch queries to the
// execution engine(s) and relay their results to the clientComm, and to
// implement the state machine maintaining the various aspects of a connection's
// state. The state machine implementation is further divided into two aspects:
// maintaining the transaction status of the connection (outside of a txn,
// inside a txn, in an aborted txn, in a txn awaiting client restart, etc.) and
// maintaining the cursor position (i.e. correctly jumping to whatever the
// "next" statement to execute is in various situations).
//
// The cursor normally advances one statement at a time, but it can also skip
// some statements (remaining statements in a query string are skipped once an
// error is encountered) and it can sometimes be rewound when performing
// automatic retries. Rewinding can only be done if results for the rewound
// statements have not actually been delivered to the client; see below.
//
// +---------------------+
// |connExecutor |
// | |
// +->execution+--------------+
// || + | |
// || |fsm.Event | |
// || | | |
// || v | |
// || fsm.Machine(TxnStateTransitions)
// || + +--------+ | |
// +--------------------+ || | |txnState| | |
// |stmtBuf | || | +--------+ | |
// | | statements are read || | | |
// | +-+-+ +-+-+ +-+-+ +------------------------+ | | |
// | | | | | | | | | | | | | +-------------+ |
// +---> +-+-+ +++-+ +-+-+ | | | |session data | |
// | | ^ | | | +-------------+ |
// | | | +-----------------------------------+ | |
// | | + v | cursor is advanced | advanceInfo | |
// | | cursor | | | |
// | +--------------------+ +---------------------+ |
// | |
// | |
// +-------------+ |
// +--------+ |
// | parser | |
// +--------+ |
// | |
// | |
// | +----------------+ |
// +-------+------+ |execution engine<--------+
// | pgwire conn | +------------+(local/DistSQL) |
// | | | +----------------+
// | +----------+ |
// | |clientComm<---------------+
// | +----------+ results are produced
// | |
// +-------^------+
// |
// |
// +-------+------+
// | SQL client |
// +--------------+
//
// The connExecutor is disconnected from client communication (i.e. generally
// network communication - i.e. pgwire.conn); the module doing client
// communication is responsible for pushing statements into the buffer and for
// providing an implementation of the clientConn interface (and thus sending
// results to the client). The connExecutor does not control when
// results are delivered to the client, but still it does have some influence
// over that; this is because of the fact that the possibility of doing
// automatic retries goes away the moment results for the transaction in
// question are delivered to the client. The communication module has full
// freedom in sending results whenever it sees fit; however the connExecutor
// influences communication in the following ways:
//
// a) When deciding whether an automatic retry can be performed for a
// transaction, the connExecutor needs to:
//
// 1) query the communication status to check that no results for the txn have
// been delivered to the client and, if this check passes:
// 2) lock the communication so that no further results are delivered to the
// client, and, eventually:
// 3) rewind the clientComm to a certain position corresponding to the start
// of the transaction, thereby discarding all the results that had been
// accumulated for the previous attempt to run the transaction in question.
//
// These steps are all orchestrated through clientComm.lockCommunication() and
// rewindCapability{}.
//
// b) The connExecutor sometimes ask the clientComm to deliver everything
// (most commonly in response to a Sync command).
//
// As of Feb 2018, the pgwire.conn delivers results synchronously to the client
// when its internal buffer overflows. In principle, delivery of result could be
// done asynchronously wrt the processing of commands (e.g. we could have a
// timing policy in addition to the buffer size). The first implementation of
// that showed a performance impact of involving a channel communication in the
// Sync processing path.
//
//
// Implementation notes:
//
// --- Error handling ---
//
// The key to understanding how the connExecutor handles errors is understanding
// the fact that there's two distinct categories of errors to speak of. There
// are "query execution errors" and there are the rest. Most things fall in the
// former category: invalid queries, queries that fail constraints at runtime,
// data unavailability errors, retriable errors (i.e. serializability
// violations) "internal errors" (e.g. connection problems in the cluster). This
// category of errors doesn't represent dramatic events as far as the connExecutor
// is concerned: they produce "results" for the query to be passed to the client
// just like more successful queries do and they produce Events for the
// state machine just like the successful queries (the events in question
// are generally event{non}RetriableErr and they generally cause the
// state machine to move to the Aborted state, but the connExecutor doesn't
// concern itself with this). The way the connExecutor reacts to these errors is
// the same as how it reacts to a successful query completing: it moves the
// cursor over the incoming statements as instructed by the state machine and
// continues running statements.
//
// And then there's other errors that don't have anything to do with a
// particular query, but with the connExecutor itself. In other languages, these
// would perhaps be modeled as Exceptions: we want them to unwind the stack
// significantly. These errors cause the connExecutor.run() to break out of its
// loop and return an error. Example of such errors include errors in
// communication with the client (e.g. the network connection is broken) or the
// connection's context being canceled.
//
// All of connExecutor's methods only return errors for the 2nd category. Query
// execution errors are written to a CommandResult. Low-level methods don't
// operate on a CommandResult directly; instead they operate on a wrapper
// (resultWithStoredErr), which provides access to the query error for purposes
// of building the correct state machine event.
//
// --- Context management ---
//
// At the highest level, there's connExecutor.run() that takes a context. That
// context is supposed to represent "the connection's context": its lifetime is
// the client connection's lifetime and it is assigned to
// connEx.ctxHolder.connCtx. Below that, every SQL transaction has its own
// derived context because that's the level at which we trace operations. The
// lifetime of SQL transactions is determined by the txnState: the state machine
// decides when transactions start and end in txnState.performStateTransition().
// When we're inside a SQL transaction, most operations are considered to happen
// in the context of that txn. When there's no SQL transaction (i.e.
// stateNoTxn), everything happens in the connection's context.
//
// High-level code in connExecutor is agnostic of whether it currently is inside
// a txn or not. To deal with both cases, such methods don't explicitly take a
// context; instead they use connEx.Ctx(), which returns the appropriate ctx
// based on the current state.
// Lower-level code (everything from connEx.execStmt() and below which runs in
// between state transitions) knows what state its running in, and so the usual
// pattern of explicitly taking a context as an argument is used.
// Server is the top level singleton for handling SQL connections. It creates
// connExecutors to server every incoming connection.
type Server struct {
_ util.NoCopy
cfg *ExecutorConfig
// sqlStats tracks per-application statistics for all applications on each
// node. Newly collected statistics flow into sqlStats.
sqlStats *persistedsqlstats.PersistedSQLStats
// sqlStatsController is the control-plane interface for sqlStats.
sqlStatsController *persistedsqlstats.Controller
// schemaTelemetryController is the control-plane interface for schema
// telemetry.
schemaTelemetryController *schematelemetrycontroller.Controller
// indexUsageStatsController is the control-plane interface for
// indexUsageStats.
indexUsageStatsController *idxusage.Controller
// reportedStats is a pool of stats that is held for reporting, and is
// cleared on a lower interval than sqlStats. Stats from sqlStats flow
// into reported stats when sqlStats is cleared.
reportedStats sqlstats.Provider
// reportedStatsController is the control-plane interface for
// reportedStatsController.
reportedStatsController *sslocal.Controller
insights insights.Provider
reCache *tree.RegexpCache
toCharFormatCache *tochar.FormatCache
// pool is the parent monitor for all session monitors.
pool *mon.BytesMonitor
// indexUsageStats tracks the index usage statistics queries that use current
// node as gateway node.
indexUsageStats *idxusage.LocalIndexUsageStats
// txnIDCache stores the mapping from transaction ID to transaction
// fingerprint IDs for all recently executed transactions.
txnIDCache *txnidcache.Cache
// Metrics is used to account normal queries.
Metrics Metrics
// InternalMetrics is used to account internal queries.
InternalMetrics Metrics
// ServerMetrics is used to account for Server activities that are unrelated to
// query planning and execution.
ServerMetrics ServerMetrics
// TelemetryLoggingMetrics is used to track metrics for logging to the telemetry channel.
TelemetryLoggingMetrics *TelemetryLoggingMetrics
idxRecommendationsCache *idxrecommendations.IndexRecCache
mu struct {
syncutil.Mutex
connectionCount int64
rootConnectionCount int64
}
}
// Metrics collects timeseries data about SQL activity.
type Metrics struct {
// EngineMetrics is exported as required by the metrics.Struct magic we use
// for metrics registration.
EngineMetrics EngineMetrics
// StartedStatementCounters contains metrics for statements initiated by
// users. These metrics count user-initiated operations, regardless of
// success (in particular, TxnCommitCount is the number of COMMIT statements
// attempted, not the number of transactions that successfully commit).
StartedStatementCounters StatementCounters
// ExecutedStatementCounters contains metrics for successfully executed
// statements.
ExecutedStatementCounters StatementCounters
// GuardrailMetrics contains metrics related to different guardrails in the
// SQL layer.
GuardrailMetrics GuardrailMetrics
}
// ServerMetrics collects timeseries data about Server activities that are
// unrelated to SQL planning and execution.
type ServerMetrics struct {
// StatsMetrics contains metrics for SQL statistics collection.
StatsMetrics StatsMetrics
// ContentionSubsystemMetrics contains metrics related to contention
// subsystem.
ContentionSubsystemMetrics txnidcache.Metrics
// InsightsMetrics contains metrics related to outlier detection.
InsightsMetrics insights.Metrics
}
// NewServer creates a new Server. Start() needs to be called before the Server
// is used.
func NewServer(cfg *ExecutorConfig, pool *mon.BytesMonitor) *Server {
metrics := makeMetrics(false /* internal */)
serverMetrics := makeServerMetrics(cfg)
insightsProvider := insights.New(cfg.Settings, serverMetrics.InsightsMetrics)
reportedSQLStats := sslocal.New(
cfg.Settings,
sqlstats.MaxMemReportedSQLStatsStmtFingerprints,
sqlstats.MaxMemReportedSQLStatsTxnFingerprints,
serverMetrics.StatsMetrics.ReportedSQLStatsMemoryCurBytesCount,
serverMetrics.StatsMetrics.ReportedSQLStatsMemoryMaxBytesHist,
insightsProvider.Writer,
pool,
nil, /* reportedProvider */
cfg.SQLStatsTestingKnobs,
)
reportedSQLStatsController :=
reportedSQLStats.GetController(cfg.SQLStatusServer, cfg.DB, cfg.InternalExecutor)
memSQLStats := sslocal.New(
cfg.Settings,
sqlstats.MaxMemSQLStatsStmtFingerprints,
sqlstats.MaxMemSQLStatsTxnFingerprints,
serverMetrics.StatsMetrics.SQLStatsMemoryCurBytesCount,
serverMetrics.StatsMetrics.SQLStatsMemoryMaxBytesHist,
insightsProvider.Writer,
pool,
reportedSQLStats,
cfg.SQLStatsTestingKnobs,
)
s := &Server{
cfg: cfg,
Metrics: metrics,
InternalMetrics: makeMetrics(true /* internal */),
ServerMetrics: serverMetrics,
pool: pool,
reportedStats: reportedSQLStats,
reportedStatsController: reportedSQLStatsController,
insights: insightsProvider,
reCache: tree.NewRegexpCache(512),
toCharFormatCache: tochar.NewFormatCache(512),
indexUsageStats: idxusage.NewLocalIndexUsageStats(&idxusage.Config{
ChannelSize: idxusage.DefaultChannelSize,
Setting: cfg.Settings,
}),
txnIDCache: txnidcache.NewTxnIDCache(
cfg.Settings,
&serverMetrics.ContentionSubsystemMetrics),
idxRecommendationsCache: idxrecommendations.NewIndexRecommendationsCache(cfg.Settings),
}
telemetryLoggingMetrics := &TelemetryLoggingMetrics{}
telemetryLoggingMetrics.Knobs = cfg.TelemetryLoggingTestingKnobs
s.TelemetryLoggingMetrics = telemetryLoggingMetrics
sqlStatsInternalExecutorMonitor := MakeInternalExecutorMemMonitor(MemoryMetrics{}, s.GetExecutorConfig().Settings)
sqlStatsInternalExecutorMonitor.StartNoReserved(context.Background(), s.GetBytesMonitor())
sqlStatsInternalExecutor := MakeInternalExecutor(s, MemoryMetrics{}, sqlStatsInternalExecutorMonitor)
persistedSQLStats := persistedsqlstats.New(&persistedsqlstats.Config{
Settings: s.cfg.Settings,
InternalExecutor: &sqlStatsInternalExecutor,
InternalExecutorMonitor: sqlStatsInternalExecutorMonitor,
KvDB: cfg.DB,
SQLIDContainer: cfg.NodeInfo.NodeID,
JobRegistry: s.cfg.JobRegistry,
Knobs: cfg.SQLStatsTestingKnobs,
FlushCounter: serverMetrics.StatsMetrics.SQLStatsFlushStarted,
FailureCounter: serverMetrics.StatsMetrics.SQLStatsFlushFailure,
FlushDuration: serverMetrics.StatsMetrics.SQLStatsFlushDuration,
}, memSQLStats)
s.sqlStats = persistedSQLStats
s.sqlStatsController = persistedSQLStats.GetController(cfg.SQLStatusServer)
schemaTelemetryIEMonitor := MakeInternalExecutorMemMonitor(MemoryMetrics{}, s.GetExecutorConfig().Settings)
schemaTelemetryIEMonitor.StartNoReserved(context.Background(), s.GetBytesMonitor())
schemaTelemetryIE := MakeInternalExecutor(s, MemoryMetrics{}, schemaTelemetryIEMonitor)
s.schemaTelemetryController = schematelemetrycontroller.NewController(
s.cfg.DB, &schemaTelemetryIE, schemaTelemetryIEMonitor, s.cfg.Settings, s.cfg.JobRegistry,
s.cfg.NodeInfo.LogicalClusterID,
)
s.indexUsageStatsController = idxusage.NewController(cfg.SQLStatusServer)
return s
}
func makeMetrics(internal bool) Metrics {
return Metrics{
EngineMetrics: EngineMetrics{
DistSQLSelectCount: metric.NewCounter(getMetricMeta(MetaDistSQLSelect, internal)),
SQLOptFallbackCount: metric.NewCounter(getMetricMeta(MetaSQLOptFallback, internal)),
SQLOptPlanCacheHits: metric.NewCounter(getMetricMeta(MetaSQLOptPlanCacheHits, internal)),
SQLOptPlanCacheMisses: metric.NewCounter(getMetricMeta(MetaSQLOptPlanCacheMisses, internal)),
// TODO(mrtracy): See HistogramWindowInterval in server/config.go for the 6x factor.
DistSQLExecLatency: metric.NewHistogram(metric.HistogramOptions{
Mode: metric.HistogramModePreferHdrLatency,
Metadata: getMetricMeta(MetaDistSQLExecLatency, internal),
Duration: 6 * metricsSampleInterval,
Buckets: metric.IOLatencyBuckets,
}),
SQLExecLatency: metric.NewHistogram(metric.HistogramOptions{
Mode: metric.HistogramModePreferHdrLatency,
Metadata: getMetricMeta(MetaSQLExecLatency, internal),
Duration: 6 * metricsSampleInterval,
Buckets: metric.IOLatencyBuckets,
}),
DistSQLServiceLatency: metric.NewHistogram(metric.HistogramOptions{
Mode: metric.HistogramModePreferHdrLatency,
Metadata: getMetricMeta(MetaDistSQLServiceLatency, internal),
Duration: 6 * metricsSampleInterval,
Buckets: metric.IOLatencyBuckets,
}),
SQLServiceLatency: metric.NewHistogram(metric.HistogramOptions{
Mode: metric.HistogramModePreferHdrLatency,
Metadata: getMetricMeta(MetaSQLServiceLatency, internal),
Duration: 6 * metricsSampleInterval,
Buckets: metric.IOLatencyBuckets,
}),
SQLTxnLatency: metric.NewHistogram(metric.HistogramOptions{
Mode: metric.HistogramModePreferHdrLatency,
Metadata: getMetricMeta(MetaSQLTxnLatency, internal),
Duration: 6 * metricsSampleInterval,
Buckets: metric.IOLatencyBuckets,
}),
SQLTxnsOpen: metric.NewGauge(getMetricMeta(MetaSQLTxnsOpen, internal)),
SQLActiveStatements: metric.NewGauge(getMetricMeta(MetaSQLActiveQueries, internal)),
SQLContendedTxns: metric.NewCounter(getMetricMeta(MetaSQLTxnContended, internal)),
TxnAbortCount: metric.NewCounter(getMetricMeta(MetaTxnAbort, internal)),
FailureCount: metric.NewCounter(getMetricMeta(MetaFailure, internal)),
FullTableOrIndexScanCount: metric.NewCounter(getMetricMeta(MetaFullTableOrIndexScan, internal)),
FullTableOrIndexScanRejectedCount: metric.NewCounter(getMetricMeta(MetaFullTableOrIndexScanRejected, internal)),
},
StartedStatementCounters: makeStartedStatementCounters(internal),
ExecutedStatementCounters: makeExecutedStatementCounters(internal),
GuardrailMetrics: GuardrailMetrics{
TxnRowsWrittenLogCount: metric.NewCounter(getMetricMeta(MetaTxnRowsWrittenLog, internal)),
TxnRowsWrittenErrCount: metric.NewCounter(getMetricMeta(MetaTxnRowsWrittenErr, internal)),
TxnRowsReadLogCount: metric.NewCounter(getMetricMeta(MetaTxnRowsReadLog, internal)),
TxnRowsReadErrCount: metric.NewCounter(getMetricMeta(MetaTxnRowsReadErr, internal)),
},
}
}
func makeServerMetrics(cfg *ExecutorConfig) ServerMetrics {
return ServerMetrics{
StatsMetrics: StatsMetrics{
SQLStatsMemoryMaxBytesHist: metric.NewHistogram(metric.HistogramOptions{
Metadata: MetaSQLStatsMemMaxBytes,
Duration: cfg.HistogramWindowInterval,
MaxVal: log10int64times1000,
SigFigs: 3,
Buckets: metric.MemoryUsage64MBBuckets,
}),
SQLStatsMemoryCurBytesCount: metric.NewGauge(MetaSQLStatsMemCurBytes),
ReportedSQLStatsMemoryMaxBytesHist: metric.NewHistogram(metric.HistogramOptions{
Metadata: MetaReportedSQLStatsMemMaxBytes,
Duration: cfg.HistogramWindowInterval,
MaxVal: log10int64times1000,
SigFigs: 3,
Buckets: metric.MemoryUsage64MBBuckets,
}),
ReportedSQLStatsMemoryCurBytesCount: metric.NewGauge(MetaReportedSQLStatsMemCurBytes),
DiscardedStatsCount: metric.NewCounter(MetaDiscardedSQLStats),
SQLStatsFlushStarted: metric.NewCounter(MetaSQLStatsFlushStarted),
SQLStatsFlushFailure: metric.NewCounter(MetaSQLStatsFlushFailure),
SQLStatsFlushDuration: metric.NewHistogram(metric.HistogramOptions{
Mode: metric.HistogramModePreferHdrLatency,
Metadata: MetaSQLStatsFlushDuration,
Duration: 6 * metricsSampleInterval,
Buckets: metric.IOLatencyBuckets,
}),
SQLStatsRemovedRows: metric.NewCounter(MetaSQLStatsRemovedRows),
SQLTxnStatsCollectionOverhead: metric.NewHistogram(metric.HistogramOptions{
Mode: metric.HistogramModePreferHdrLatency,
Metadata: MetaSQLTxnStatsCollectionOverhead,
Duration: 6 * metricsSampleInterval,
Buckets: metric.IOLatencyBuckets,
}),
},
ContentionSubsystemMetrics: txnidcache.NewMetrics(),
InsightsMetrics: insights.NewMetrics(),
}
}
// Start starts the Server's background processing.
func (s *Server) Start(ctx context.Context, stopper *stop.Stopper) {
// Exclude SQL background processing from cost accounting and limiting.
// NOTE: Only exclude background processing that is not under user control.
// If a user can opt in/out of some aspect of background processing, then it
// should be accounted for in their costs.
ctx = multitenant.WithTenantCostControlExemption(ctx)
s.sqlStats.Start(ctx, stopper)
s.schemaTelemetryController.Start(ctx, stopper)
// reportedStats is periodically cleared to prevent too many SQL Stats
// accumulated in the reporter when the telemetry server fails.
// Usually it is telemetry's reporter's job to clear the reporting SQL Stats.
s.reportedStats.Start(ctx, stopper)
s.insights.Start(ctx, stopper)
s.txnIDCache.Start(ctx, stopper)
}
// GetSQLStatsController returns the persistedsqlstats.Controller for current
// sql.Server's SQL Stats.
func (s *Server) GetSQLStatsController() *persistedsqlstats.Controller {
return s.sqlStatsController
}
// GetSchemaTelemetryController returns the schematelemetryschedule.Controller
// for current sql.Server's schema telemetry.
func (s *Server) GetSchemaTelemetryController() *schematelemetrycontroller.Controller {
return s.schemaTelemetryController
}
// GetIndexUsageStatsController returns the idxusage.Controller for current
// sql.Server's index usage stats.
func (s *Server) GetIndexUsageStatsController() *idxusage.Controller {
return s.indexUsageStatsController
}
// GetInsightsReader returns the insights.Reader for the current sql.Server's
// detected execution insights.
func (s *Server) GetInsightsReader() insights.Reader {
return s.insights.Reader()
}
// GetSQLStatsProvider returns the provider for the sqlstats subsystem.
func (s *Server) GetSQLStatsProvider() sqlstats.Provider {
return s.sqlStats
}
// GetReportedSQLStatsController returns the sqlstats.Controller for the current
// sql.Server's reported SQL Stats.
func (s *Server) GetReportedSQLStatsController() *sslocal.Controller {
return s.reportedStatsController
}
// GetTxnIDCache returns the txnidcache.Cache for the current sql.Server.
func (s *Server) GetTxnIDCache() *txnidcache.Cache {
return s.txnIDCache
}
// GetScrubbedStmtStats returns the statement statistics by app, with the
// queries scrubbed of their identifiers. Any statements which cannot be
// scrubbed will be omitted from the returned map.
func (s *Server) GetScrubbedStmtStats(
ctx context.Context,
) ([]roachpb.CollectedStatementStatistics, error) {
return s.getScrubbedStmtStats(ctx, s.sqlStats.GetLocalMemProvider())
}
// Avoid lint errors.
var _ = (*Server).GetScrubbedStmtStats
// GetUnscrubbedStmtStats returns the same thing as GetScrubbedStmtStats, except
// identifiers (e.g. table and column names) aren't scrubbed from the statements.
func (s *Server) GetUnscrubbedStmtStats(
ctx context.Context,
) ([]roachpb.CollectedStatementStatistics, error) {
var stmtStats []roachpb.CollectedStatementStatistics
stmtStatsVisitor := func(_ context.Context, stat *roachpb.CollectedStatementStatistics) error {
stmtStats = append(stmtStats, *stat)
return nil
}
err :=
s.sqlStats.GetLocalMemProvider().IterateStatementStats(ctx, &sqlstats.IteratorOptions{}, stmtStatsVisitor)
if err != nil {
return nil, errors.Wrap(err, "failed to fetch statement stats")
}
return stmtStats, nil
}
// GetUnscrubbedTxnStats returns the same transaction statistics by app.
// Identifiers (e.g. table and column names) aren't scrubbed from the statements.
func (s *Server) GetUnscrubbedTxnStats(
ctx context.Context,
) ([]roachpb.CollectedTransactionStatistics, error) {
var txnStats []roachpb.CollectedTransactionStatistics
txnStatsVisitor := func(_ context.Context, stat *roachpb.CollectedTransactionStatistics) error {
txnStats = append(txnStats, *stat)
return nil
}
err :=
s.sqlStats.GetLocalMemProvider().IterateTransactionStats(ctx, &sqlstats.IteratorOptions{}, txnStatsVisitor)
if err != nil {
return nil, errors.Wrap(err, "failed to fetch statement stats")
}
return txnStats, nil
}
// GetScrubbedReportingStats does the same thing as GetScrubbedStmtStats but
// returns statistics from the reported stats pool.
func (s *Server) GetScrubbedReportingStats(
ctx context.Context,
) ([]roachpb.CollectedStatementStatistics, error) {
return s.getScrubbedStmtStats(ctx, s.reportedStats)
}
func (s *Server) getScrubbedStmtStats(
ctx context.Context, statsProvider sqlstats.Provider,
) ([]roachpb.CollectedStatementStatistics, error) {
salt := ClusterSecret.Get(&s.cfg.Settings.SV)
var scrubbedStats []roachpb.CollectedStatementStatistics
stmtStatsVisitor := func(_ context.Context, stat *roachpb.CollectedStatementStatistics) error {
// Scrub the statement itself.
scrubbedQueryStr, ok := scrubStmtStatKey(s.cfg.VirtualSchemas, stat.Key.Query)
// We don't want to report this stats if scrubbing has failed. We also don't
// wish to abort here because we want to try our best to report all the
// stats.
if !ok {
return nil
}
stat.Key.Query = scrubbedQueryStr
// Possibly scrub the app name.
if !strings.HasPrefix(stat.Key.App, catconstants.ReportableAppNamePrefix) {
stat.Key.App = HashForReporting(salt, stat.Key.App)
}
// Quantize the counts to avoid leaking information that way.
quantizeCounts(&stat.Stats)
stat.Stats.SensitiveInfo = stat.Stats.SensitiveInfo.GetScrubbedCopy()
scrubbedStats = append(scrubbedStats, *stat)
return nil
}
err :=
statsProvider.IterateStatementStats(ctx, &sqlstats.IteratorOptions{}, stmtStatsVisitor)
if err != nil {
return nil, errors.Wrap(err, "failed to fetch scrubbed statement stats")
}
return scrubbedStats, nil
}
// GetStmtStatsLastReset returns the time at which the statement statistics were
// last cleared.
func (s *Server) GetStmtStatsLastReset() time.Time {
return s.sqlStats.GetLastReset()
}
// GetExecutorConfig returns this server's executor config.
func (s *Server) GetExecutorConfig() *ExecutorConfig {
return s.cfg
}
// GetBytesMonitor returns this server's BytesMonitor.
func (s *Server) GetBytesMonitor() *mon.BytesMonitor {
return s.pool
}
// SetupConn creates a connExecutor for the client connection.
//
// When this method returns there are no resources allocated yet that
// need to be close()d.
//
// Args:
// args: The initial session parameters. They are validated by SetupConn
// and an error is returned if this validation fails.
// stmtBuf: The incoming statement for the new connExecutor.
// clientComm: The interface through which the new connExecutor is going to
// produce results for the client.
// memMetrics: The metrics that statements executed on this connection will
// contribute to.
func (s *Server) SetupConn(
ctx context.Context,
args SessionArgs,
stmtBuf *StmtBuf,
clientComm ClientComm,
memMetrics MemoryMetrics,
onDefaultIntSizeChange func(newSize int32),
) (ConnectionHandler, error) {
sd := s.newSessionData(args)
sds := sessiondata.NewStack(sd)
// Set the SessionData from args.SessionDefaults. This also validates the
// respective values.
sdMutIterator := s.makeSessionDataMutatorIterator(sds, args.SessionDefaults)
sdMutIterator.onDefaultIntSizeChange = onDefaultIntSizeChange
if err := sdMutIterator.applyOnEachMutatorError(func(m sessionDataMutator) error {
for varName, v := range varGen {
if v.Set != nil {
hasDefault, defVal := getSessionVarDefaultString(varName, v, m.sessionDataMutatorBase)
if hasDefault {
if err := v.Set(ctx, m, defVal); err != nil {
return err
}
}
}
}
return nil
}); err != nil {
log.Errorf(ctx, "error setting up client session: %s", err)
return ConnectionHandler{}, err
}
ex := s.newConnExecutor(
ctx, sdMutIterator, stmtBuf, clientComm, memMetrics, &s.Metrics,
s.sqlStats.GetApplicationStats(sd.ApplicationName, false /* internal */),
nil, /* postSetupFn */
)
return ConnectionHandler{ex}, nil
}
// IncrementConnectionCount increases connectionCount by 1.
func (s *Server) IncrementConnectionCount() {
s.mu.Lock()
defer s.mu.Unlock()
s.mu.connectionCount++
}
// IncrementRootConnectionCount increases both connectionCount and rootConnectionCount by 1.
func (s *Server) IncrementRootConnectionCount() {
s.mu.Lock()
defer s.mu.Unlock()
s.mu.connectionCount++
s.mu.rootConnectionCount++
}
// DecrementConnectionCount decreases connectionCount by 1.
func (s *Server) DecrementConnectionCount() {
s.mu.Lock()
defer s.mu.Unlock()
s.mu.connectionCount--
}
// DecrementRootConnectionCount decreases both connectionCount and rootConnectionCount by 1.
func (s *Server) DecrementRootConnectionCount() {
s.mu.Lock()
defer s.mu.Unlock()
s.mu.connectionCount--
s.mu.rootConnectionCount--
}
// IncrementConnectionCountIfLessThan increases connectionCount by 1 and returns true if connectionCount < max,
// otherwise it does nothing and returns false.
func (s *Server) IncrementConnectionCountIfLessThan(max int64) bool {
s.mu.Lock()
defer s.mu.Unlock()
lt := s.mu.connectionCount < max
if lt {
s.mu.connectionCount++
}
return lt
}
// GetConnectionCount returns the current number of connections.
func (s *Server) GetConnectionCount() int64 {
s.mu.Lock()
defer s.mu.Unlock()
return s.mu.connectionCount
}
// GetNonRootConnectionCount returns the current number of non root connections.
func (s *Server) GetNonRootConnectionCount() int64 {
s.mu.Lock()
defer s.mu.Unlock()
return s.mu.connectionCount - s.mu.rootConnectionCount
}
// ConnectionHandler is the interface between the result of SetupConn
// and the ServeConn below. It encapsulates the connExecutor and hides
// it away from other packages.
type ConnectionHandler struct {
ex *connExecutor
}
// GetParamStatus retrieves the configured value of the session
// variable identified by varName. This is used for the initial
// message sent to a client during a session set-up.
func (h ConnectionHandler) GetParamStatus(ctx context.Context, varName string) string {
name := strings.ToLower(varName)
v, ok := varGen[name]
if !ok {
log.Fatalf(ctx, "programming error: status param %q must be defined session var", varName)
return ""
}
hasDefault, defVal := getSessionVarDefaultString(name, v, h.ex.dataMutatorIterator.sessionDataMutatorBase)
if !hasDefault {
log.Fatalf(ctx, "programming error: status param %q must have a default value", varName)
return ""
}
return defVal
}
// GetQueryCancelKey returns the per-session identifier that can be used to
// cancel a query using the pgwire cancel protocol.
func (h ConnectionHandler) GetQueryCancelKey() pgwirecancel.BackendKeyData {
return h.ex.queryCancelKey
}
// ServeConn serves a client connection by reading commands from the stmtBuf
// embedded in the ConnHandler.
//
// If not nil, reserved represents memory reserved for the connection. The
// connExecutor takes ownership of this memory and will close the account before
// exiting.
func (s *Server) ServeConn(
ctx context.Context, h ConnectionHandler, reserved *mon.BoundAccount, cancel context.CancelFunc,
) error {
// Make sure to close the reserved account even if closeWrapper below
// panics: so we do it in a defer that is guaranteed to execute. We also
// cannot close it before closeWrapper since we need to close the internal
// monitors of the connExecutor first.
defer reserved.Close(ctx)
defer func(ctx context.Context, h ConnectionHandler) {
r := recover()
h.ex.closeWrapper(ctx, r)
}(ctx, h)
return h.ex.run(ctx, s.pool, reserved, cancel)
}
// GetLocalIndexStatistics returns a idxusage.LocalIndexUsageStats.
func (s *Server) GetLocalIndexStatistics() *idxusage.LocalIndexUsageStats {
return s.indexUsageStats
}
// newSessionData a SessionData that can be passed to newConnExecutor.
func (s *Server) newSessionData(args SessionArgs) *sessiondata.SessionData {
sd := &sessiondata.SessionData{
SessionData: sessiondatapb.SessionData{
UserProto: args.User.EncodeProto(),
},
LocalUnmigratableSessionData: sessiondata.LocalUnmigratableSessionData{
RemoteAddr: args.RemoteAddr,
},
LocalOnlySessionData: sessiondatapb.LocalOnlySessionData{
ResultsBufferSize: args.ConnResultsBufferSize,
IsSuperuser: args.IsSuperuser,
},
}
if len(args.CustomOptionSessionDefaults) > 0 {
sd.CustomOptions = make(map[string]string)
for k, v := range args.CustomOptionSessionDefaults {
sd.CustomOptions[k] = v
}
}
s.populateMinimalSessionData(sd)
return sd
}
func (s *Server) makeSessionDataMutatorIterator(
sds *sessiondata.Stack, defaults SessionDefaults,
) *sessionDataMutatorIterator {
return &sessionDataMutatorIterator{
sds: sds,
sessionDataMutatorBase: sessionDataMutatorBase{
defaults: defaults,
settings: s.cfg.Settings,
},
sessionDataMutatorCallbacks: sessionDataMutatorCallbacks{},
}
}
// populateMinimalSessionData populates sd with some minimal values needed for
// not crashing. Fields of sd that are already set are not overwritten.
func (s *Server) populateMinimalSessionData(sd *sessiondata.SessionData) {
if sd.SequenceState == nil {
sd.SequenceState = sessiondata.NewSequenceState()
}
if sd.Location == nil {
sd.Location = time.UTC
}
if len(sd.SearchPath.GetPathArray()) == 0 {
sd.SearchPath = sessiondata.DefaultSearchPathForUser(sd.User())
}
}
// newConnExecutor creates a new connExecutor.
//
// sd is expected to be fully initialized with the values of all the session
// vars.
// sdDefaults controls what the session vars will be reset to through
// RESET statements.
func (s *Server) newConnExecutor(
ctx context.Context,
sdMutIterator *sessionDataMutatorIterator,
stmtBuf *StmtBuf,
clientComm ClientComm,
memMetrics MemoryMetrics,
srvMetrics *Metrics,
applicationStats sqlstats.ApplicationStats,
// postSetupFn is to override certain field of a conn executor.
// It is set when conn executor is init under an internal executor
// with a not-nil txn.
postSetupFn func(ex *connExecutor),
) *connExecutor {
// Create the various monitors.
// The session monitors are started in activate().
sessionRootMon := mon.NewMonitor(
"session root",
mon.MemoryResource,
memMetrics.CurBytesCount,
memMetrics.MaxBytesHist,
-1 /* increment */, math.MaxInt64, s.cfg.Settings,
)
sessionMon := mon.NewMonitor(
"session",
mon.MemoryResource,
memMetrics.SessionCurBytesCount,
memMetrics.SessionMaxBytesHist,
-1 /* increment */, noteworthyMemoryUsageBytes, s.cfg.Settings,
)
sessionPreparedMon := mon.NewMonitor(
"session prepared statements",
mon.MemoryResource,
memMetrics.SessionPreparedCurBytesCount,
memMetrics.SessionPreparedMaxBytesHist,
1024 /* increment */, noteworthyMemoryUsageBytes, s.cfg.Settings,
)
// The txn monitor is started in txnState.resetForNewSQLTxn().
txnMon := mon.NewMonitor(
"txn",
mon.MemoryResource,
memMetrics.TxnCurBytesCount,
memMetrics.TxnMaxBytesHist,
-1 /* increment */, noteworthyMemoryUsageBytes, s.cfg.Settings,
)
nodeIDOrZero, _ := s.cfg.NodeInfo.NodeID.OptionalNodeID()
ex := &connExecutor{
server: s,
metrics: srvMetrics,
stmtBuf: stmtBuf,
clientComm: clientComm,
mon: sessionRootMon,
sessionMon: sessionMon,
sessionPreparedMon: sessionPreparedMon,
sessionDataStack: sdMutIterator.sds,