forked from trivago/gollum
/
kinesis.go
334 lines (294 loc) · 10.7 KB
/
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
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
// Copyright 2015-2016 trivago GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package producer
import (
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/kinesis"
"github.com/trivago/gollum/core"
"github.com/trivago/gollum/core/log"
"github.com/trivago/gollum/shared"
"strings"
"sync"
"sync/atomic"
"time"
)
const (
kinesisCredentialEnv = "environment"
kinesisCredentialStatic = "static"
kinesisCredentialShared = "shared"
kinesisCredentialNone = "none"
)
// Kinesis producer plugin
// This producer sends data to an AWS kinesis stream.
// Configuration example
//
// - "producer.Kinesis":
// Region: "eu-west-1"
// Endpoint: "kinesis.eu-west-1.amazonaws.com"
// CredentialType: "none"
// CredentialId: ""
// CredentialToken: ""
// CredentialSecret: ""
// CredentialFile: ""
// CredentialProfile: ""
// BatchMaxMessages: 500
// RecordMaxMessages: 1
// RecordMessageDelimiter: "\n"
// SendTimeframeSec: 1
// BatchTimeoutSec: 3
// StreamMapping:
// "*" : "default"
//
// KinesisStream defines the stream to read from.
// By default this is set to "default"
//
// Region defines the amazon region of your kinesis stream.
// By default this is set to "eu-west-1".
//
// Endpoint defines the amazon endpoint for your kinesis stream.
// By default this is et to "kinesis.eu-west-1.amazonaws.com"
//
// CredentialType defines the credentials that are to be used when
// connectiong to kensis. This can be one of the following: environment,
// static, shared, none.
// Static enables the parameters CredentialId, CredentialToken and
// CredentialSecret shared enables the parameters CredentialFile and
// CredentialProfile. None will not use any credentials and environment
// will pull the credentials from environmental settings.
// By default this is set to none.
//
// BatchMaxMessages defines the maximum number of messages to send per
// batch. By default this is set to 500.
//
// RecordMaxMessages defines the maximum number of messages to join into
// a kinesis record. By default this is set to 500.
//
// RecordMessageDelimiter defines the string to delimit messages within
// a kinesis record. By default this is set to "\n".
//
// SendTimeframeMs defines the timeframe in milliseconds in which a second
// batch send can be triggered. By default this is set to 1000, i.e. one
// send operation per second.
//
// BatchTimeoutSec defines the number of seconds after which a batch is
// flushed automatically. By default this is set to 3.
//
// StreamMapping defines a translation from gollum stream to kinesis stream
// name. If no mapping is given the gollum stream name is used as kinesis
// stream name.
type Kinesis struct {
core.ProducerBase
client *kinesis.Kinesis
config *aws.Config
streamMap map[core.MessageStreamID]string
batch core.MessageBatch
recordMaxMessages int
delimiter []byte
flushFrequency time.Duration
lastSendTime time.Time
sendTimeLimit time.Duration
counters map[string]*int64
lastMetricUpdate time.Time
}
const (
kinesisMetricMessages = "Kinesis:Messages-"
kinesisMetricMessagesSec = "Kinesis:MessagesSec-"
)
type streamData struct {
content *kinesis.PutRecordsInput
original [][]*core.Message
lastRecordMessages int
}
func init() {
shared.TypeRegistry.Register(Kinesis{})
}
// Configure initializes this producer with values from a plugin config.
func (prod *Kinesis) Configure(conf core.PluginConfig) error {
err := prod.ProducerBase.Configure(conf)
if err != nil {
return err
}
prod.SetStopCallback(prod.close)
prod.streamMap = conf.GetStreamMap("StreamMapping", "")
prod.batch = core.NewMessageBatch(conf.GetInt("BatchMaxMessages", 500))
prod.recordMaxMessages = conf.GetInt("RecordMaxMessages", 1)
prod.delimiter = []byte(conf.GetString("RecordMessageDelimiter", "\n"))
prod.flushFrequency = time.Duration(conf.GetInt("BatchTimeoutSec", 3)) * time.Second
prod.sendTimeLimit = time.Duration(conf.GetInt("SendTimeframeMs", 1000)) * time.Millisecond
prod.lastSendTime = time.Now()
prod.counters = make(map[string]*int64)
prod.lastMetricUpdate = time.Now()
if prod.recordMaxMessages < 1 {
prod.recordMaxMessages = 1
Log.Warning.Print("RecordMaxMessages was < 1. Defaulting to 1.")
}
if prod.recordMaxMessages > 1 && len(prod.delimiter) == 0 {
prod.delimiter = []byte("\n")
Log.Warning.Print("RecordMessageDelimiter was empty. Defaulting to \"\\n\".")
}
// Config
prod.config = aws.NewConfig()
if endpoint := conf.GetString("Endpoint", "kinesis.eu-west-1.amazonaws.com"); endpoint != "" {
prod.config.WithEndpoint(endpoint)
}
if region := conf.GetString("Region", "eu-west-1"); region != "" {
prod.config.WithRegion(region)
}
// Credentials
credentialType := strings.ToLower(conf.GetString("CredentialType", kinesisCredentialNone))
switch credentialType {
case kinesisCredentialEnv:
prod.config.WithCredentials(credentials.NewEnvCredentials())
case kinesisCredentialStatic:
id := conf.GetString("CredentialId", "")
token := conf.GetString("CredentialToken", "")
secret := conf.GetString("CredentialSecret", "")
prod.config.WithCredentials(credentials.NewStaticCredentials(id, secret, token))
case kinesisCredentialShared:
filename := conf.GetString("CredentialFile", "")
profile := conf.GetString("CredentialProfile", "")
prod.config.WithCredentials(credentials.NewSharedCredentials(filename, profile))
case kinesisCredentialNone:
// Nothing
default:
return fmt.Errorf("Unknown CredentialType: %s", credentialType)
}
for _, streamName := range prod.streamMap {
shared.Metric.New(kinesisMetricMessages + streamName)
shared.Metric.New(kinesisMetricMessagesSec + streamName)
prod.counters[streamName] = new(int64)
}
return nil
}
func (prod *Kinesis) bufferMessage(msg core.Message) {
prod.batch.AppendOrFlush(msg, prod.sendBatch, prod.IsActiveOrStopping, prod.Drop)
}
func (prod *Kinesis) sendBatchOnTimeOut() {
// Flush if necessary
if prod.batch.ReachedTimeThreshold(prod.flushFrequency) || prod.batch.ReachedSizeThreshold(prod.batch.Len()/2) {
prod.sendBatch()
}
duration := time.Since(prod.lastMetricUpdate)
prod.lastMetricUpdate = time.Now()
for streamName, counter := range prod.counters {
count := atomic.SwapInt64(counter, 0)
shared.Metric.Add(kinesisMetricMessages+streamName, count)
shared.Metric.SetF(kinesisMetricMessagesSec+streamName, float64(count)/duration.Seconds())
}
}
func (prod *Kinesis) sendBatch() {
prod.batch.Flush(prod.transformMessages)
}
func (prod *Kinesis) dropMessages(messages []core.Message) {
for _, msg := range messages {
prod.Drop(msg)
}
}
func (prod *Kinesis) transformMessages(messages []core.Message) {
streamRecords := make(map[core.MessageStreamID]*streamData)
// Format and sort
for idx, msg := range messages {
msgData, streamID := prod.ProducerBase.Format(msg)
messageHash := fmt.Sprintf("%X-%d", streamID, msg.Sequence)
// Fetch buffer for this stream
records, recordsExists := streamRecords[streamID]
if !recordsExists {
// Select the correct kinesis stream
streamName, streamMapped := prod.streamMap[streamID]
if !streamMapped {
streamName, streamMapped = prod.streamMap[core.WildcardStreamID]
if !streamMapped {
streamName = core.StreamRegistry.GetStreamName(streamID)
prod.streamMap[streamID] = streamName
shared.Metric.New(kinesisMetricMessages + streamName)
shared.Metric.New(kinesisMetricMessagesSec + streamName)
prod.counters[streamName] = new(int64)
}
}
// Create buffers for this kinesis stream
maxLength := len(messages)/prod.recordMaxMessages + 1
records = &streamData{
content: &kinesis.PutRecordsInput{
Records: make([]*kinesis.PutRecordsRequestEntry, 0, maxLength),
StreamName: aws.String(streamName),
},
original: make([][]*core.Message, 0, maxLength),
lastRecordMessages: 0,
}
streamRecords[streamID] = records
}
// Fetch record for this buffer
var record *kinesis.PutRecordsRequestEntry
recordExists := len(records.content.Records) > 0
if !recordExists || records.lastRecordMessages+1 > prod.recordMaxMessages {
// Append record to stream
record = &kinesis.PutRecordsRequestEntry{
Data: make([]byte, 0, len(msgData)),
PartitionKey: aws.String(messageHash),
}
records.content.Records = append(records.content.Records, record)
records.original = append(records.original, make([]*core.Message, 0, prod.recordMaxMessages))
records.lastRecordMessages = 0
} else {
record = records.content.Records[len(records.content.Records)-1]
record.Data = append(record.Data, prod.delimiter...)
}
// Append message to record
record.Data = append(record.Data, msgData...)
records.lastRecordMessages++
records.original[len(records.original)-1] = append(records.original[len(records.original)-1], &messages[idx])
}
sleepDuration := prod.sendTimeLimit - time.Since(prod.lastSendTime)
if sleepDuration > 0 {
time.Sleep(sleepDuration)
}
// Send to Kinesis
for _, records := range streamRecords {
result, err := prod.client.PutRecords(records.content)
atomic.AddInt64(prod.counters[*records.content.StreamName], int64(len(records.content.Records)))
if err != nil {
// Batch failed, drop all
Log.Error.Print("Kinesis write error: ", err)
for _, messages := range records.original {
for _, msg := range messages {
prod.Drop(*msg)
}
}
} else {
// Check each message for errors
for msgIdx, record := range result.Records {
if record.ErrorMessage != nil {
Log.Error.Print("Kinesis message write error: ", *record.ErrorMessage)
for _, msg := range records.original[msgIdx] {
prod.Drop(*msg)
}
}
}
}
}
}
func (prod *Kinesis) close() {
defer prod.WorkerDone()
prod.CloseMessageChannel(prod.bufferMessage)
prod.batch.Close(prod.transformMessages, prod.GetShutdownTimeout())
}
// Produce writes to stdout or stderr.
func (prod *Kinesis) Produce(workers *sync.WaitGroup) {
prod.AddMainWorker(workers)
prod.client = kinesis.New(session.New(prod.config))
prod.TickerMessageControlLoop(prod.bufferMessage, prod.flushFrequency, prod.sendBatchOnTimeOut)
}