-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathconn_executor.go
2928 lines (2668 loc) · 99.5 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.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
package sql
import (
"context"
"fmt"
"io"
"math"
"strconv"
"sync"
"time"
"unicode/utf8"
"unsafe"
"github.com/lib/pq/oid"
"github.com/pkg/errors"
"github.com/cockroachdb/cockroach/pkg/config"
"github.com/cockroachdb/cockroach/pkg/internal/client"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/security"
"github.com/cockroachdb/cockroach/pkg/server/serverpb"
"github.com/cockroachdb/cockroach/pkg/sql/coltypes"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgwirebase"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sem/types"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
"github.com/cockroachdb/cockroach/pkg/storage/engine/enginepb"
"github.com/cockroachdb/cockroach/pkg/util"
"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/uint128"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
)
// 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 - pgwire); the module doing client communication is
// responsible for pushing statements into the buffer and for providing an
// implementation of the clientConn interface (and thus consume results and send
// them 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) The connExecutor calls clientComm.flush(), informing the implementer that
// all the previous results can be delivered to the client at will.
//
// b) 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{}.
//
// 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 don'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.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.
// TODO(andrei): mention sessionEventf().
//
// 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 below connEx.execStmt() which dispatches based
// on the current state) 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
// connExecutor's to server every incoming connection.
type Server struct {
noCopy util.NoCopy
cfg *ExecutorConfig
// sqlStats tracks per-application statistics for all applications on each
// node.
sqlStats sqlStats
reCache *tree.RegexpCache
// pool is the parent monitor for all session monitors.
pool *mon.BytesMonitor
// EngineMetrics is exported as required by the metrics.Struct magic we use
// for metrics registration.
EngineMetrics SQLEngineMetrics
// StatementCounters contains metrics.
StatementCounters StatementCounters
// dbCache is a cache for database descriptors, maintained through Gossip
// updates.
dbCache *databaseCacheHolder
// Attempts to use unimplemented features.
unimplementedErrors struct {
syncutil.Mutex
counts map[string]int64
}
}
// 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,
EngineMetrics: SQLEngineMetrics{
DistSQLSelectCount: metric.NewCounter(MetaDistSQLSelect),
// TODO(mrtracy): See HistogramWindowInterval in server/config.go for the 6x factor.
DistSQLExecLatency: metric.NewLatency(MetaDistSQLExecLatency,
6*metricsSampleInterval),
SQLExecLatency: metric.NewLatency(MetaSQLExecLatency,
6*metricsSampleInterval),
DistSQLServiceLatency: metric.NewLatency(MetaDistSQLServiceLatency,
6*metricsSampleInterval),
SQLServiceLatency: metric.NewLatency(MetaSQLServiceLatency,
6*metricsSampleInterval),
},
StatementCounters: makeStatementCounters(),
// dbCache will be updated on Start().
dbCache: newDatabaseCacheHolder(newDatabaseCache(config.SystemConfig{})),
pool: pool,
sqlStats: sqlStats{st: cfg.Settings, apps: make(map[string]*appStats)},
reCache: tree.NewRegexpCache(512),
}
}
// Start starts the Server's background processing.
func (s *Server) Start(ctx context.Context, stopper *stop.Stopper) {
var wg sync.WaitGroup
wg.Add(1)
gossipUpdateC := s.cfg.Gossip.RegisterSystemConfigChannel()
stopper.RunWorker(ctx, func(ctx context.Context) {
first := true
for {
select {
case <-gossipUpdateC:
sysCfg, _ := s.cfg.Gossip.GetSystemConfig()
s.dbCache.updateSystemConfig(sysCfg)
if first {
first = false
wg.Done()
}
case <-stopper.ShouldStop():
return
}
}
})
// Wait for the databaseCache to be initialized. RegisterSystemConfigChannel()
// fires immediately.
wg.Wait()
}
func (s *Server) recordUnimplementedFeature(feature string) {
if feature == "" {
return
}
s.unimplementedErrors.Lock()
if s.unimplementedErrors.counts == nil {
s.unimplementedErrors.counts = make(map[string]int64)
}
s.unimplementedErrors.counts[feature]++
s.unimplementedErrors.Unlock()
}
// FillUnimplementedErrorCounts fills the passed map with the server's current
// counts of how often individual unimplemented features have been encountered.
func (s *Server) FillUnimplementedErrorCounts(fill map[string]int64) {
s.unimplementedErrors.Lock()
for k, v := range s.unimplementedErrors.counts {
fill[k] = v
}
s.unimplementedErrors.Unlock()
}
// ResetUnimplementedCounts resets counting of unimplemented errors.
func (s *Server) ResetUnimplementedCounts() {
s.unimplementedErrors.Lock()
s.unimplementedErrors.counts = make(map[string]int64, len(s.unimplementedErrors.counts))
s.unimplementedErrors.Unlock()
}
// ResetStatementStats resets the executor's collected statement statistics.
func (s *Server) ResetStatementStats(ctx context.Context) {
s.sqlStats.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)
}
// !!! comment and this method now serves
// NewConnExecutor creates a connExecutor tied to this Server.
//
// Args:
// stmtBuf: The incoming statement for the new connExecutor.
// clientComm: The interface through which the new connExecutor is going to
// produce results for the client.
// reserved: An amount on memory reserved for the connection. The connExecutor
// takes ownership of this memory.
// memMetrics: The metrics that statements executed on this connection will
// contribute to.
func (s *Server) ServeConn(
ctx context.Context,
args SessionArgs,
stmtBuf *StmtBuf,
clientComm ClientComm,
reserved mon.BoundAccount,
memMetrics *MemoryMetrics,
) error {
// Create the various monitors. They are Start()ed later.
//
// Note: we pass `reserved` to sessionRootMon where it causes it to act as a
// buffer. This is not done for sessionMon nor state.mon: these monitors don't
// start with any buffer, so they'll need to ask their "parent" for memory as
// soon as the first allocation. This is acceptable because the session is
// single threaded, and the point of buffering is just to avoid contention.
sessionRootMon := mon.MakeMonitor("session root",
mon.MemoryResource,
memMetrics.CurBytesCount,
memMetrics.MaxBytesHist,
-1, math.MaxInt64)
sessionRootMon.Start(ctx, s.pool, reserved)
sessionMon := mon.MakeMonitor("session",
mon.MemoryResource,
memMetrics.SessionCurBytesCount,
memMetrics.SessionMaxBytesHist,
-1 /* increment */, noteworthyMemoryUsageBytes)
sessionMon.Start(ctx, &sessionRootMon, mon.BoundAccount{})
// We merely prepare the txn monitor here. It is started in
// txnState.resetForNewSQLTxn().
txnMon := mon.MakeMonitor("txn",
mon.MemoryResource,
memMetrics.TxnCurBytesCount,
memMetrics.TxnMaxBytesHist,
-1 /* increment */, noteworthyMemoryUsageBytes)
settings := &s.cfg.Settings.SV
distSQLMode := sessiondata.DistSQLExecMode(DistSQLClusterExecMode.Get(settings))
ex := connExecutor{
server: s,
stmtBuf: stmtBuf,
clientComm: clientComm,
mon: sessionRootMon,
sessionMon: sessionMon,
sessionData: sessiondata.SessionData{
Database: args.Database,
DistSQLMode: distSQLMode,
SearchPath: sqlbase.DefaultSearchPath,
Location: time.UTC,
User: args.User,
SequenceState: sessiondata.NewSequenceState(),
RemoteAddr: args.RemoteAddr,
},
prepStmts: make(map[string]*PreparedStatement),
portals: make(map[string]*PreparedPortal),
state: txnState2{
mon: &txnMon,
txnAbortCount: s.StatementCounters.TxnAbortCount,
},
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,
},
parallelizeQueue: MakeParallelizeQueue(NewSpanBasedDependencyAnalyzer()),
memMetrics: memMetrics,
extraTxnState: transactionState{
tables: TableCollection{
leaseMgr: s.cfg.LeaseManager,
databaseCache: s.dbCache.getDatabaseCache(),
dbCacheSubscriber: s.dbCache,
},
schemaChangers: schemaChangerCollection{},
},
txnStartPos: -1,
appStats: s.sqlStats.getStatsForApplication(args.ApplicationName),
}
ex.mu.ActiveQueries = make(map[uint128.Uint128]*queryMeta)
ex.machine = fsm.MakeMachine(TxnStateTransitions, stateNoTxn{}, &ex.state)
ex.dataMutator = sessionDataMutator{
data: &ex.sessionData,
defaults: sessionDefaults{
applicationName: args.ApplicationName,
database: args.Database,
},
settings: s.cfg.Settings,
curTxnReadOnly: &ex.state.readOnly,
sessionTracing: &ex.state.tracing,
applicationNameChanged: func(newName string) {
ex.appStats = ex.server.sqlStats.getStatsForApplication(newName)
},
}
ex.dataMutator.SetApplicationName(args.ApplicationName)
return ex.run(ctx)
}
// WIP(andrei)
var _ = Server{}
type connExecutor struct {
noCopy util.NoCopy
// The server to which this connExecutor is attached. The reference is used
// for getting access to configuration settings and metrics.
server *Server
// 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 txnState2
// 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 transactionState
// txnStartPos is the position within stmtBuf at which the current SQL
// transaction started. If we're going to perform an automatic txn retry, this
// is the position from which we'll start executing again.
// The value is only defined while the connection is in the stateOpen.
//
// Set via setTxnStartPos().
txnStartPos CmdPos
// sessionData contains the user-configurable connection variables.
sessionData sessiondata.SessionData
dataMutator sessionDataMutator
// connCtx is the root context in which all statements from the connection are
// running. This generally should not be used directly, but through the Ctx()
// method; if we're inside a transaction, Ctx() is going to return a derived
// context. See the Context Management comments at the top of the file.
connCtx context.Context
// planner is the "default planner" on a session, to save planner allocations
// during serial execution. Since planners are not threadsafe, this is only
// safe to use when a statement is not being parallelized. It must be reset
// before using.
planner planner
// parallelizeQueue is a queue managing all parallelized SQL statements
// running on this connection.
parallelizeQueue ParallelizeQueue
// prepStmts contains the prepared statements currently available on the
// session.
prepStmts map[string]*PreparedStatement
// portals contains the portals currently available on the session.
portals map[string]*PreparedPortal
// 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
transitionCtx transitionCtx
// appStats tracks per-application SQL usage statistics. It is maintained to
// represent statistrics for the application currently identified by
// sessiondata.ApplicationName.
appStats *appStats
//
// Per-session statistics.
//
// phaseTimes tracks session-level phase times. It is copied-by-value
// to each planner in session.newPlanner.
phaseTimes phaseTimes
// mu contains of all elements of the struct that can be changed
// after initialization, and may be accessed from another thread.
mu struct {
syncutil.RWMutex
//
// Session parameters, user-configurable.
//
// ApplicationName is the name of the application running the current
// session. This can be used for logging and per-application statistics.
// Change via resetApplicationName().
ApplicationName string
//
// State structures for the logical SQL session.
//
// ActiveQueries contains all queries in flight.
ActiveQueries map[uint128.Uint128]*queryMeta
// LastActiveQuery contains a reference to the AST of the last
// query that ran on this session.
LastActiveQuery tree.Statement
}
}
// transactionState groups state that's specific to a SQL transaction. They all
// need to be reset if that transaction is committed, rolled-back or retried.
type transactionState struct {
// tables collects descriptors used by the current transaction.
// TODO(andrei, vivek): I think this TableCollection guy should go away, or at
// least only contain tables *mutated* in the current txn. I don't understand
// what purpose it serves beyond that.
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
// 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
}
// reset wipes the transactionState.
func (ts *transactionState) reset(ctx context.Context, ev txnEvent, dbCacheHolder *databaseCacheHolder) {
ts.schemaChangers.reset()
var opt releaseOpt
if ev == txnCommit {
opt = blockForDBCacheUpdate
} else {
opt = dontBlockForDBCacheUpdate
}
ts.tables.releaseTables(ctx, opt)
ts.tables.databaseCache = dbCacheHolder.getDatabaseCache()
ts.autoRetryCounter = 0
}
func (ex *connExecutor) Ctx() context.Context {
if _, ok := ex.machine.CurState().(stateNoTxn); ok {
return ex.connCtx
}
return ex.state.Ctx
}
// run implements the run loop for a connExecutor. Commands are read one by one
// from the input buffer; they are executed and the resulting state transitions
// are performed.
//
// run returns when either the stmtBuf is closed by someone else or when an
// error is propagated from query execution. Note that query errors are not
// propagated as errors to this layer; only things that are supposed to
// terminate the session are (e.g. client communication errors and ctx
// cancelations).
// run() is expected to react on ctx cancelation, but the caller needs to also
// close the stmtBuf at the same time as canceling the ctx. If cancelation
// happens in the middle of a query execution, that's expected to interrupt the
// execution and generate an error. run() is then supposed to return because the
// buffer is closed and no further commands can be read.
//
// !!! the connEx needs a close to stop monitors?
//
// !!! document returned errors need to be sent on the connection.
func (ex *connExecutor) run(ctx context.Context) error {
defer ex.extraTxnState.reset(ctx, txnAborted, ex.server.dbCache)
ex.server.cfg.SessionRegistry.register(ex)
defer ex.server.cfg.SessionRegistry.deregister(ex)
ex.connCtx = ctx
var draining bool
for {
if err := ctx.Err(); err != nil {
return err
}
cmd, pos, err := ex.stmtBuf.curCmd(ex.Ctx())
if err != nil {
if err == io.EOF {
return nil
}
return err
}
var ev fsm.Event
var payload fsm.EventPayload
var res ResultBase
switch tcmd := cmd.(type) {
case ExecPortal:
// ExecPortal is handled like ExecStmt, except that the placeholder info
// is taken from the portal.
portal, ok := ex.portals[tcmd.Name]
if !ok {
err := pgerror.NewErrorf(
pgerror.CodeInvalidCursorNameError, "unknown portal %q", tcmd.Name)
ev = eventNonRetriableErr{IsCommit: fsm.False}
payload = eventNonRetriableErrPayload{err: err}
res = ex.clientComm.CreateErrorResult(pos)
break
}
pinfo := &tree.PlaceholderInfo{
TypeHints: portal.Stmt.TypeHints,
Types: portal.Stmt.Types,
Values: portal.Qargs,
}
// No parsing is taking place, but we need to set the parsing phase time
// because the service latency is measured from
// phaseTimes[sessionStartParse].
now := timeutil.Now()
ex.phaseTimes[sessionStartParse] = now
ex.phaseTimes[sessionEndParse] = now
if portal.Stmt.Statement == nil {
res = ex.clientComm.CreateEmptyQueryResult(pos)
break
}
stmtRes := ex.clientComm.CreateStatementResult(
portal.Stmt.Statement,
// The client is using the extended protocol, so no row description is
// needed.
DontNeedRowDesc,
pos, portal.OutFormats, ex.sessionData.Location)
stmtRes.SetLimit(tcmd.Limit)
res = stmtRes
curStmt := Statement{
AST: portal.Stmt.Statement,
ExpectedTypes: portal.Stmt.Columns,
AnonymizedStr: portal.Stmt.AnonymizedStr,
}
ev, payload, err = ex.execStmt(curStmt, stmtRes, pinfo, pos)
if err != nil {
return err
}
case ExecStmt:
if tcmd.Stmt == nil {
res = ex.clientComm.CreateEmptyQueryResult(pos)
break
}
stmtRes := ex.clientComm.CreateStatementResult(
tcmd.Stmt, NeedRowDesc, pos, nil /* formatCodes */, ex.sessionData.Location)
res = stmtRes
curStmt := Statement{AST: tcmd.Stmt}
ev, payload, err = ex.execStmt(curStmt, stmtRes, nil /* pinfo */, pos)
if err != nil {
return err
}
case PrepareStmt:
ev, payload = ex.execPrepare(ex.Ctx(), tcmd)
res = ex.clientComm.CreateParseResult(pos)
case DescribeStmt:
descRes := ex.clientComm.CreateDescribeResult(pos)
res = descRes
ev, payload = ex.execDescribe(ex.Ctx(), tcmd, descRes)
case BindStmt:
ev, payload = ex.execBind(ex.Ctx(), tcmd)
res = ex.clientComm.CreateBindResult(pos)
case DeletePreparedStmt:
ev, payload = ex.execDelPrepStmt(ex.Ctx(), tcmd)
res = ex.clientComm.CreateDeleteResult(pos)
case SendError:
ev = eventNonRetriableErr{IsCommit: fsm.False}
payload = eventNonRetriableErrPayload{err: tcmd.Err}
res = ex.clientComm.CreateErrorResult(pos)
case Sync:
// Note that the Sync result will flush results to the network connection.
res = ex.clientComm.CreateSyncResult(pos)
if draining {
// If we're draining, check whether this is a good time to finish the
// connection.
if snt, ok := ex.machine.CurState().(stateNoTxn); ok {
res.Close(stateToTxnStatusIndicator(snt))
return nil
}
}
case CopyIn:
res = ex.clientComm.CreateCopyInResult(pos)
var err error
ev, payload, err = ex.execCopyIn(ex.Ctx(), tcmd)
if err != nil {
return err
}
case DrainRequest:
// We received a drain request. We terminate immediately if we're not in a
// transaction. If we are in a transaction, we'll finish as soon as a Sync
// command (i.e. the end of a batch) is processed outside of a
// transaction.
draining = true
if _, ok := ex.machine.CurState().(stateNoTxn); ok {
return nil
}
default:
panic(fmt.Sprintf("unsupported command type: %T", cmd))
}
var advInfo advanceInfo
// If an event was generated, feed it to the state machine.
if ev != nil {
var err error
advInfo, err = ex.txnStateTransitionsApplyWrapper(ctx, ev, payload, res, pos)
if err != nil {
return err
}
} else {
// If no event was generated synthesize an advance code.
advInfo = advanceInfo{
code: advanceOne,
flush: false,
}
}
// Decide if we need to close the result or not. We don't need to do it if
// we're staying in place or rewinding - the statement will be executed
// again.
if advInfo.code != stayInPlace && advInfo.code != rewind {
// Close the result. In case of an execution error, the result might have
// its error set already or it might not.
pe, ok := payload.(payloadWithError)
if ok {
ex.recordUnimplementedErrorMaybe(pe.errorCause())
}
if res.Err() == nil && ok {
if advInfo.code == stayInPlace {
return errors.Errorf("unexpected stayInPlace code with err: %s", pe.errorCause())
}
// Depending on whether the result has the error already or not, we have
// to call either Close or CloseWithErr.
if res.Err() == nil {
res.CloseWithErr(pe.errorCause())
} else {
res.Close(stateToTxnStatusIndicator(ex.machine.CurState()))
}
} else {
res.Close(stateToTxnStatusIndicator(ex.machine.CurState()))
}
} else {
res.Discard()
}
// Move the cursor according to what the state transition told us to do.
switch advInfo.code {
case advanceOne:
ex.stmtBuf.advanceOne(ex.Ctx())
case skipBatch:
if err := ex.stmtBuf.seekToNextBatch(ex.Ctx()); err != nil {
return err
}
case rewind:
advInfo.rewCap.rewindAndUnlock(ex.Ctx())
case stayInPlace:
// Nothing to do. The same statement will be executed again.
default:
log.Fatalf(ex.Ctx(), "unexpected advance code: %s", advInfo.code)
}
if err := ex.updateTxnStartPosMaybe(cmd, pos, advInfo); err != nil {
return err
}
}
}
// We handle the CopyFrom statement by creating a copyMachine and handing it
// control over the connection until the copying is done. The contract is that,
// when this is called, the pgwire.conn is not reading from the network
// connection any more until this returns. The copyMachine will to the reading
// and writing up to the CommandComplete message.
func (ex *connExecutor) execCopyIn(
ctx context.Context, cmd CopyIn,
) (fsm.Event, fsm.EventPayload, error) {
// When we're done, unblock the network connection.
defer cmd.CopyDone.Done()
state := ex.machine.CurState()
_, isNoTxn := state.(stateNoTxn)
_, isOpen := state.(stateOpen)
if !isNoTxn && !isOpen {
ev := eventNonRetriableErr{IsCommit: fsm.False}
payload := eventNonRetriableErrPayload{
err: sqlbase.NewTransactionAbortedError("" /* customMsg */)}
return ev, payload, nil
}
// If we're in an explicit txn, then the copying will be done within that
// txn. Otherwise, we tell the copyMachine to manage its own transactions.
var txnOpt copyTxnOpt
if isOpen {
txnOpt = copyTxnOpt{
txn: ex.state.mu.txn,
txnTimestamp: ex.state.sqlTimestamp,
stmtTimestamp: ex.server.cfg.Clock.PhysicalTime(),
}
}
var monToStop *mon.BytesMonitor
defer func() {
if monToStop != nil {
monToStop.Stop(ctx)
}
}()
if isNoTxn {
// HACK: We're reaching inside ex.state and starting the monitor. Normally
// that's driven by the state machine, but we're bypassing the state machine
// here.
ex.state.mon.Start(ctx, &ex.sessionMon, mon.BoundAccount{} /* reserved */)
monToStop = ex.state.mon
}
cm, err := newCopyMachine(
ctx, cmd.Conn, cmd.Stmt, txnOpt, ex.server.cfg,
// resetPlanner
func(p *planner, txn *client.Txn, txnTS time.Time, stmtTS time.Time) {
// HACK: We're reaching inside ex.state and changing sqlTimestamp by hand.
// It is used by resetPlanner. Normally sqlTimestamp is updated by the
// state machine, but the copyMachine manages its own transactions without
// going through the state machine.
ex.state.sqlTimestamp = txnTS
ex.resetPlanner(p, txn, stmtTS)
},
)
if err != nil {
return nil, nil, err
}
if err := cm.run(ctx); err != nil {
// TODO(andrei): We don't have a retriable error story for the copy machine.
// When running outside of a txn, the copyMachine should probably do retries
// internally. When not, it's unclear what we should do. For now, we abort
// the txn (if any).
// We also don't have a story for distinguishing communication errors (which
// should terminate the connection) from query errors. For now, we treat all
// errors as query errors.
ev := eventNonRetriableErr{IsCommit: fsm.False}
payload := eventNonRetriableErrPayload{err: err}
return ev, payload, nil
}
return nil, nil, nil
}
// updateTxnStartPosMaybe checks whether the ex.txnStartPos should be advanced,
// based on the advInfo produced by running cmd at position pos.
func (ex *connExecutor) updateTxnStartPosMaybe(
cmd Command, pos CmdPos, advInfo advanceInfo,
) error {
// txnStartPos is only maintained while in stateOpen.
if _, ok := ex.machine.CurState().(stateOpen); !ok {
return nil
}
if advInfo.txnEvent == txnStart || advInfo.txnEvent == txnRestart {
var nextPos CmdPos
switch advInfo.code {
case stayInPlace:
nextPos = pos
case advanceOne:
// Future rewinds will refer to the next position; the statement that
// started the transaction (i.e. BEGIN) will not be itself be executed
// again.
nextPos = pos + 1
case rewind:
if advInfo.rewCap.rewindPos != ex.txnStartPos {
return errors.Errorf("unexpected rewind position: %s when txn start is: %d",
advInfo.rewCap.rewindPos, ex.txnStartPos)
}
// txnStartPos stays unchanged.
return nil
default:
return errors.Errorf("unexpected advance code when starting a txn: %s", advInfo.code)
}
ex.setTxnStartPos(ex.Ctx(), nextPos)
} else {
// See if we can advance the rewind point even if this is not the point
// where the transaction started. We can do that after running a special
// statement (e.g. SET TRANSACTION or SAVEPOINT) or when we just ran a Sync
// command. The idea with the Sync command is that we don't want the
// following sequence to disable retries for what comes after the sequence:
// 1: PrepareStmt BEGIN
// 2: BindStmt
// 3: ExecutePortal
// 4: Sync
//
// This code ensures that txnStartPos ends up at position 5: running
// ExecutePortal will set it to 4, and then this code here will set it to 5.
//
// Note that we don't bump the txnStartPos when preparing statements or
// portals. So, for example, preparing a SET TRANSACTION... statement will
// mean that the respective statement loses its magic that it would have had
// if it was executed without being prepared. This is because preparing
// statements has non-transactional effects: the statement name is
// overwritten (particularly the unnamed statement). If we were to bump
// txnStartPos on PrepareStmt commands, the following sequence would result
// in incorrect execution:
// 1. BEGIN
// 2. PrepareStmt SET TRANSACTION ... (unnamed prepared stmt)
// 3. BindStmt
// 4. ExecutePortal
// 5. PrepareStmt SELECT 1
// 6. BindStmt
// 7. ExecutePortal
// 8. PrepareStmt SELECT 2
// 9. BindStmt
// 10. ExecutePortal -> retriable error
//
// If this code would bump txnStartPos on PrepareStmt/BindStmt commands,
// then txnStartPos would end up being 7. When command 10 gets a retriable
// error, we'd rewind to 7, but now the unnamed portal erroneously referes
// to SELECT 2 instead of SELECT 1. That's why we force PrepareStmt commands
// to be executed again (and so we rewind to 2), even if it means that a
// Sync in between 4 and 5 would preclude us from doing automatic retries in
// this case.
_, inOpen := ex.machine.CurState().(stateOpen)
if inOpen && (ex.txnStartPos == pos) {
if _, isSync := cmd.(Sync); isSync {
ex.setTxnStartPos(ex.Ctx(), pos+1)
return nil
}
if tcmd, ok := cmd.(ExecStmt); ok {