-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
conn_executor.go
3234 lines (2943 loc) · 120 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/roachpb"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/server/serverpb"
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/catconstants"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/colinfo"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descs"
"github.com/cockroachdb/cockroach/pkg/sql/execstats"
"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/rowenc"
"github.com/cockroachdb/cockroach/pkg/sql/schemachanger/scbuild"
"github.com/cockroachdb/cockroach/pkg/sql/schemachanger/scexec"
"github.com/cockroachdb/cockroach/pkg/sql/schemachanger/scpb"
"github.com/cockroachdb/cockroach/pkg/sql/schemachanger/scplan"
"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/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/cancelchecker"
"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/tracing"
"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
// 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
reCache *tree.RegexpCache
// 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
// Metrics is used to account normal queries.
Metrics Metrics
// InternalMetrics is used to account internal queries.
InternalMetrics Metrics
// TelemetryLoggingMetrics is used to track metrics for logging to the telemetry channel.
TelemetryLoggingMetrics *TelemetryLoggingMetrics
}
// 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
// StatsMetrics contains metrics for SQL statistics collection.
StatsMetrics StatsMetrics
// GuardrailMetrics contains metrics related to different guardrails in the
// SQL layer.
GuardrailMetrics GuardrailMetrics
}
// 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(cfg, false /* internal */)
reportedSQLStats := sslocal.New(
cfg.Settings,
sqlstats.MaxMemReportedSQLStatsStmtFingerprints,
sqlstats.MaxMemReportedSQLStatsTxnFingerprints,
metrics.StatsMetrics.ReportedSQLStatsMemoryCurBytesCount,
metrics.StatsMetrics.ReportedSQLStatsMemoryMaxBytesHist,
pool,
nil, /* resetInterval */
nil, /* reportedProvider */
)
reportedSQLStatsController :=
reportedSQLStats.GetController(cfg.SQLStatusServer, cfg.DB, cfg.InternalExecutor)
memSQLStats := sslocal.New(
cfg.Settings,
sqlstats.MaxMemSQLStatsStmtFingerprints,
sqlstats.MaxMemSQLStatsTxnFingerprints,
metrics.StatsMetrics.SQLStatsMemoryCurBytesCount,
metrics.StatsMetrics.SQLStatsMemoryMaxBytesHist,
pool,
sqlstats.SQLStatReset,
reportedSQLStats,
)
s := &Server{
cfg: cfg,
Metrics: metrics,
InternalMetrics: makeMetrics(cfg, true /* internal */),
pool: pool,
reportedStats: reportedSQLStats,
reportedStatsController: reportedSQLStatsController,
reCache: tree.NewRegexpCache(512),
indexUsageStats: idxusage.NewLocalIndexUsageStats(&idxusage.Config{
ChannelSize: idxusage.DefaultChannelSize,
Setting: cfg.Settings,
Knobs: cfg.IndexUsageStatsTestingKnobs,
}),
}
telemetryLoggingMetrics := &TelemetryLoggingMetrics{}
telemetryLoggingMetrics.Knobs = cfg.TelemetryLoggingTestingKnobs
s.TelemetryLoggingMetrics = telemetryLoggingMetrics
sqlStatsInternalExecutor := MakeInternalExecutor(context.Background(), s, MemoryMetrics{}, cfg.Settings)
persistedSQLStats := persistedsqlstats.New(&persistedsqlstats.Config{
Settings: s.cfg.Settings,
InternalExecutor: &sqlStatsInternalExecutor,
KvDB: cfg.DB,
SQLIDContainer: cfg.NodeID,
JobRegistry: s.cfg.JobRegistry,
Knobs: cfg.SQLStatsTestingKnobs,
FlushCounter: metrics.StatsMetrics.SQLStatsFlushStarted,
FailureCounter: metrics.StatsMetrics.SQLStatsFlushFailure,
FlushDuration: metrics.StatsMetrics.SQLStatsFlushDuration,
}, memSQLStats)
s.sqlStats = persistedSQLStats
s.sqlStatsController = persistedSQLStats.GetController(cfg.SQLStatusServer)
return s
}
func makeMetrics(cfg *ExecutorConfig, 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.NewLatency(getMetricMeta(MetaDistSQLExecLatency, internal),
6*metricsSampleInterval),
SQLExecLatency: metric.NewLatency(getMetricMeta(MetaSQLExecLatency, internal),
6*metricsSampleInterval),
DistSQLServiceLatency: metric.NewLatency(getMetricMeta(MetaDistSQLServiceLatency, internal),
6*metricsSampleInterval),
SQLServiceLatency: metric.NewLatency(getMetricMeta(MetaSQLServiceLatency, internal),
6*metricsSampleInterval),
SQLTxnLatency: metric.NewLatency(getMetricMeta(MetaSQLTxnLatency, internal),
6*metricsSampleInterval),
SQLTxnsOpen: metric.NewGauge(getMetricMeta(MetaSQLTxnsOpen, 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),
StatsMetrics: StatsMetrics{
SQLStatsMemoryMaxBytesHist: metric.NewHistogram(
getMetricMeta(MetaSQLStatsMemMaxBytes, internal),
cfg.HistogramWindowInterval,
log10int64times1000,
3, /* sigFigs */
),
SQLStatsMemoryCurBytesCount: metric.NewGauge(
getMetricMeta(MetaSQLStatsMemCurBytes, internal)),
ReportedSQLStatsMemoryMaxBytesHist: metric.NewHistogram(
getMetricMeta(MetaReportedSQLStatsMemMaxBytes, internal),
cfg.HistogramWindowInterval,
log10int64times1000,
3, /* sigFigs */
),
ReportedSQLStatsMemoryCurBytesCount: metric.NewGauge(
getMetricMeta(MetaReportedSQLStatsMemCurBytes, internal)),
DiscardedStatsCount: metric.NewCounter(getMetricMeta(MetaDiscardedSQLStats, internal)),
SQLStatsFlushStarted: metric.NewCounter(getMetricMeta(MetaSQLStatsFlushStarted, internal)),
SQLStatsFlushFailure: metric.NewCounter(getMetricMeta(MetaSQLStatsFlushFailure, internal)),
SQLStatsFlushDuration: metric.NewLatency(
getMetricMeta(MetaSQLStatsFlushDuration, internal), 6*metricsSampleInterval,
),
SQLStatsRemovedRows: metric.NewCounter(getMetricMeta(MetaSQLStatsRemovedRows, 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)),
},
}
}
// Start starts the Server's background processing.
func (s *Server) Start(ctx context.Context, stopper *stop.Stopper) {
s.indexUsageStats.Start(ctx, stopper)
// Start a loop to clear SQL stats at the max reset interval. This is
// to ensure that we always have some worker clearing SQL stats to avoid
// continually allocating space for the SQL stats. Additionally, spawn
// a loop to clear the reported stats at the same large interval just
// in case the telemetry worker fails.
s.sqlStats.Start(ctx, stopper)
s.reportedStats.Start(ctx, stopper)
}
// GetSQLStatsController returns the persistedsqlstats.Controller for current
// sql.Server's SQL Stats.
func (s *Server) GetSQLStatsController() *persistedsqlstats.Controller {
return s.sqlStatsController
}
// 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
}
// 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
}
// 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 {
return resetSessionVars(ctx, m)
}); 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), ExtraTxnState{},
)
return ConnectionHandler{ex}, nil
}
// 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
}
// 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.
func (s *Server) ServeConn(
ctx context.Context, h ConnectionHandler, reserved mon.BoundAccount, cancel context.CancelFunc,
) error {
defer func() {
r := recover()
h.ex.closeWrapper(ctx, r)
}()
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,
},
}
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,
extraTxnState ExtraTxnState,
) *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,
)
// 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.NodeID.OptionalNodeID()
ex := &connExecutor{
server: s,
metrics: srvMetrics,
stmtBuf: stmtBuf,
clientComm: clientComm,
mon: sessionRootMon,
sessionMon: sessionMon,
sessionDataStack: sdMutIterator.sds,
dataMutatorIterator: sdMutIterator,
state: txnState{
mon: txnMon,
connCtx: ctx,
testingForceRealTracingSpans: s.cfg.TestingKnobs.ForceRealTracingSpans,
},
transitionCtx: transitionCtx{
db: s.cfg.DB,
nodeIDOrZero: nodeIDOrZero,
clock: s.cfg.Clock,
// Future transaction's monitors will inherits from sessionRootMon.
connMon: sessionRootMon,
tracer: s.cfg.AmbientCtx.Tracer,
settings: s.cfg.Settings,
execTestingKnobs: s.GetExecutorConfig().TestingKnobs,
},
memMetrics: memMetrics,
planner: planner{execCfg: s.cfg, alloc: &rowenc.DatumAlloc{}},
// ctxHolder will be reset at the start of run(). We only define
// it here so that an early call to close() doesn't panic.
ctxHolder: ctxHolder{connCtx: ctx},
phaseTimes: sessionphase.NewTimes(),
rng: rand.New(rand.NewSource(timeutil.Now().UnixNano())),
executorType: executorTypeExec,
hasCreatedTemporarySchema: false,
stmtDiagnosticsRecorder: s.cfg.StmtDiagnosticsRecorder,
indexUsageStats: s.indexUsageStats,
}
ex.state.txnAbortCount = ex.metrics.EngineMetrics.TxnAbortCount
// The transaction_read_only variable is special; its updates need to be
// hooked-up to the executor.
ex.dataMutatorIterator.setCurTxnReadOnly = func(val bool) {
ex.state.readOnly = val
}
ex.dataMutatorIterator.onTempSchemaCreation = func() {
ex.hasCreatedTemporarySchema = true
}
ex.applicationName.Store(ex.sessionData().ApplicationName)
ex.applicationStats = applicationStats
ex.statsCollector = sslocal.NewStatsCollector(applicationStats, ex.phaseTimes)
ex.dataMutatorIterator.onApplicationNameChange = func(newName string) {
ex.applicationName.Store(newName)
ex.applicationStats = ex.server.sqlStats.GetApplicationStats(newName)
}
ex.phaseTimes.SetSessionPhaseTime(sessionphase.SessionInit, timeutil.Now())
ex.mu.ActiveQueries = make(map[ClusterWideID]*queryMeta)
ex.machine = fsm.MakeMachine(TxnStateTransitions, stateNoTxn{}, &ex.state)
ex.sessionTracing.ex = ex
ex.transitionCtx.sessionTracing = &ex.sessionTracing
ex.extraTxnState.prepStmtsNamespace = prepStmtNamespace{
prepStmts: make(map[string]*PreparedStatement),
portals: make(map[string]PreparedPortal),
}
ex.extraTxnState.prepStmtsNamespaceAtTxnRewindPos = prepStmtNamespace{
prepStmts: make(map[string]*PreparedStatement),
portals: make(map[string]PreparedPortal),
}
ex.extraTxnState.prepStmtsNamespaceMemAcc = ex.sessionMon.MakeBoundAccount()
ex.extraTxnState.txnRewindPos = -1
ex.extraTxnState.schemaChangeJobRecords = make(map[descpb.ID]*jobs.Record)
ex.extraTxnState.hasAdminRoleCache = HasAdminRoleCache{}
if extraTxnState.descs != nil {
ex.extraTxnState.descCollection = extraTxnState.descs
ex.extraTxnState.keepDescCollectionOnClose = true
} else {
descCol := s.cfg.CollectionFactory.MakeCollection(
descs.NewTemporarySchemaProvider(sdMutIterator.sds),
)
ex.extraTxnState.descCollection = &descCol
}
ex.initPlanner(ctx, &ex.planner)
return ex
}
// newConnExecutorWithTxn creates a connExecutor that will execute statements
// under a higher-level txn. This connExecutor runs with a different state
// machine, much reduced from the regular one. It cannot initiate or end
// transactions (so, no BEGIN, COMMIT, ROLLBACK, no auto-commit, no automatic
// retries).
//
// If there is no error, this function also activate()s the returned
// executor, so the caller does not need to run the
// activation. However this means that run() or close() must be called
// to release resources.
func (s *Server) newConnExecutorWithTxn(
ctx context.Context,
sdMutIterator *sessionDataMutatorIterator,
stmtBuf *StmtBuf,
clientComm ClientComm,
parentMon *mon.BytesMonitor,
memMetrics MemoryMetrics,
srvMetrics *Metrics,
txn *kv.Txn,
syntheticDescs []catalog.Descriptor,
applicationStats sqlstats.ApplicationStats,
extraTxnState ExtraTxnState,
) *connExecutor {
ex := s.newConnExecutor(
ctx,
sdMutIterator,
stmtBuf,
clientComm,
memMetrics,
srvMetrics,
applicationStats,
extraTxnState,
)
if txn.Type() == kv.LeafTxn {
// If the txn is a leaf txn it is not allowed to perform mutations. For
// sanity, set read only on the session.
ex.dataMutatorIterator.applyForEachMutator(func(m sessionDataMutator) {
m.SetReadOnly(true)
})
}
// The new transaction stuff below requires active monitors and traces, so
// we need to activate the executor now.
ex.activate(ctx, parentMon, mon.BoundAccount{})
// Perform some surgery on the executor - replace its state machine and
// initialize the state.
ex.machine = fsm.MakeMachine(
BoundTxnStateTransitions,
stateOpen{ImplicitTxn: fsm.False},
&ex.state,
)
ex.state.resetForNewSQLTxn(
ctx,
explicitTxn,
txn.ReadTimestamp().GoTime(),
nil, /* historicalTimestamp */
roachpb.UnspecifiedUserPriority,
tree.ReadWrite,
txn,
ex.transitionCtx)
// Modify the Collection to match the parent executor's Collection.
// This allows the InternalExecutor to see schema changes made by the
// parent executor.
ex.extraTxnState.descCollection.SetSyntheticDescriptors(syntheticDescs)
return ex
}
type closeType int
const (
normalClose closeType = iota
panicClose
// externalTxnClose means that the connExecutor has been used within a
// higher-level txn (through the InternalExecutor).
externalTxnClose
)
func (ex *connExecutor) closeWrapper(ctx context.Context, recovered interface{}) {
if recovered != nil {
panicErr := logcrash.PanicAsError(1, recovered)
// If there's a statement currently being executed, we'll report
// on it.
if ex.curStmtAST != nil {
// A warning header guaranteed to go to stderr.
log.SqlExec.Shoutf(ctx, severity.ERROR,
"a SQL panic has occurred while executing the following statement:\n%s",
// For the log message, the statement is not anonymized.
truncateStatementStringForTelemetry(ex.curStmtAST.String()))
// Embed the statement in the error object for the telemetry
// report below. The statement gets anonymized.
vt := ex.planner.extendedEvalCtx.VirtualSchemas
panicErr = WithAnonymizedStatement(panicErr, ex.curStmtAST, vt)
}
// Report the panic to telemetry in any case.
logcrash.ReportPanic(ctx, &ex.server.cfg.Settings.SV, panicErr, 1 /* depth */)
// Close the executor before propagating the panic further.
ex.close(ctx, panicClose)
// Propagate - this may be meant to stop the process.
panic(panicErr)
}
// Closing is not cancelable.
closeCtx := logtags.WithTags(context.Background(), logtags.FromContext(ctx))
ex.close(closeCtx, normalClose)
}
func (ex *connExecutor) close(ctx context.Context, closeType closeType) {
ex.sessionEventf(ctx, "finishing connExecutor")
txnEv := noEvent
if _, noTxn := ex.machine.CurState().(stateNoTxn); !noTxn {
txnEv = txnRollback
}
if closeType == normalClose {
// We'll cleanup the SQL txn by creating a non-retriable (commit:true) event.
// This event is guaranteed to be accepted in every state.
ev := eventNonRetriableErr{IsCommit: fsm.True}
payload := eventNonRetriableErrPayload{err: pgerror.Newf(pgcode.AdminShutdown,
"connExecutor closing")}
if err := ex.machine.ApplyWithPayload(ctx, ev, payload); err != nil {
log.Warningf(ctx, "error while cleaning up connExecutor: %s", err)
}
switch t := ex.machine.CurState().(type) {
case stateNoTxn:
// No txn to finish.
case stateAborted:
// A non-retriable error with IsCommit set to true causes the transaction
// to be cleaned up.
case stateCommitWait:
ex.state.finishSQLTxn()
default:
if util.CrdbTestBuild {
panic(errors.AssertionFailedf("unexpected state in conn executor after ApplyWithPayload %T", t))
}
}
if util.CrdbTestBuild && ex.state.Ctx != nil {
panic(errors.AssertionFailedf("txn span not closed in state %s", ex.machine.CurState()))
}
} else if closeType == externalTxnClose {
ex.state.finishExternalTxn()
}
if err := ex.resetExtraTxnState(ctx, txnEv); err != nil {
log.Warningf(ctx, "error while cleaning up connExecutor: %s", err)
}
if ex.hasCreatedTemporarySchema && !ex.server.cfg.TestingKnobs.DisableTempObjectsCleanupOnSessionExit {