forked from twitchscience/kinsumer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kinsumer_test.go
617 lines (509 loc) · 16.9 KB
/
kinsumer_test.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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
// Copyright (c) 2016 Twitch Interactive
package kinsumer
import (
"flag"
"fmt"
"math/rand"
"sort"
"strconv"
"sync"
"testing"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
"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/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var (
awsRegion = flag.String("region", "us-west-2", "Region to run tests in")
dynamoEndpoint = flag.String("dynamo_endpoint", "http://localhost:4567", "Endpoint for dynamo test server")
kinesisEndpoint = flag.String("kinesis_endpoint", "http://localhost:4568", "Endpoint for kinesis test server")
resourceChangeTimeout = flag.Duration("resource_change_timeout", 50*time.Millisecond, "Timeout between changes to the resource infrastructure")
streamName = flag.String("stream_name", "kinsumer_test", "Name of kinesis stream to use for tests")
applicationName = flag.String("application_name", "kinsumer_test", "Name of the application, will impact dynamo table names")
)
const (
shardCount int64 = 10
shardLimit int64 = 100
)
func TestNewWithInterfaces(t *testing.T) {
s := session.Must(session.NewSession())
k := kinesis.New(s)
d := dynamodb.New(s)
// No kinesis
_, err := NewWithInterfaces(nil, d, "stream", "app", "client", NewConfig())
assert.NotEqual(t, err, nil)
// No dynamodb
_, err = NewWithInterfaces(k, nil, "stream", "app", "client", NewConfig())
assert.NotEqual(t, err, nil)
// No streamName
_, err = NewWithInterfaces(k, d, "", "app", "client", NewConfig())
assert.NotEqual(t, err, nil)
// No applicationName
_, err = NewWithInterfaces(k, d, "stream", "", "client", NewConfig())
assert.NotEqual(t, err, nil)
// Invalid config
_, err = NewWithInterfaces(k, d, "stream", "app", "client", Config{})
assert.NotEqual(t, err, nil)
// All ok
kinsumer, err := NewWithInterfaces(k, d, "stream", "app", "client", NewConfig())
assert.Equal(t, err, nil)
assert.NotEqual(t, kinsumer, nil)
}
func CreateFreshStream(t *testing.T, k kinesisiface.KinesisAPI) error {
_, err := k.DeleteStream(&kinesis.DeleteStreamInput{
StreamName: streamName,
})
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
if awsErr.Code() != "ResourceNotFoundException" {
return err
}
}
} else {
// Wait for the stream to be deleted
time.Sleep(*resourceChangeTimeout)
}
_, err = k.CreateStream(&kinesis.CreateStreamInput{
ShardCount: aws.Int64(shardCount),
StreamName: streamName,
})
if err != nil {
return err
}
time.Sleep(*resourceChangeTimeout)
return nil
}
func SetupTestEnvironment(t *testing.T, k kinesisiface.KinesisAPI, d dynamodbiface.DynamoDBAPI) error {
err := CreateFreshStream(t, k)
if err != nil {
return fmt.Errorf("Error creating fresh stream: %s", err)
}
testConf := NewConfig().WithDynamoWaiterDelay(*resourceChangeTimeout)
client, _ := NewWithInterfaces(k, d, "N/A", *applicationName, "N/A", testConf)
err = client.DeleteTables()
if err != nil {
return fmt.Errorf("Error deleting tables: %s", err)
}
err = client.CreateRequiredTables()
if err != nil {
return fmt.Errorf("Error creating fresh tables: %s", err)
}
return nil
}
func ignoreResourceNotFound(err error) error {
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
if awsErr.Code() != "ResourceNotFoundException" {
return err
}
}
} else {
time.Sleep(*resourceChangeTimeout)
}
return nil
}
func CleanupTestEnvironment(t *testing.T, k kinesisiface.KinesisAPI, d dynamodbiface.DynamoDBAPI) error {
_, err := k.DeleteStream(&kinesis.DeleteStreamInput{
StreamName: streamName,
})
if e := ignoreResourceNotFound(err); e != nil {
return fmt.Errorf("Error deleting kinesis stream: %s", e)
}
testConf := NewConfig().WithDynamoWaiterDelay(*resourceChangeTimeout)
client, _ := NewWithInterfaces(k, d, "N/A", *applicationName, "", testConf)
err = client.DeleteTables()
if err != nil {
return fmt.Errorf("Error deleting tables: %s", err)
}
return nil
}
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
func randStringBytes(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = letterBytes[rand.Intn(len(letterBytes))]
}
return string(b)
}
func SpamStream(t *testing.T, k kinesisiface.KinesisAPI, numEvents int64) error {
var (
records []*kinesis.PutRecordsRequestEntry
counter int64
)
for counter = 0; counter < numEvents; counter++ {
records = append(records, &kinesis.PutRecordsRequestEntry{
Data: []byte(strconv.FormatInt(counter, 10)),
PartitionKey: aws.String(randStringBytes(10)),
})
if len(records) == 100 {
pro, err := k.PutRecords(&kinesis.PutRecordsInput{
StreamName: streamName,
Records: records,
})
if err != nil {
return fmt.Errorf("Error putting records onto stream: %s", err)
}
failed := aws.Int64Value(pro.FailedRecordCount)
require.EqualValues(t, 0, failed)
records = nil
}
}
if len(records) > 0 {
pro, err := k.PutRecords(&kinesis.PutRecordsInput{
StreamName: streamName,
Records: records,
})
if err != nil {
return fmt.Errorf("Error putting records onto stream: %s", err)
}
failed := aws.Int64Value(pro.FailedRecordCount)
require.EqualValues(t, 0, failed)
}
return nil
}
func KinesisAndDynamoInstances() (kinesisiface.KinesisAPI, dynamodbiface.DynamoDBAPI) {
kc := aws.NewConfig().WithRegion(*awsRegion).WithLogLevel(3)
if len(*kinesisEndpoint) > 0 {
kc = kc.WithEndpoint(*kinesisEndpoint)
}
dc := aws.NewConfig().WithRegion(*awsRegion).WithLogLevel(3)
if len(*dynamoEndpoint) > 0 {
dc = dc.WithEndpoint(*dynamoEndpoint)
}
k := kinesis.New(session.Must(session.NewSession(kc)))
d := dynamodb.New(session.Must(session.NewSession(dc)))
return k, d
}
func TestSetup(t *testing.T) {
if testing.Short() {
t.Skip("skipping test in short mode.")
}
k, d := KinesisAndDynamoInstances()
defer func() {
err := CleanupTestEnvironment(t, k, d)
require.NoError(t, err, "Problems cleaning up the test environment")
}()
err := SetupTestEnvironment(t, k, d)
require.NoError(t, err, "Problems setting up the test environment")
err = SpamStream(t, k, 233)
require.NoError(t, err, "Problems spamming stream with events")
}
// This is not a real final test. It's just a harness for development and to kind of think through the interface
func TestKinsumer(t *testing.T) {
const (
numberOfEventsToTest = 4321
numberOfClients = 3
)
if testing.Short() {
t.Skip("skipping test in short mode.")
}
k, d := KinesisAndDynamoInstances()
defer func() {
err := CleanupTestEnvironment(t, k, d)
require.NoError(t, err, "Problems cleaning up the test environment")
}()
err := SetupTestEnvironment(t, k, d)
require.NoError(t, err, "Problems setting up the test environment")
clients := make([]*Kinsumer, numberOfClients)
eventsPerClient := make([]int, numberOfClients)
output := make(chan int, numberOfClients)
var waitGroup sync.WaitGroup
config := NewConfig().WithBufferSize(numberOfEventsToTest)
config = config.WithShardCheckFrequency(500 * time.Millisecond)
config = config.WithLeaderActionFrequency(500 * time.Millisecond)
for i := 0; i < numberOfClients; i++ {
if i > 0 {
time.Sleep(50 * time.Millisecond) // Add the clients slowly
}
clients[i], err = NewWithInterfaces(k, d, *streamName, *applicationName, fmt.Sprintf("test_%d", i), config)
require.NoError(t, err, "NewWithInterfaces() failed")
err = clients[i].Run()
require.NoError(t, err, "kinsumer.Run() failed")
err = clients[i].Run()
assert.Error(t, err, "second time calling kinsumer.Run() should fail")
waitGroup.Add(1)
go func(client *Kinsumer, ci int) {
defer waitGroup.Done()
for {
data, innerError := client.Next()
require.NoError(t, innerError, "kinsumer.Next() failed")
if data == nil {
return
}
idx, _ := strconv.Atoi(string(data))
output <- idx
eventsPerClient[ci]++
}
}(clients[i], i)
defer func(ci int) {
if clients[ci] != nil {
clients[ci].Stop()
}
}(i)
}
err = SpamStream(t, k, numberOfEventsToTest)
require.NoError(t, err, "Problems spamming stream with events")
readEvents(t, output, numberOfEventsToTest)
for ci, client := range clients {
client.Stop()
clients[ci] = nil
}
drain(t, output)
// Make sure the go routines have finished
waitGroup.Wait()
}
// TestLeader is an integration test of leadership claiming and deleting old clients.
func TestLeader(t *testing.T) {
const (
numberOfEventsToTest = 4321
numberOfClients = 2
)
if testing.Short() {
t.Skip("skipping test in short mode.")
}
k, d := KinesisAndDynamoInstances()
defer func() {
err := CleanupTestEnvironment(t, k, d)
require.NoError(t, err, "Problems cleaning up the test environment")
}()
err := SetupTestEnvironment(t, k, d)
require.NoError(t, err, "Problems setting up the test environment")
clients := make([]*Kinsumer, numberOfClients)
output := make(chan int, numberOfClients)
var waitGroup sync.WaitGroup
// Put an old client that should be deleted.
now := time.Now().Add(-time.Hour * 24 * 7)
item, err := dynamodbattribute.MarshalMap(clientRecord{
ID: "Old",
Name: "Old",
LastUpdate: now.UnixNano(),
LastUpdateRFC: now.UTC().Format(time.RFC1123Z),
})
require.NoError(t, err, "Problems converting old client")
clientsTableName := aws.String(*streamName + "_clients")
_, err = d.PutItem(&dynamodb.PutItemInput{
TableName: clientsTableName,
Item: item,
})
require.NoError(t, err, "Problems putting old client")
config := NewConfig().WithBufferSize(numberOfEventsToTest)
config = config.WithShardCheckFrequency(500 * time.Millisecond)
config = config.WithLeaderActionFrequency(500 * time.Millisecond)
for i := 0; i < numberOfClients; i++ {
if i > 0 {
time.Sleep(50 * time.Millisecond) // Add the clients slowly
}
clients[i], err = NewWithInterfaces(k, d, *streamName, *applicationName, fmt.Sprintf("test_%d", i), config)
require.NoError(t, err, "NewWithInterfaces() failed")
clients[i].clientID = strconv.Itoa(i + 1)
err = clients[i].Run()
require.NoError(t, err, "kinsumer.Run() failed")
waitGroup.Add(1)
go func(client *Kinsumer, ci int) {
defer waitGroup.Done()
for {
data, innerError := client.Next()
require.NoError(t, innerError, "kinsumer.Next() failed")
if data == nil {
return
}
idx, _ := strconv.Atoi(string(data))
output <- idx
}
}(clients[i], i)
defer func(ci int) {
if clients[ci] != nil {
clients[ci].Stop()
}
}(i)
}
err = SpamStream(t, k, numberOfEventsToTest)
require.NoError(t, err, "Problems spamming stream with events")
readEvents(t, output, numberOfEventsToTest)
resp, err := d.GetItem(&dynamodb.GetItemInput{
TableName: clientsTableName,
ConsistentRead: aws.Bool(true),
Key: map[string]*dynamodb.AttributeValue{
"ID": {S: aws.String("Old")},
},
})
require.NoError(t, err, "Problem getting old client")
require.Equal(t, 0, len(resp.Item), "Old client was not deleted")
assert.Equal(t, true, clients[0].isLeader, "First client is not leader")
assert.Equal(t, false, clients[1].isLeader, "Second leader is also leader")
c, err := NewWithInterfaces(k, d, *streamName, *applicationName, fmt.Sprintf("_test_%d", numberOfClients), config)
require.NoError(t, err, "NewWithInterfaces() failed")
c.clientID = "0"
err = c.Run()
require.NoError(t, err, "kinsumer.Run() failed")
require.Equal(t, true, c.isLeader, "New client is not leader")
_, err = clients[0].refreshShards()
require.NoError(t, err, "Problem refreshing shards of original leader")
require.Equal(t, false, clients[0].isLeader, "Original leader is still leader")
c.Stop()
for ci, client := range clients {
client.Stop()
clients[ci] = nil
}
drain(t, output)
// Make sure the go routines have finished
waitGroup.Wait()
}
// TestSplit is an integration test of merging shards, checking the closed and new shards are handled correctly.
func TestSplit(t *testing.T) {
const (
numberOfEventsToTest = 4321
numberOfClients = 3
)
if testing.Short() {
t.Skip("skipping test in short mode.")
}
k, d := KinesisAndDynamoInstances()
defer func() {
err := CleanupTestEnvironment(t, k, d)
require.NoError(t, err, "Problems cleaning up the test environment")
}()
err := SetupTestEnvironment(t, k, d)
require.NoError(t, err, "Problems setting up the test environment")
clients := make([]*Kinsumer, numberOfClients)
output := make(chan int, numberOfClients)
var waitGroup sync.WaitGroup
config := NewConfig().WithBufferSize(numberOfEventsToTest)
config = config.WithShardCheckFrequency(500 * time.Millisecond)
config = config.WithLeaderActionFrequency(500 * time.Millisecond)
config = config.WithCommitFrequency(50 * time.Millisecond)
for i := 0; i < numberOfClients; i++ {
if i > 0 {
time.Sleep(50 * time.Millisecond) // Add the clients slowly
}
clients[i], err = NewWithInterfaces(k, d, *streamName, *applicationName, fmt.Sprintf("test_%d", i), config)
require.NoError(t, err, "NewWithInterfaces() failed")
clients[i].clientID = strconv.Itoa(i + 1)
err = clients[i].Run()
require.NoError(t, err, "kinsumer.Run() failed")
waitGroup.Add(1)
go func(client *Kinsumer, ci int) {
defer waitGroup.Done()
for {
data, innerError := client.Next()
require.NoError(t, innerError, "kinsumer.Next() failed")
if data == nil {
return
}
idx, _ := strconv.Atoi(string(data))
output <- idx
}
}(clients[i], i)
defer func(ci int) {
if clients[ci] != nil {
clients[ci].Stop()
}
}(i)
}
err = SpamStream(t, k, numberOfEventsToTest)
require.NoError(t, err, "Problems spamming stream with events")
readEvents(t, output, numberOfEventsToTest)
desc, err := k.DescribeStream(&kinesis.DescribeStreamInput{
StreamName: streamName,
Limit: aws.Int64(shardLimit),
})
require.NoError(t, err, "Error describing stream")
shards := desc.StreamDescription.Shards
shardMap := make(map[string]*kinesis.Shard)
for _, shard := range shards {
shardMap[*shard.ShardId] = shard
}
require.True(t, len(shards) >= 2, "Fewer than 2 shards")
_, err = k.MergeShards(&kinesis.MergeShardsInput{
StreamName: streamName,
ShardToMerge: aws.String(*shards[0].ShardId),
AdjacentShardToMerge: aws.String(*shards[1].ShardId),
})
require.NoError(t, err, "Problem merging shards")
require.True(t, shardCount <= shardLimit, "Too many shards")
timeout := time.After(time.Second)
for {
desc, err = k.DescribeStream(&kinesis.DescribeStreamInput{
StreamName: streamName,
Limit: aws.Int64(shardLimit),
})
require.NoError(t, err, "Error describing stream")
if *desc.StreamDescription.StreamStatus == "ACTIVE" {
break
}
select {
case <-timeout:
require.FailNow(t, "Timedout after merging shards")
default:
time.Sleep(*resourceChangeTimeout)
}
}
newShards := desc.StreamDescription.Shards
require.Equal(t, shardCount+1, int64(len(newShards)), "Wrong number of shards after merging")
err = SpamStream(t, k, numberOfEventsToTest)
require.NoError(t, err, "Problems spamming stream with events")
readEvents(t, output, numberOfEventsToTest)
// Sleep here to wait for stuff to calm down. When running this test
// by itself it passes without the sleep but when running all the tests
// it fails. Since we delete all tables I suspect it's kinesalite having
// issues.
time.Sleep(500 * time.Millisecond)
// Validate finished shards are no longer in the cache
var expectedShards []string
for _, shard := range newShards {
if *shard.ShardId != *shards[0].ShardId && *shard.ShardId != *shards[1].ShardId {
expectedShards = append(expectedShards, *shard.ShardId)
}
}
sort.Strings(expectedShards)
cachedShards, err := loadShardIDsFromDynamo(d, clients[0].metadataTableName)
require.NoError(t, err, "Error loading cached shard IDs")
require.Equal(t, expectedShards, cachedShards, "Finished shards are still in the cache")
for ci, client := range clients {
client.Stop()
clients[ci] = nil
}
drain(t, output)
// Make sure the go routines have finished
waitGroup.Wait()
}
func drain(t *testing.T, output chan int) {
extraEvents := 0
// Drain in case events duplicated, so we don't hang.
DrainLoop:
for {
select {
case <-output:
extraEvents++
default:
break DrainLoop
}
}
assert.Equal(t, 0, extraEvents, "Got %d extra events afterwards", extraEvents)
}
func readEvents(t *testing.T, output chan int, numberOfEventsToTest int) {
eventsFound := make([]bool, numberOfEventsToTest)
total := 0
ProcessLoop:
for {
select {
case idx := <-output:
assert.Equal(t, false, eventsFound[idx], "Got duplicate event %d", idx)
eventsFound[idx] = true
total++
if total == numberOfEventsToTest {
break ProcessLoop
}
case <-time.After(3 * time.Second):
break ProcessLoop
}
}
t.Logf("Got all %d out of %d events\n", total, numberOfEventsToTest)
}