forked from redpanda-data/connect
-
Notifications
You must be signed in to change notification settings - Fork 1
/
read_until.go
295 lines (254 loc) · 8.17 KB
/
read_until.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
// 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 input
import (
"encoding/json"
"errors"
"fmt"
"sync/atomic"
"time"
"github.com/Jeffail/benthos/lib/metrics"
"github.com/Jeffail/benthos/lib/processor/condition"
"github.com/Jeffail/benthos/lib/types"
"github.com/Jeffail/benthos/lib/util/service/log"
)
//------------------------------------------------------------------------------
func init() {
Constructors["read_until"] = TypeSpec{
constructor: NewReadUntil,
description: `
Reads from an input and tests a condition on each message. When the condition
returns true the message is sent out and the input is closed. Use this type to
define inputs where the stream should end once a certain message appears.
Sometimes inputs close themselves. For example, when the ` + "`file`" + ` input
type reaches the end of a file it will shut down. By default this type will also
shut down. If you wish for the input type to be restarted every time it shuts
down until the condition is met then set ` + "`restart_input` to `true`.",
}
}
//------------------------------------------------------------------------------
// ReadUntilConfig is configuration values for the ReadUntil input type.
type ReadUntilConfig struct {
Input *Config `json:"input" yaml:"input"`
Restart bool `json:"restart_input" yaml:"restart_input"`
Condition condition.Config `json:"condition" yaml:"condition"`
}
// NewReadUntilConfig creates a new ReadUntilConfig with default values.
func NewReadUntilConfig() ReadUntilConfig {
return ReadUntilConfig{
Input: nil,
Restart: false,
Condition: condition.NewConfig(),
}
}
//------------------------------------------------------------------------------
type dummyReadUntilConfig struct {
Input interface{} `json:"input" yaml:"input"`
Restart bool `json:"restart_input" yaml:"restart_input"`
Condition condition.Config `json:"condition" yaml:"condition"`
}
// MarshalJSON prints an empty object instead of nil.
func (r ReadUntilConfig) MarshalJSON() ([]byte, error) {
dummy := dummyReadUntilConfig{
Input: r.Input,
Restart: r.Restart,
Condition: r.Condition,
}
if r.Input == nil {
dummy.Input = struct{}{}
}
return json.Marshal(dummy)
}
// MarshalYAML prints an empty object instead of nil.
func (r ReadUntilConfig) MarshalYAML() (interface{}, error) {
dummy := dummyReadUntilConfig{
Input: r.Input,
Restart: r.Restart,
Condition: r.Condition,
}
if r.Input == nil {
dummy.Input = struct{}{}
}
return dummy, nil
}
//------------------------------------------------------------------------------
// ReadUntil is an input type that reads from a ReadUntil instance.
type ReadUntil struct {
running int32
conf ReadUntilConfig
wrapped Type
cond condition.Type
wrapperMgr types.Manager
wrapperLog log.Modular
wrapperStats metrics.Type
stats metrics.Type
log log.Modular
transactions chan types.Transaction
closeChan chan struct{}
closedChan chan struct{}
}
// NewReadUntil creates a new ReadUntil input type.
func NewReadUntil(
conf Config,
mgr types.Manager,
log log.Modular,
stats metrics.Type,
) (Type, error) {
if conf.ReadUntil.Input == nil {
return nil, errors.New("cannot create read_until input without a child")
}
wrapped, err := New(*conf.ReadUntil.Input, mgr, log, stats)
if err != nil {
return nil, fmt.Errorf("failed to create input '%v': %v", conf.ReadUntil.Input.Type, err)
}
var cond condition.Type
if cond, err = condition.New(conf.ReadUntil.Condition, mgr, log, stats); err != nil {
return nil, fmt.Errorf("failed to create condition '%v': %v", conf.ReadUntil.Condition.Type, err)
}
rdr := &ReadUntil{
running: 1,
conf: conf.ReadUntil,
wrapperLog: log,
wrapperStats: stats,
wrapperMgr: mgr,
log: log.NewModule(".input.read_until"),
stats: stats,
wrapped: wrapped,
cond: cond,
transactions: make(chan types.Transaction),
closeChan: make(chan struct{}),
closedChan: make(chan struct{}),
}
go rdr.loop()
return rdr, nil
}
//------------------------------------------------------------------------------
func (r *ReadUntil) loop() {
var (
mRunning = r.stats.GetCounter("input.read_until.running")
mRestartErr = r.stats.GetCounter("input.read_until.input.restart.error")
mRestartSucc = r.stats.GetCounter("input.read_until.input.restart.success")
mInputClosed = r.stats.GetCounter("input.read_until.input.closed")
mCount = r.stats.GetCounter("input.read_until.count")
mPropagated = r.stats.GetCounter("input.read_until.propagated")
mFinalPropagated = r.stats.GetCounter("input.read_until.final.propagated")
mFinalResSent = r.stats.GetCounter("input.read_until.final.response.sent")
mFinalResSucc = r.stats.GetCounter("input.read_until.final.response.success")
mFinalResErr = r.stats.GetCounter("input.read_until.final.response.error")
)
defer func() {
if r.wrapped != nil {
r.wrapped.CloseAsync()
err := r.wrapped.WaitForClose(time.Second)
for ; err != nil; err = r.wrapped.WaitForClose(time.Second) {
}
}
mRunning.Decr(1)
close(r.transactions)
close(r.closedChan)
}()
mRunning.Incr(1)
var open bool
runLoop:
for atomic.LoadInt32(&r.running) == 1 {
if r.wrapped == nil {
if r.conf.Restart {
var err error
if r.wrapped, err = New(
*r.conf.Input, r.wrapperMgr, r.wrapperLog, r.wrapperStats,
); err != nil {
mRestartErr.Incr(1)
r.log.Errorf("Failed to create input '%v': %v\n", r.conf.Input.Type, err)
return
}
mRestartSucc.Incr(1)
} else {
return
}
}
var tran types.Transaction
select {
case tran, open = <-r.wrapped.TransactionChan():
if !open {
mInputClosed.Incr(1)
r.wrapped = nil
continue runLoop
}
case <-r.closeChan:
return
}
mCount.Incr(1)
if !r.cond.Check(tran.Payload) {
select {
case r.transactions <- tran:
mPropagated.Incr(1)
case <-r.closeChan:
return
}
continue
}
// If this transaction succeeds we shut down.
tmpRes := make(chan types.Response)
select {
case r.transactions <- types.NewTransaction(tran.Payload, tmpRes):
mFinalPropagated.Incr(1)
case <-r.closeChan:
return
}
var res types.Response
select {
case res, open = <-tmpRes:
streamEnds := res.Error() == nil
select {
case tran.ResponseChan <- res:
mFinalResSent.Incr(1)
case <-r.closeChan:
return
}
if streamEnds {
mFinalResSucc.Incr(1)
return
}
mFinalResErr.Incr(1)
case <-r.closeChan:
return
}
}
}
// TransactionChan returns the transactions channel.
func (r *ReadUntil) TransactionChan() <-chan types.Transaction {
return r.transactions
}
// CloseAsync shuts down the ReadUntil input and stops processing requests.
func (r *ReadUntil) CloseAsync() {
if atomic.CompareAndSwapInt32(&r.running, 1, 0) {
close(r.closeChan)
}
}
// WaitForClose blocks until the ReadUntil input has closed down.
func (r *ReadUntil) WaitForClose(timeout time.Duration) error {
select {
case <-r.closedChan:
case <-time.After(timeout):
return types.ErrTimeout
}
return nil
}
//------------------------------------------------------------------------------