-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
conn_executor.go
2573 lines (2343 loc) · 92.3 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"
"strings"
"sync/atomic"
"time"
"unicode/utf8"
"github.com/cockroachdb/cockroach/pkg/config"
"github.com/cockroachdb/cockroach/pkg/internal/client"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"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/parser"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
"github.com/cockroachdb/cockroach/pkg/sql/sqlutil"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util"
"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/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/cockroach/pkg/util/uuid"
"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.
sqlStats sqlStats
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
// dbCache is a cache for database descriptors, maintained through Gossip
// updates.
dbCache *databaseCacheHolder
}
// 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 {
systemCfg := config.NewSystemConfig(cfg.DefaultZoneConfig)
return &Server{
cfg: cfg,
Metrics: makeMetrics(false /*internal*/),
InternalMetrics: makeMetrics(true /*internal*/),
// dbCache will be updated on Start().
dbCache: newDatabaseCacheHolder(newDatabaseCache(systemCfg)),
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),
TxnAbortCount: metric.NewCounter(getMetricMeta(MetaTxnAbort, internal)),
FailureCount: metric.NewCounter(getMetricMeta(MetaFailure, internal)),
},
StartedStatementCounters: makeStartedStatementCounters(internal),
ExecutedStatementCounters: makeExecutedStatementCounters(internal),
}
}
// Start starts the Server's background processing.
func (s *Server) Start(ctx context.Context, stopper *stop.Stopper) {
gossipUpdateC := s.cfg.Gossip.RegisterSystemConfigChannel()
stopper.RunWorker(ctx, func(ctx context.Context) {
for {
select {
case <-gossipUpdateC:
sysCfg := s.cfg.Gossip.GetSystemConfig()
s.dbCache.updateSystemConfig(sysCfg)
case <-stopper.ShouldStop():
return
}
}
})
// 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.PeriodicallyClearSQLStats(ctx, stopper, maxSQLStatReset, &s.reportedStats)
// Start a second loop to clear SQL stats at the requested interval.
s.PeriodicallyClearSQLStats(ctx, stopper, sqlStatReset, &s.sqlStats)
s.PeriodicallyPollForStatementInfoRequests(ctx, stopper)
}
// 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.reportedStats.Add(&s.sqlStats)
s.sqlStats.resetStats(ctx)
}
// ResetReportedStats resets the executor's collected reported stats.
func (s *Server) ResetReportedStats(ctx context.Context) {
s.reportedStats.resetStats(ctx)
}
// 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)
}
// 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)
}
// GetUnscrubbedReportingStats does the same thing as GetUnscrubbedStmtStats but
// returns statistics from the reported stats pool.
func (s *Server) GetUnscrubbedReportingStats() []roachpb.CollectedStatementStatistics {
return s.reportedStats.getUnscrubbedStmtStats(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)
sdMut := s.makeSessionDataMutator(sd, args.SessionDefaults)
ex, err := s.newConnExecutor(
ctx, sd, &sdMut, stmtBuf, clientComm, memMetrics, &s.Metrics, resetSessionDataToDefaults)
return ConnectionHandler{ex}, err
}
// 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 int
if h.ex != nil {
// The executor will be nil in certain testing situations where
// no server is actually present.
size = h.ex.sessionData.DefaultIntSize
}
switch size {
case 4, 32:
return types.Int4
default:
return types.Int
}
}
// 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{
User: args.User,
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.DataConversion == (sessiondata.DataConversionConfig{}) {
sd.DataConversion = sessiondata.DataConversionConfig{
Location: time.UTC,
}
}
if len(sd.SearchPath.GetPathArray()) == 0 {
sd.SearchPath = sqlbase.DefaultSearchPath
}
}
type sdResetOption bool
const (
resetSessionDataToDefaults sdResetOption = true
dontResetSessionDataToDefaults = false
)
// newConnExecutor creates a new connExecutor.
//
// resetOpt controls whether sd is to be reset to the default values.
// TODO(andrei): resetOpt is a hack needed by the InternalExecutor, which
// doesn't want this resetting. Figure out a better API where the responsibility
// of assigning default values is either entirely inside or outside of this
// ctor.
func (s *Server) newConnExecutor(
ctx context.Context,
sd *sessiondata.SessionData,
sdMutator *sessionDataMutator,
stmtBuf *StmtBuf,
clientComm ClientComm,
memMetrics MemoryMetrics,
srvMetrics *Metrics,
resetOpt sdResetOption,
) (*connExecutor, error) {
// Create the various monitors.
// The session monitors are started in activate().
sessionRootMon := mon.MakeMonitor(
"session root",
mon.MemoryResource,
memMetrics.CurBytesCount,
memMetrics.MaxBytesHist,
-1 /* increment */, math.MaxInt64, s.cfg.Settings,
)
sessionMon := mon.MakeMonitor(
"session",
mon.MemoryResource,
memMetrics.SessionCurBytesCount,
memMetrics.SessionMaxBytesHist,
-1 /* increment */, noteworthyMemoryUsageBytes, s.cfg.Settings,
)
// The txn monitor is started in txnState.resetForNewSQLTxn().
txnMon := mon.MakeMonitor(
"txn",
mon.MemoryResource,
memMetrics.TxnCurBytesCount,
memMetrics.TxnMaxBytesHist,
-1 /* increment */, noteworthyMemoryUsageBytes, s.cfg.Settings,
)
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,
nodeID: s.cfg.NodeID.Get(),
clock: s.cfg.Clock,
// Future transaction's monitors will inherits from sessionRootMon.
connMon: &sessionRootMon,
tracer: s.cfg.AmbientCtx.Tracer,
settings: s.cfg.Settings,
},
memMetrics: memMetrics,
planner: planner{execCfg: s.cfg},
// 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},
executorType: executorTypeExec,
hasCreatedTemporarySchema: false,
stmtInfoRegistry: s.cfg.stmtInfoRequestRegistry,
}
ex.state.txnAbortCount = ex.metrics.EngineMetrics.TxnAbortCount
sdMutator.setCurTxnReadOnly = func(val bool) {
ex.state.readOnly = val
}
sdMutator.onTempSchemaCreation = func() {
ex.hasCreatedTemporarySchema = true
}
sdMutator.RegisterOnSessionDataChange("application_name", func(newName string) {
ex.appStats = ex.server.sqlStats.getStatsForApplication(newName)
ex.applicationName.Store(newName)
})
// Initialize the session data from provided defaults. We need to do this early
// because other initializations below use the configured values.
if resetOpt == resetSessionDataToDefaults {
if err := resetSessionVars(ctx, sdMutator); err != nil {
log.Errorf(ctx, "error setting up client session: %v", err)
return nil, err
}
} else {
// We have set the ex.sessionData without using the dataMutator.
// So we need to update the application name manually.
ex.applicationName.Store(ex.sessionData.ApplicationName)
// When the connEx is serving an internal executor, it can inherit
// the application name from an outer session. This happens
// e.g. during ::regproc casts and built-in functions that use SQL internally.
// In that case, we do not want to record statistics against
// the outer application name directly; instead we want
// to use a separate bucket. However we will still
// want to have separate buckets for different applications so that
// we can measure their respective "pressure" on internal queries.
// Hence the choice here to add the delegate prefix
// to the current app name.
var appStatsBucketName string
if !strings.HasPrefix(ex.sessionData.ApplicationName, sqlbase.InternalAppNamePrefix) {
appStatsBucketName = sqlbase.DelegatedAppNamePrefix + ex.sessionData.ApplicationName
} else {
// If this is already an "internal app", don't put more prefix.
appStatsBucketName = ex.sessionData.ApplicationName
}
ex.appStats = s.sqlStats.getStatsForApplication(appStatsBucketName)
}
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.tables = TableCollection{
leaseMgr: s.cfg.LeaseManager,
databaseCache: s.dbCache.getDatabaseCache(),
dbCacheSubscriber: s.dbCache,
settings: s.cfg.Settings,
}
ex.extraTxnState.txnRewindPos = -1
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.initPlanner(ctx, &ex.planner)
return ex, nil
}
// 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,
sdMutator *sessionDataMutator,
stmtBuf *StmtBuf,
clientComm ClientComm,
parentMon *mon.BytesMonitor,
memMetrics MemoryMetrics,
srvMetrics *Metrics,
txn *client.Txn,
tcModifier tableCollectionModifier,
resetOpt sdResetOption,
) (*connExecutor, error) {
ex, err := s.newConnExecutor(
ctx, sd, sdMutator, stmtBuf, clientComm, memMetrics, srvMetrics, resetOpt)
if err != nil {
return nil, err
}
// 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 */
txn.UserPriority(),
tree.ReadWrite,
txn,
ex.transitionCtx)
// Modify the TableCollection to match the parent executor's TableCollection.
// This allows the InternalExecutor to see schema changes made by the
// parent executor.
if tcModifier != nil {
tcModifier.copyModifiedSchema(&ex.extraTxnState.tables)
}
return ex, nil
}
var sqlStatReset = settings.RegisterPublicNonNegativeDurationSettingWithMaximum(
"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,
time.Hour*24,
)
var maxSQLStatReset = settings.RegisterPublicNonNegativeDurationSettingWithMaximum(
"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
time.Hour*24,
)
// PeriodicallyClearSQLStats spawns a loop to reset stats based on the setting
// of a given duration settings variable.
func (s *Server) PeriodicallyClearSQLStats(
ctx context.Context, stopper *stop.Stopper, setting *settings.DurationSetting, stats *sqlStats,
) {
stopper.RunWorker(ctx, 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 {
stats.resetStats(ctx)
} else {
timer.Reset(wait)
select {
case <-stopper.ShouldQuiesce():
return
case <-timer.C:
timer.Read = true
}
}
}
})
}
// PeriodicallyPollForStatementInfoRequests runs a worker that periodically
// polls system.statement_diagnostics_requests.
func (s *Server) PeriodicallyPollForStatementInfoRequests(
ctx context.Context, stopper *stop.Stopper,
) {
pollingInterval := 10 * time.Second
stopper.RunWorker(ctx, func(ctx context.Context) {
ctx, _ = stopper.WithCancelOnQuiesce(ctx)
var timer timeutil.Timer
for {
if err := s.cfg.stmtInfoRequestRegistry.pollRequests(ctx); err != nil {
log.Warningf(ctx, "error polling for statement diagnostics requests: %s", err)
}
timer.Reset(pollingInterval)
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 {
// A warning header guaranteed to go to stderr. This is unanonymized.
var cutStmt string
var stmt string
if ex.curStmt != nil {
stmt = ex.curStmt.String()
cutStmt = stmt
}
if len(cutStmt) > panicLogOutputCutoffChars {
cutStmt = cutStmt[:panicLogOutputCutoffChars] + " [...]"
}
log.Shout(ctx, log.Severity_ERROR,
fmt.Sprintf("a SQL panic has occurred while executing %q: %s", cutStmt, recovered))
ex.close(ctx, panicClose)
safeErr := AnonymizeStatementsForReporting("executing", stmt, recovered)
log.ReportPanic(ctx, &ex.server.cfg.Settings.SV, safeErr, 1 /* depth */)
// Propagate the (sanitized) panic further.
// NOTE(andrei): It used to be that we sanitized the panic and then a higher
// layer was in charge of doing the log.ReportPanic() call. Now that the
// call is above, it's unclear whether we should propagate the original
// panic or safeErr. I'm propagating safeErr to be on the safe side.
panic(safeErr)
}
// 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")
if ex.hasCreatedTemporarySchema {
err := cleanupSessionTempObjects(ctx, ex.server, 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,
)
}
}
ev := noEvent
if _, noTxn := ex.machine.CurState().(stateNoTxn); !noTxn {
ev = 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)
}
} else if closeType == externalTxnClose {
ex.state.finishExternalTxn()
}
if err := ex.resetExtraTxnState(ctx, ex.server.dbCache, ev); err != nil {
log.Warningf(ctx, "error while cleaning up connExecutor: %s", err)
}
if closeType != panicClose {
// Close all statements and prepared portals.
ex.extraTxnState.prepStmtsNamespace.resetTo(ctx, prepStmtNamespace{})
ex.extraTxnState.prepStmtsNamespaceAtTxnRewindPos.resetTo(ctx, prepStmtNamespace{})
}
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
}
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)
}
}
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 {
// tables collects descriptors used by the current transaction.
tables TableCollection
// schemaChangers accumulate schema changes staged for execution. Staging
// happens when executing DDL statements. The staged changes are executed once
// the transaction that staged them commits (which is once the DDL statement
// is done if the statement was executed in an implicit txn).
schemaChangers schemaChangerCollection
// 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
// 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
// txnRewindPos is the position within stmtBuf to which we'll rewind when
// performing automatic retries. This is more or less the position where the
// current transaction started.
// This field is only defined while in stateOpen.
//
// Set via setTxnRewindPos().
txnRewindPos CmdPos
// prepStmtNamespace contains the prepared statements and portals that the
// session currently has access to.
// Portals are bound to a transaction and they're all destroyed once the
// transaction finishes.
// Prepared statements are not transactional and so it's a bit weird that
// they're part of extraTxnState, but it's convenient to put them here
// because they need the same kind of "snapshoting" as the portals (see
// prepStmtsNamespaceAtTxnRewindPos).
prepStmtsNamespace prepStmtNamespace