-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
conn_executor.go
2865 lines (2604 loc) · 105 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/clusterversion"
"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/settings"
"github.com/cockroachdb/cockroach/pkg/sql/catalog"
"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/parser"
"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/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/sqlerrors"
"github.com/cockroachdb/cockroach/pkg/sql/stmtdiagnostics"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"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 sqlStats
// 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
reCache *tree.RegexpCache
// pool is the parent monitor for all session monitors except "internal" ones.
pool *mon.BytesMonitor
// Metrics is used to account normal queries.
Metrics Metrics
// InternalMetrics is used to account internal queries.
InternalMetrics Metrics
}
// 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
}
// NewServer creates a new Server. Start() needs to be called before the Server
// is used.
func NewServer(cfg *ExecutorConfig, pool *mon.BytesMonitor) *Server {
return &Server{
cfg: cfg,
Metrics: makeMetrics(false /*internal*/),
InternalMetrics: makeMetrics(true /*internal*/),
pool: pool,
sqlStats: sqlStats{st: cfg.Settings, apps: make(map[string]*appStats)},
reportedStats: sqlStats{st: cfg.Settings, apps: make(map[string]*appStats)},
reCache: tree.NewRegexpCache(512),
}
}
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.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)),
},
StartedStatementCounters: makeStartedStatementCounters(internal),
ExecutedStatementCounters: makeExecutedStatementCounters(internal),
}
}
// Start starts the Server's background processing.
func (s *Server) Start(ctx context.Context, stopper *stop.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.PeriodicallyClearSQLStats(ctx, stopper, MaxSQLStatReset, &s.sqlStats, s.ResetSQLStats)
s.PeriodicallyClearSQLStats(ctx, stopper, MaxSQLStatReset, &s.reportedStats, s.ResetReportedStats)
// Start a second loop to clear SQL stats at the requested interval.
s.PeriodicallyClearSQLStats(ctx, stopper, SQLStatReset, &s.sqlStats, s.ResetSQLStats)
}
// ResetSQLStats resets the executor's collected sql statistics.
func (s *Server) ResetSQLStats(ctx context.Context) {
// Dump the SQL stats into the reported stats before clearing the SQL stats.
s.sqlStats.resetAndMaybeDumpStats(ctx, &s.reportedStats)
}
// ResetReportedStats resets the executor's collected reported stats.
func (s *Server) ResetReportedStats(ctx context.Context) {
s.reportedStats.resetAndMaybeDumpStats(ctx, nil /* target */)
}
// 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() []roachpb.CollectedStatementStatistics {
return s.sqlStats.getScrubbedStmtStats(s.cfg.VirtualSchemas)
}
// 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() []roachpb.CollectedStatementStatistics {
return s.sqlStats.getUnscrubbedStmtStats(s.cfg.VirtualSchemas)
}
// 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() []roachpb.CollectedTransactionStatistics {
return s.sqlStats.getUnscrubbedTxnStats()
}
// GetScrubbedReportingStats does the same thing as GetScrubbedStmtStats but
// returns statistics from the reported stats pool.
func (s *Server) GetScrubbedReportingStats() []roachpb.CollectedStatementStatistics {
return s.reportedStats.getScrubbedStmtStats(s.cfg.VirtualSchemas)
}
// 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,
) (ConnectionHandler, error) {
sd := s.newSessionData(args)
// Set the SessionData from args.SessionDefaults. This also validates the
// respective values.
sdMut := s.makeSessionDataMutator(sd, args.SessionDefaults)
if err := resetSessionVars(ctx, &sdMut); err != nil {
log.Errorf(ctx, "error setting up client session: %s", err)
return ConnectionHandler{}, err
}
ex := s.newConnExecutor(
ctx, sd, args.SessionDefaults, stmtBuf, clientComm, memMetrics, &s.Metrics,
s.sqlStats.getStatsForApplication(sd.ApplicationName),
)
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
}
// GetUnqualifiedIntSize implements pgwire.sessionDataProvider and returns
// the type that INT should be parsed as.
func (h ConnectionHandler) GetUnqualifiedIntSize() *types.T {
var size int32
if h.ex != nil {
// The executor will be nil in certain testing situations where
// no server is actually present.
size = h.ex.sessionData.DefaultIntSize
}
return parser.NakedIntTypeFromDefaultIntSize(size)
}
// 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.dataMutator)
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)
}
// 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(),
},
LocalOnlySessionData: sessiondata.LocalOnlySessionData{
RemoteAddr: args.RemoteAddr,
ResultsBufferSize: args.ConnResultsBufferSize,
},
}
s.populateMinimalSessionData(sd)
return sd
}
func (s *Server) makeSessionDataMutator(
sd *sessiondata.SessionData, defaults SessionDefaults,
) sessionDataMutator {
return sessionDataMutator{
data: sd,
defaults: defaults,
settings: s.cfg.Settings,
paramStatusUpdater: &noopParamStatusUpdater{},
}
}
// 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,
sd *sessiondata.SessionData,
sdDefaults SessionDefaults,
stmtBuf *StmtBuf,
clientComm ClientComm,
memMetrics MemoryMetrics,
srvMetrics *Metrics,
appStats *appStats,
) *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()
sdMutator := new(sessionDataMutator)
*sdMutator = s.makeSessionDataMutator(sd, sdDefaults)
ex := &connExecutor{
server: s,
metrics: srvMetrics,
stmtBuf: stmtBuf,
clientComm: clientComm,
mon: sessionRootMon,
sessionMon: sessionMon,
sessionData: sd,
dataMutator: sdMutator,
state: txnState{
mon: txnMon,
connCtx: ctx,
},
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},
rng: rand.New(rand.NewSource(timeutil.Now().UnixNano())),
executorType: executorTypeExec,
hasCreatedTemporarySchema: false,
stmtDiagnosticsRecorder: s.cfg.StmtDiagnosticsRecorder,
}
ex.state.txnAbortCount = ex.metrics.EngineMetrics.TxnAbortCount
// The transaction_read_only variable is special; its updates need to be
// hooked-up to the executor.
sdMutator.setCurTxnReadOnly = func(val bool) {
ex.state.readOnly = val
}
sdMutator.onTempSchemaCreation = func() {
ex.hasCreatedTemporarySchema = true
}
ex.applicationName.Store(ex.sessionData.ApplicationName)
ex.appStats = appStats
sdMutator.RegisterOnSessionDataChange("application_name", func(newName string) {
ex.applicationName.Store(newName)
ex.appStats = ex.server.sqlStats.getStatsForApplication(newName)
})
ex.phaseTimes[sessionInit] = timeutil.Now()
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.descCollection = descs.MakeCollection(
s.cfg.LeaseManager, s.cfg.Settings, sd, s.cfg.HydratedTables)
ex.extraTxnState.txnRewindPos = -1
ex.extraTxnState.schemaChangeJobsCache = make(map[descpb.ID]*jobs.Job)
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.statsCollector = ex.newStatsCollector()
ex.extraTxnState.hasAdminRoleCache = HasAdminRoleCache{}
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,
sd *sessiondata.SessionData,
sdDefaults SessionDefaults,
stmtBuf *StmtBuf,
clientComm ClientComm,
parentMon *mon.BytesMonitor,
memMetrics MemoryMetrics,
srvMetrics *Metrics,
txn *kv.Txn,
syntheticDescs []catalog.Descriptor,
appStats *appStats,
) *connExecutor {
ex := s.newConnExecutor(ctx, sd, sdDefaults, stmtBuf, clientComm, memMetrics, srvMetrics, appStats)
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.dataMutator.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
}
// SQLStatReset is the cluster setting that controls at what interval SQL
// statement statistics should be reset.
var SQLStatReset = settings.RegisterDurationSetting(
"diagnostics.sql_stat_reset.interval",
"interval controlling how often SQL statement statistics should "+
"be reset (should be less than diagnostics.forced_sql_stat_reset.interval). It has a max value of 24H.",
time.Hour,
settings.NonNegativeDurationWithMaximum(time.Hour*24),
).WithPublic()
// MaxSQLStatReset is the cluster setting that controls at what interval SQL
// statement statistics must be flushed within.
var MaxSQLStatReset = settings.RegisterDurationSetting(
"diagnostics.forced_sql_stat_reset.interval",
"interval after which SQL statement statistics are refreshed even "+
"if not collected (should be more than diagnostics.sql_stat_reset.interval). It has a max value of 24H.",
time.Hour*2, // 2 x diagnostics.sql_stat_reset.interval
settings.NonNegativeDurationWithMaximum(time.Hour*24),
).WithPublic()
// PeriodicallyClearSQLStats spawns a loop to reset stats based on the setting
// of a given duration settings variable. We take in a function to actually do
// the resetting, as some stats have extra work that needs to be performed
// during the reset. For example, the SQL stats need to dump into the parent
// stats before clearing data fully.
func (s *Server) PeriodicallyClearSQLStats(
ctx context.Context,
stopper *stop.Stopper,
setting *settings.DurationSetting,
stats *sqlStats,
reset func(ctx context.Context),
) {
_ = stopper.RunAsyncTask(ctx, "sql-stats-clearer", func(ctx context.Context) {
var timer timeutil.Timer
for {
s.sqlStats.Lock()
last := stats.lastReset
s.sqlStats.Unlock()
next := last.Add(setting.Get(&s.cfg.Settings.SV))
wait := next.Sub(timeutil.Now())
if wait < 0 {
reset(ctx)
} else {
timer.Reset(wait)
select {
case <-stopper.ShouldQuiesce():
return
case <-timer.C:
timer.Read = true
}
}
}
})
}
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.sp != 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 {
ie := MakeInternalExecutor(ctx, ex.server, MemoryMetrics{}, ex.server.cfg.Settings)
err := cleanupSessionTempObjects(
ctx,
ex.server.cfg.Settings,
ex.server.cfg.LeaseManager,
ex.server.cfg.DB,
ex.server.cfg.Codec,
&ie,
ex.sessionID,
)
if err != nil {
log.Errorf(
ctx,
"error deleting temporary objects at session close, "+
"the temp tables deletion job will retry periodically: %s",
err,
)
}
}
if closeType != panicClose {
// Close all statements and prepared portals.
ex.extraTxnState.prepStmtsNamespace.resetTo(
ctx, prepStmtNamespace{}, &ex.extraTxnState.prepStmtsNamespaceMemAcc,
)
ex.extraTxnState.prepStmtsNamespaceAtTxnRewindPos.resetTo(
ctx, prepStmtNamespace{}, &ex.extraTxnState.prepStmtsNamespaceMemAcc,
)
ex.extraTxnState.prepStmtsNamespaceMemAcc.Close(ctx)
}
if ex.sessionTracing.Enabled() {
if err := ex.sessionTracing.StopTracing(); err != nil {
log.Warningf(ctx, "error stopping tracing: %s", err)
}
}
if ex.eventLog != nil {
ex.eventLog.Finish()
ex.eventLog = nil
}
// Stop idle timer if the connExecutor is closed to ensure cancel session
// is not called.
ex.mu.IdleInSessionTimeout.Stop()
ex.mu.IdleInTransactionSessionTimeout.Stop()
if closeType != panicClose {
ex.state.mon.Stop(ctx)
ex.sessionMon.Stop(ctx)
ex.mon.Stop(ctx)
} else {
ex.state.mon.EmergencyStop(ctx)
ex.sessionMon.EmergencyStop(ctx)
ex.mon.EmergencyStop(ctx)
}
}
// HasAdminRoleCache is stored in extraTxnState and used to cache if the
// user has admin role throughout a transaction.
// This is used for admin audit logging to check if a transaction is being
// executed with admin privileges.
// HasAdminRoleCache does not have to be reset when a transaction restarts
// or roles back as the user's admin status will not change throughout the
// lifecycle of a single transaction.
type HasAdminRoleCache struct {
HasAdminRole bool
// IsSet is used to determine if the value for caching is set or not.
IsSet bool
}
type connExecutor struct {
_ util.NoCopy
// The server to which this connExecutor is attached. The reference is used
// for getting access to configuration settings.
// Note: do not use server.Metrics directly. Use metrics below instead.
server *Server
// The metrics to which the statement metrics should be accounted.
// This is different whether the executor is for regular client
// queries or for "internal" queries.
metrics *Metrics
// mon tracks memory usage for SQL activity within this session. It
// is not directly used, but rather indirectly used via sessionMon
// and state.mon. sessionMon tracks session-bound objects like prepared
// statements and result sets.
//
// The reason why state.mon and mon are split is to enable
// separate reporting of statistics per transaction and per
// session. This is because the "interesting" behavior w.r.t memory
// is typically caused by transactions, not sessions. The reason why
// sessionMon and mon are split is to enable separate reporting of
// statistics for result sets (which escape transactions).
mon *mon.BytesMonitor
sessionMon *mon.BytesMonitor
// memMetrics contains the metrics that statements executed on this connection
// will contribute to.
memMetrics MemoryMetrics
// The buffer with incoming statements to execute.
stmtBuf *StmtBuf
// The interface for communicating statement results to the client.
clientComm ClientComm
// Finity "the machine" Automaton is the state machine controlling the state
// below.
machine fsm.Machine
// state encapsulates fields related to the ongoing SQL txn. It is mutated as
// the machine's ExtendedState.
state txnState
transitionCtx transitionCtx
sessionTracing SessionTracing
// eventLog for SQL statements and other important session events. Will be set
// if traceSessionEventLogEnabled; it is used by ex.sessionEventf()
eventLog trace.EventLog
// extraTxnState groups fields scoped to a SQL txn that are not handled by
// ex.state, above. The rule of thumb is that, if the state influences state
// transitions, it should live in state, otherwise it can live here.
// This is only used in the Open state. extraTxnState is reset whenever a
// transaction finishes or gets retried.
extraTxnState struct {
// descCollection collects descriptors used by the current transaction.
descCollection descs.Collection
// jobs accumulates jobs staged for execution inside the transaction.
// Staging happens when executing statements that are implemented with a
// job. The jobs are staged via the function QueueJob in
// pkg/sql/planner.go. The staged jobs are executed once the transaction
// that staged them commits.
jobs jobsCollection
// schemaChangeJobsCache is a map of descriptor IDs to Jobs.
// Used in createOrUpdateSchemaChangeJob so we can check if a job has been
// queued up for the given ID.
schemaChangeJobsCache map[descpb.ID]*jobs.Job
// autoRetryCounter keeps track of the which iteration of a transaction
// auto-retry we're currently in. It's 0 whenever the transaction state is not
// stateOpen.
autoRetryCounter int
// numDDL keeps track of how many DDL statements have been
// executed so far.
numDDL int
// numRows keeps track of the number of rows that have been observed by this
// transaction. This is simply the summation of number of rows observed by