forked from redpanda-data/connect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
type.go
379 lines (329 loc) · 10.2 KB
/
type.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
// Copyright (c) 2018 Ashley Jeffs
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package stream
import (
"bytes"
"os"
"runtime/pprof"
"time"
"github.com/Jeffail/benthos/lib/buffer"
"github.com/Jeffail/benthos/lib/input"
"github.com/Jeffail/benthos/lib/log"
"github.com/Jeffail/benthos/lib/metrics"
"github.com/Jeffail/benthos/lib/output"
"github.com/Jeffail/benthos/lib/pipeline"
"github.com/Jeffail/benthos/lib/types"
)
//------------------------------------------------------------------------------
// Type creates and manages the lifetime of a Benthos stream.
type Type struct {
conf Config
inputLayer input.Type
bufferLayer buffer.Type
pipelineLayer pipeline.Type
outputLayer output.Type
complementaryInputPipes []pipeline.ConstructorFunc
complementaryProcs []pipeline.ProcConstructorFunc
complementaryOutputPipes []pipeline.ConstructorFunc
manager types.Manager
stats metrics.Type
logger log.Modular
onClose func()
}
// New creates a new stream.Type.
func New(conf Config, opts ...func(*Type)) (*Type, error) {
t := &Type{
conf: conf,
stats: metrics.DudType{},
logger: log.New(os.Stdout, log.Config{LogLevel: "NONE"}),
manager: types.DudMgr{},
onClose: func() {},
}
for _, opt := range opts {
opt(t)
}
if err := t.start(); err != nil {
return nil, err
}
return t, nil
}
//------------------------------------------------------------------------------
// OptAddInputPipelines adds additional pipelines that will be constructed for
// each input of the Benthos stream.
func OptAddInputPipelines(pipes ...pipeline.ConstructorFunc) func(*Type) {
return func(t *Type) {
t.complementaryInputPipes = append(t.complementaryInputPipes, pipes...)
}
}
// OptAddProcessors adds additional processors that will be constructed for each
// logical thread of the processing pipeline layer of the Benthos stream.
func OptAddProcessors(procs ...pipeline.ProcConstructorFunc) func(*Type) {
return func(t *Type) {
t.complementaryProcs = append(t.complementaryProcs, procs...)
}
}
// OptAddOutputPipelines adds additional pipelines that will be constructed for
// each output of the Benthos stream.
func OptAddOutputPipelines(pipes ...pipeline.ConstructorFunc) func(*Type) {
return func(t *Type) {
t.complementaryOutputPipes = append(t.complementaryOutputPipes, pipes...)
}
}
// OptSetStats sets the metrics aggregator to be used by all components of the
// stream.
func OptSetStats(stats metrics.Type) func(*Type) {
return func(t *Type) {
t.stats = stats
}
}
// OptSetLogger sets the logging output to be used by all components of the
// stream.
func OptSetLogger(log log.Modular) func(*Type) {
return func(t *Type) {
t.logger = log
}
}
// OptSetManager sets the service manager to be used by all components of the
// stream.
func OptSetManager(mgr types.Manager) func(*Type) {
return func(t *Type) {
t.manager = mgr
}
}
// OptOnClose sets a closure to be called when the stream closes.
func OptOnClose(onClose func()) func(*Type) {
return func(t *Type) {
t.onClose = onClose
}
}
//------------------------------------------------------------------------------
func (t *Type) start() (err error) {
// Constructors
if t.inputLayer, err = input.New(
t.conf.Input, t.manager, t.logger, t.stats, t.complementaryInputPipes...,
); err != nil {
return
}
if t.conf.Buffer.Type != "none" {
if t.bufferLayer, err = buffer.New(
t.conf.Buffer, t.logger, t.stats,
); err != nil {
return
}
}
if tLen := len(t.complementaryProcs) + len(t.conf.Pipeline.Processors); tLen > 0 {
if t.pipelineLayer, err = pipeline.New(
t.conf.Pipeline, t.manager, t.logger, t.stats, t.complementaryProcs...,
); err != nil {
return
}
}
if t.outputLayer, err = output.New(
t.conf.Output, t.manager, t.logger, t.stats, t.complementaryOutputPipes...,
); err != nil {
return
}
// Start chaining components
var nextTranChan <-chan types.Transaction
nextTranChan = t.inputLayer.TransactionChan()
if t.bufferLayer != nil {
if err = t.bufferLayer.StartReceiving(nextTranChan); err != nil {
return
}
nextTranChan = t.bufferLayer.TransactionChan()
}
if t.pipelineLayer != nil {
if err = t.pipelineLayer.StartReceiving(nextTranChan); err != nil {
return
}
nextTranChan = t.pipelineLayer.TransactionChan()
}
if err = t.outputLayer.StartReceiving(nextTranChan); err != nil {
return
}
go func(out output.Type) {
for {
if err := out.WaitForClose(time.Second); err == nil {
t.onClose()
return
}
}
}(t.outputLayer)
return nil
}
// stopGracefully attempts to close the stream in the most graceful way by only
// closing the input layer and waiting for all other layers to terminate by
// proxy. This should guarantee that all in-flight and buffered data is resolved
// before shutting down.
func (t *Type) stopGracefully(timeout time.Duration) (err error) {
t.inputLayer.CloseAsync()
started := time.Now()
if err = t.inputLayer.WaitForClose(timeout); err != nil {
return
}
var remaining time.Duration
// If we have a buffer then wait right here. We want to try and allow the
// buffer to empty out before prompting the other layers to shut down.
if t.bufferLayer != nil {
t.bufferLayer.StopConsuming()
remaining = timeout - time.Since(started)
if remaining < 0 {
return types.ErrTimeout
}
if err = t.bufferLayer.WaitForClose(remaining); err != nil {
return
}
}
// After this point we can start closing the remaining components.
if t.pipelineLayer != nil {
t.pipelineLayer.CloseAsync()
remaining = timeout - time.Since(started)
if remaining < 0 {
return types.ErrTimeout
}
if err = t.pipelineLayer.WaitForClose(remaining); err != nil {
return
}
}
t.outputLayer.CloseAsync()
remaining = timeout - time.Since(started)
if remaining < 0 {
return types.ErrTimeout
}
if err = t.outputLayer.WaitForClose(remaining); err != nil {
return
}
return nil
}
// stopOrdered attempts to close all components of the stream in the order of
// positions within the stream, this allows data to flush all the way through
// the pipeline under certain circumstances but is less graceful than
// stopGracefully, which should be attempted first.
func (t *Type) stopOrdered(timeout time.Duration) (err error) {
t.inputLayer.CloseAsync()
started := time.Now()
if err = t.inputLayer.WaitForClose(timeout); err != nil {
return
}
var remaining time.Duration
if t.bufferLayer != nil {
t.bufferLayer.CloseAsync()
remaining = timeout - time.Since(started)
if remaining < 0 {
return types.ErrTimeout
}
if err = t.bufferLayer.WaitForClose(remaining); err != nil {
return
}
}
if t.pipelineLayer != nil {
t.pipelineLayer.CloseAsync()
remaining = timeout - time.Since(started)
if remaining < 0 {
return types.ErrTimeout
}
if err = t.pipelineLayer.WaitForClose(remaining); err != nil {
return
}
}
t.outputLayer.CloseAsync()
remaining = timeout - time.Since(started)
if remaining < 0 {
return types.ErrTimeout
}
if err = t.outputLayer.WaitForClose(remaining); err != nil {
return
}
return nil
}
// stopUnorderd attempts to close all components in parallel without allowing
// the stream to gracefully wind down in the order of component layers. This
// should only be attempted if both stopGracefully and stopOrdered failed.
func (t *Type) stopUnordered(timeout time.Duration) (err error) {
t.inputLayer.CloseAsync()
if t.bufferLayer != nil {
t.bufferLayer.CloseAsync()
}
if t.pipelineLayer != nil {
t.pipelineLayer.CloseAsync()
}
t.outputLayer.CloseAsync()
started := time.Now()
if err = t.inputLayer.WaitForClose(timeout); err != nil {
return
}
var remaining time.Duration
if t.bufferLayer != nil {
remaining = timeout - time.Since(started)
if remaining < 0 {
return types.ErrTimeout
}
if err = t.bufferLayer.WaitForClose(remaining); err != nil {
return
}
}
if t.pipelineLayer != nil {
remaining = timeout - time.Since(started)
if remaining < 0 {
return types.ErrTimeout
}
if err = t.pipelineLayer.WaitForClose(remaining); err != nil {
return
}
}
remaining = timeout - time.Since(started)
if remaining < 0 {
return types.ErrTimeout
}
if err = t.outputLayer.WaitForClose(remaining); err != nil {
return
}
return nil
}
// Stop attempts to close the stream within the specified timeout period.
// Initially the attempt is graceful, but as the timeout draws close the attempt
// becomes progressively less graceful.
func (t *Type) Stop(timeout time.Duration) error {
tOutUnordered := timeout / 4
tOutGraceful := timeout - tOutUnordered
err := t.stopGracefully(tOutGraceful)
if err == nil {
return nil
}
if err == types.ErrTimeout {
t.logger.Infoln("Unable to fully drain buffered messages within target time.")
} else {
t.logger.Errorf("Encountered error whilst shutting down: %v\n", err)
}
err = t.stopUnordered(tOutUnordered)
if err == nil {
return nil
}
if err == types.ErrTimeout {
t.logger.Errorln("Failed to stop stream gracefully within target time.")
dumpBuf := bytes.NewBuffer(nil)
pprof.Lookup("goroutine").WriteTo(dumpBuf, 1)
t.logger.Debugln(dumpBuf.String())
} else {
t.logger.Errorf("Encountered error whilst shutting down: %v\n", err)
}
return err
}
//------------------------------------------------------------------------------