-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
flow.go
496 lines (424 loc) · 15.1 KB
/
flow.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
// Copyright 2019 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 flowinfra
import (
"context"
"sync"
"github.com/cockroachdb/cockroach/pkg/kv"
"github.com/cockroachdb/cockroach/pkg/sql/execinfra"
"github.com/cockroachdb/cockroach/pkg/sql/execinfrapb"
"github.com/cockroachdb/cockroach/pkg/sql/mutations"
"github.com/cockroachdb/cockroach/pkg/util/cancelchecker"
"github.com/cockroachdb/cockroach/pkg/util/contextutil"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/errors"
"github.com/opentracing/opentracing-go"
)
type flowStatus int
// Flow status indicators.
const (
FlowNotStarted flowStatus = iota
FlowRunning
FlowFinished
)
// Startable is any component that can be started (a router or an outbox).
type Startable interface {
Start(ctx context.Context, wg *sync.WaitGroup, ctxCancel context.CancelFunc)
}
// StartableFn is an adapter when a customer function (i.e. a custom goroutine)
// needs to become Startable.
type StartableFn func(context.Context, *sync.WaitGroup, context.CancelFunc)
// Start is a part of the Startable interface.
func (f StartableFn) Start(ctx context.Context, wg *sync.WaitGroup, ctxCancel context.CancelFunc) {
f(ctx, wg, ctxCancel)
}
// FuseOpt specifies options for processor fusing at Flow.Setup() time.
type FuseOpt bool
const (
// FuseNormally means fuse what you can, but don't serialize unordered input
// synchronizers.
FuseNormally FuseOpt = false
// FuseAggressively means serialize unordered input synchronizers.
// This is useful for flows that might have mutations which can't have any
// concurrency.
FuseAggressively = true
)
// Flow represents a flow which consists of processors and streams.
type Flow interface {
// Setup sets up all the infrastructure for the flow as defined by the flow
// spec. The flow will then need to be started and run. A new context (along
// with a context cancellation function) is derived. The new context must be
// used when running a flow so that all components running in their own
// goroutines could listen for a cancellation on the same context.
Setup(ctx context.Context, spec *execinfrapb.FlowSpec, opt FuseOpt) (context.Context, error)
// SetTxn is used to provide the transaction in which the flow will run.
// It needs to be called after Setup() and before Start/Run.
SetTxn(*kv.Txn)
// Start starts the flow. Processors run asynchronously in their own goroutines.
// Wait() needs to be called to wait for the flow to finish.
// See Run() for a synchronous version.
//
// Generally if errors are encountered during the setup part, they're returned.
// But if the flow is a synchronous one, then no error is returned; instead the
// setup error is pushed to the syncFlowConsumer. In this case, a subsequent
// call to f.Wait() will not block.
Start(_ context.Context, doneFn func()) error
// Run runs the flow to completion. The last processor is run in the current
// goroutine; others may run in different goroutines depending on how the flow
// was configured.
// f.Wait() is called internally, so the call blocks until all the flow's
// goroutines are done.
// The caller needs to call f.Cleanup().
Run(_ context.Context, doneFn func()) error
// Wait waits for all the goroutines for this flow to exit. If the context gets
// canceled before all goroutines exit, it calls f.cancel().
Wait()
// IsLocal returns whether this flow does not have any remote execution.
IsLocal() bool
// IsVectorized returns whether this flow will run with vectorized execution.
IsVectorized() bool
// GetFlowCtx returns the flow context of this flow.
GetFlowCtx() *execinfra.FlowCtx
// AddStartable accumulates a Startable object.
AddStartable(Startable)
// GetID returns the flow ID.
GetID() execinfrapb.FlowID
// Cleanup should be called when the flow completes (after all processors and
// mailboxes exited).
Cleanup(context.Context)
// ConcurrentTxnUse returns true if multiple processors/operators in the flow
// will execute concurrently (i.e. if not all of them have been fused) and
// more than one goroutine will be using a txn.
// Can only be called after Setup().
ConcurrentTxnUse() bool
}
// FlowBase is the shared logic between row based and vectorized flows. It
// implements Flow interface for convenience and for usage in tests, but if
// FlowBase.Setup is called, it'll panic.
type FlowBase struct {
execinfra.FlowCtx
flowRegistry *FlowRegistry
// processors contains a subset of the processors in the flow - the ones that
// run in their own goroutines. Some processors that implement RowSource are
// scheduled to run in their consumer's goroutine; those are not present here.
processors []execinfra.Processor
// startables are entities that must be started when the flow starts;
// currently these are outboxes and routers.
startables []Startable
// syncFlowConsumer is a special outbox which instead of sending rows to
// another host, returns them directly (as a result to a SetupSyncFlow RPC,
// or to the local host).
syncFlowConsumer execinfra.RowReceiver
localProcessors []execinfra.LocalProcessor
// startedGoroutines specifies whether this flow started any goroutines. This
// is used in Wait() to avoid the overhead of waiting for non-existent
// goroutines.
startedGoroutines bool
// inboundStreams are streams that receive data from other hosts; this map
// is to be passed to FlowRegistry.RegisterFlow.
inboundStreams map[execinfrapb.StreamID]*InboundStreamInfo
// waitGroup is used to wait for async components of the flow:
// - processors
// - inbound streams
// - outboxes
waitGroup sync.WaitGroup
doneFn func()
status flowStatus
// Cancel function for ctx. Call this to cancel the flow (safe to be called
// multiple times).
ctxCancel context.CancelFunc
ctxDone <-chan struct{}
// spec is the request that produced this flow. Only used for debugging.
spec *execinfrapb.FlowSpec
}
// Setup is part of the Flow interface.
func (f *FlowBase) Setup(
ctx context.Context, spec *execinfrapb.FlowSpec, _ FuseOpt,
) (context.Context, error) {
ctx, f.ctxCancel = contextutil.WithCancel(ctx)
f.ctxDone = ctx.Done()
f.spec = spec
mutationsTestingMaxBatchSize := int64(0)
if f.FlowCtx.Cfg.Settings != nil {
mutationsTestingMaxBatchSize = mutations.MutationsTestingMaxBatchSize.Get(&f.FlowCtx.Cfg.Settings.SV)
}
if mutationsTestingMaxBatchSize != 0 {
mutations.SetMaxBatchSizeForTests(int(mutationsTestingMaxBatchSize))
} else {
mutations.ResetMaxBatchSizeForTests()
}
return ctx, nil
}
// SetTxn is part of the Flow interface.
func (f *FlowBase) SetTxn(txn *kv.Txn) {
f.FlowCtx.Txn = txn
f.EvalCtx.Txn = txn
}
// ConcurrentTxnUse is part of the Flow interface.
func (f *FlowBase) ConcurrentTxnUse() bool {
numProcessorsThatMightUseTxn := 0
for _, proc := range f.processors {
if txnUser, ok := proc.(execinfra.DoesNotUseTxn); !ok || !txnUser.DoesNotUseTxn() {
numProcessorsThatMightUseTxn++
if numProcessorsThatMightUseTxn > 1 {
return true
}
}
}
return false
}
var _ Flow = &FlowBase{}
// NewFlowBase creates a new FlowBase.
func NewFlowBase(
flowCtx execinfra.FlowCtx,
flowReg *FlowRegistry,
syncFlowConsumer execinfra.RowReceiver,
localProcessors []execinfra.LocalProcessor,
) *FlowBase {
base := &FlowBase{
FlowCtx: flowCtx,
flowRegistry: flowReg,
syncFlowConsumer: syncFlowConsumer,
localProcessors: localProcessors,
}
base.status = FlowNotStarted
return base
}
// GetFlowCtx is part of the Flow interface.
func (f *FlowBase) GetFlowCtx() *execinfra.FlowCtx {
return &f.FlowCtx
}
// AddStartable is part of the Flow interface.
func (f *FlowBase) AddStartable(s Startable) {
f.startables = append(f.startables, s)
}
// GetID is part of the Flow interface.
func (f *FlowBase) GetID() execinfrapb.FlowID {
return f.ID
}
// CheckInboundStreamID takes a stream ID and returns an error if an inbound
// stream already exists with that ID in the inbound streams map, creating the
// inbound streams map if it is nil.
func (f *FlowBase) CheckInboundStreamID(sid execinfrapb.StreamID) error {
if _, found := f.inboundStreams[sid]; found {
return errors.Errorf("inbound stream %d already exists in map", sid)
}
if f.inboundStreams == nil {
f.inboundStreams = make(map[execinfrapb.StreamID]*InboundStreamInfo)
}
return nil
}
// GetWaitGroup returns the wait group of this flow.
func (f *FlowBase) GetWaitGroup() *sync.WaitGroup {
return &f.waitGroup
}
// GetCtxDone returns done channel of the context of this flow.
func (f *FlowBase) GetCtxDone() <-chan struct{} {
return f.ctxDone
}
// GetCancelFlowFn returns the context cancellation function of the context of
// this flow.
func (f *FlowBase) GetCancelFlowFn() context.CancelFunc {
return f.ctxCancel
}
// SetProcessors overrides the current f.processors with the provided
// processors. This is used to set up the vectorized flow.
func (f *FlowBase) SetProcessors(processors []execinfra.Processor) {
f.processors = processors
}
// AddRemoteStream adds a remote stream to this flow.
func (f *FlowBase) AddRemoteStream(streamID execinfrapb.StreamID, streamInfo *InboundStreamInfo) {
f.inboundStreams[streamID] = streamInfo
}
// GetSyncFlowConsumer returns the special syncFlowConsumer outbox.
func (f *FlowBase) GetSyncFlowConsumer() execinfra.RowReceiver {
return f.syncFlowConsumer
}
// GetLocalProcessors return the execinfra.LocalProcessors of this flow.
func (f *FlowBase) GetLocalProcessors() []execinfra.LocalProcessor {
return f.localProcessors
}
// startInternal starts the flow. All processors are started, each in their own
// goroutine. The caller must forward any returned error to syncFlowConsumer if
// set.
func (f *FlowBase) startInternal(
ctx context.Context, processors []execinfra.Processor, doneFn func(),
) error {
f.doneFn = doneFn
log.VEventf(
ctx, 1, "starting (%d processors, %d startables)", len(processors), len(f.startables),
)
// Only register the flow if there will be inbound stream connections that
// need to look up this flow in the flow registry.
if !f.IsLocal() {
// Once we call RegisterFlow, the inbound streams become accessible; we must
// set up the WaitGroup counter before.
// The counter will be further incremented below to account for the
// processors.
f.waitGroup.Add(len(f.inboundStreams))
if err := f.flowRegistry.RegisterFlow(
ctx, f.ID, f, f.inboundStreams, SettingFlowStreamTimeout.Get(&f.FlowCtx.Cfg.Settings.SV),
); err != nil {
return err
}
}
f.status = FlowRunning
if log.V(1) {
log.Infof(ctx, "registered flow %s", f.ID.Short())
}
for _, s := range f.startables {
s.Start(ctx, &f.waitGroup, f.ctxCancel)
}
for i := 0; i < len(processors); i++ {
f.waitGroup.Add(1)
go func(i int) {
processors[i].Run(ctx)
f.waitGroup.Done()
}(i)
}
f.startedGoroutines = len(f.startables) > 0 || len(processors) > 0 || !f.IsLocal()
return nil
}
// IsLocal returns whether this flow does not have any remote execution.
func (f *FlowBase) IsLocal() bool {
return len(f.inboundStreams) == 0
}
// IsVectorized returns whether this flow will run with vectorized execution.
func (f *FlowBase) IsVectorized() bool {
panic("IsVectorized should not be called on FlowBase")
}
// Start is part of the Flow interface.
func (f *FlowBase) Start(ctx context.Context, doneFn func()) error {
if err := f.startInternal(ctx, f.processors, doneFn); err != nil {
// For sync flows, the error goes to the consumer.
if f.syncFlowConsumer != nil {
f.syncFlowConsumer.Push(nil /* row */, &execinfrapb.ProducerMetadata{Err: err})
f.syncFlowConsumer.ProducerDone()
return nil
}
return err
}
return nil
}
// Run is part of the Flow interface.
func (f *FlowBase) Run(ctx context.Context, doneFn func()) error {
defer f.Wait()
// We'll take care of the last processor in particular.
var headProc execinfra.Processor
if len(f.processors) == 0 {
return errors.AssertionFailedf("no processors in flow")
}
headProc = f.processors[len(f.processors)-1]
otherProcs := f.processors[:len(f.processors)-1]
var err error
if err = f.startInternal(ctx, otherProcs, doneFn); err != nil {
// For sync flows, the error goes to the consumer.
if f.syncFlowConsumer != nil {
f.syncFlowConsumer.Push(nil /* row */, &execinfrapb.ProducerMetadata{Err: err})
f.syncFlowConsumer.ProducerDone()
return nil
}
return err
}
headProc.Run(ctx)
return nil
}
// Wait is part of the Flow interface.
func (f *FlowBase) Wait() {
if !f.startedGoroutines {
return
}
var panicVal interface{}
if panicVal = recover(); panicVal != nil {
// If Wait is called as part of stack unwinding during a panic, the flow
// context must be canceled to ensure that all asynchronous goroutines get
// the message that they must exit (otherwise we will wait indefinitely).
f.ctxCancel()
}
waitChan := make(chan struct{})
go func() {
f.waitGroup.Wait()
close(waitChan)
}()
select {
case <-f.ctxDone:
f.cancel()
<-waitChan
case <-waitChan:
// Exit normally
}
if panicVal != nil {
panic(panicVal)
}
}
// Releasable is an interface for objects than can be Released back into a
// memory pool when finished.
type Releasable interface {
// Release allows this object to be returned to a memory pool. Objects must
// not be used after Release is called.
Release()
}
// Cleanup is part of the Flow interface.
// NOTE: this implements only the shared clean up logic between row-based and
// vectorized flows.
func (f *FlowBase) Cleanup(ctx context.Context) {
if f.status == FlowFinished {
panic("flow cleanup called twice")
}
// Release any descriptors accessed by this flow
if f.TypeResolverFactory != nil {
f.TypeResolverFactory.CleanupFunc(ctx)
}
// This closes the monitor opened in ServerImpl.setupFlow.
f.EvalCtx.Stop(ctx)
for _, p := range f.processors {
if d, ok := p.(Releasable); ok {
d.Release()
}
}
if log.V(1) {
log.Infof(ctx, "cleaning up")
}
sp := opentracing.SpanFromContext(ctx)
// Local flows do not get registered.
if !f.IsLocal() && f.status != FlowNotStarted {
f.flowRegistry.UnregisterFlow(f.ID)
}
f.status = FlowFinished
f.ctxCancel()
if f.doneFn != nil {
f.doneFn()
}
if sp != nil {
sp.Finish()
}
}
// cancel iterates through all unconnected streams of this flow and marks them canceled.
// This function is called in Wait() after the associated context has been canceled.
// In order to cancel a flow, call f.ctxCancel() instead of this function.
//
// For a detailed description of the distsql query cancellation mechanism,
// read docs/RFCS/query_cancellation.md.
func (f *FlowBase) cancel() {
// If the flow is local, there are no inbound streams to cancel.
if f.IsLocal() {
return
}
f.flowRegistry.Lock()
timedOutReceivers := f.flowRegistry.cancelPendingStreamsLocked(f.ID)
f.flowRegistry.Unlock()
for _, receiver := range timedOutReceivers {
go func(receiver InboundStreamHandler) {
// Stream has yet to be started; send an error to its
// receiver and prevent it from being connected.
receiver.Timeout(cancelchecker.QueryCanceledError)
}(receiver)
}
}