-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
distsql_running.go
1648 lines (1513 loc) · 56.4 KB
/
distsql_running.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 2016 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package sql
import (
"context"
"fmt"
"math"
"sync"
"sync/atomic"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/col/coldata"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/rangecache"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/rpc"
"github.com/cockroachdb/cockroach/pkg/rpc/nodedialer"
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"github.com/cockroachdb/cockroach/pkg/sql/colflow"
"github.com/cockroachdb/cockroach/pkg/sql/contention"
"github.com/cockroachdb/cockroach/pkg/sql/contentionpb"
"github.com/cockroachdb/cockroach/pkg/sql/distsql"
"github.com/cockroachdb/cockroach/pkg/sql/execinfra"
"github.com/cockroachdb/cockroach/pkg/sql/execinfrapb"
"github.com/cockroachdb/cockroach/pkg/sql/flowinfra"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
"github.com/cockroachdb/cockroach/pkg/sql/physicalplan"
"github.com/cockroachdb/cockroach/pkg/sql/row"
"github.com/cockroachdb/cockroach/pkg/sql/rowenc"
"github.com/cockroachdb/cockroach/pkg/sql/rowexec"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondatapb"
"github.com/cockroachdb/cockroach/pkg/sql/sqltelemetry"
"github.com/cockroachdb/cockroach/pkg/sql/types"
"github.com/cockroachdb/cockroach/pkg/util/contextutil"
"github.com/cockroachdb/cockroach/pkg/util/errorutil/unimplemented"
"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/ring"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/errors"
pbtypes "github.com/gogo/protobuf/types"
)
// To allow queries to send out flow RPCs in parallel, we use a pool of workers
// that can issue the RPCs on behalf of the running code. The pool is shared by
// multiple queries.
const numRunners = 16
const clientRejectedMsg string = "client rejected when attempting to run DistSQL plan"
// runnerRequest is the request that is sent (via a channel) to a worker.
type runnerRequest struct {
ctx context.Context
nodeDialer *nodedialer.Dialer
flowReq *execinfrapb.SetupFlowRequest
sqlInstanceID base.SQLInstanceID
resultChan chan<- runnerResult
}
// runnerResult is returned by a worker (via a channel) for each received
// request.
type runnerResult struct {
nodeID base.SQLInstanceID
err error
}
func (req runnerRequest) run() {
res := runnerResult{nodeID: req.sqlInstanceID}
conn, err := req.nodeDialer.Dial(req.ctx, roachpb.NodeID(req.sqlInstanceID), rpc.DefaultClass)
if err != nil {
res.err = err
} else {
client := execinfrapb.NewDistSQLClient(conn)
// TODO(radu): do we want a timeout here?
if sp := tracing.SpanFromContext(req.ctx); sp != nil && !sp.IsNoop() {
req.flowReq.TraceInfo = sp.Meta().ToProto()
}
resp, err := client.SetupFlow(req.ctx, req.flowReq)
if err != nil {
res.err = err
} else {
res.err = resp.Error.ErrorDetail(req.ctx)
}
}
req.resultChan <- res
}
func (dsp *DistSQLPlanner) initRunners(ctx context.Context) {
// This channel has to be unbuffered because we want to only be able to send
// requests if a worker is actually there to receive them.
dsp.runnerChan = make(chan runnerRequest)
for i := 0; i < numRunners; i++ {
_ = dsp.stopper.RunAsyncTask(ctx, "distsql-runner", func(context.Context) {
runnerChan := dsp.runnerChan
stopChan := dsp.stopper.ShouldQuiesce()
for {
select {
case req := <-runnerChan:
req.run()
case <-stopChan:
return
}
}
})
}
}
// To allow for canceling flows via CancelDeadFlows RPC on different nodes
// simultaneously, we use a pool of workers. It is likely that these workers
// will be less busy than SetupFlow runners, so we instantiate smaller number of
// the canceling workers.
const numCancelingWorkers = numRunners / 4
func (dsp *DistSQLPlanner) initCancelingWorkers(initCtx context.Context) {
dsp.cancelFlowsCoordinator.workerWait = make(chan struct{}, numCancelingWorkers)
const cancelRequestTimeout = 10 * time.Second
for i := 0; i < numCancelingWorkers; i++ {
workerID := i + 1
_ = dsp.stopper.RunAsyncTask(initCtx, "distsql-canceling-worker", func(parentCtx context.Context) {
stopChan := dsp.stopper.ShouldQuiesce()
for {
select {
case <-stopChan:
return
case <-dsp.cancelFlowsCoordinator.workerWait:
req, sqlInstanceID := dsp.cancelFlowsCoordinator.getFlowsToCancel()
if req == nil {
// There are no flows to cancel at the moment. This
// shouldn't really happen.
log.VEventf(parentCtx, 2, "worker %d woke up but didn't find any flows to cancel", workerID)
continue
}
log.VEventf(parentCtx, 2, "worker %d is canceling at most %d flows on node %d", workerID, len(req.FlowIDs), sqlInstanceID)
// TODO: Double check that we only ever cancel flows on SQL nodes/pods here.
conn, err := dsp.podNodeDialer.Dial(parentCtx, roachpb.NodeID(sqlInstanceID), rpc.DefaultClass)
if err != nil {
// We failed to dial the node, so we give up given that
// our cancellation is best effort. It is possible that
// the node is dead anyway.
continue
}
client := execinfrapb.NewDistSQLClient(conn)
_ = contextutil.RunWithTimeout(
parentCtx,
"cancel dead flows",
cancelRequestTimeout,
func(ctx context.Context) error {
_, _ = client.CancelDeadFlows(ctx, req)
return nil
})
}
}
})
}
}
type deadFlowsOnNode struct {
ids []execinfrapb.FlowID
sqlInstanceID base.SQLInstanceID
}
// cancelFlowsCoordinator is responsible for batching up the requests to cancel
// remote flows initiated on the behalf of the current node when the local flows
// errored out.
type cancelFlowsCoordinator struct {
mu struct {
syncutil.Mutex
// deadFlowsByNode is a ring of pointers to deadFlowsOnNode objects.
deadFlowsByNode ring.Buffer
}
// workerWait should be used by canceling workers to block until there are
// some dead flows to cancel.
workerWait chan struct{}
}
// getFlowsToCancel returns a request to cancel some dead flows on a particular
// node. If there are no dead flows to cancel, it returns nil, 0. Safe for
// concurrent usage.
func (c *cancelFlowsCoordinator) getFlowsToCancel() (
*execinfrapb.CancelDeadFlowsRequest,
base.SQLInstanceID,
) {
c.mu.Lock()
defer c.mu.Unlock()
if c.mu.deadFlowsByNode.Len() == 0 {
return nil, base.SQLInstanceID(0)
}
deadFlows := c.mu.deadFlowsByNode.GetFirst().(*deadFlowsOnNode)
c.mu.deadFlowsByNode.RemoveFirst()
req := &execinfrapb.CancelDeadFlowsRequest{
FlowIDs: deadFlows.ids,
}
return req, deadFlows.sqlInstanceID
}
// addFlowsToCancel adds all remote flows from flows map to be canceled via
// CancelDeadFlows RPC. Safe for concurrent usage.
func (c *cancelFlowsCoordinator) addFlowsToCancel(
flows map[base.SQLInstanceID]*execinfrapb.FlowSpec,
) {
c.mu.Lock()
for sqlInstanceID, f := range flows {
if sqlInstanceID != f.Gateway {
// c.mu.deadFlowsByNode.Len() is at most the number of nodes in the
// cluster, so a linear search for the node ID should be
// sufficiently fast.
found := false
for j := 0; j < c.mu.deadFlowsByNode.Len(); j++ {
deadFlows := c.mu.deadFlowsByNode.Get(j).(*deadFlowsOnNode)
if sqlInstanceID == deadFlows.sqlInstanceID {
deadFlows.ids = append(deadFlows.ids, f.FlowID)
found = true
break
}
}
if !found {
c.mu.deadFlowsByNode.AddLast(&deadFlowsOnNode{
ids: []execinfrapb.FlowID{f.FlowID},
sqlInstanceID: sqlInstanceID,
})
}
}
}
queueLength := c.mu.deadFlowsByNode.Len()
c.mu.Unlock()
// Notify the canceling workers that there are some flows to cancel (we send
// on the channel at most the length of the queue number of times in order
// to not wake up the workers uselessly). Note that we do it in a
// non-blocking fashion (because the workers might be busy canceling other
// flows at the moment). Also because the channel is buffered, they won't go
// to sleep once they are done.
numWorkersToWakeUp := numCancelingWorkers
if numWorkersToWakeUp > queueLength {
numWorkersToWakeUp = queueLength
}
for i := 0; i < numWorkersToWakeUp; i++ {
select {
case c.workerWait <- struct{}{}:
default:
// We have filled the buffer of the channel, so there is no need to
// try to send any more notifications.
return
}
}
}
// setupFlows sets up all the flows specified in flows using the provided state.
// It will first attempt to set up all remote flows using the dsp workers if
// available or sequentially if not, and then finally set up the gateway flow,
// whose output is the DistSQLReceiver provided. This flow is then returned to
// be run.
func (dsp *DistSQLPlanner) setupFlows(
ctx context.Context,
evalCtx *extendedEvalContext,
leafInputState *roachpb.LeafTxnInputState,
flows map[base.SQLInstanceID]*execinfrapb.FlowSpec,
recv *DistSQLReceiver,
localState distsql.LocalState,
collectStats bool,
statementSQL string,
) (context.Context, flowinfra.Flow, execinfra.OpChains, error) {
thisNodeID := dsp.gatewaySQLInstanceID
_, ok := flows[thisNodeID]
if !ok {
return nil, nil, nil, errors.AssertionFailedf("missing gateway flow")
}
if localState.IsLocal && len(flows) != 1 {
return nil, nil, nil, errors.AssertionFailedf("IsLocal set but there's multiple flows")
}
const setupFlowRequestStmtMaxLength = 500
if len(statementSQL) > setupFlowRequestStmtMaxLength {
statementSQL = statementSQL[:setupFlowRequestStmtMaxLength]
}
setupReq := execinfrapb.SetupFlowRequest{
LeafTxnInputState: leafInputState,
Version: execinfra.Version,
EvalContext: execinfrapb.MakeEvalContext(&evalCtx.EvalContext),
TraceKV: evalCtx.Tracing.KVTracingEnabled(),
CollectStats: collectStats,
StatementSQL: statementSQL,
}
// Start all the flows except the flow on this node (there is always a flow on
// this node).
var resultChan chan runnerResult
if len(flows) > 1 {
resultChan = make(chan runnerResult, len(flows)-1)
}
if vectorizeMode := evalCtx.SessionData().VectorizeMode; vectorizeMode != sessiondatapb.VectorizeOff {
// Now we determine whether the vectorized engine supports the flow
// specs.
for _, spec := range flows {
if err := colflow.IsSupported(vectorizeMode, spec); err != nil {
log.VEventf(ctx, 2, "failed to vectorize: %s", err)
if vectorizeMode == sessiondatapb.VectorizeExperimentalAlways {
return nil, nil, nil, err
}
// Vectorization is not supported for this flow, so we override the
// setting.
setupReq.EvalContext.SessionData.VectorizeMode = sessiondatapb.VectorizeOff
break
}
}
}
for nodeID, flowSpec := range flows {
if nodeID == thisNodeID {
// Skip this node.
continue
}
req := setupReq
req.Flow = *flowSpec
runReq := runnerRequest{
ctx: ctx,
nodeDialer: dsp.podNodeDialer,
flowReq: &req,
sqlInstanceID: nodeID,
resultChan: resultChan,
}
// Send out a request to the workers; if no worker is available, run
// directly.
select {
case dsp.runnerChan <- runReq:
default:
runReq.run()
}
}
var firstErr error
// Now wait for all the flows to be scheduled on remote nodes. Note that we
// are not waiting for the flows themselves to complete.
for i := 0; i < len(flows)-1; i++ {
res := <-resultChan
if firstErr == nil {
firstErr = res.err
}
// TODO(radu): accumulate the flows that we failed to set up and move them
// into the local flow.
}
if firstErr != nil {
return nil, nil, nil, firstErr
}
// Set up the flow on this node.
setupReq.Flow = *flows[thisNodeID]
var batchReceiver execinfra.BatchReceiver
if recv.batchWriter != nil {
// Use the DistSQLReceiver as an execinfra.BatchReceiver only if the
// former has the corresponding writer set.
batchReceiver = recv
}
return dsp.distSQLSrv.SetupLocalSyncFlow(ctx, evalCtx.Mon, &setupReq, recv, batchReceiver, localState)
}
// Run executes a physical plan. The plan should have been finalized using
// FinalizePlan.
//
// All errors encountered are reported to the DistSQLReceiver's resultWriter.
// Additionally, if the error is a "communication error" (an error encountered
// while using that resultWriter), the error is also stored in
// DistSQLReceiver.commErr. That can be tested to see if a client session needs
// to be closed.
//
// Args:
// - txn is the transaction in which the plan will run. If nil, the different
// processors are expected to manage their own internal transactions.
// - evalCtx is the evaluation context in which the plan will run. It might be
// mutated.
// - finishedSetupFn, if non-nil, is called synchronously after all the
// processors have successfully started up.
//
// It returns a non-nil (although it can be a noop when an error is
// encountered) cleanup function that must be called in order to release the
// resources.
func (dsp *DistSQLPlanner) Run(
ctx context.Context,
planCtx *PlanningCtx,
txn *kv.Txn,
plan *PhysicalPlan,
recv *DistSQLReceiver,
evalCtx *extendedEvalContext,
finishedSetupFn func(),
) (cleanup func()) {
cleanup = func() {}
flows := plan.GenerateFlowSpecs()
defer func() {
for _, flowSpec := range flows {
physicalplan.ReleaseFlowSpec(flowSpec)
}
}()
if _, ok := flows[dsp.gatewaySQLInstanceID]; !ok {
recv.SetError(errors.Errorf("expected to find gateway flow"))
return cleanup
}
var (
localState distsql.LocalState
leafInputState *roachpb.LeafTxnInputState
)
// NB: putting part of evalCtx in localState means it might be mutated down
// the line.
localState.EvalContext = &evalCtx.EvalContext
localState.Txn = txn
localState.LocalProcs = plan.LocalProcessors
// If we need to perform some operation on the flow specs, we want to
// preserve the specs during the flow setup.
localState.PreserveFlowSpecs = planCtx.saveFlows != nil
// If we have access to a planner and are currently being used to plan
// statements in a user transaction, then take the descs.Collection to resolve
// types with during flow execution. This is necessary to do in the case of
// a transaction that has already created or updated some types. If we do not
// use the local descs.Collection, we would attempt to acquire a lease on
// modified types when accessing them, which would error out.
if planCtx.planner != nil && !planCtx.planner.isInternalPlanner {
localState.Collection = planCtx.planner.Descriptors()
}
// noMutations indicates whether we know for sure that the plan doesn't have
// any mutations. If we don't have the access to the planner (which can be
// the case not on the main query execution path, i.e. BulkIO, CDC, etc),
// then we are ignorant of the details of the execution plan, so we choose
// to be on the safe side and mark 'noMutations' as 'false'.
noMutations := planCtx.planner != nil && !planCtx.planner.curPlan.flags.IsSet(planFlagContainsMutation)
if planCtx.isLocal {
localState.IsLocal = true
if noMutations && planCtx.parallelizeScansIfLocal {
// Even though we have a single flow on the gateway node, we might
// have decided to parallelize the scans. If that's the case, we
// will need to use the Leaf txn.
for _, flow := range flows {
localState.HasConcurrency = localState.HasConcurrency || execinfra.HasParallelProcessors(flow)
}
}
}
if noMutations {
// Even if planCtx.isLocal is false (which is the case when we think
// it's worth distributing the query), we need to go through the
// processors to figure out whether any of them have concurrency.
//
// However, the concurrency requires the usage of LeafTxns which is only
// acceptable if we don't have any mutations in the plan.
// TODO(yuzefovich): we could be smarter here and allow the usage of the
// RootTxn by the mutations while still using the Streamer (that gets a
// LeafTxn) iff the plan is such that there is no concurrency between
// the root and the leaf txns.
//
// At the moment of writing, this is only relevant whenever the Streamer
// API might be used by some of the processors. The Streamer internally
// can have concurrency, so it expects to be given a LeafTxn. In order
// for that LeafTxn to be created later, during the flow setup, we need
// to populate leafInputState below, so we tell the localState that
// there is concurrency.
if row.CanUseStreamer(ctx, dsp.st) {
for _, proc := range plan.Processors {
if jr := proc.Spec.Core.JoinReader; jr != nil {
if jr.IsIndexJoin() {
// Index joins are executed via the Streamer API that has
// concurrency.
localState.HasConcurrency = true
break
}
}
}
}
}
if localState.MustUseLeafTxn() && txn != nil {
// Set up leaf txns using the txnCoordMeta if we need to.
tis, err := txn.GetLeafTxnInputStateOrRejectClient(ctx)
if err != nil {
log.Infof(ctx, "%s: %s", clientRejectedMsg, err)
recv.SetError(err)
return cleanup
}
leafInputState = tis
}
if logPlanDiagram {
log.VEvent(ctx, 3, "creating plan diagram for logging")
var stmtStr string
if planCtx.planner != nil && planCtx.planner.stmt.AST != nil {
stmtStr = planCtx.planner.stmt.String()
}
_, url, err := execinfrapb.GeneratePlanDiagramURL(stmtStr, flows, execinfrapb.DiagramFlags{})
if err != nil {
log.Infof(ctx, "error generating diagram: %s", err)
} else {
log.Infof(ctx, "plan diagram URL:\n%s", url.String())
}
}
log.VEvent(ctx, 2, "running DistSQL plan")
dsp.distSQLSrv.ServerConfig.Metrics.QueryStart()
defer dsp.distSQLSrv.ServerConfig.Metrics.QueryStop()
recv.outputTypes = plan.GetResultTypes()
recv.contendedQueryMetric = dsp.distSQLSrv.Metrics.ContendedQueriesCount
if len(flows) == 1 {
// We ended up planning everything locally, regardless of whether we
// intended to distribute or not.
localState.IsLocal = true
} else {
defer func() {
if recv.resultWriter.Err() != nil {
// The execution of this query encountered some error, so we
// will eagerly cancel all scheduled flows on the remote nodes
// (if they haven't been started yet) because they are now dead.
// TODO(yuzefovich): consider whether augmenting
// ConnectInboundStream to keep track of the streams that
// initiated FlowStream RPC is worth it - the flows containing
// such streams must have been started, so there is no point in
// trying to cancel them this way. This will allow us to reduce
// the size of the CancelDeadFlows request and speed up the
// lookup on the remote node whether a particular dead flow
// should be canceled. However, this improves the unhappy case,
// but it'll slowdown the happy case - by introducing additional
// tracking.
dsp.cancelFlowsCoordinator.addFlowsToCancel(flows)
}
}()
}
// Currently, we get the statement only if there is a planner available in
// the planCtx which is the case only on the "main" query path (for
// user-issued queries).
// TODO(yuzefovich): propagate the statement in all cases.
var statementSQL string
if planCtx.planner != nil {
statementSQL = planCtx.planner.stmt.StmtNoConstants
}
ctx, flow, opChains, err := dsp.setupFlows(
ctx, evalCtx, leafInputState, flows, recv, localState, planCtx.collectExecStats, statementSQL,
)
// Make sure that the local flow is always cleaned up if it was created.
if flow != nil {
cleanup = func() {
flow.Cleanup(ctx)
}
}
if err != nil {
recv.SetError(err)
return cleanup
}
if finishedSetupFn != nil {
finishedSetupFn()
}
if planCtx.planner != nil && flow.IsVectorized() {
planCtx.planner.curPlan.flags.Set(planFlagVectorized)
}
if planCtx.saveFlows != nil {
if err := planCtx.saveFlows(flows, opChains); err != nil {
recv.SetError(err)
return cleanup
}
}
// Check that flows that were forced to be planned locally and didn't need
// to have concurrency don't actually have it.
//
// This is important, since these flows are forced to use the RootTxn (since
// they might have mutations), and the RootTxn does not permit concurrency.
// For such flows, we were supposed to have fused everything.
if txn != nil && !localState.MustUseLeafTxn() && flow.ConcurrentTxnUse() {
recv.SetError(errors.AssertionFailedf(
"unexpected concurrency for a flow that was forced to be planned locally"))
return cleanup
}
// TODO(radu): this should go through the flow scheduler.
flow.Run(ctx, func() {})
// TODO(yuzefovich): it feels like this closing should happen after
// PlanAndRun. We should refactor this and get rid off ignoreClose field.
if planCtx.planner != nil && !planCtx.ignoreClose {
// planCtx can change before the cleanup function is executed, so we make
// a copy of the planner and bind it to the function.
curPlan := &planCtx.planner.curPlan
return func() {
// We need to close the planNode tree we translated into a DistSQL plan
// before flow.Cleanup, which closes memory accounts that expect to be
// emptied.
curPlan.close(ctx)
flow.Cleanup(ctx)
}
}
// ignoreClose is set to true meaning that someone else will handle the
// closing of the current plan, so we simply clean up the flow.
return cleanup
}
// DistSQLReceiver is an execinfra.RowReceiver and execinfra.BatchReceiver that
// writes results to a rowResultWriter and batchResultWriter, respectively. This
// is where the DistSQL execution meets the SQL Session - the result writer
// comes from a client Session.
//
// DistSQLReceiver also update the RangeDescriptorCache in response to DistSQL
// metadata about misplanned ranges.
type DistSQLReceiver struct {
ctx context.Context
// These two interfaces refer to the same object, but batchWriter might be
// unset (resultWriter is always set). These are used to send the results
// to.
resultWriter rowResultWriter
batchWriter batchResultWriter
stmtType tree.StatementReturnType
// outputTypes are the types of the result columns produced by the plan.
outputTypes []*types.T
// existsMode indicates that the caller is only interested in the existence
// of a single row. Used by subqueries in EXISTS mode.
existsMode bool
// discardRows is set when we want to discard rows (for testing/benchmarks).
// See EXECUTE .. DISCARD ROWS.
discardRows bool
// commErr keeps track of the error received from interacting with the
// resultWriter. This represents a "communication error" and as such is unlike
// query execution errors: when the DistSQLReceiver is used within a SQL
// session, such errors mean that we have to bail on the session.
// Query execution errors are reported to the resultWriter. For some client's
// convenience, communication errors are also reported to the resultWriter.
//
// Once set, no more rows are accepted.
commErr error
row tree.Datums
status execinfra.ConsumerStatus
alloc tree.DatumAlloc
closed bool
rangeCache *rangecache.RangeCache
tracing *SessionTracing
// cleanup will be called when the DistSQLReceiver is Release()'d back to
// its sync.Pool.
cleanup func()
// The transaction in which the flow producing data for this
// receiver runs. The DistSQLReceiver updates the transaction in
// response to RetryableTxnError's and when distributed processors
// pass back LeafTxnFinalState objects via ProducerMetas. Nil if no
// transaction should be updated on errors (i.e. if the flow overall
// doesn't run in a transaction).
txn *kv.Txn
// A handler for clock signals arriving from remote nodes. This should update
// this node's clock.
clockUpdater clockUpdater
stats *topLevelQueryStats
expectedRowsRead int64
progressAtomic *uint64
// contendedQueryMetric is a Counter that is incremented at most once if the
// query produces at least one contention event.
contendedQueryMetric *metric.Counter
// contentionRegistry is a Registry that contention events are added to.
contentionRegistry *contention.Registry
testingKnobs struct {
// pushCallback, if set, will be called every time DistSQLReceiver.Push
// is called, with the same arguments.
pushCallback func(rowenc.EncDatumRow, *execinfrapb.ProducerMetadata)
}
}
// rowResultWriter is a subset of CommandResult to be used with the
// DistSQLReceiver. It's implemented by RowResultWriter.
type rowResultWriter interface {
// AddRow writes a result row.
// Note that the caller owns the row slice and might reuse it.
AddRow(ctx context.Context, row tree.Datums) error
IncrementRowsAffected(ctx context.Context, n int)
SetError(error)
Err() error
}
// batchResultWriter is a subset of CommandResult to be used with the
// DistSQLReceiver when the consumer can operate on columnar batches directly.
type batchResultWriter interface {
AddBatch(context.Context, coldata.Batch) error
}
// MetadataResultWriter is used to stream metadata rather than row results in a
// DistSQL flow.
type MetadataResultWriter interface {
AddMeta(ctx context.Context, meta *execinfrapb.ProducerMetadata)
}
// MetadataCallbackWriter wraps a rowResultWriter to stream metadata in a
// DistSQL flow. It executes a given callback when metadata is added.
type MetadataCallbackWriter struct {
rowResultWriter
fn func(ctx context.Context, meta *execinfrapb.ProducerMetadata) error
}
// AddMeta implements the MetadataResultWriter interface.
func (w *MetadataCallbackWriter) AddMeta(ctx context.Context, meta *execinfrapb.ProducerMetadata) {
if err := w.fn(ctx, meta); err != nil {
w.SetError(err)
}
}
// NewMetadataCallbackWriter creates a new MetadataCallbackWriter.
func NewMetadataCallbackWriter(
rowResultWriter rowResultWriter,
metaFn func(ctx context.Context, meta *execinfrapb.ProducerMetadata) error,
) *MetadataCallbackWriter {
return &MetadataCallbackWriter{rowResultWriter: rowResultWriter, fn: metaFn}
}
// errOnlyResultWriter is a rowResultWriter and batchResultWriter that only
// supports receiving an error. All other functions that deal with producing
// results panic.
type errOnlyResultWriter struct {
err error
}
var _ rowResultWriter = &errOnlyResultWriter{}
var _ batchResultWriter = &errOnlyResultWriter{}
func (w *errOnlyResultWriter) SetError(err error) {
w.err = err
}
func (w *errOnlyResultWriter) Err() error {
return w.err
}
func (w *errOnlyResultWriter) AddRow(ctx context.Context, row tree.Datums) error {
panic("AddRow not supported by errOnlyResultWriter")
}
func (w *errOnlyResultWriter) AddBatch(ctx context.Context, batch coldata.Batch) error {
panic("AddBatch not supported by errOnlyResultWriter")
}
func (w *errOnlyResultWriter) IncrementRowsAffected(ctx context.Context, n int) {
panic("IncrementRowsAffected not supported by errOnlyResultWriter")
}
// RowResultWriter is a thin wrapper around a RowContainer.
type RowResultWriter struct {
rowContainer *rowContainerHelper
rowsAffected int
err error
}
var _ rowResultWriter = &RowResultWriter{}
// NewRowResultWriter creates a new RowResultWriter.
func NewRowResultWriter(rowContainer *rowContainerHelper) *RowResultWriter {
return &RowResultWriter{rowContainer: rowContainer}
}
// IncrementRowsAffected implements the rowResultWriter interface.
func (b *RowResultWriter) IncrementRowsAffected(ctx context.Context, n int) {
b.rowsAffected += n
}
// AddRow implements the rowResultWriter interface.
func (b *RowResultWriter) AddRow(ctx context.Context, row tree.Datums) error {
if b.rowContainer != nil {
return b.rowContainer.AddRow(ctx, row)
}
return nil
}
// SetError is part of the rowResultWriter interface.
func (b *RowResultWriter) SetError(err error) {
b.err = err
}
// Err is part of the rowResultWriter interface.
func (b *RowResultWriter) Err() error {
return b.err
}
// CallbackResultWriter is a rowResultWriter that runs a callback function
// on AddRow.
type CallbackResultWriter struct {
fn func(ctx context.Context, row tree.Datums) error
rowsAffected int
err error
}
var _ rowResultWriter = &CallbackResultWriter{}
// NewCallbackResultWriter creates a new CallbackResultWriter.
func NewCallbackResultWriter(
fn func(ctx context.Context, row tree.Datums) error,
) *CallbackResultWriter {
return &CallbackResultWriter{fn: fn}
}
// IncrementRowsAffected is part of the rowResultWriter interface.
func (c *CallbackResultWriter) IncrementRowsAffected(ctx context.Context, n int) {
c.rowsAffected += n
}
// AddRow is part of the rowResultWriter interface.
func (c *CallbackResultWriter) AddRow(ctx context.Context, row tree.Datums) error {
return c.fn(ctx, row)
}
// SetError is part of the rowResultWriter interface.
func (c *CallbackResultWriter) SetError(err error) {
c.err = err
}
// Err is part of the rowResultWriter interface.
func (c *CallbackResultWriter) Err() error {
return c.err
}
var _ execinfra.RowReceiver = &DistSQLReceiver{}
var _ execinfra.BatchReceiver = &DistSQLReceiver{}
var receiverSyncPool = sync.Pool{
New: func() interface{} {
return &DistSQLReceiver{}
},
}
// ClockUpdater describes an object that can be updated with an observed
// timestamp. Usually wraps an hlc.Clock.
type clockUpdater interface {
// Update updates this ClockUpdater with the observed hlc.Timestamp.
Update(observedTS hlc.ClockTimestamp)
}
// MakeDistSQLReceiver creates a DistSQLReceiver.
//
// ctx is the Context that the receiver will use throughout its
// lifetime. resultWriter is the container where the results will be
// stored. If only the row count is needed, this can be nil.
//
// txn is the transaction in which the producer flow runs; it will be updated
// on errors. Nil if the flow overall doesn't run in a transaction.
func MakeDistSQLReceiver(
ctx context.Context,
resultWriter rowResultWriter,
stmtType tree.StatementReturnType,
rangeCache *rangecache.RangeCache,
txn *kv.Txn,
clockUpdater clockUpdater,
tracing *SessionTracing,
contentionRegistry *contention.Registry,
testingPushCallback func(rowenc.EncDatumRow, *execinfrapb.ProducerMetadata),
) *DistSQLReceiver {
consumeCtx, cleanup := tracing.TraceExecConsume(ctx)
r := receiverSyncPool.Get().(*DistSQLReceiver)
// Check whether the result writer supports pushing batches into it directly
// without having to materialize them.
var batchWriter batchResultWriter
if commandResult, ok := resultWriter.(RestrictedCommandResult); ok {
if commandResult.SupportsAddBatch() {
batchWriter = commandResult
}
}
*r = DistSQLReceiver{
ctx: consumeCtx,
cleanup: cleanup,
resultWriter: resultWriter,
batchWriter: batchWriter,
rangeCache: rangeCache,
txn: txn,
clockUpdater: clockUpdater,
stats: &topLevelQueryStats{},
stmtType: stmtType,
tracing: tracing,
contentionRegistry: contentionRegistry,
}
r.testingKnobs.pushCallback = testingPushCallback
return r
}
// Release releases this DistSQLReceiver back to the pool.
func (r *DistSQLReceiver) Release() {
r.cleanup()
*r = DistSQLReceiver{}
receiverSyncPool.Put(r)
}
// clone clones the receiver for running sub- and post-queries. Not all fields
// are cloned. The receiver should be released when no longer needed.
func (r *DistSQLReceiver) clone() *DistSQLReceiver {
ret := receiverSyncPool.Get().(*DistSQLReceiver)
*ret = DistSQLReceiver{
ctx: r.ctx,
cleanup: func() {},
rangeCache: r.rangeCache,
txn: r.txn,
clockUpdater: r.clockUpdater,
stats: r.stats,
stmtType: tree.Rows,
tracing: r.tracing,
contentionRegistry: r.contentionRegistry,
}
return ret
}
// SetError provides a convenient way for a client to pass in an error, thus
// pretending that a query execution error happened. The error is passed along
// to the resultWriter.
//
// The status of DistSQLReceiver is updated accordingly.
func (r *DistSQLReceiver) SetError(err error) {
r.resultWriter.SetError(err)
// If we encountered an error, we will transition to draining unless we were
// canceled.
if r.ctx.Err() != nil {
log.VEventf(r.ctx, 1, "encountered error (transitioning to shutting down): %v", r.ctx.Err())
r.status = execinfra.ConsumerClosed
} else {
log.VEventf(r.ctx, 1, "encountered error (transitioning to draining): %v", err)
r.status = execinfra.DrainRequested
}
}
// pushMeta takes in non-empty metadata object and pushes it to the result
// writer. Possibly updated status is returned.
func (r *DistSQLReceiver) pushMeta(meta *execinfrapb.ProducerMetadata) execinfra.ConsumerStatus {
if metaWriter, ok := r.resultWriter.(MetadataResultWriter); ok {
metaWriter.AddMeta(r.ctx, meta)
}
if meta.LeafTxnFinalState != nil {
if r.txn != nil {
if r.txn.ID() == meta.LeafTxnFinalState.Txn.ID {
if err := r.txn.UpdateRootWithLeafFinalState(r.ctx, meta.LeafTxnFinalState); err != nil {
r.SetError(err)
}
}
} else {
r.SetError(
errors.Errorf("received a leaf final state (%s); but have no root", meta.LeafTxnFinalState))
}
}
if meta.Err != nil {
// Check if the error we just received should take precedence over a
// previous error (if any).
if roachpb.ErrPriority(meta.Err) > roachpb.ErrPriority(r.resultWriter.Err()) {
if r.txn != nil {
if retryErr := (*roachpb.UnhandledRetryableError)(nil); errors.As(meta.Err, &retryErr) {
// Update the txn in response to remote errors. In the non-DistSQL
// world, the TxnCoordSender handles "unhandled" retryable errors,
// but this one is coming from a distributed SQL node, which has
// left the handling up to the root transaction.
meta.Err = r.txn.UpdateStateOnRemoteRetryableErr(r.ctx, &retryErr.PErr)
// Update the clock with information from the error. On non-DistSQL
// code paths, the DistSender does this.
// TODO(andrei): We don't propagate clock signals on success cases
// through DistSQL; we should. We also don't propagate them through
// non-retryable errors; we also should.
if r.clockUpdater != nil {
r.clockUpdater.Update(retryErr.PErr.Now)
}
}
}
r.SetError(meta.Err)
}
}
if len(meta.Ranges) > 0 {
r.rangeCache.Insert(r.ctx, meta.Ranges...)
}
if len(meta.TraceData) > 0 {
if span := tracing.SpanFromContext(r.ctx); span != nil {
span.ImportRemoteSpans(meta.TraceData)
}