-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
distsql_running.go
2308 lines (2148 loc) · 81.5 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"
"runtime"
"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/kv/kvpb"
"github.com/cockroachdb/cockroach/pkg/multitenant"
"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/settings"
"github.com/cockroachdb/cockroach/pkg/sql/colflow"
"github.com/cockroachdb/cockroach/pkg/sql/distsql"
"github.com/cockroachdb/cockroach/pkg/sql/execinfra"
"github.com/cockroachdb/cockroach/pkg/sql/execinfra/execopnode"
"github.com/cockroachdb/cockroach/pkg/sql/execinfrapb"
"github.com/cockroachdb/cockroach/pkg/sql/flowinfra"
"github.com/cockroachdb/cockroach/pkg/sql/opt/exec"
"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/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/mon"
"github.com/cockroachdb/cockroach/pkg/util/ring"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/tracing"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/logtags"
)
var settingDistSQLNumRunners = settings.RegisterIntSetting(
settings.TenantWritable,
"sql.distsql.num_runners",
"determines the number of DistSQL runner goroutines used for issuing SetupFlow RPCs",
// We use GOMAXPROCS instead of NumCPU because the former could be adjusted
// based on cgroup limits (see cgroups.AdjustMaxProcs).
//
// The choice of the default multiple of 4 was made in order to get the
// original value of 16 on machines with 4 CPUs.
4*int64(runtime.GOMAXPROCS(0)), /* defaultValue */
func(v int64) error {
if v < 0 {
return errors.Errorf("cannot be set to a negative value: %d", v)
}
if v > distSQLNumRunnersMax {
return errors.Errorf("cannot be set to a value exceeding %d: %d", distSQLNumRunnersMax, v)
}
return nil
},
)
// Somewhat arbitrary upper bound.
var distSQLNumRunnersMax = 256 * int64(runtime.GOMAXPROCS(0))
// runnerRequest is the request that is sent (via a channel) to a worker.
type runnerRequest struct {
ctx context.Context
podNodeDialer *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
}
// run executes the request. An error, if encountered, is both sent on the
// result channel and returned.
func (req runnerRequest) run() error {
res := runnerResult{nodeID: req.sqlInstanceID}
defer func() {
req.resultChan <- res
physicalplan.ReleaseFlowSpec(&req.flowReq.Flow)
}()
conn, err := req.podNodeDialer.Dial(req.ctx, roachpb.NodeID(req.sqlInstanceID), rpc.DefaultClass)
if err != nil {
res.err = err
return err
}
client := execinfrapb.NewDistSQLClient(conn)
// TODO(radu): do we want a timeout here?
resp, err := client.SetupFlow(req.ctx, req.flowReq)
if err != nil {
res.err = err
} else {
res.err = resp.Error.ErrorDetail(req.ctx)
}
return res.err
}
type runnerCoordinator struct {
// runnerChan is used by the DistSQLPlanner to send out requests (for
// running SetupFlow RPCs) to a pool of workers.
runnerChan chan runnerRequest
// newDesiredNumWorkers is used to notify the coordinator that the size of
// the pool of workers might have changed.
newDesiredNumWorkers chan int64
atomics struct {
// numWorkers tracks the number of workers running at the moment. This
// needs to be accessed atomically, but only because of the usage in
// tests.
numWorkers int64
}
}
func (c *runnerCoordinator) init(ctx context.Context, stopper *stop.Stopper, sv *settings.Values) {
// 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.
c.runnerChan = make(chan runnerRequest)
stopWorkerChan := make(chan struct{})
worker := func(context.Context) {
for {
select {
case req := <-c.runnerChan:
_ = req.run()
case <-stopWorkerChan:
return
}
}
}
stopChan := stopper.ShouldQuiesce()
// This is a buffered channel because we will be sending on it from the
// callback when the corresponding setting changes. The buffer size of 1
// should be sufficient, but we use a larger buffer out of caution (in case
// the cluster setting is updated rapidly) - in order to not block the
// goroutine that is updating the settings.
c.newDesiredNumWorkers = make(chan int64, 4)
// setNewNumWorkers sets the new target size of the pool of workers.
setNewNumWorkers := func(newNumWorkers int64) {
select {
case c.newDesiredNumWorkers <- newNumWorkers:
case <-stopChan:
// If the server is quescing, then the new size of the pool doesn't
// matter.
return
}
}
// Whenever the corresponding setting is updated, we need to notify the
// coordinator.
// NB: runnerCoordinator.init is called once per server lifetime so this
// won't leak an unbounded number of OnChange callbacks.
settingDistSQLNumRunners.SetOnChange(sv, func(ctx context.Context) {
setNewNumWorkers(settingDistSQLNumRunners.Get(sv))
})
// We need to set the target pool size based on the current setting
// explicitly since the OnChange callback won't ever be called for the
// initial value - the setting initialization has already been performed
// before we registered the OnChange callback.
setNewNumWorkers(settingDistSQLNumRunners.Get(sv))
// Spin up the coordinator goroutine.
_ = stopper.RunAsyncTask(ctx, "distsql-runner-coordinator", func(context.Context) {
// Make sure to stop all workers when the coordinator exits.
defer close(stopWorkerChan)
for {
select {
case newNumWorkers := <-c.newDesiredNumWorkers:
for {
numWorkers := atomic.LoadInt64(&c.atomics.numWorkers)
if numWorkers == newNumWorkers {
break
}
if numWorkers < newNumWorkers {
// Need to spin another worker.
err := stopper.RunAsyncTask(ctx, "distsql-runner", worker)
if err != nil {
return
}
atomic.AddInt64(&c.atomics.numWorkers, 1)
} else {
// Need to stop one of the workers.
select {
case stopWorkerChan <- struct{}{}:
atomic.AddInt64(&c.atomics.numWorkers, -1)
case <-stopChan:
return
}
}
}
case <-stopChan:
return
}
}
})
}
// To allow for canceling flows via CancelDeadFlows RPC on different nodes
// simultaneously, we use a pool of workers.
const numCancelingWorkers = 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.
//
// This mechanism is used in addition to the cancellation that occurs when the
// gRPC streams are closed between nodes, which happens when the query errors
// out. This mechanism works on the best-effort basis.
type cancelFlowsCoordinator struct {
mu struct {
syncutil.Mutex
// deadFlowsByNode is a ring of pointers to deadFlowsOnNode objects.
deadFlowsByNode ring.Buffer[*deadFlowsOnNode]
}
// 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()
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)
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 the gateway flow (whose output is the
// DistSQLReceiver provided) and - if successful - will proceed to setting up
// the remote flows using the dsp workers if available or sequentially if not.
//
// The gateway flow is returned to be Run(). It is the caller's responsibility
// to clean up that flow if a non-nil value is returned.
//
// The method doesn't wait for the setup of remote flows (if any) to return and,
// instead, optimistically proceeds once the corresponding SetupFlow RPCs are
// issued. A separate goroutine is spun up to listen for the RPCs to come back,
// and if the setup of a remote flow fails, then that goroutine updates the
// DistSQLReceiver with the error and cancels the gateway flow.
func (dsp *DistSQLPlanner) setupFlows(
ctx context.Context,
evalCtx *extendedEvalContext,
planCtx *PlanningCtx,
leafInputState *roachpb.LeafTxnInputState,
flows map[base.SQLInstanceID]*execinfrapb.FlowSpec,
recv *DistSQLReceiver,
localState distsql.LocalState,
statementSQL string,
) (context.Context, flowinfra.Flow, error) {
thisNodeID := dsp.gatewaySQLInstanceID
_, ok := flows[thisNodeID]
if !ok {
return nil, nil, errors.AssertionFailedf("missing gateway flow")
}
if localState.IsLocal && len(flows) != 1 {
return nil, nil, errors.AssertionFailedf("IsLocal set but there's multiple flows")
}
const setupFlowRequestStmtMaxLength = 500
if len(statementSQL) > setupFlowRequestStmtMaxLength {
statementSQL = statementSQL[:setupFlowRequestStmtMaxLength]
}
getJobTag := func(ctx context.Context) string {
tags := logtags.FromContext(ctx)
if tags != nil {
for _, tag := range tags.Get() {
if tag.Key() == "job" {
return tag.ValueStr()
}
}
}
return ""
}
setupReq := execinfrapb.SetupFlowRequest{
// TODO(yuzefovich): avoid populating some fields of the SetupFlowRequest
// for local plans.
LeafTxnInputState: leafInputState,
Version: execinfra.Version,
EvalContext: execinfrapb.MakeEvalContext(&evalCtx.Context),
TraceKV: evalCtx.Tracing.KVTracingEnabled(),
CollectStats: planCtx.collectExecStats,
StatementSQL: statementSQL,
JobTag: getJobTag(ctx),
}
var isVectorized bool
if vectorizeMode := evalCtx.SessionData().VectorizeMode; vectorizeMode != sessiondatapb.VectorizeOff {
// Now we determine whether the vectorized engine supports the flow
// specs.
isVectorized = true
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, err
}
// Vectorization is not supported for this flow, so we override
// the setting.
setupReq.EvalContext.SessionData.VectorizeMode = sessiondatapb.VectorizeOff
isVectorized = false
break
}
}
}
if !planCtx.subOrPostQuery && planCtx.planner != nil && isVectorized {
// Only set the vectorized flag for the main query (to be consistent
// with the 'vectorized' attribute of the EXPLAIN output).
planCtx.planner.curPlan.flags.Set(planFlagVectorized)
}
// First, set up the flow on this node.
setupReq.Flow = *flows[thisNodeID]
var batchReceiver execinfra.BatchReceiver
if recv.resultWriterMu.batch != nil {
// Use the DistSQLReceiver as an execinfra.BatchReceiver only if the
// former has the corresponding writer set.
batchReceiver = recv
}
origCtx := ctx
ctx, flow, opChains, err := dsp.distSQLSrv.SetupLocalSyncFlow(ctx, evalCtx.Planner.Mon(), &setupReq, recv, batchReceiver, localState)
if err == nil && planCtx.saveFlows != nil {
err = planCtx.saveFlows(flows, opChains, isVectorized)
}
if len(flows) == 1 || err != nil {
// If there are no remote flows, or we fail to set up the local flow, we
// can just short-circuit.
//
// Note that we need to return the local flow even if err is non-nil so
// that the local flow is properly cleaned up.
return ctx, flow, err
}
// Start all the remote flows.
//
// usedWorker indicates whether we used at least one DistSQL worker
// goroutine to issue the SetupFlow RPC.
var usedWorker bool
// numIssuedRequests tracks the number of the SetupFlow RPCs that were
// issued (either by the current goroutine directly or delegated to the
// DistSQL workers).
var numIssuedRequests int
if sp := tracing.SpanFromContext(origCtx); sp != nil && !sp.IsNoop() {
setupReq.TraceInfo = sp.Meta().ToProto()
}
resultChan := make(chan runnerResult, len(flows)-1)
// We use a separate context for the runnerRequests so that - in case they
// are issued concurrently and some RPCs are actually run after the current
// goroutine performs Flow.Cleanup() on the local flow - DistSQL workers
// don't attempt to reuse already finished tracing span from the local flow
// context. For the same reason we can't use origCtx (parent of the local
// flow context).
//
// In particular, consider the following scenario:
// - a runnerRequest is handled by the DistSQL worker;
// - in runnerRequest.run() the worker dials the remote node and issues the
// SetupFlow RPC. However, the client-side goroutine of that RPC is not
// yet scheduled on the local node;
// - the local flow runs to completion canceling the context and finishing
// the tracing span;
// - now the client-side goroutine of the RPC is scheduled, and it attempts
// to use the span from the context, but it has already been finished.
runnerCtx, cancelRunnerCtx := context.WithCancel(origCtx)
var runnerSpan *tracing.Span
// This span is necessary because it can outlive its parent.
runnerCtx, runnerSpan = tracing.ChildSpan(runnerCtx, "setup-flow-async" /* opName */)
// runnerCleanup can only be executed _after_ all issued RPCs are complete.
runnerCleanup := func() {
cancelRunnerCtx()
runnerSpan.Finish()
}
// Make sure that we call runnerCleanup unless a new goroutine takes that
// responsibility.
var listenerGoroutineWillCleanup bool
defer func() {
if !listenerGoroutineWillCleanup {
// Make sure to receive from the result channel as many times as
// there were total SetupFlow RPCs issued, regardless of whether
// they were executed concurrently by a DistSQL worker or serially
// in the current goroutine. This is needed in order to block
// finishing the runner span (in runnerCleanup) until all concurrent
// requests are done since the runner span is used as the parent for
// the RPC span, and, thus, the runner span can only be finished
// when we know that all SetupFlow RPCs have already been completed.
//
// Note that even in case of an error in runnerRequest.run we still
// send on the result channel.
for i := 0; i < numIssuedRequests; i++ {
<-resultChan
}
// At this point, we know that all concurrent requests (if there
// were any) are complete, so we can safely perform the runner
// cleanup.
runnerCleanup()
}
}()
for nodeID, flowSpec := range flows {
if nodeID == thisNodeID {
// Skip this node since we already handled the local flow above.
continue
}
req := setupReq
req.Flow = *flowSpec
runReq := runnerRequest{
ctx: runnerCtx,
podNodeDialer: dsp.podNodeDialer,
flowReq: &req,
sqlInstanceID: nodeID,
resultChan: resultChan,
}
// Send out a request to the workers; if no worker is available, run
// directly.
numIssuedRequests++
select {
case dsp.runnerCoordinator.runnerChan <- runReq:
usedWorker = true
default:
// Use the context of the local flow since we're executing this
// SetupFlow RPC synchronously.
runReq.ctx = ctx
if err = runReq.run(); err != nil {
return ctx, flow, err
}
}
}
if !usedWorker {
// We executed all SetupFlow RPCs in the current goroutine, and all RPCs
// succeeded.
return ctx, flow, nil
}
// Some of the SetupFlow RPCs were executed concurrently, and at the moment
// it's not clear whether the setup of the remote flows is successful, but
// in order to not introduce an execution stall, we will proceed to run the
// local flow assuming that all RPCs are successful. However, in case the
// setup of a remote flow fails, we want to eagerly cancel all the flows,
// and we do so in a separate goroutine.
//
// We need to synchronize the new goroutine with flow.Cleanup() being called
// for two reasons:
// - flow.Cleanup() is the last thing before DistSQLPlanner.Run returns at
// which point the rowResultWriter is no longer protected by the mutex of
// the DistSQLReceiver
// - flow.Cancel can only be called before flow.Cleanup.
cleanupCalledMu := struct {
syncutil.Mutex
called bool
}{}
flow.AddOnCleanupStart(func() {
cleanupCalledMu.Lock()
defer cleanupCalledMu.Unlock()
cleanupCalledMu.called = true
// Cancel any outstanding RPCs while holding the lock to protect from
// the context canceled error (the result of the RPC) being set on the
// DistSQLReceiver by the listener goroutine below.
cancelRunnerCtx()
})
err = dsp.stopper.RunAsyncTask(origCtx, "distsql-remote-flows-setup-listener", func(ctx context.Context) {
// Note that in the loop below we always receive from the result channel
// as many times as there were SetupFlow RPCs issued, thus, by the time
// this defer is executed, we are certain that all RPCs were complete,
// and runnerCleanup() is safe to be executed.
defer runnerCleanup()
var seenError bool
for i := 0; i < len(flows)-1; i++ {
res := <-resultChan
if res.err != nil && !seenError {
// The setup of at least one remote flow failed.
seenError = true
func() {
cleanupCalledMu.Lock()
// Flow.Cancel cannot be called after or concurrently with
// Flow.Cleanup.
defer cleanupCalledMu.Unlock()
if cleanupCalledMu.called {
// Cleanup of the local flow has already been performed,
// so there is nothing to do.
return
}
// First, we update the DistSQL receiver with the error to
// be returned to the client eventually.
//
// In order to not protect DistSQLReceiver.status with a
// mutex, we do not update the status here and, instead,
// rely on the DistSQLReceiver detecting the error the next
// time an object is pushed into it.
recv.setErrorWithoutStatusUpdate(res.err, true /* willDeferStatusUpdate */)
// Now explicitly cancel the local flow.
flow.Cancel()
}()
}
}
})
if err != nil {
return ctx, flow, err
}
// Now the responsibility of calling runnerCleanup is passed on to the new
// goroutine.
listenerGoroutineWillCleanup = true
return ctx, flow, nil
}
const clientRejectedMsg string = "client rejected when attempting to run DistSQL plan"
const executingParallelAndSerialChecks = "executing %d checks concurrently and %d checks serially"
// 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 root transaction in which the plan will run (or will be used to
// derive leaf transactions if the plan has concurrency). If nil, then 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.
func (dsp *DistSQLPlanner) Run(
ctx context.Context,
planCtx *PlanningCtx,
txn *kv.Txn,
plan *PhysicalPlan,
recv *DistSQLReceiver,
evalCtx *extendedEvalContext,
finishedSetupFn func(localFlow flowinfra.Flow),
) {
flows := plan.GenerateFlowSpecs()
gatewayFlowSpec, ok := flows[dsp.gatewaySQLInstanceID]
if !ok {
recv.SetError(errors.Errorf("expected to find gateway flow"))
return
}
// Specs of the remote flows are released after performing the corresponding
// SetupFlow RPCs. This is needed in case the local flow is canceled before
// the SetupFlow RPCs are issued (which might happen in parallel).
defer physicalplan.ReleaseFlowSpec(gatewayFlowSpec)
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.Context
localState.IsLocal = planCtx.isLocal
localState.MustUseLeaf = planCtx.mustUseLeafTxn
localState.Txn = txn
localState.LocalProcs = plan.LocalProcessors
localState.LocalVectorSources = plan.LocalVectorSources
// 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 || planCtx.usePlannerDescriptorsForLocalFlow) {
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 txn == nil {
// Txn can be nil in some cases, like BulkIO flows. In such a case, we
// cannot create a LeafTxn, so we cannot parallelize scans.
planCtx.parallelizeScansIfLocal = false
} else {
if planCtx.isLocal && 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.
// At the moment, we disable the usage of the Streamer API for local
// plans when non-default key locking modes are requested on some of
// the processors. This is the case since the lock spans propagation
// doesn't happen for the leaf txns which can result in excessive
// contention for future reads (since the acquired locks are not
// cleaned up properly when the txn commits).
// TODO(yuzefovich): fix the propagation of the lock spans with the
// leaf txns and remove this check. See #94290.
containsNonDefaultLocking := planCtx.planner != nil && planCtx.planner.curPlan.flags.IsSet(planFlagContainsNonDefaultLocking)
if !containsNonDefaultLocking {
if execinfra.CanUseStreamer(dsp.st) {
for _, proc := range plan.Processors {
if jr := proc.Spec.Core.JoinReader; jr != nil {
// Both index and lookup joins, with and without
// ordering, are executed via the Streamer API that has
// concurrency.
localState.HasConcurrency = true
break
}
}
}
}
}
if localState.MustUseLeafTxn() {
// 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
}
if tis == nil {
recv.SetError(errors.AssertionFailedf(
"leafInputState is nil when txn is non-nil and we must use the leaf txn",
))
return
}
leafInputState = tis
}
}
if !planCtx.skipDistSQLDiagramGeneration && log.ExpensiveLogEnabled(ctx, 2) {
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.VEventf(ctx, 2, "error generating diagram: %s", err)
} else {
log.VEventf(ctx, 2, "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()
if multitenant.TenantRUEstimateEnabled.Get(&dsp.st.SV) &&
dsp.distSQLSrv.TenantCostController != nil && planCtx.planner != nil {
if instrumentation := planCtx.planner.curPlan.instrumentation; instrumentation != nil {
// Only collect the network egress estimate for a tenant that is running
// EXPLAIN ANALYZE, since the overhead is non-negligible.
recv.isTenantExplainAnalyze = instrumentation.outputMode != unmodifiedOutput
}
}
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.getError() != nil {
// The execution of this query encountered some error, so we
// will eagerly cancel all flows running on the remote nodes
// because they are now dead.
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
}
var flow flowinfra.Flow
var err error
if m := planCtx.getPortalPauseInfo(); m != nil && m.flow != nil {
flow = m.flow
} else {
ctx, flow, err = dsp.setupFlows(
ctx, evalCtx, planCtx, leafInputState, flows, recv, localState, statementSQL,
)
if m != nil {
m.flow = flow
m.outputTypes = plan.GetResultTypes()
}
}
if flow != nil {
// Make sure that the local flow is always cleaned up if it was created.
// If the flow is not for retained portal, we clean the flow up here.
// Otherwise, we delay the clean up via portalPauseInfo.flowCleanup until
// the portal is closed.
if planCtx.getPortalPauseInfo() == nil {
defer func() {
flow.Cleanup(ctx)
}()
}
}
if err != nil {
recv.SetError(err)
return
}
if finishedSetupFn != nil {
finishedSetupFn(flow)
}
// 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
}
noWait := planCtx.getPortalPauseInfo() != nil
flow.Run(ctx, noWait)
}
// 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
resultWriterMu struct {
// Mutex only protects SetError() and Err() methods of the
// rowResultWriter.
syncutil.Mutex
// These two interfaces refer to the same object, but batch might be
// unset (row is always set). These are used to send the results to.
row rowResultWriter
batch batchResultWriter
}
// updateStatus, if true, indicates that a concurrent goroutine has set an
// error on the rowResultWriter without updating status, so the main
// goroutine needs to update the status.
updateStatus atomic.Bool
status execinfra.ConsumerStatus
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
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
// isTenantExplainAnalyze is used to indicate that network egress should be
// collected in order to estimate RU consumption for a tenant that is running
// a query with EXPLAIN ANALYZE.
isTenantExplainAnalyze bool
egressCounter TenantNetworkEgressCounter
expectedRowsRead int64
progressAtomic *uint64
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)
}
// TenantNetworkEgressCounter is used by tenants running EXPLAIN ANALYZE to
// measure the number of bytes that would be sent over the network if the