-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
Copy pathconn_executor.go
1857 lines (1690 loc) · 67.6 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"
"sync"
"time"
"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/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/pkg/errors"
)
// 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 StatementResult. Low-level methods don't
// operate on a StatementResult 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
// WIP(andrei): this needs to be pgwire.Server.sqlMemoryPool.
pool *mon.BytesMonitor
// memMetrics track memory usage by SQL execution.
memMetrics *MemoryMetrics
// EngineMetrics is exported as required by the metrics.Struct magic we use
// for metrics registration.
EngineMetrics sqlEngineMetrics
// dbCache is a cache for database descriptors. It is updated in response to
// system config updates. connExecutors get a reference to one version of the
// cache and periodically refresh that reference.
// TODO(andrei): I don't understand the benefits of this scheme very well -
// databaseCache instance are shared; but the top-level databaseCacheHolder is
// not. It has been ported over from who knows when. Rethink it.
dbCache *databaseCacheHolder
}
// NewServer creates a new Server. Start() needs to be called before the Server
// is used.
func NewServer(cfg *ExecutorConfig) *Server {
// WIP(andrei): take the stopper and listen to Gossip like the Executor does.
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),
},
// dbCache will be updated on Start().
dbCache: newDatabaseCacheHolder(newDatabaseCache(config.SystemConfig{})),
}
}
// 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) {
var first bool
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()
}
// 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) newConnExecutor(
ctx context.Context,
args SessionArgs,
stmtBuf *StmtBuf,
clientComm clientComm,
reserved mon.BoundAccount,
memMetrics *MemoryMetrics,
) *connExecutor {
// 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,
s.memMetrics.SessionCurBytesCount,
s.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,
sessionData: sessiondata.SessionData{
Database: args.Database,
DistSQLMode: distSQLMode,
SearchPath: sqlbase.DefaultSearchPath,
Location: time.UTC,
User: args.User,
SequenceState: sessiondata.NewSequenceState(),
},
dataMutator: sessionDataMutator{},
state: txnState2{
mon: &txnMon,
},
transitionCtx: transitionCtx{
db: s.cfg.DB,
nodeID: s.cfg.NodeID.Get(),
clock: s.cfg.Clock,
// The transaction's monitor 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(),
},
schemaChangers: schemaChangerCollection{},
},
}
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: &SessionTracing{},
applicationNameChanged: func(newName string) {
if ex.server.sqlStats != nil {
ex.appStats = ex.server.sqlStats.getStatsForApplication(newName)
}
},
}
return &ex
}
// 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
// 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, dbCache *databaseCache) {
ts.schemaChangers.reset()
var opt releaseOpt
if ev == txnCommit {
opt = blockForDBCacheUpdate
} else {
opt = dontBlockForDBCacheUpdate
}
ts.tables.releaseTables(ctx, opt)
ts.tables.databaseCache = dbCache
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.
func (ex *connExecutor) run(ctx context.Context) error {
defer ex.extraTxnState.reset(ctx, txnAborted, nil /* dbCache */)
ex.connCtx = ctx
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
}
exec, ok := cmd.(ExecStmt)
if !ok {
panic("not implemented")
}
// Execute the statement.
res := ex.clientComm.createStatementResult(exec.Stmt, pos)
ev, payload, err := ex.execStmt(Statement{AST: exec.Stmt}, res, nil /* pinfo */, pos)
if err != nil {
return err
}
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)
if err != nil {
return err
}
} else {
// If no event was generated synthesize an advance code.
_, inOpen := ex.machine.CurState().(stateOpen)
advInfo = advanceInfo{
code: advanceOne,
flush: !inOpen,
}
}
// 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 res.Err() == nil && ok {
if advInfo.code == stayInPlace {
return errors.Errorf("unexpected stayInPlace code with err: %s", pe.errorCause())
}
if res.Err() == nil {
res.CloseWithErr(pe.errorCause())
}
} else {
res.Close()
}
if _, inOpen := ex.machine.CurState().(stateOpen); !inOpen && !advInfo.flush {
return errors.Errorf("expected flush to be set when in state: %#v", ex.machine.CurState())
}
// 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 flush is set, we reset the point to which future rewinds will refer.
if advInfo.flush {
if err := ex.clientComm.flush(); err != nil {
return err
}
// Future rewinds will refer to the next position; the flushed statement
// cannot be rewound to.
ex.setTxnStartPos(ex.Ctx(), pos+1)
}
}
}
type descriptorsPolicy int
const (
useCachedDescs descriptorsPolicy = iota
disallowCachedDescs
)
// execStmt executes one statement by dispatching according to the current
// state. Returns an Event to be passed to the state machine, or nil if no
// transition is needed. If nil is returned, then the cursor is supposed to
// advance to the next statement.
//
// If an error is returned, the session is supposed to be considered done. Query
// execution errors are not returned explicitly and they're also not
// communicated to the client. Instead they're incorporated in the returned
// event (the returned payload will implement payloadWithError). It is the
// caller's responsibility to deliver execution errors to the client.
//
// Args:
// stmt: The statement to execute.
// res: Used to produce query results.
// pinfo: The placeholders to use in the statements.
// pos: The position of stmt.
func (ex *connExecutor) execStmt(
stmt Statement, res RestrictedCommandResult, pinfo *tree.PlaceholderInfo, pos cmdPos,
) (fsm.Event, fsm.EventPayload, error) {
// Run SHOW TRANSACTION STATUS in a separate code path; it's execution does
// not depend on the current transaction state.
if _, ok := stmt.AST.(*tree.ShowTransactionStatus); ok {
err := ex.runShowTransactionState(res)
return nil, nil, err
}
queryID := ex.generateQueryID()
stmt.queryID = queryID
// Dispatch the statement for execution based on the current state.
var ev fsm.Event
var payload fsm.EventPayload
var err error
switch ex.machine.CurState().(type) {
case stateNoTxn:
ev, payload = ex.execStmtInNoTxnState(ex.Ctx(), stmt)
case stateOpen:
ev, payload, err = ex.execStmtInOpenState(ex.Ctx(), stmt, pinfo, res)
// If the execution generated an event, we short-circuit here. Otherwise,
// if we're told that nothing exceptional happened, we have further loose
// ends to tie.
if err != nil || ev != nil {
break
}
var autoCommitErr error
if ex.machine.CurState().(stateOpen).ImplicitTxn.Get() {
autoCommitErr = ex.handleAutoCommit(stmt.AST)
}
if autoCommitErr != nil {
ev, payload = ex.handleSerializablePushMaybe(ex.Ctx(), stmt.AST)
}
if ev == nil {
if payload != nil {
panic("nil event but payload")
}
ev = eventTxnFinish{}
payload = eventTxnFinishPayload{commit: true}
}
return ev, payload, nil
case stateAborted, stateRestartWait:
ev, payload = ex.execStmtInAbortedState(stmt, res)
case stateCommitWait:
ev, payload = ex.execStmtInCommitWaitState(stmt, res)
default:
panic(fmt.Sprintf("unexpected txn state: %#v", ex.machine.CurState()))
}
if filter := ex.server.cfg.TestingKnobs.StatementFilter2; filter != nil {
if err := filter(ex.Ctx(), stmt.String(), ev); err != nil {
return nil, nil, err
}
}
return ev, payload, err
}
// runShowTransactionState returns the state of current transaction.
// res is closed.
// If an error is returned, the connection needs to stop processing queries.
func (ex *connExecutor) runShowTransactionState(res RestrictedCommandResult) error {
res.SetColumns(sqlbase.ResultColumns{{Name: "TRANSACTION STATUS", Typ: types.String}})
// WIP(andrei): figure out what to print here
state := fmt.Sprintf("%s", ex.machine.CurState())
return res.AddRow(ex.Ctx(), tree.Datums{tree.NewDString(state)})
}
// generateQueryID generates a unique ID for a query based on the node's
// ID and its current HLC timestamp.
func (ex *connExecutor) generateQueryID() uint128.Uint128 {
timestamp := ex.server.cfg.Clock.Now()
loInt := (uint64)(ex.server.cfg.NodeID.Get())
loInt = loInt | ((uint64)(timestamp.Logical) << 32)
return uint128.FromInts((uint64)(timestamp.WallTime), loInt)
}
// addActiveQuery adds a running query to the list of running queries.
//
// It returns a cleanup function that needs to be run when the query is no
// longer "running": i.e. after it has finished execution and its results have
// been delivered to the client.
func (ex *connExecutor) addActiveQuery(
queryID uint128.Uint128, stmt tree.Statement, cancelFun context.CancelFunc,
) func() {
_, hidden := stmt.(tree.HiddenFromShowQueries)
qm := queryMeta{
start: ex.phaseTimes[sessionEndParse],
stmt: stmt,
phase: preparing,
isDistributed: false,
ctxCancel: cancelFun,
hidden: hidden,
}
ex.mu.Lock()
ex.mu.ActiveQueries[queryID] = &qm
ex.mu.Unlock()
return func() {
ex.mu.Lock()
_, ok := ex.mu.ActiveQueries[queryID]
if !ok {
ex.mu.Unlock()
panic(fmt.Sprintf("query %d missing from ActiveQueries", queryID))
}
delete(ex.mu.ActiveQueries, queryID)
ex.mu.Unlock()
}
}
// setTxnStartPos updates the position to which future rewinds will refer.
//
// All statements with lower position in stmtBuf (if any) are removed, as we
// won't ever need them again.
func (ex *connExecutor) setTxnStartPos(ctx context.Context, pos cmdPos) {
if pos <= ex.txnStartPos {
log.Fatalf(ctx, "can only move the txnStartpos forward."+
"Was: %d; new value: %d", ex.txnStartPos, pos)
}
ex.txnStartPos = pos
ex.stmtBuf.ltrim(ctx, pos)
}
// getRewindTxnCapability checks whether rewinding to the position previously
// set through setTxnStartPos() is possible and, if it is, returns a
// rewindCapability bound to that position. The returned bool is true if the
// rewind is possible. If it is, client communication is blocked until the
// rewindCapability is exercised.
func (ex *connExecutor) getRewindTxnCapability() (rewindCapability, bool) {
cl := ex.clientComm.lockCommunication()
// If we already delivered results at or past the start position, we can't
// rewind.
if cl.clientPos() >= ex.txnStartPos {
cl.Close()
return rewindCapability{}, false
}
return rewindCapability{
cl: cl,
buf: ex.stmtBuf,
rewindPos: ex.txnStartPos,
}, true
}
// isCommit returns true if stmt is a "COMMIT" statement.
func isCommit(stmt tree.Statement) bool {
_, ok := stmt.(*tree.CommitTransaction)
return ok
}
// makeErrEvent takes an error and returns either an eventRetriableErr or an
// eventNonRetriableErr, depending on the error type.
func (ex *connExecutor) makeErrEvent(err error, stmt tree.Statement) (fsm.Event, fsm.EventPayload) {
retErr, retriable := err.(*roachpb.HandledRetryableTxnError)
if retriable {
if _, inOpen := ex.machine.CurState().(stateOpen); !inOpen {
log.Fatalf(ex.Ctx(), "retriable error in unexpected state: %#v",
ex.machine.CurState())
}
}
if retriable && ex.state.mu.txn.IsRetryableErrMeantForTxn(*retErr) {
rc, canAutoRetry := ex.getRewindTxnCapability()
ev := eventRetriableErr{
IsCommit: fsm.FromBool(isCommit(stmt)),
CanAutoRetry: fsm.FromBool(canAutoRetry),
}
payload := eventRetriableErrPayload{
err: err,
rewCap: rc,
}
return ev, payload
}
ev := eventNonRetriableErr{
IsCommit: fsm.FromBool(isCommit(stmt)),
}
payload := eventNonRetriableErrPayload{err: err}
return ev, payload
}
// handleAutoCommit commits the KV transaction if it hasn't been committed
// already.
//
// It's possible that the statement constituting the implicit txn has already
// committed it (in case it tried to run as a 1PC). This method detects that
// case.
// NOTE(andrei): It bothers me some that we're peeking at txn to figure out
// whether we committed or not, where SQL could already know that - individual
// statements could report this back through the Event.
//
// Args:
// stmt: The statement that we just ran.
func (ex *connExecutor) handleAutoCommit(stmt tree.Statement) error {
_, inOpen := ex.machine.CurState().(stateOpen)
if !inOpen {
log.Fatalf(ex.Ctx(), "handleAutoCommit called in state: %#v",
ex.machine.CurState())
}
txn := ex.state.mu.txn
if txn.IsCommitted() {
return nil
}
var skipCommit bool
var err error
if knob := ex.server.cfg.TestingKnobs.BeforeAutoCommit; knob != nil {
err = knob(ex.Ctx(), stmt.String())
skipCommit = err != nil
}
if !skipCommit {
err = txn.Commit(ex.Ctx())
}
log.Eventf(ex.Ctx(), "AutoCommit. err: %v", err)
if err != nil {
return err
}
return nil
}
// handleSerializablePushMaybe takes action in some cases when a serializable
// transaction is detected to have been pushed - it generates a
// eventRetriableErr. Otherwise it returns nil.
//
// Generally, if the transaction is serializable and it has been pushed, we
// don't deal with the push until commit time (when we return a retriable error
// to the client). This is because we want the transaction to continue and lay
// down all the intents it wants, so that a future attempt is more likely to
// succeed. However, there are two situations when we do want to detect the push
// and restart early:
// 1. If we can still automatically retry the txn, we go ahead and retry now -
// if we'd execute further statements, we probably wouldn't be allowed to retry
// automatically any more.
// 2. If the client is not following the client-directed retries protocol, then
// technically there won't be any retries, so the client would not benefit from
// letting the transaction run more statements.
//
// This is only supposed to be called if we're in the Open state and we're not
// already transitioning away from that state for some other reason.
func (ex *connExecutor) handleSerializablePushMaybe(
ctx context.Context, stmt tree.Statement,
) (fsm.Event, fsm.EventPayload) {
os, ok := ex.machine.CurState().(stateOpen)
if !ok {
log.Fatalf(ex.Ctx(),
"handleSerializablePushMaybe called in state: %#v", ex.machine.CurState())
}
// rewCap ownership will be passed to the returned event.
var rewCap *rewindCapability
rc, canAutoRetry := ex.getRewindTxnCapability()
if !(canAutoRetry || !os.RetryIntent.Get()) {
return nil, nil
}
rewCap = &rc
defer func() {
if rewCap != nil {
rewCap.close()
}
}()
// Flush the parallel execution queue.
// If we just ran a statement synchronously, then the parallel queue would
// have been synchronized first, so this would be a no-op. However, if we
// just ran a statement asynchronously, then the queue could still contain
// statements executing. So if we're in a "serializable restart" state, we
// synchronize to drain the rest of the stmts and clear the parallel batch's
// error-set before restarting. If we did not drain the parallel stmts then
// the txn.Proto().Restart() call below might cause them to write at the wrong
// epoch.
//
// TODO(nvanbenschoten): like elsewhere, we should try to actively cancel
// these parallel queries instead of just waiting for them to finish.
if parErr := ex.synchronizeParallelStmts(ex.Ctx()); parErr != nil {
// If synchronizing results in a non-retriable error, it takes priority.
if _, ok := parErr.(*roachpb.HandledRetryableTxnError); !ok {
return ex.makeErrEvent(parErr, stmt)
}
log.VEventf(ex.Ctx(), 2, "parallel execution queue returned retriable error, "+
"which will be swallowed because the transaction has been pushed anyway: %s",
parErr)
}
ex.state.mu.txn.Proto().Restart(
0 /* userPriority */, 0 /* upgradePriority */, ex.server.cfg.Clock.Now())
injectedErr := roachpb.NewHandledRetryableTxnError(
"serializable transaction timestamp pushed (detected by connExecutor)",
ex.state.mu.txn.ID(),
// No updated transaction required; we've already manually updated our
// client.Txn.
roachpb.Transaction{},
)
ev := eventRetriableErr{
CanAutoRetry: fsm.True,
}
payload := eventRetriableErrPayload{
err: injectedErr,
// We're passing the rewCap to the caller.
rewCap: *rewCap,
}
rewCap = nil
return ev, payload
}
// synchronizeParallelStmts waits for all statements in the parallelizeQueue to
// finish. If errors are seen in the parallel batch, we attempt to turn these
// errors into a single error we can send to the client. We do this by prioritizing
// non-retryable errors over retryable errors.
// Note that the returned error is to always be considered a "query execution
// error". This means that it should never interrupt the connection.
func (ex *connExecutor) synchronizeParallelStmts(ctx context.Context) error {
if errs := ex.parallelizeQueue.Wait(); len(errs) > 0 {