forked from benthosdev/benthos
/
output_kinesis.go
281 lines (244 loc) · 8.22 KB
/
output_kinesis.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
package aws
import (
"context"
"fmt"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/kinesis"
"github.com/aws/aws-sdk-go/service/kinesis/kinesisiface"
"github.com/cenkalti/backoff/v4"
"github.com/benthosdev/benthos/v4/internal/component"
"github.com/benthosdev/benthos/v4/internal/component/output"
"github.com/benthosdev/benthos/v4/internal/impl/aws/config"
"github.com/benthosdev/benthos/v4/internal/impl/pure"
"github.com/benthosdev/benthos/v4/public/service"
)
const (
// Kinesis Output Fields
koFieldStream = "stream"
koFieldHashKey = "hash_key"
koFieldPartitionKey = "partition_key"
koFieldBatching = "batching"
)
type koConfig struct {
Stream string
HashKey *service.InterpolatedString
PartitionKey *service.InterpolatedString
session *session.Session
backoffCtor func() backoff.BackOff
}
func koConfigFromParsed(pConf *service.ParsedConfig) (conf koConfig, err error) {
if conf.Stream, err = pConf.FieldString(koFieldStream); err != nil {
return
}
if conf.PartitionKey, err = pConf.FieldInterpolatedString(koFieldPartitionKey); err != nil {
return
}
if pConf.Contains(koFieldHashKey) {
if conf.HashKey, err = pConf.FieldInterpolatedString(koFieldHashKey); err != nil {
return
}
}
if conf.session, err = GetSession(pConf); err != nil {
return
}
if conf.backoffCtor, err = pure.CommonRetryBackOffCtorFromParsed(pConf); err != nil {
return
}
return
}
func koOutputSpec() *service.ConfigSpec {
return service.NewConfigSpec().
Stable().
Version("3.36.0").
Categories("Services", "AWS").
Summary(`Sends messages to a Kinesis stream.`).
Description(output.Description(true, true, `
Both the `+"`partition_key`"+`(required) and `+"`hash_key`"+` (optional) fields can be dynamically set using function interpolations described [here](/docs/configuration/interpolation#bloblang-queries). When sending batched messages the interpolations are performed per message part.
### Credentials
By default Benthos will use a shared credentials file when connecting to AWS services. It's also possible to set them explicitly at the component level, allowing you to transfer data across accounts. You can find out more [in this document](/docs/guides/cloud/aws).`)).
Fields(
service.NewStringField(koFieldStream).
Description("The stream to publish messages to."),
service.NewInterpolatedStringField(koFieldPartitionKey).
Description("A required key for partitioning messages."),
service.NewInterpolatedStringField(koFieldHashKey).
Description("A optional hash key for partitioning messages.").
Optional().
Advanced(),
service.NewOutputMaxInFlightField().
Description("The maximum number of parallel message batches to have in flight at any given time."),
service.NewBatchPolicyField(koFieldBatching),
).
Fields(config.SessionFields()...).
Fields(pure.CommonRetryBackOffFields(0, "1s", "5s", "30s")...)
}
func init() {
err := service.RegisterBatchOutput("aws_kinesis", koOutputSpec(),
func(conf *service.ParsedConfig, mgr *service.Resources) (out service.BatchOutput, batchPolicy service.BatchPolicy, maxInFlight int, err error) {
if maxInFlight, err = conf.FieldMaxInFlight(); err != nil {
return
}
if batchPolicy, err = conf.FieldBatchPolicy(koFieldBatching); err != nil {
return
}
var wConf koConfig
if wConf, err = koConfigFromParsed(conf); err != nil {
return
}
out, err = newKinesisWriter(wConf, mgr)
return
})
if err != nil {
panic(err)
}
}
const (
kinesisMaxRecordsCount = 500
mebibyte = 1048576
)
type kinesisWriter struct {
conf koConfig
kinesis kinesisiface.KinesisAPI
log *service.Logger
}
func newKinesisWriter(conf koConfig, mgr *service.Resources) (*kinesisWriter, error) {
return &kinesisWriter{
conf: conf,
log: mgr.Logger(),
}, nil
}
// toRecords converts an individual benthos message into a slice of Kinesis
// batch put entries by promoting each message part into a single part message
// and passing each new message through the partition and hash key interpolation
// process, allowing the user to define the partition and hash key per message
// part.
func (a *kinesisWriter) toRecords(batch service.MessageBatch) ([]*kinesis.PutRecordsRequestEntry, error) {
entries := make([]*kinesis.PutRecordsRequestEntry, len(batch))
err := batch.WalkWithBatchedErrors(func(i int, m *service.Message) error {
partKey, err := batch.TryInterpolatedString(i, a.conf.PartitionKey)
if err != nil {
return fmt.Errorf("partition key interpolation error: %w", err)
}
mBytes, err := m.AsBytes()
if err != nil {
return err
}
entry := kinesis.PutRecordsRequestEntry{
Data: mBytes,
PartitionKey: aws.String(partKey),
}
if len(entry.Data) > mebibyte {
a.log.Errorf("part %d exceeds the maximum Kinesis payload limit of 1 MiB\n", i)
return component.ErrMessageTooLarge
}
var hashKey string
if a.conf.HashKey != nil {
if hashKey, err = batch.TryInterpolatedString(i, a.conf.HashKey); err != nil {
return fmt.Errorf("hash key interpolation error: %w", err)
}
}
if hashKey != "" {
entry.ExplicitHashKey = aws.String(hashKey)
}
entries[i] = &entry
return nil
})
return entries, err
}
func (a *kinesisWriter) Connect(ctx context.Context) error {
if a.kinesis != nil {
return nil
}
k := kinesis.New(a.conf.session)
if _, err := k.DescribeStreamWithContext(ctx, &kinesis.DescribeStreamInput{
StreamName: &a.conf.Stream,
}); err != nil {
return err
}
if err := k.WaitUntilStreamExistsWithContext(ctx, &kinesis.DescribeStreamInput{
StreamName: &a.conf.Stream,
}); err != nil {
return err
}
a.kinesis = k
a.log.Infof("Sending messages to Kinesis stream: %v\n", a.conf.Stream)
return nil
}
func (a *kinesisWriter) WriteBatch(ctx context.Context, batch service.MessageBatch) error {
if a.kinesis == nil {
return component.ErrNotConnected
}
backOff := a.conf.backoffCtor()
records, err := a.toRecords(batch)
if err != nil {
return err
}
input := &kinesis.PutRecordsInput{
Records: records,
StreamName: &a.conf.Stream,
}
// trim input record length to max kinesis batch size
if len(records) > kinesisMaxRecordsCount {
input.Records, records = records[:kinesisMaxRecordsCount], records[kinesisMaxRecordsCount:]
} else {
records = nil
}
var failed []*kinesis.PutRecordsRequestEntry
backOff.Reset()
for len(input.Records) > 0 {
wait := backOff.NextBackOff()
// batch write to kinesis
output, err := a.kinesis.PutRecords(input)
if err != nil {
a.log.Warnf("kinesis error: %v\n", err)
// bail if a message is too large or all retry attempts expired
if wait == backoff.Stop {
return err
}
continue
}
// requeue any individual records that failed due to throttling
failed = nil
if output.FailedRecordCount != nil {
for i, entry := range output.Records {
if entry.ErrorCode != nil {
failed = append(failed, input.Records[i])
switch *entry.ErrorCode {
case kinesis.ErrCodeProvisionedThroughputExceededException:
a.log.Errorf("Kinesis record write request rate too high, either the frequency or the size of the data exceeds your available throughput.")
case kinesis.ErrCodeKMSThrottlingException:
a.log.Errorf("Kinesis record write request throttling exception, the send traffic exceeds your request quota.")
default:
err = fmt.Errorf("record failed with code [%s] %s: %+v", *entry.ErrorCode, *entry.ErrorMessage, input.Records[i])
a.log.Errorf("kinesis record write error: %v\n", err)
return err
}
}
}
}
input.Records = failed
// if throttling errors detected, pause briefly
l := len(failed)
if l > 0 {
a.log.Warnf("scheduling retry of throttled records (%d)\n", l)
if wait == backoff.Stop {
return component.ErrTimeout
}
time.Sleep(wait)
}
// add remaining records to batch
if n := len(records); n > 0 && l < kinesisMaxRecordsCount {
if remaining := kinesisMaxRecordsCount - l; remaining < n {
input.Records, records = append(input.Records, records[:remaining]...), records[remaining:]
} else {
input.Records, records = append(input.Records, records...), nil
}
}
}
return err
}
func (a *kinesisWriter) Close(context.Context) error {
return nil
}