-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
1735 lines (1539 loc) · 58.5 KB
/
session.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 2015 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 (
"fmt"
"net"
"strings"
"sync/atomic"
"time"
"unicode/utf8"
opentracing "github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
"golang.org/x/net/context"
"golang.org/x/net/trace"
"github.com/cockroachdb/cockroach/pkg/base"
"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/settings"
"github.com/cockroachdb/cockroach/pkg/sql/mon"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"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/duration"
"github.com/cockroachdb/cockroach/pkg/util/envutil"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/retry"
"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/uint128"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
)
// debugTrace7881Enabled causes all SQL transactions to be traced, in the hope
// that we'll catch #7881 and dump the current trace for debugging.
var debugTrace7881Enabled = envutil.EnvOrDefaultBool("COCKROACH_TRACE_7881", false)
// span baggage key used for marking a span
const keyFor7881Sample = "found#7881"
// traceTxnThreshold can be used to log SQL transactions that take
// longer than duration to complete. For example, traceTxnThreshold=1s
// will log the trace for any transaction that takes 1s or longer. To
// log traces for all transactions use traceTxnThreshold=1ns. Note
// that any positive duration will enable tracing and will slow down
// all execution because traces are gathered for all transactions even
// if they are not output.
var traceTxnThreshold = settings.RegisterDurationSetting(
"sql.trace.txn.enable_threshold",
"duration beyond which all transactions are traced (set to 0 to disable)", 0,
)
// traceSessionEventLogEnabled can be used to enable the event log
// that is normally kept for every SQL connection. The event log has a
// non-trivial performance impact and also reveals SQL statements
// which may be a privacy concern.
var traceSessionEventLogEnabled = settings.RegisterBoolSetting(
"sql.trace.session_eventlog.enabled",
"set to true to enable session tracing", false,
)
// DistSQLClusterExecMode controls the cluster default for when DistSQL is used.
var DistSQLClusterExecMode = settings.RegisterEnumSetting(
"sql.defaults.distsql",
"Default distributed SQL execution mode",
"Auto",
map[int64]string{
int64(DistSQLOff): "Off",
int64(DistSQLAuto): "Auto",
int64(DistSQLOn): "On",
},
)
// DistSQLExecMode controls if and when the Executor uses DistSQL.
type DistSQLExecMode int64
const (
// DistSQLOff means that we never use distSQL.
DistSQLOff DistSQLExecMode = iota
// DistSQLAuto means that we automatically decide on a case-by-case basis if
// we use distSQL.
DistSQLAuto
// DistSQLOn means that we use distSQL for queries that are supported.
DistSQLOn
// DistSQLAlways means that we only use distSQL; unsupported queries fail.
DistSQLAlways
)
func (m DistSQLExecMode) String() string {
switch m {
case DistSQLOff:
return "off"
case DistSQLAuto:
return "auto"
case DistSQLOn:
return "on"
case DistSQLAlways:
return "always"
default:
return fmt.Sprintf("invalid (%d)", m)
}
}
// DistSQLExecModeFromString converts a string into a DistSQLExecMode
func DistSQLExecModeFromString(val string) DistSQLExecMode {
switch strings.ToUpper(val) {
case "OFF":
return DistSQLOff
case "AUTO":
return DistSQLAuto
case "ON":
return DistSQLOn
case "ALWAYS":
return DistSQLAlways
default:
panic(fmt.Sprintf("unknown DistSQL mode %s", val))
}
}
// queryPhase represents a phase during a query's execution.
type queryPhase int
const (
// The phase before start of execution (includes parsing, building a plan).
preparing queryPhase = 0
// Execution phase.
executing = 1
)
// queryMeta stores metadata about a query. Stored as reference in
// session.mu.ActiveQueries.
type queryMeta struct {
// The timestamp when this query began execution.
start time.Time
// AST of the SQL statement - converted to query string only when necessary.
stmt parser.Statement
// States whether this query is distributed. Note that all queries,
// including those that are distributed, have this field set to false until
// start of execution; only at that point can we can actually determine whether
// this query will be distributed. Use the phase variable below
// to determine whether this query has entered execution yet.
isDistributed bool
// Current phase of execution of query.
phase queryPhase
// Context associated with this query's transaction.
ctx context.Context
// Cancellation function for the context associated with this query's transaction.
// Set to session.txnState.cancel in executor.
ctxCancel context.CancelFunc
// Reference to the Session that contains this query.
session *Session
}
// cancel cancels the query associated with this queryMeta, by closing the associated
// txn context.
func (q *queryMeta) cancel() {
q.ctxCancel()
}
// Session contains the state of a SQL client connection.
// Create instances using NewSession().
type Session struct {
//
// Session parameters, user-configurable.
//
// Database indicates the "current" database for the purpose of
// resolving names. See searchAndQualifyDatabase() for details.
Database string
// DefaultIsolationLevel indicates the default isolation level of
// newly created transactions.
DefaultIsolationLevel enginepb.IsolationType
// DistSQLMode indicates whether to run queries using the distributed
// execution engine.
DistSQLMode DistSQLExecMode
// Location indicates the current time zone.
Location *time.Location
// SearchPath is a list of databases that will be searched for a table name
// before the database. Currently, this is used only for SELECTs.
// Names in the search path must have been normalized already.
SearchPath parser.SearchPath
// User is the name of the user logged into the session.
User string
// SafeUpdates causes errors when the client
// sends syntax that may have unwanted side effects.
SafeUpdates bool
//
// Session parameters, non-user-configurable.
//
// defaults is used to restore default configuration values into
// SET ... TO DEFAULT statements.
defaults sessionDefaults
// ClientAddr is the client's IP address and port.
ClientAddr string
//
// State structures for the logical SQL session.
//
// TxnState carries information about the open transaction (if any),
// including the retry status and the KV client Txn object.
TxnState txnState
// PreparedStatements and PreparedPortals store the statements/portals
// that have been prepared via pgwire.
PreparedStatements PreparedStatements
PreparedPortals PreparedPortals
// virtualSchemas aliases Executor.virtualSchemas.
// It is duplicated in Session to provide easier access to
// the various methods that need this reference.
// TODO(knz): place this in an executionContext parameter-passing
// structure.
virtualSchemas virtualSchemaHolder
// 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
//
// Run-time state.
//
// execCfg is the configuration of the Executor that is executing this
// session.
execCfg *ExecutorConfig
// distSQLPlanner is in charge of distSQL physical planning and running
// logic.
distSQLPlanner *distSQLPlanner
// context is the Session's base context, to be used for all
// SQL-related logging. See Ctx().
context context.Context
// eventLog for SQL statements and results.
eventLog trace.EventLog
// cancel is a method to call when the session terminates, to
// release resources associated with the context above.
// TODO(andrei): We need to either get rid of this cancel field, or
// it needs to move to the TxnState and become a per-txn
// cancel. Right now, we're cancelling all the txns that have ever
// run on this session when the session is closed, as opposed to
// cancelling the individual transactions as soon as they
// COMMIT/ROLLBACK.
cancel context.CancelFunc
// parallelizeQueue is a queue managing all parallelized SQL statements
// running in this session.
parallelizeQueue ParallelizeQueue
// mon tracks memory usage for SQL activity within this session. It
// is not directly used, but rather indirectly used via sessionMon
// and TxnState.mon. sessionMon tracks session-bound objects like prepared
// statements and result sets.
//
// The reason why TxnState.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
// emergencyShutdown is set to true by EmergencyClose() to
// indicate to Finish() that the session is already closed.
emergencyShutdown bool
// ResultsWriter is where query results are written to. It's set to a
// pgwire.v3conn for sessions opened for SQL client connections and a
// bufferedResultWriter for internal uses.
ResultsWriter ResultsWriter
Tracing SessionTracing
tables TableCollection
// If set, contains the in progress COPY FROM columns.
copyFrom *copyNode
// ActiveSyncQueries contains query IDs of all synchronous (i.e. non-parallel)
// queries in flight. All ActiveSyncQueries must also be in mu.ActiveQueries.
ActiveSyncQueries []uint128.Uint128
// 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 parser.Statement
}
//
// Testing state.
//
// If set, called after the Session is done executing the current SQL statement.
// It can be used to verify assumptions about how metadata will be asynchronously
// updated. Note that this can overwrite a previous callback that was waiting to be
// verified, which is not ideal.
testingVerifyMetadataFn func(config.SystemConfig) error
verifyFnCheckedOnce bool
//
// Per-session statistics.
//
// memMetrics track memory usage by SQL execution.
memMetrics *MemoryMetrics
// sqlStats tracks per-application statistics for all
// applications on each node.
sqlStats *sqlStats
// appStats track per-application SQL usage statistics.
appStats *appStats
// phaseTimes tracks session-level phase times. It is copied-by-value
// to each planner in session.newPlanner.
phaseTimes phaseTimes
// noCopy is placed here to guarantee that Session objects are not
// copied.
noCopy util.NoCopy
}
// sessionDefaults mirrors fields in Session, for restoring default
// configuration values in SET ... TO DEFAULT statements.
type sessionDefaults struct {
applicationName string
database string
}
// SessionArgs contains arguments for creating a new Session with NewSession().
type SessionArgs struct {
Database string
User string
ApplicationName string
}
// SessionRegistry stores a set of all sessions on this node.
// Use register() and deregister() to modify this registry.
type SessionRegistry struct {
syncutil.Mutex
store map[*Session]struct{}
}
// MakeSessionRegistry creates a new SessionRegistry with an empty set
// of sessions.
func MakeSessionRegistry() *SessionRegistry {
return &SessionRegistry{store: make(map[*Session]struct{})}
}
func (r *SessionRegistry) register(s *Session) {
r.Lock()
r.store[s] = struct{}{}
r.Unlock()
}
func (r *SessionRegistry) deregister(s *Session) {
r.Lock()
delete(r.store, s)
r.Unlock()
}
// CancelQuery looks up the associated query in the session registry and cancels it.
func (r *SessionRegistry) CancelQuery(queryIDStr string, username string) (bool, error) {
queryID, err := uint128.FromString(queryIDStr)
if err != nil {
return false, fmt.Errorf("query ID %s malformed: %s", queryID, err)
}
r.Lock()
defer r.Unlock()
for session := range r.store {
if !(username == security.RootUser || username == session.User) {
// Skip this session.
continue
}
session.mu.Lock()
if queryMeta, exists := session.mu.ActiveQueries[queryID]; exists {
queryMeta.cancel()
session.mu.Unlock()
return true, nil
}
session.mu.Unlock()
}
return false, fmt.Errorf("query ID %s not found", queryID)
}
// SerializeAll returns a slice of all sessions in the registry, converted to serverpb.Sessions.
func (r *SessionRegistry) SerializeAll() []serverpb.Session {
r.Lock()
defer r.Unlock()
response := make([]serverpb.Session, 0, len(r.store))
for s := range r.store {
response = append(response, s.serialize())
}
return response
}
// NewSession creates and initializes a new Session object.
// remote can be nil.
func NewSession(
ctx context.Context, args SessionArgs, e *Executor, remote net.Addr, memMetrics *MemoryMetrics,
) *Session {
ctx = e.AnnotateCtx(ctx)
distSQLMode := DistSQLExecMode(DistSQLClusterExecMode.Get(&e.cfg.Settings.SV))
s := &Session{
Database: args.Database,
DistSQLMode: distSQLMode,
SearchPath: sqlbase.DefaultSearchPath,
Location: time.UTC,
User: args.User,
virtualSchemas: e.virtualSchemas,
execCfg: &e.cfg,
distSQLPlanner: e.distSQLPlanner,
parallelizeQueue: MakeParallelizeQueue(NewSpanBasedDependencyAnalyzer()),
memMetrics: memMetrics,
sqlStats: &e.sqlStats,
defaults: sessionDefaults{
applicationName: args.ApplicationName,
database: args.Database,
},
tables: TableCollection{
leaseMgr: e.cfg.LeaseManager,
databaseCache: e.getDatabaseCache(),
},
}
s.phaseTimes[sessionInit] = timeutil.Now()
s.resetApplicationName(args.ApplicationName)
s.PreparedStatements = makePreparedStatements(s)
s.PreparedPortals = makePreparedPortals(s)
s.Tracing.session = s
s.mu.ActiveQueries = make(map[uint128.Uint128]*queryMeta)
s.ActiveSyncQueries = make([]uint128.Uint128, 0)
remoteStr := "<admin>"
if remote != nil {
remoteStr = remote.String()
}
s.ClientAddr = remoteStr
if traceSessionEventLogEnabled.Get(&e.cfg.Settings.SV) {
s.eventLog = trace.NewEventLog(fmt.Sprintf("sql [%s]", args.User), remoteStr)
}
s.context, s.cancel = context.WithCancel(ctx)
e.cfg.SessionRegistry.register(s)
return s
}
// Finish releases resources held by the Session. It is called by the Session's
// main goroutine, so no synchronous queries will be in-flight during the
// method's execution. However, it could be called when asynchronous queries are
// operating in the background in the case of parallelized statements, which
// is why we make sure to drain background statements.
func (s *Session) Finish(e *Executor) {
log.VEvent(s.context, 2, "finishing session")
if s.emergencyShutdown {
// closed by EmergencyClose() already.
return
}
if s.mon == (mon.BytesMonitor{}) {
// This check won't catch the cases where Finish is never called, but it's
// proven to be easier to remember to call Finish than it is to call
// StartMonitor.
panic("session.Finish: session monitors were never initialized. Missing call " +
"to session.StartMonitor?")
}
// Make sure that no statements remain in the ParallelizeQueue. If no statements
// are in the queue, this will be a no-op. If there are statements in the
// queue, they would have eventually drained on their own, but if we don't
// wait here, we risk alarming the MemoryMonitor. We ignore the error because
// it will only ever be non-nil if there are statements in the queue, meaning
// that the Session was abandoned in the middle of a transaction, in which
// case the error doesn't matter.
//
// TODO(nvanbenschoten): Once we have better support for cancelling ongoing
// statement execution by the infrastructure added to support CancelRequest,
// we should try to actively drain this queue instead of passively waiting
// for it to drain. (andrei, 2017/09) - We now have support for statement
// cancellation. Now what?
_ = s.synchronizeParallelStmts(s.context)
// If we're inside a txn, roll it back.
if s.TxnState.State().kvTxnIsOpen() {
_ = s.TxnState.updateStateAndCleanupOnErr(fmt.Errorf("session closing"), e)
}
if s.TxnState.State() != NoTxn {
s.TxnState.finishSQLTxn(s)
}
// We might have unreleased tables if we're finishing the
// session abruptly in the middle of a transaction, or, until #7648 is
// addressed, there might be leases accumulated by preparing statements.
s.tables.releaseTables(s.context)
s.ClearStatementsAndPortals(s.context)
s.sessionMon.Stop(s.context)
s.mon.Stop(s.context)
if s.eventLog != nil {
s.eventLog.Finish()
s.eventLog = nil
}
if s.Tracing.Enabled() {
if err := s.Tracing.StopTracing(); err != nil {
log.Infof(s.context, "error stopping tracing: %s", err)
}
}
// Clear this session from the sessions registry.
e.cfg.SessionRegistry.deregister(s)
// This will stop the heartbeating of the of the txn record.
// TODO(andrei): This shouldn't have any effect, since, if there was a
// transaction, we just explicitly rolled it back above, so the heartbeat loop
// in the TxnCoordSender should not be waiting on this channel any more.
// Consider getting rid of this cancel field all-together.
s.cancel()
}
// EmergencyClose is a simplified replacement for Finish() which is
// less picky about the current state of the Session. In particular
// this can be used to tidy up after a session even in the middle of a
// transaction, where there may still be memory activity registered to
// a monitor and not cleanly released.
func (s *Session) EmergencyClose() {
// Ensure that all in-flight statements are done, so that monitor
// traffic is stopped.
_ = s.synchronizeParallelStmts(s.context)
// Release the leases - to ensure other sessions don't get stuck.
s.tables.releaseTables(s.context)
// The KV txn may be unusable - just leave it dead. Simply
// shut down its memory monitor.
s.TxnState.mon.EmergencyStop(s.context)
// Shut the remaining monitors down.
s.sessionMon.EmergencyStop(s.context)
s.mon.EmergencyStop(s.context)
// Finalize the event log.
if s.eventLog != nil {
s.eventLog.Finish()
s.eventLog = nil
}
// Stop the heartbeating.
s.cancel()
// Mark the session as already closed, so that Finish() doesn't get confused.
s.emergencyShutdown = true
}
// Ctx returns the current context for the session: if there is an active SQL
// transaction it returns the transaction context, otherwise it returns the
// session context.
// Note that in some cases we may want the session context even if there is an
// active transaction (an example is when we want to log an event to the session
// event log); in that case s.context should be used directly.
func (s *Session) Ctx() context.Context {
if s.TxnState.State() != NoTxn {
return s.TxnState.Ctx
}
return s.context
}
func (s *Session) resetPlanner(p *planner, e *Executor, txn *client.Txn) {
p.session = s
// phaseTimes is an array, not a slice, so this performs a copy-by-value.
p.phaseTimes = s.phaseTimes
p.stmt = nil
p.cancelChecker = sqlbase.NewCancelChecker(s.Ctx())
p.semaCtx = parser.MakeSemaContext(s.User == security.RootUser)
p.semaCtx.Location = &s.Location
p.semaCtx.SearchPath = s.SearchPath
p.evalCtx = s.evalCtx()
p.evalCtx.Planner = p
if e != nil {
p.evalCtx.ClusterID = e.cfg.ClusterID()
p.evalCtx.NodeID = e.cfg.NodeID.Get()
p.evalCtx.ReCache = e.reCache
}
p.setTxn(txn)
}
// FinishPlan releases the resources that were consumed by the currently active
// default planner. It does not check to see whether any other resources are
// still pointing to the planner, so it should only be called when a connection
// is entirely finished executing a statement and all results have been sent.
func (s *Session) FinishPlan() {
if len(s.ActiveSyncQueries) > 0 {
s.mu.Lock()
// Store the last sync query as the last active query.
lastQueryID := s.ActiveSyncQueries[len(s.ActiveSyncQueries)-1]
s.mu.LastActiveQuery = s.mu.ActiveQueries[lastQueryID].stmt
// All results have been sent to the client; so deregister all synchronous
// active queries from this session. Cannot deregister asynchronous ones
// because those might still be executing in the parallelizeQueue.
for _, queryID := range s.ActiveSyncQueries {
delete(s.mu.ActiveQueries, queryID)
}
s.mu.Unlock()
s.ActiveSyncQueries = make([]uint128.Uint128, 0)
}
s.planner = emptyPlanner
}
// newPlanner creates a planner inside the scope of the given Session. The
// statement executed by the planner will be executed in txn. The planner
// should only be used to execute one statement.
func (s *Session) newPlanner(e *Executor, txn *client.Txn) *planner {
p := &planner{}
s.resetPlanner(p, e, txn)
return p
}
// evalCtx creates a parser.EvalContext from the Session's current configuration.
func (s *Session) evalCtx() parser.EvalContext {
return parser.EvalContext{
Location: &s.Location,
Database: s.Database,
User: s.User,
SearchPath: s.SearchPath,
Ctx: s.Ctx,
Mon: &s.TxnState.mon,
}
}
// resetForBatch prepares the Session for executing a new batch of statements.
func (s *Session) resetForBatch(e *Executor) {
// Update the database cache to a more recent copy, so that we can use tables
// that we created in previous batches of the same transaction.
s.tables.databaseCache = e.getDatabaseCache()
s.TxnState.schemaChangers.curGroupNum++
}
// setTestingVerifyMetadata sets a callback to be called after the Session
// is done executing the current SQL statement. It can be used to verify
// assumptions about how metadata will be asynchronously updated.
// Note that this can overwrite a previous callback that was waiting to be
// verified, which is not ideal.
func (s *Session) setTestingVerifyMetadata(fn func(config.SystemConfig) error) {
s.testingVerifyMetadataFn = fn
s.verifyFnCheckedOnce = false
}
// addActiveQuery adds a running query to the session's internal store of active
// queries, as well as to the executor's query registry. Called from executor
// before start of execution.
func (s *Session) addActiveQuery(queryID uint128.Uint128, queryMeta *queryMeta) {
s.mu.Lock()
s.mu.ActiveQueries[queryID] = queryMeta
queryMeta.session = s
s.mu.Unlock()
// addActiveQuery is called from the main goroutine of the session;
// and at this stage, this query is a synchronous query for our purposes.
// setQueryExecutionMode will remove this element if this query enters the
// parallelizeQueue.
s.ActiveSyncQueries = append(s.ActiveSyncQueries, queryID)
}
// removeActiveQuery removes a query from a session's internal store of active
// queries, as well as from the executor's query registry.
// Called when a query finishes execution.
func (s *Session) removeActiveQuery(queryID uint128.Uint128) {
s.mu.Lock()
queryMeta, ok := s.mu.ActiveQueries[queryID]
if ok {
delete(s.mu.ActiveQueries, queryID)
s.mu.LastActiveQuery = queryMeta.stmt
}
s.mu.Unlock()
}
// setQueryExecutionMode is called upon start of execution of a query, and sets
// the query's metadata to indicate whether it's distributed or not.
func (s *Session) setQueryExecutionMode(
queryID uint128.Uint128, isDistributed bool, isParallel bool,
) {
s.mu.Lock()
defer s.mu.Unlock()
queryMeta, ok := s.mu.ActiveQueries[queryID]
if !ok {
// Could be a statement that implements HiddenFromShowQueries.
// These statements have a query ID but do not have an entry
// in session.mu.ActiveQueries.
return
}
queryMeta.phase = executing
queryMeta.isDistributed = isDistributed
if isParallel {
// We default to putting queries in ActiveSyncQueries. Since
// this query is not synchronous anymore, remove it from
// ActiveSyncQueries. We expect the last element in
// ActiveSyncQueries to be this query; because all execution
// up to this call of setQueryExecutionMode is synchronous.
lenSyncQueries := len(s.ActiveSyncQueries)
s.ActiveSyncQueries = s.ActiveSyncQueries[:lenSyncQueries-1]
}
}
// 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.
func (s *Session) synchronizeParallelStmts(ctx context.Context) error {
if errs := s.parallelizeQueue.Wait(); len(errs) > 0 {
s.TxnState.mu.Lock()
defer s.TxnState.mu.Unlock()
// Check that all errors are retryable. If any are not, return the
// first non-retryable error.
var retryErr *roachpb.HandledRetryableTxnError
for _, err := range errs {
switch t := err.(type) {
case *roachpb.HandledRetryableTxnError:
// Ignore retryable errors to previous incarnations of this transaction.
curTxn := s.TxnState.mu.txn.Proto()
errTxn := t.Transaction
if errTxn.ID == curTxn.ID && errTxn.Epoch == curTxn.Epoch {
retryErr = t
}
case *roachpb.UntrackedTxnError:
// Symptom of concurrent retry, ignore.
case *roachpb.TxnPrevAttemptError:
// Symptom of concurrent retry, ignore.
default:
return err
}
}
if retryErr == nil {
log.Fatalf(ctx, "found symptoms of a concurrent retry, but did "+
"not find the final retry error: %v", errs)
}
// If all errors are retryable, we return the one meant for the current
// incarnation of this transaction. Before doing so though, we need to bump
// the transaction epoch to invalidate any writes performed by any workers
// after the retry updated the txn's proto but before we synchronized (some
// of these writes might have been performed at the wrong epoch). Note
// that we don't need to lock the client.Txn because we're synchronized.
// See #17197.
s.TxnState.mu.txn.Proto().BumpEpoch()
return retryErr
}
return nil
}
// MaxSQLBytes is the maximum length in bytes of SQL statements serialized
// into a serverpb.Session. Exported for testing.
const MaxSQLBytes = 1000
// serialize serializes a Session into a serverpb.Session
// that can be served over RPC.
func (s *Session) serialize() serverpb.Session {
s.mu.RLock()
defer s.mu.RUnlock()
s.TxnState.mu.RLock()
defer s.TxnState.mu.RUnlock()
var kvTxnID *uuid.UUID
txn := s.TxnState.mu.txn
if txn != nil {
id := txn.ID()
kvTxnID = &id
}
activeQueries := make([]serverpb.ActiveQuery, 0, len(s.mu.ActiveQueries))
truncateSQL := func(sql string) string {
if len(sql) > MaxSQLBytes {
sql = sql[:MaxSQLBytes-utf8.RuneLen('…')]
// Ensure the resulting string is valid utf8.
for {
if r, _ := utf8.DecodeLastRuneInString(sql); r != utf8.RuneError {
break
}
sql = sql[:len(sql)-1]
}
sql += "…"
}
return sql
}
for id, query := range s.mu.ActiveQueries {
sql := truncateSQL(query.stmt.String())
activeQueries = append(activeQueries, serverpb.ActiveQuery{
ID: id.String(),
Start: query.start.UTC(),
Sql: sql,
IsDistributed: query.isDistributed,
Phase: (serverpb.ActiveQuery_Phase)(query.phase),
})
}
lastActiveQuery := ""
if s.mu.LastActiveQuery != nil {
lastActiveQuery = truncateSQL(s.mu.LastActiveQuery.String())
}
return serverpb.Session{
Username: s.User,
ClientAddress: s.ClientAddr,
ApplicationName: s.mu.ApplicationName,
Start: s.phaseTimes[sessionInit].UTC(),
ActiveQueries: activeQueries,
KvTxnID: kvTxnID,
LastActiveQuery: lastActiveQuery,
}
}
// TxnStateEnum represents the state of a SQL txn.
type TxnStateEnum int64
//go:generate stringer -type=TxnStateEnum
const (
// No txn is in scope. Either there never was one, or it got committed/rolled
// back. Note that this state will not be experienced outside of the Session
// and Executor (i.e. it will not be observed by a running query) because the
// Executor opens implicit transactions before executing non-transactional
// queries.
NoTxn TxnStateEnum = iota
// Like Open, a txn is in scope. The difference is that, while in the
// AutoRetry state, a retriable error will be handled by an automatic
// transaction retry, whereas we can't do that in Open. There's a caveat -
// even if we're in AutoRetry, we can't do automatic retries if any
// results for statements in the current transaction have already been
// delivered to the client.
// In principle, we can do automatic retries for the first batch of statements
// in a transaction. There is an extension to the rule, though: for
// example, is we get a batch with "BEGIN; SET TRANSACTION ISOLATION LEVEL
// foo; SAVEPOINT cockroach_restart;" followed by a 2nd batch, we can
// automatically retry the 2nd batch even though the statements in the first
// batch will not be executed again and their results have already been sent
// to the clients. We can do this because some statements are special in that
// their execution always generates exactly the same results to the consumer
// (i.e. the SQL client).
//
// TODO(andrei): This state shouldn't exist; the decision about whether we can
// retry automatically or not should be entirely dynamic, based on which
// results we've delivered to the client already. It should have nothing to do
// with the client's batching of statements. For example, the client can send
// 100 batches but, if we haven't sent it any results yet, we should still be
// able to retry them all). Currently the splitting into batches is relevant
// because we don't keep track of statements from previous batches, so we
// would not be capable of retrying them even if we knew that no results have
// been delivered.
AutoRetry
// A txn is in scope.
Open
// The txn has encountered a (non-retriable) error.
// Statements will be rejected until a COMMIT/ROLLBACK is seen.
Aborted
// The txn has encountered a retriable error.
// Statements will be rejected until a RESTART_TRANSACTION is seen.
RestartWait
// The KV txn has been committed successfully through a RELEASE.
// Statements are rejected until a COMMIT is seen.
CommitWait
)
// Some states mean that a client.Txn is open, others don't.
func (s TxnStateEnum) kvTxnIsOpen() bool {
return s == Open || s == AutoRetry || s == RestartWait
}
// txnState contains state associated with an ongoing SQL txn.
// There may or may not be an open KV txn associated with the SQL txn.
// For interactive transactions (open across batches of SQL commands sent by a
// user), txnState is intended to be stored as part of a user Session.
type txnState struct {
// state is read and written to atomically because it can be updated
// concurrently with the execution of statements in the parallelizeQueue.
// Access with State() / SetState().
//
// NOTE: Only state updates that are inconsequential to statement execution
// are allowed concurrently with the execution of the parallizeQueue (e.g.
// Open->AutoRetry).
state TxnStateEnum
// Mutable fields accessed from goroutines not synchronized by this txn's session,
// such as when a SHOW SESSIONS statement is executed on another session.
// Note that reads of mu.txn from the session's main goroutine
// do not require acquiring a read lock - since only that
// goroutine will ever write to mu.txn.
mu struct {
syncutil.RWMutex
txn *client.Txn
}
// If we're in a SQL txn, txnResults is the ResultsGroup that statements in
// this transaction should write results to.
txnResults ResultsGroup
// Ctx is the context for everything running in this SQL txn.
Ctx context.Context
// cancel is the cancellation function for the above context. Called upon
// COMMIT/ROLLBACK of the transaction to release resources associated with
// the context. nil when no txn is in progress.
cancel context.CancelFunc
// implicitTxn if set if the transaction was automatically created for a
// single statement.
implicitTxn bool
// If set, the user declared the intention to retry the txn in case of retriable
// errors. The txn will enter a RestartWait state in case of such errors.
retryIntent bool
// A COMMIT statement has been processed. Useful for allowing the txn to
// survive retriable errors if it will be auto-retried (BEGIN; ... COMMIT; in
// the same batch), but not if the error needs to be reported to the user.
commitSeen bool
// The schema change closures to run when this txn is done.
schemaChangers schemaChangerCollection
sp opentracing.Span
// The timestamp to report for current_timestamp(), now() etc.
// This must be constant for the lifetime of a SQL transaction.
sqlTimestamp time.Time
// The transaction's isolation level.
isolation enginepb.IsolationType
// The transaction's priority.
priority roachpb.UserPriority
// mon tracks txn-bound objects like the running state of
// planNode in the midst of performing a computation. We
// host this here instead of TxnState because TxnState is
// fully reset upon each call to resetForNewSQLTxn().
mon mon.BytesMonitor
}
// State returns the current state of the session.