forked from twitchscience/kinsumer
-
Notifications
You must be signed in to change notification settings - Fork 1
/
kinsumer.go
583 lines (513 loc) · 19.4 KB
/
kinsumer.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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
// Copyright (c) 2016 Twitch Interactive
package kinsumer
import (
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface"
"github.com/aws/aws-sdk-go/service/kinesis"
"github.com/aws/aws-sdk-go/service/kinesis/kinesisiface"
"github.com/google/uuid"
"golang.org/x/sync/errgroup"
)
type shardConsumerError struct {
shardID string
action string
err error
}
type consumedRecord struct {
record *kinesis.Record // Record retrieved from kinesis
checkpointer *checkpointer // Object that will store the checkpoint back to the database
retrievedAt time.Time // Time the record was retrieved from Kinesis
}
// Kinsumer is a Kinesis Consumer that tries to reduce duplicate reads while allowing for multiple
// clients each processing multiple shards
type Kinsumer struct {
kinesis kinesisiface.KinesisAPI // interface to the kinesis service
dynamodb dynamodbiface.DynamoDBAPI // interface to the dynamodb service
streamName string // name of the kinesis stream to consume from
shardIDs []string // all the shards in the stream, for detecting when the shards change
stop chan struct{} // channel used to signal to all the go routines that we want to stop consuming
stoprequest chan bool // channel used internally to signal to the main go routine to stop processing
records chan *consumedRecord // channel for the go routines to put the consumed records on
output chan *consumedRecord // unbuffered channel used to communicate from the main loop to the Next() method
errors chan error // channel used to communicate errors back to the caller
waitGroup sync.WaitGroup // waitGroup to sync the consumers go routines on
mainWG sync.WaitGroup // WaitGroup for the mainLoop
shardErrors chan shardConsumerError // all the errors found by the consumers that were not handled
clientsTableName string // dynamo table of info about each client
checkpointTableName string // dynamo table of the checkpoints for each shard
metadataTableName string // dynamo table of metadata about the leader and shards
clientID string // identifier to differentiate between the running clients
clientName string // display name of the client - used just for debugging
totalClients int // The number of clients that are currently working on this stream
thisClient int // The (sorted by name) index of this client in the total list
config Config // configuration struct
numberOfRuns int32 // Used to atomically make sure we only ever allow one Run() to be called
isLeader bool // Whether this client is the leader
leaderLost chan bool // Channel that receives an event when the node loses leadership
leaderWG sync.WaitGroup // waitGroup for the leader loop
maxAgeForClientRecord time.Duration // Cutoff for client/checkpoint records we read from dynamodb before we assume the record is stale
maxAgeForLeaderRecord time.Duration // Cutoff for leader/shard cache records we read from dynamodb before we assume the record is stale
}
// New returns a Kinsumer Interface with default kinesis and dynamodb instances, to be used in ec2 instances to get default auth and config
func New(streamName, applicationName, clientName string, config Config) (*Kinsumer, error) {
s, err := session.NewSession()
if err != nil {
return nil, err
}
return NewWithSession(s, streamName, applicationName, clientName, config)
}
// NewWithSession should be used if you want to override the Kinesis and Dynamo instances with a non-default aws session
func NewWithSession(session *session.Session, streamName, applicationName, clientName string, config Config) (*Kinsumer, error) {
k := kinesis.New(session)
d := dynamodb.New(session)
return NewWithInterfaces(k, d, streamName, applicationName, clientName, config)
}
// NewWithInterfaces allows you to override the Kinesis and Dynamo instances for mocking or using a local set of servers
func NewWithInterfaces(kinesis kinesisiface.KinesisAPI, dynamodb dynamodbiface.DynamoDBAPI, streamName, applicationName, clientName string, config Config) (*Kinsumer, error) {
if kinesis == nil {
return nil, ErrNoKinesisInterface
}
if dynamodb == nil {
return nil, ErrNoDynamoInterface
}
if streamName == "" {
return nil, ErrNoStreamName
}
if applicationName == "" {
return nil, ErrNoApplicationName
}
if err := validateConfig(&config); err != nil {
return nil, err
}
consumer := &Kinsumer{
streamName: streamName,
kinesis: kinesis,
dynamodb: dynamodb,
stoprequest: make(chan bool),
records: make(chan *consumedRecord, config.bufferSize),
output: make(chan *consumedRecord),
errors: make(chan error, 10),
shardErrors: make(chan shardConsumerError, 10),
checkpointTableName: applicationName + "_checkpoints",
clientsTableName: applicationName + "_clients",
metadataTableName: applicationName + "_metadata",
clientID: uuid.New().String(),
clientName: clientName,
config: config,
maxAgeForClientRecord: config.shardCheckFrequency * 5,
maxAgeForLeaderRecord: config.leaderActionFrequency * 5,
}
return consumer, nil
}
// refreshShards registers our client, refreshes the lists of clients and shards, checks if we
// have become/unbecome the leader, and returns whether the shards/clients changed.
//TODO: Write unit test - needs dynamo _and_ kinesis mocking
func (k *Kinsumer) refreshShards() (bool, error) {
var shardIDs []string
if err := registerWithClientsTable(k.dynamodb, k.clientID, k.clientName, k.clientsTableName); err != nil {
return false, err
}
//TODO: Move this out of refreshShards and into refreshClients
clients, err := getClients(k.dynamodb, k.clientID, k.clientsTableName, k.maxAgeForClientRecord)
if err != nil {
return false, err
}
totalClients := len(clients)
thisClient := 0
found := false
for i, c := range clients {
if c.ID == k.clientID {
thisClient = i
found = true
break
}
}
if !found {
return false, ErrThisClientNotInDynamo
}
if thisClient == 0 && !k.isLeader {
k.becomeLeader()
} else if thisClient != 0 && k.isLeader {
k.unbecomeLeader()
}
shardIDs, err = loadShardIDsFromDynamo(k.dynamodb, k.metadataTableName)
if err != nil {
return false, err
}
if len(shardIDs) == 0 {
shardIDs, err = loadShardIDsFromKinesis(k.kinesis, k.streamName)
if err == nil {
err = k.setCachedShardIDs(shardIDs)
}
}
if err != nil {
return false, err
}
changed := (totalClients != k.totalClients) ||
(thisClient != k.thisClient) ||
(len(k.shardIDs) != len(shardIDs))
if !changed {
for idx := range shardIDs {
if shardIDs[idx] != k.shardIDs[idx] {
changed = true
break
}
}
}
if changed {
k.shardIDs = shardIDs
}
k.thisClient = thisClient
k.totalClients = totalClients
return changed, nil
}
// startConsumers launches a shard consumer for each shard we should own
// TODO: Can we unit test this at all?
func (k *Kinsumer) startConsumers() error {
k.stop = make(chan struct{})
assigned := false
if k.thisClient >= len(k.shardIDs) {
return nil
}
for i, shard := range k.shardIDs {
if (i % k.totalClients) == k.thisClient {
k.waitGroup.Add(1)
assigned = true
go k.consume(shard)
}
}
if len(k.shardIDs) != 0 && !assigned {
return ErrNoShardsAssigned
}
return nil
}
// stopConsumers stops all our shard consumers
func (k *Kinsumer) stopConsumers() {
close(k.stop)
k.waitGroup.Wait()
DrainLoop:
for {
select {
case <-k.records:
default:
break DrainLoop
}
}
}
// dynamoTableReady returns an error if the given table is not ACTIVE or UPDATING
func (k *Kinsumer) dynamoTableReady(name string) error {
out, err := k.dynamodb.DescribeTable(&dynamodb.DescribeTableInput{
TableName: aws.String(name),
})
if err != nil {
return fmt.Errorf("error describing table %s: %v", name, err)
}
status := aws.StringValue(out.Table.TableStatus)
if status != "ACTIVE" && status != "UPDATING" {
return fmt.Errorf("table %s exists but state '%s' is not 'ACTIVE' or 'UPDATING'",
name, status)
}
return nil
}
// dynamoTableExists returns an true if the given table exists
func (k *Kinsumer) dynamoTableExists(name string) bool {
_, err := k.dynamodb.DescribeTable(&dynamodb.DescribeTableInput{
TableName: aws.String(name),
})
return err == nil
}
// dynamoCreateTableIfNotExists creates a table with the given name and distKey
// if it doesn't exist and will wait until it is created
func (k *Kinsumer) dynamoCreateTableIfNotExists(name, distKey string) error {
if k.dynamoTableExists(name) {
return nil
}
_, err := k.dynamodb.CreateTable(&dynamodb.CreateTableInput{
AttributeDefinitions: []*dynamodb.AttributeDefinition{{
AttributeName: aws.String(distKey),
AttributeType: aws.String(dynamodb.ScalarAttributeTypeS),
}},
KeySchema: []*dynamodb.KeySchemaElement{{
AttributeName: aws.String(distKey),
KeyType: aws.String(dynamodb.KeyTypeHash),
}},
ProvisionedThroughput: &dynamodb.ProvisionedThroughput{
ReadCapacityUnits: aws.Int64(k.config.dynamoReadCapacity),
WriteCapacityUnits: aws.Int64(k.config.dynamoWriteCapacity),
},
TableName: aws.String(name),
})
if err != nil {
return err
}
err = k.dynamodb.WaitUntilTableExistsWithContext(
aws.BackgroundContext(),
&dynamodb.DescribeTableInput{
TableName: aws.String(name),
},
request.WithWaiterDelay(request.ConstantWaiterDelay(k.config.dynamoWaiterDelay)),
)
return err
}
// dynamoDeleteTableIfExists delete a table with the given name if it exists
// and will wait until it is deleted
func (k *Kinsumer) dynamoDeleteTableIfExists(name string) error {
if !k.dynamoTableExists(name) {
return nil
}
_, err := k.dynamodb.DeleteTable(&dynamodb.DeleteTableInput{
TableName: aws.String(name),
})
if err != nil {
return err
}
err = k.dynamodb.WaitUntilTableNotExistsWithContext(
aws.BackgroundContext(),
&dynamodb.DescribeTableInput{
TableName: aws.String(name),
},
request.WithWaiterDelay(request.ConstantWaiterDelay(k.config.dynamoWaiterDelay)),
)
return err
}
// kinesisStreamReady returns an error if the given stream is not ACTIVE
func (k *Kinsumer) kinesisStreamReady() error {
out, err := k.kinesis.DescribeStream(&kinesis.DescribeStreamInput{
StreamName: aws.String(k.streamName),
})
if err != nil {
return fmt.Errorf("error describing stream %s: %v", k.streamName, err)
}
status := aws.StringValue(out.StreamDescription.StreamStatus)
if status != "ACTIVE" && status != "UPDATING" {
return fmt.Errorf("stream %s exists but state '%s' is not 'ACTIVE' or 'UPDATING'", k.streamName, status)
}
return nil
}
// Run runs the main kinesis consumer process. This is a non-blocking call, use Stop() to force it to return.
// This goroutine is responsible for starting/stopping consumers, aggregating all consumers' records,
// updating checkpointers as records are consumed, and refreshing our shard/client list and leadership
//TODO: Can we unit test this at all?
func (k *Kinsumer) Run() error {
if err := k.dynamoTableReady(k.checkpointTableName); err != nil {
return err
}
if err := k.dynamoTableReady(k.clientsTableName); err != nil {
return err
}
if err := k.kinesisStreamReady(); err != nil {
return err
}
allowRun := atomic.CompareAndSwapInt32(&k.numberOfRuns, 0, 1)
if !allowRun {
return ErrRunTwice
}
if _, err := k.refreshShards(); err != nil {
deregErr := deregisterFromClientsTable(k.dynamodb, k.clientID, k.clientsTableName)
if deregErr != nil {
return fmt.Errorf("error in kinsumer Run initial refreshShards: (%v); "+
"error deregistering from clients table: (%v)", err, deregErr)
}
return fmt.Errorf("error in kinsumer Run initial refreshShards: %v", err)
}
k.mainWG.Add(1)
go func() {
defer k.mainWG.Done()
defer func() {
// Deregister is a nice to have but clients also time out if they
// fail to deregister, so ignore error here.
err := deregisterFromClientsTable(k.dynamodb, k.clientID, k.clientsTableName)
if err != nil {
k.errors <- fmt.Errorf("error deregistering client: %s", err)
}
k.unbecomeLeader()
// Do this outside the k.isLeader check in case k.isLeader was false because
// we lost leadership but haven't had time to shutdown the goroutine yet.
k.leaderWG.Wait()
}()
// We close k.output so that Next() stops, this is also the reason
// we can't allow Run() to be called after Stop() has happened
defer close(k.output)
shardChangeTicker := time.NewTicker(k.config.shardCheckFrequency)
defer func() {
shardChangeTicker.Stop()
}()
var record *consumedRecord
if err := k.startConsumers(); err != nil {
k.errors <- fmt.Errorf("error starting consumers: %s", err)
}
defer k.stopConsumers()
for {
var (
input chan *consumedRecord
output chan *consumedRecord
)
// We only want to be handing one record from the consumers
// to the user of kinsumer at a time. We do this by only reading
// one record off the records queue if we do not already have a
// record to give away
if record != nil {
output = k.output
} else {
input = k.records
}
select {
case <-k.stoprequest:
return
case record = <-input:
case output <- record:
if !k.config.manualCheckpointing {
record.checkpointer.update(aws.StringValue(record.record.SequenceNumber))
}
record = nil
case se := <-k.shardErrors:
k.errors <- fmt.Errorf("shard error (%s) in %s: %s", se.shardID, se.action, se.err)
case <-shardChangeTicker.C:
changed, err := k.refreshShards()
if err != nil {
k.errors <- fmt.Errorf("error refreshing shards: %s", err)
} else if changed {
shardChangeTicker.Stop()
k.stopConsumers()
record = nil
if err := k.startConsumers(); err != nil {
k.errors <- fmt.Errorf("error restarting consumers: %s", err)
}
// We create a new shardChangeTicker here so that the time it takes to stop and
// start the consumers is not included in the wait for the next tick.
shardChangeTicker = time.NewTicker(k.config.shardCheckFrequency)
}
}
}
}()
return nil
}
// Stop stops the consumption of kinesis events
//TODO: Can we unit test this at all?
func (k *Kinsumer) Stop() {
k.stoprequest <- true
k.mainWG.Wait()
}
// Next is a blocking function used to get the next record from the kinesis queue, or errors that
// occurred during the processing of kinesis. It's up to the caller to stop processing by calling 'Stop()'
//
// if err is non nil an error occurred in the system.
// if err is nil and data is nil then kinsumer has been stopped
func (k *Kinsumer) Next() (data []byte, err error) {
if k.config.manualCheckpointing {
return nil, fmt.Errorf("manual checkpointing is enabled, use NextWithCheckpointer() instead")
}
select {
case err = <-k.errors:
return nil, err
case record, ok := <-k.output:
if ok {
k.config.stats.EventToClient(*record.record.ApproximateArrivalTimestamp, record.retrievedAt)
data = record.record.Data
}
}
return data, err
}
// NextRecord is a blocking function used to get the next record from the kinesis queue, or errors that
// occurred during the processing of kinesis. It's up to the caller to stop processing by calling 'Stop()'
//
// if err is non nil an error occurred in the system.
// if err is nil and record is nil then kinsumer has been stopped
func (k *Kinsumer) NextRecord() (rec *kinesis.Record, err error) {
if k.config.manualCheckpointing {
return nil, fmt.Errorf("manual checkpointing is enabled, use NextRecordWithCheckpointer() instead")
}
select {
case err = <-k.errors:
return nil, err
case record, ok := <-k.output:
if ok {
k.config.stats.EventToClient(*record.record.ApproximateArrivalTimestamp, record.retrievedAt)
rec = record.record
}
}
return rec, err
}
// NextWithCheckpointer is a blocking function used to get the next record from the kinesis queue, or errors that
// occurred during the processing of kinesis. It's up to the caller to stop processing by calling 'Stop()'
// checkpointer must be called when the record is fully processed. Kinsumer will ensure checkpointer calls are ordered.
// WARNING: checkpointer() can block indefinitely if not called in order.
//
// if err is non nil an error occurred in the system.
// if err is nil and data is nil then kinsumer has been stopped
func (k *Kinsumer) NextWithCheckpointer() (data []byte, checkpointer func(), err error) {
if !k.config.manualCheckpointing {
return nil, nil, fmt.Errorf("manual checkpointing is disabled, use Next() instead")
}
select {
case err = <-k.errors:
return nil, nil, err
case record, ok := <-k.output:
if ok {
k.config.stats.EventToClient(*record.record.ApproximateArrivalTimestamp, record.retrievedAt)
data = record.record.Data
checkpointer = record.checkpointer.updateFunc(aws.StringValue(record.record.SequenceNumber))
}
}
return data, checkpointer, err
}
// NextRecordWithCheckpointer is a blocking function used to get the next record from the kinesis queue, or errors that
// occurred during the processing of kinesis. It's up to the caller to stop processing by calling 'Stop()'
// checkpointer must be called when the record is fully processed. Kinsumer will ensure checkpointer calls are ordered.
// WARNING: checkpointer() can block indefinitely if not called in order.
//
// if err is non nil an error occurred in the system.
// if err is nil and data is nil then kinsumer has been stopped
func (k *Kinsumer) NextRecordWithCheckpointer() (rec *kinesis.Record, checkpointer func(), err error) {
if !k.config.manualCheckpointing {
return nil, nil, fmt.Errorf("manual checkpointing is disabled, use NextRecord() instead")
}
select {
case err = <-k.errors:
return nil, nil, err
case record, ok := <-k.output:
if ok {
k.config.stats.EventToClient(*record.record.ApproximateArrivalTimestamp, record.retrievedAt)
rec = record.record
checkpointer = record.checkpointer.updateFunc(aws.StringValue(record.record.SequenceNumber))
}
}
return rec, checkpointer, err
}
// CreateRequiredTables will create the required dynamodb tables
// based on the applicationName
func (k *Kinsumer) CreateRequiredTables() error {
g := &errgroup.Group{}
g.Go(func() error {
return k.dynamoCreateTableIfNotExists(k.clientsTableName, "ID")
})
g.Go(func() error {
return k.dynamoCreateTableIfNotExists(k.checkpointTableName, "Shard")
})
g.Go(func() error {
return k.dynamoCreateTableIfNotExists(k.metadataTableName, "Key")
})
return g.Wait()
}
// DeleteTables will delete the dynamodb tables that were created
// based on the applicationName
func (k *Kinsumer) DeleteTables() error {
g := &errgroup.Group{}
g.Go(func() error {
return k.dynamoDeleteTableIfExists(k.clientsTableName)
})
g.Go(func() error {
return k.dynamoDeleteTableIfExists(k.checkpointTableName)
})
g.Go(func() error {
return k.dynamoDeleteTableIfExists(k.metadataTableName)
})
return g.Wait()
}