forked from redpanda-data/connect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate.go
293 lines (267 loc) · 9.32 KB
/
generate.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
package input
import (
"context"
"fmt"
"strings"
"sync/atomic"
"time"
"github.com/dafanshu/benthos/v3/internal/bloblang/mapping"
"github.com/dafanshu/benthos/v3/internal/bloblang/parser"
"github.com/dafanshu/benthos/v3/internal/docs"
"github.com/dafanshu/benthos/v3/internal/interop"
"github.com/dafanshu/benthos/v3/lib/input/reader"
"github.com/dafanshu/benthos/v3/lib/log"
"github.com/dafanshu/benthos/v3/lib/message"
"github.com/dafanshu/benthos/v3/lib/metrics"
"github.com/dafanshu/benthos/v3/lib/types"
"github.com/robfig/cron/v3"
)
//------------------------------------------------------------------------------
func init() {
Constructors[TypeGenerate] = TypeSpec{
constructor: fromSimpleConstructor(func(conf Config, mgr types.Manager, log log.Modular, stats metrics.Type) (Type, error) {
b, err := newBloblang(mgr, conf.Generate)
if err != nil {
return nil, err
}
return NewAsyncReader(TypeGenerate, false, reader.NewAsyncPreserver(b), log, stats)
}),
Version: "3.40.0",
Status: docs.StatusStable,
Summary: `
Generates messages at a given interval using a [Bloblang](/docs/guides/bloblang/about)
mapping executed without a context. This allows you to generate messages for
testing your pipeline configs.`,
FieldSpecs: docs.FieldSpecs{
docs.FieldBloblang(
"mapping", "A [bloblang](/docs/guides/bloblang/about) mapping to use for generating messages.",
`root = "hello world"`,
`root = {"test":"message","id":uuid_v4()}`,
),
docs.FieldCommon(
"interval",
"The time interval at which messages should be generated, expressed either as a duration string or as a cron expression. If set to an empty string messages will be generated as fast as downstream services can process them. Cron expressions can specify a timezone by prefixing the expression with `TZ=<location name>`, where the location name corresponds to a file within the IANA Time Zone database.",
"5s", "1m", "1h",
"@every 1s", "0,30 */2 * * * *", "TZ=Europe/London 30 3-6,20-23 * * *",
),
docs.FieldCommon("count", "An optional number of messages to generate, if set above 0 the specified number of messages is generated and then the input will shut down."),
},
Categories: []Category{
CategoryUtility,
},
Examples: []docs.AnnotatedExample{
{
Title: "Cron Scheduled Processing",
Summary: "A common use case for the generate input is to trigger processors on a schedule so that the processors themselves can behave similarly to an input. The following configuration reads rows from a PostgreSQL table every 5 minutes.",
Config: `
input:
generate:
interval: '@every 5m'
mapping: 'root = {}'
processors:
- sql_select:
driver: postgres
dsn: postgres://foouser:foopass@localhost:5432/testdb?sslmode=disable
table: foo
columns: [ "*" ]
`,
},
{
Title: "Generate 100 Rows",
Summary: "The generate input can be used as a convenient way to generate test data. The following example generates 100 rows of structured data by setting an explicit count. The interval field is set to empty, which means data is generated as fast as the downstream components can consume it.",
Config: `
input:
generate:
count: 100
interval: ""
mapping: |
root = if random_int() % 2 == 0 {
{
"type": "foo",
"foo": "is yummy"
}
} else {
{
"type": "bar",
"bar": "is gross"
}
}
`,
},
},
}
Constructors[TypeBloblang] = TypeSpec{
constructor: fromSimpleConstructor(func(conf Config, mgr types.Manager, log log.Modular, stats metrics.Type) (Type, error) {
b, err := newBloblang(mgr, conf.Bloblang)
if err != nil {
return nil, err
}
return NewAsyncReader(TypeBloblang, true, b, log, stats)
}),
Status: docs.StatusDeprecated,
Summary: `
Generates messages at a given interval using a [Bloblang](/docs/guides/bloblang/about)
mapping executed without a context. This allows you to generate messages for
testing your pipeline configs.`,
Description: `
## Alternatives
This input has been ` + "[renamed to `generate`](/docs/components/inputs/generate)" + `.
`,
FieldSpecs: docs.FieldSpecs{
docs.FieldBloblang(
"mapping", "A [bloblang](/docs/guides/bloblang/about) mapping to use for generating messages.",
`root = "hello world"`,
`root = {"test":"message","id":uuid_v4()}`,
),
docs.FieldCommon(
"interval",
"The time interval at which messages should be generated, expressed either as a duration string or as a cron expression. If set to an empty string messages will be generated as fast as downstream services can process them.",
"5s", "1m", "1h",
"@every 1s", "0,30 */2 * * * *", "30 3-6,20-23 * * *",
),
docs.FieldCommon("count", "An optional number of messages to generate, if set above 0 the specified number of messages is generated and then the input will shut down."),
},
Categories: []Category{
CategoryUtility,
},
}
}
//------------------------------------------------------------------------------
// BloblangConfig contains configuration for the Bloblang input type.
type BloblangConfig struct {
Mapping string `json:"mapping" yaml:"mapping"`
// internal can be both duration string or cron expression
Interval string `json:"interval" yaml:"interval"`
Count int `json:"count" yaml:"count"`
}
// NewBloblangConfig creates a new BloblangConfig with default values.
func NewBloblangConfig() BloblangConfig {
return BloblangConfig{
Mapping: "",
Interval: "1s",
Count: 0,
}
}
// Bloblang executes a bloblang mapping with an empty context each time this
// input is read from. An interval period must be specified that determines how
// often a message is generated.
type Bloblang struct {
remaining int64
limited bool
firstIsFree bool
exec *mapping.Executor
timer *time.Ticker
schedule *cron.Schedule
location *time.Location
}
// newBloblang creates a new bloblang input reader type.
func newBloblang(mgr types.Manager, conf BloblangConfig) (*Bloblang, error) {
var (
duration time.Duration
timer *time.Ticker
schedule *cron.Schedule
location *time.Location
err error
firstIsFree = true
)
if len(conf.Interval) > 0 {
if duration, err = time.ParseDuration(conf.Interval); err != nil {
// interval is not a duration so try to parse as a cron expression
var cerr error
if schedule, location, cerr = parseCronExpression(conf.Interval); cerr != nil {
return nil, fmt.Errorf("failed to parse interval as duration string: %v, or as cron expression: %w", err, cerr)
}
firstIsFree = false
duration = getDurationTillNextSchedule(*schedule, location)
}
if duration > 0 {
timer = time.NewTicker(duration)
}
}
exec, err := interop.NewBloblangMapping(mgr, conf.Mapping)
if err != nil {
if perr, ok := err.(*parser.Error); ok {
return nil, fmt.Errorf("failed to parse mapping: %v", perr.ErrorAtPosition([]rune(conf.Mapping)))
}
return nil, fmt.Errorf("failed to parse mapping: %v", err)
}
remaining := int64(conf.Count)
return &Bloblang{
exec: exec,
remaining: remaining,
limited: remaining > 0,
timer: timer,
schedule: schedule,
location: location,
firstIsFree: firstIsFree,
}, nil
}
func getDurationTillNextSchedule(schedule cron.Schedule, location *time.Location) time.Duration {
now := time.Now().In(location)
return schedule.Next(now).Sub(now)
}
func parseCronExpression(cronExpression string) (*cron.Schedule, *time.Location, error) {
// If time zone is not included, set default to UTC
if !strings.HasPrefix(cronExpression, "TZ=") {
cronExpression = fmt.Sprintf("TZ=%s %s", "UTC", cronExpression)
}
end := strings.Index(cronExpression, " ")
eq := strings.Index(cronExpression, "=")
tz := cronExpression[eq+1 : end]
loc, err := time.LoadLocation(tz)
if err != nil {
return nil, nil, err
}
parser := cron.NewParser(cron.SecondOptional | cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow | cron.Descriptor)
cronSchedule, err := parser.Parse(cronExpression)
if err != nil {
return nil, nil, err
}
return &cronSchedule, loc, nil
}
// ConnectWithContext establishes a Bloblang reader.
func (b *Bloblang) ConnectWithContext(ctx context.Context) error {
return nil
}
// ReadWithContext a new bloblang generated message.
func (b *Bloblang) ReadWithContext(ctx context.Context) (types.Message, reader.AsyncAckFn, error) {
if b.limited {
if remaining := atomic.AddInt64(&b.remaining, -1); remaining < 0 {
return nil, nil, types.ErrTypeClosed
}
}
if !b.firstIsFree && b.timer != nil {
select {
case _, open := <-b.timer.C:
if !open {
return nil, nil, types.ErrTypeClosed
}
if b.schedule != nil {
b.timer.Reset(getDurationTillNextSchedule(*b.schedule, b.location))
}
case <-ctx.Done():
return nil, nil, types.ErrTimeout
}
}
b.firstIsFree = false
p, err := b.exec.MapPart(0, message.New(nil))
if err != nil {
return nil, nil, err
}
if p == nil {
return nil, nil, types.ErrTimeout
}
msg := message.New(nil)
msg.Append(p)
return msg, func(context.Context, types.Response) error { return nil }, nil
}
// CloseAsync shuts down the bloblang reader.
func (b *Bloblang) CloseAsync() {
if b.timer != nil {
b.timer.Stop()
}
}
// WaitForClose blocks until the bloblang input has closed down.
func (b *Bloblang) WaitForClose(timeout time.Duration) error {
return nil
}