Support enhanced fan-out feature (#90)
* Implement enhanced fan-out consumer Signed-off-by: Ilia Cimpoes <ilia.cimpoes@ellation.com> * Add test cases Signed-off-by: Ilia Cimpoes <ilia.cimpoes@ellation.com> * Small adjustments in fan-out consumer Signed-off-by: Ilia Cimpoes <ilia.cimpoes@ellation.com>
This commit is contained in:
parent
909d1774a3
commit
ddcc2d0f95
16 changed files with 846 additions and 384 deletions
|
|
@ -31,7 +31,6 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/aws/awserr"
|
||||
"github.com/aws/aws-sdk-go/aws/client"
|
||||
"github.com/aws/aws-sdk-go/aws/session"
|
||||
"github.com/aws/aws-sdk-go/service/dynamodb"
|
||||
|
|
@ -39,6 +38,7 @@ import (
|
|||
|
||||
"github.com/vmware/vmware-go-kcl/clientlibrary/config"
|
||||
par "github.com/vmware/vmware-go-kcl/clientlibrary/partition"
|
||||
"github.com/vmware/vmware-go-kcl/clientlibrary/utils"
|
||||
"github.com/vmware/vmware-go-kcl/logger"
|
||||
)
|
||||
|
||||
|
|
@ -144,7 +144,7 @@ func (checkpointer *DynamoCheckpoint) GetLease(shard *par.ShardStatus, newAssign
|
|||
return ErrLeaseNotAcquired{"current lease timeout not yet expired"}
|
||||
}
|
||||
|
||||
checkpointer.log.Debugf("Attempting to get a lock for shard: %s, leaseTimeout: %s, assignedTo: %s", shard.ID, currentLeaseTimeout, assignedTo)
|
||||
checkpointer.log.Debugf("Attempting to get a lock for shard: %s, leaseTimeout: %s, assignedTo: %s, newAssignedTo: %s", shard.ID, currentLeaseTimeout, assignedTo, newAssignTo)
|
||||
conditionalExpression = "ShardID = :id AND AssignedTo = :assigned_to AND LeaseTimeout = :lease_timeout"
|
||||
expressionAttributeValues = map[string]*dynamodb.AttributeValue{
|
||||
":id": {
|
||||
|
|
@ -175,18 +175,16 @@ func (checkpointer *DynamoCheckpoint) GetLease(shard *par.ShardStatus, newAssign
|
|||
marshalledCheckpoint[ParentShardIdKey] = &dynamodb.AttributeValue{S: aws.String(shard.ParentShardId)}
|
||||
}
|
||||
|
||||
if shard.Checkpoint != "" {
|
||||
if shard.GetCheckpoint() != "" {
|
||||
marshalledCheckpoint[SequenceNumberKey] = &dynamodb.AttributeValue{
|
||||
S: aws.String(shard.Checkpoint),
|
||||
S: aws.String(shard.GetCheckpoint()),
|
||||
}
|
||||
}
|
||||
|
||||
err = checkpointer.conditionalUpdate(conditionalExpression, expressionAttributeValues, marshalledCheckpoint)
|
||||
if err != nil {
|
||||
if awsErr, ok := err.(awserr.Error); ok {
|
||||
if awsErr.Code() == dynamodb.ErrCodeConditionalCheckFailedException {
|
||||
return ErrLeaseNotAcquired{dynamodb.ErrCodeConditionalCheckFailedException}
|
||||
}
|
||||
if utils.AWSErrCode(err) == dynamodb.ErrCodeConditionalCheckFailedException {
|
||||
return ErrLeaseNotAcquired{dynamodb.ErrCodeConditionalCheckFailedException}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
|
@ -207,7 +205,7 @@ func (checkpointer *DynamoCheckpoint) CheckpointSequence(shard *par.ShardStatus)
|
|||
S: aws.String(shard.ID),
|
||||
},
|
||||
SequenceNumberKey: {
|
||||
S: aws.String(shard.Checkpoint),
|
||||
S: aws.String(shard.GetCheckpoint()),
|
||||
},
|
||||
LeaseOwnerKey: {
|
||||
S: aws.String(shard.AssignedTo),
|
||||
|
|
@ -236,12 +234,10 @@ func (checkpointer *DynamoCheckpoint) FetchCheckpoint(shard *par.ShardStatus) er
|
|||
return ErrSequenceIDNotFound
|
||||
}
|
||||
checkpointer.log.Debugf("Retrieved Shard Iterator %s", *sequenceID.S)
|
||||
shard.Mux.Lock()
|
||||
defer shard.Mux.Unlock()
|
||||
shard.Checkpoint = aws.StringValue(sequenceID.S)
|
||||
shard.SetCheckpoint(aws.StringValue(sequenceID.S))
|
||||
|
||||
if assignedTo, ok := checkpoint[LeaseOwnerKey]; ok {
|
||||
shard.AssignedTo = aws.StringValue(assignedTo.S)
|
||||
shard.SetLeaseOwner(aws.StringValue(assignedTo.S))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -33,12 +33,11 @@ import (
|
|||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/aws/awserr"
|
||||
"github.com/aws/aws-sdk-go/service/dynamodb"
|
||||
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface"
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
cfg "github.com/vmware/vmware-go-kcl/clientlibrary/config"
|
||||
par "github.com/vmware/vmware-go-kcl/clientlibrary/partition"
|
||||
|
|
@ -75,7 +74,7 @@ func TestGetLeaseNotAquired(t *testing.T) {
|
|||
err := checkpoint.GetLease(&par.ShardStatus{
|
||||
ID: "0001",
|
||||
Checkpoint: "",
|
||||
Mux: &sync.Mutex{},
|
||||
Mux: &sync.RWMutex{},
|
||||
}, "abcd-efgh")
|
||||
if err != nil {
|
||||
t.Errorf("Error getting lease %s", err)
|
||||
|
|
@ -84,7 +83,7 @@ func TestGetLeaseNotAquired(t *testing.T) {
|
|||
err = checkpoint.GetLease(&par.ShardStatus{
|
||||
ID: "0001",
|
||||
Checkpoint: "",
|
||||
Mux: &sync.Mutex{},
|
||||
Mux: &sync.RWMutex{},
|
||||
}, "ijkl-mnop")
|
||||
if err == nil || !errors.As(err, &ErrLeaseNotAcquired{}) {
|
||||
t.Errorf("Got a lease when it was already held by abcd-efgh: %s", err)
|
||||
|
|
@ -124,7 +123,7 @@ func TestGetLeaseAquired(t *testing.T) {
|
|||
shard := &par.ShardStatus{
|
||||
ID: "0001",
|
||||
Checkpoint: "deadbeef",
|
||||
Mux: &sync.Mutex{},
|
||||
Mux: &sync.RWMutex{},
|
||||
}
|
||||
err := checkpoint.GetLease(shard, "ijkl-mnop")
|
||||
|
||||
|
|
@ -145,7 +144,7 @@ func TestGetLeaseAquired(t *testing.T) {
|
|||
|
||||
status := &par.ShardStatus{
|
||||
ID: shard.ID,
|
||||
Mux: &sync.Mutex{},
|
||||
Mux: &sync.RWMutex{},
|
||||
}
|
||||
checkpoint.FetchCheckpoint(status)
|
||||
|
||||
|
|
|
|||
|
|
@ -41,6 +41,7 @@ import (
|
|||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
creds "github.com/aws/aws-sdk-go/aws/credentials"
|
||||
|
||||
"github.com/vmware/vmware-go-kcl/clientlibrary/metrics"
|
||||
"github.com/vmware/vmware-go-kcl/logger"
|
||||
)
|
||||
|
|
@ -169,13 +170,24 @@ type (
|
|||
// StreamName is the name of Kinesis stream
|
||||
StreamName string
|
||||
|
||||
// EnableEnhancedFanOutConsumer enables enhanced fan-out consumer
|
||||
// See: https://docs.aws.amazon.com/streams/latest/dev/enhanced-consumers.html
|
||||
// Either consumer name or consumer ARN must be specified when Enhanced Fan-Out is enabled.
|
||||
EnableEnhancedFanOutConsumer bool
|
||||
|
||||
// EnhancedFanOutConsumerName is the name of the enhanced fan-out consumer to create.
|
||||
EnhancedFanOutConsumerName string
|
||||
|
||||
// EnhancedFanOutConsumerARN is the ARN of an already created enhanced fan-out consumer, if this is set no automatic consumer creation will be attempted
|
||||
EnhancedFanOutConsumerARN string
|
||||
|
||||
// WorkerID used to distinguish different workers/processes of a Kinesis application
|
||||
WorkerID string
|
||||
|
||||
// InitialPositionInStream specifies the Position in the stream where a new application should start from
|
||||
InitialPositionInStream InitialPositionInStream
|
||||
|
||||
// InitialPositionInStreamExtended provides actual AT_TMESTAMP value
|
||||
// InitialPositionInStreamExtended provides actual AT_TIMESTAMP value
|
||||
InitialPositionInStreamExtended InitialPositionInStreamExtended
|
||||
|
||||
// credentials to access Kinesis/Dynamo: https://docs.aws.amazon.com/sdk-for-go/api/aws/credentials/
|
||||
|
|
@ -262,18 +274,18 @@ func empty(s string) bool {
|
|||
return len(strings.TrimSpace(s)) == 0
|
||||
}
|
||||
|
||||
// checkIsValuePositive make sure the value is possitive.
|
||||
// checkIsValueNotEmpty makes sure the value is not empty.
|
||||
func checkIsValueNotEmpty(key string, value string) {
|
||||
if empty(value) {
|
||||
// There is no point to continue for incorrect configuration. Fail fast!
|
||||
log.Panicf("Non-empty value exepected for %v, actual: %v", key, value)
|
||||
log.Panicf("Non-empty value expected for %v, actual: %v", key, value)
|
||||
}
|
||||
}
|
||||
|
||||
// checkIsValuePositive make sure the value is possitive.
|
||||
// checkIsValuePositive makes sure the value is possitive.
|
||||
func checkIsValuePositive(key string, value int) {
|
||||
if value <= 0 {
|
||||
// There is no point to continue for incorrect configuration. Fail fast!
|
||||
log.Panicf("Positive value exepected for %v, actual: %v", key, value)
|
||||
log.Panicf("Positive value expected for %v, actual: %v", key, value)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,10 +19,11 @@
|
|||
package config
|
||||
|
||||
import (
|
||||
"github.com/vmware/vmware-go-kcl/logger"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
"github.com/vmware/vmware-go-kcl/logger"
|
||||
)
|
||||
|
||||
func TestConfig(t *testing.T) {
|
||||
|
|
@ -32,13 +33,36 @@ func TestConfig(t *testing.T) {
|
|||
WithInitialPositionInStream(TRIM_HORIZON).
|
||||
WithIdleTimeBetweenReadsInMillis(20).
|
||||
WithCallProcessRecordsEvenForEmptyRecordList(true).
|
||||
WithTaskBackoffTimeMillis(10)
|
||||
WithTaskBackoffTimeMillis(10).
|
||||
WithEnhancedFanOutConsumer("fan-out-consumer")
|
||||
|
||||
assert.Equal(t, "appName", kclConfig.ApplicationName)
|
||||
assert.Equal(t, 500, kclConfig.FailoverTimeMillis)
|
||||
assert.Equal(t, 10, kclConfig.TaskBackoffTimeMillis)
|
||||
assert.True(t, kclConfig.EnableEnhancedFanOutConsumer)
|
||||
assert.Equal(t, "fan-out-consumer", kclConfig.EnhancedFanOutConsumerName)
|
||||
|
||||
contextLogger := kclConfig.Logger.WithFields(logger.Fields{"key1": "value1"})
|
||||
contextLogger.Debugf("Starting with default logger")
|
||||
contextLogger.Infof("Default logger is awesome")
|
||||
}
|
||||
|
||||
func TestEmptyEnhancedFanOutConsumerName(t *testing.T) {
|
||||
assert.PanicsWithValue(t, "Non-empty value expected for EnhancedFanOutConsumerName, actual: ", func() {
|
||||
NewKinesisClientLibConfig("app", "stream", "us-west-2", "worker").WithEnhancedFanOutConsumer("")
|
||||
})
|
||||
}
|
||||
|
||||
func TestConfigWithEnhancedFanOutConsumerARN(t *testing.T) {
|
||||
kclConfig := NewKinesisClientLibConfig("app", "stream", "us-west-2", "worker").
|
||||
WithEnhancedFanOutConsumerARN("consumer:arn")
|
||||
|
||||
assert.True(t, kclConfig.EnableEnhancedFanOutConsumer)
|
||||
assert.Equal(t, "consumer:arn", kclConfig.EnhancedFanOutConsumerARN)
|
||||
}
|
||||
|
||||
func TestEmptyEnhancedFanOutConsumerARN(t *testing.T) {
|
||||
assert.PanicsWithValue(t, "Non-empty value expected for EnhancedFanOutConsumerARN, actual: ", func() {
|
||||
NewKinesisClientLibConfig("app", "stream", "us-west-2", "worker").WithEnhancedFanOutConsumerARN("")
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -37,9 +37,9 @@ import (
|
|||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/vmware/vmware-go-kcl/clientlibrary/metrics"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws/credentials"
|
||||
|
||||
"github.com/vmware/vmware-go-kcl/clientlibrary/metrics"
|
||||
"github.com/vmware/vmware-go-kcl/clientlibrary/utils"
|
||||
"github.com/vmware/vmware-go-kcl/logger"
|
||||
)
|
||||
|
|
@ -212,3 +212,23 @@ func (c *KinesisClientLibConfiguration) WithMonitoringService(mService metrics.M
|
|||
c.MonitoringService = mService
|
||||
return c
|
||||
}
|
||||
|
||||
// WithEnhancedFanOutConsumer enables enhanced fan-out consumer with the specified name
|
||||
// For more info see: https://docs.aws.amazon.com/streams/latest/dev/enhanced-consumers.html
|
||||
// Note: You can register up to twenty consumers per stream to use enhanced fan-out.
|
||||
func (c *KinesisClientLibConfiguration) WithEnhancedFanOutConsumer(consumerName string) *KinesisClientLibConfiguration {
|
||||
checkIsValueNotEmpty("EnhancedFanOutConsumerName", consumerName)
|
||||
c.EnhancedFanOutConsumerName = consumerName
|
||||
c.EnableEnhancedFanOutConsumer = true
|
||||
return c
|
||||
}
|
||||
|
||||
// WithEnhancedFanOutConsumerARN enables enhanced fan-out consumer with the specified consumer ARN
|
||||
// For more info see: https://docs.aws.amazon.com/streams/latest/dev/enhanced-consumers.html
|
||||
// Note: You can register up to twenty consumers per stream to use enhanced fan-out.
|
||||
func (c *KinesisClientLibConfiguration) WithEnhancedFanOutConsumerARN(consumerARN string) *KinesisClientLibConfiguration {
|
||||
checkIsValueNotEmpty("EnhancedFanOutConsumerARN", consumerARN)
|
||||
c.EnhancedFanOutConsumerARN = consumerARN
|
||||
c.EnableEnhancedFanOutConsumer = true
|
||||
return c
|
||||
}
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ type ShardStatus struct {
|
|||
ParentShardId string
|
||||
Checkpoint string
|
||||
AssignedTo string
|
||||
Mux *sync.Mutex
|
||||
Mux *sync.RWMutex
|
||||
LeaseTimeout time.Time
|
||||
// Shard Range
|
||||
StartingSequenceNumber string
|
||||
|
|
@ -46,8 +46,8 @@ type ShardStatus struct {
|
|||
}
|
||||
|
||||
func (ss *ShardStatus) GetLeaseOwner() string {
|
||||
ss.Mux.Lock()
|
||||
defer ss.Mux.Unlock()
|
||||
ss.Mux.RLock()
|
||||
defer ss.Mux.RUnlock()
|
||||
return ss.AssignedTo
|
||||
}
|
||||
|
||||
|
|
@ -56,3 +56,15 @@ func (ss *ShardStatus) SetLeaseOwner(owner string) {
|
|||
defer ss.Mux.Unlock()
|
||||
ss.AssignedTo = owner
|
||||
}
|
||||
|
||||
func (ss *ShardStatus) GetCheckpoint() string {
|
||||
ss.Mux.RLock()
|
||||
defer ss.Mux.RUnlock()
|
||||
return ss.Checkpoint
|
||||
}
|
||||
|
||||
func (ss *ShardStatus) SetCheckpoint(c string) {
|
||||
ss.Mux.Lock()
|
||||
defer ss.Mux.Unlock()
|
||||
ss.Checkpoint = c
|
||||
}
|
||||
|
|
|
|||
31
clientlibrary/utils/awserr.go
Normal file
31
clientlibrary/utils/awserr.go
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
/*
|
||||
* Copyright (c) 2021 VMware, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
|
||||
* associated documentation files (the "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is furnished to do
|
||||
* so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all copies or substantial
|
||||
* portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
|
||||
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package utils
|
||||
|
||||
import (
|
||||
"github.com/aws/aws-sdk-go/aws/awserr"
|
||||
)
|
||||
|
||||
func AWSErrCode(err error) string {
|
||||
awsErr, _ := err.(awserr.Error)
|
||||
if awsErr != nil {
|
||||
return awsErr.Code()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
169
clientlibrary/worker/common-shard-consumer.go
Normal file
169
clientlibrary/worker/common-shard-consumer.go
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
/*
|
||||
* Copyright (c) 2021 VMware, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
|
||||
* associated documentation files (the "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is furnished to do
|
||||
* so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all copies or substantial
|
||||
* portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
|
||||
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package worker
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/service/kinesis"
|
||||
"github.com/aws/aws-sdk-go/service/kinesis/kinesisiface"
|
||||
deagg "github.com/awslabs/kinesis-aggregation/go/deaggregator"
|
||||
|
||||
chk "github.com/vmware/vmware-go-kcl/clientlibrary/checkpoint"
|
||||
"github.com/vmware/vmware-go-kcl/clientlibrary/config"
|
||||
kcl "github.com/vmware/vmware-go-kcl/clientlibrary/interfaces"
|
||||
"github.com/vmware/vmware-go-kcl/clientlibrary/metrics"
|
||||
par "github.com/vmware/vmware-go-kcl/clientlibrary/partition"
|
||||
)
|
||||
|
||||
type shardConsumer interface {
|
||||
getRecords() error
|
||||
}
|
||||
|
||||
// commonShardConsumer implements common functionality for regular and enhanced fan-out consumers
|
||||
type commonShardConsumer struct {
|
||||
shard *par.ShardStatus
|
||||
kc kinesisiface.KinesisAPI
|
||||
checkpointer chk.Checkpointer
|
||||
recordProcessor kcl.IRecordProcessor
|
||||
kclConfig *config.KinesisClientLibConfiguration
|
||||
mService metrics.MonitoringService
|
||||
}
|
||||
|
||||
// Cleanup the internal lease cache
|
||||
func (sc *commonShardConsumer) releaseLease() {
|
||||
log := sc.kclConfig.Logger
|
||||
log.Infof("Release lease for shard %s", sc.shard.ID)
|
||||
sc.shard.SetLeaseOwner("")
|
||||
|
||||
// Release the lease by wiping out the lease owner for the shard
|
||||
// Note: we don't need to do anything in case of error here and shard lease will eventually be expired.
|
||||
if err := sc.checkpointer.RemoveLeaseOwner(sc.shard.ID); err != nil {
|
||||
log.Errorf("Failed to release shard lease or shard: %s Error: %+v", sc.shard.ID, err)
|
||||
}
|
||||
|
||||
// reporting lease lose metrics
|
||||
sc.mService.LeaseLost(sc.shard.ID)
|
||||
}
|
||||
|
||||
// getStartingPosition gets kinesis stating position.
|
||||
// First try to fetch checkpoint. If checkpoint is not found use InitialPositionInStream
|
||||
func (sc *commonShardConsumer) getStartingPosition() (*kinesis.StartingPosition, error) {
|
||||
err := sc.checkpointer.FetchCheckpoint(sc.shard)
|
||||
if err != nil && err != chk.ErrSequenceIDNotFound {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
checkpoint := sc.shard.GetCheckpoint()
|
||||
if checkpoint != "" {
|
||||
sc.kclConfig.Logger.Debugf("Start shard: %v at checkpoint: %v", sc.shard.ID, checkpoint)
|
||||
return &kinesis.StartingPosition{
|
||||
Type: aws.String("AFTER_SEQUENCE_NUMBER"),
|
||||
SequenceNumber: &checkpoint,
|
||||
}, nil
|
||||
}
|
||||
|
||||
shardIteratorType := config.InitalPositionInStreamToShardIteratorType(sc.kclConfig.InitialPositionInStream)
|
||||
sc.kclConfig.Logger.Debugf("No checkpoint recorded for shard: %v, starting with: %v", sc.shard.ID, aws.StringValue(shardIteratorType))
|
||||
|
||||
if sc.kclConfig.InitialPositionInStream == config.AT_TIMESTAMP {
|
||||
return &kinesis.StartingPosition{
|
||||
Type: shardIteratorType,
|
||||
Timestamp: sc.kclConfig.InitialPositionInStreamExtended.Timestamp,
|
||||
}, nil
|
||||
}
|
||||
|
||||
return &kinesis.StartingPosition{
|
||||
Type: shardIteratorType,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Need to wait until the parent shard finished
|
||||
func (sc *commonShardConsumer) waitOnParentShard() error {
|
||||
if len(sc.shard.ParentShardId) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
pshard := &par.ShardStatus{
|
||||
ID: sc.shard.ParentShardId,
|
||||
Mux: &sync.RWMutex{},
|
||||
}
|
||||
|
||||
for {
|
||||
if err := sc.checkpointer.FetchCheckpoint(pshard); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Parent shard is finished.
|
||||
if pshard.GetCheckpoint() == chk.ShardEnd {
|
||||
return nil
|
||||
}
|
||||
|
||||
time.Sleep(time.Duration(sc.kclConfig.ParentShardPollIntervalMillis) * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
func (sc *commonShardConsumer) processRecords(getRecordsStartTime time.Time, records []*kinesis.Record, millisBehindLatest *int64, recordCheckpointer kcl.IRecordProcessorCheckpointer) {
|
||||
log := sc.kclConfig.Logger
|
||||
|
||||
getRecordsTime := time.Since(getRecordsStartTime).Milliseconds()
|
||||
sc.mService.RecordGetRecordsTime(sc.shard.ID, float64(getRecordsTime))
|
||||
|
||||
log.Debugf("Received %d original records.", len(records))
|
||||
|
||||
// De-aggregate the records if they were published by the KPL.
|
||||
dars, err := deagg.DeaggregateRecords(records)
|
||||
if err != nil {
|
||||
// The error is caused by bad KPL publisher and just skip the bad records
|
||||
// instead of being stuck here.
|
||||
log.Errorf("Error in de-aggregating KPL records: %+v", err)
|
||||
}
|
||||
|
||||
input := &kcl.ProcessRecordsInput{
|
||||
Records: dars,
|
||||
MillisBehindLatest: aws.Int64Value(millisBehindLatest),
|
||||
Checkpointer: recordCheckpointer,
|
||||
}
|
||||
|
||||
recordLength := len(input.Records)
|
||||
recordBytes := int64(0)
|
||||
log.Debugf("Received %d de-aggregated records, MillisBehindLatest: %v", recordLength, input.MillisBehindLatest)
|
||||
|
||||
for _, r := range input.Records {
|
||||
recordBytes += int64(len(r.Data))
|
||||
}
|
||||
|
||||
if recordLength > 0 || sc.kclConfig.CallProcessRecordsEvenForEmptyRecordList {
|
||||
processRecordsStartTime := time.Now()
|
||||
|
||||
// Delivery the events to the record processor
|
||||
input.CacheEntryTime = &getRecordsStartTime
|
||||
input.CacheExitTime = &processRecordsStartTime
|
||||
sc.recordProcessor.ProcessRecords(input)
|
||||
|
||||
processedRecordsTiming := time.Since(processRecordsStartTime).Milliseconds()
|
||||
sc.mService.RecordProcessRecordsTime(sc.shard.ID, float64(processedRecordsTiming))
|
||||
}
|
||||
|
||||
sc.mService.IncrRecordsProcessed(sc.shard.ID, recordLength)
|
||||
sc.mService.IncrBytesProcessed(sc.shard.ID, recordBytes)
|
||||
sc.mService.MillisBehindLatest(sc.shard.ID, float64(*millisBehindLatest))
|
||||
}
|
||||
168
clientlibrary/worker/fan-out-shard-consumer.go
Normal file
168
clientlibrary/worker/fan-out-shard-consumer.go
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
/*
|
||||
* Copyright (c) 2021 VMware, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
|
||||
* associated documentation files (the "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is furnished to do
|
||||
* so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all copies or substantial
|
||||
* portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
|
||||
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package worker
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/service/kinesis"
|
||||
|
||||
chk "github.com/vmware/vmware-go-kcl/clientlibrary/checkpoint"
|
||||
kcl "github.com/vmware/vmware-go-kcl/clientlibrary/interfaces"
|
||||
)
|
||||
|
||||
// FanOutShardConsumer is responsible for consuming data records of a (specified) shard.
|
||||
// Note: FanOutShardConsumer only deal with one shard.
|
||||
// For more info see: https://docs.aws.amazon.com/streams/latest/dev/enhanced-consumers.html
|
||||
type FanOutShardConsumer struct {
|
||||
commonShardConsumer
|
||||
consumerARN string
|
||||
consumerID string
|
||||
stop *chan struct{}
|
||||
}
|
||||
|
||||
// getRecords subscribes to a shard and reads events from it.
|
||||
// Precondition: it currently has the lease on the shard.
|
||||
func (sc *FanOutShardConsumer) getRecords() error {
|
||||
defer sc.releaseLease()
|
||||
|
||||
log := sc.kclConfig.Logger
|
||||
|
||||
// If the shard is child shard, need to wait until the parent finished.
|
||||
if err := sc.waitOnParentShard(); err != nil {
|
||||
// If parent shard has been deleted by Kinesis system already, just ignore the error.
|
||||
if err != chk.ErrSequenceIDNotFound {
|
||||
log.Errorf("Error in waiting for parent shard: %v to finish. Error: %+v", sc.shard.ParentShardId, err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
shardSub, err := sc.subscribeToShard()
|
||||
if err != nil {
|
||||
log.Errorf("Unable to subscribe to shard %s: %v", sc.shard.ID, err)
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
if shardSub == nil || shardSub.EventStream == nil {
|
||||
log.Debugf("Nothing to close, EventStream is nil")
|
||||
return
|
||||
}
|
||||
err = shardSub.EventStream.Close()
|
||||
if err != nil {
|
||||
log.Errorf("Unable to close event stream for %s: %v", sc.shard.ID, err)
|
||||
}
|
||||
}()
|
||||
|
||||
input := &kcl.InitializationInput{
|
||||
ShardId: sc.shard.ID,
|
||||
ExtendedSequenceNumber: &kcl.ExtendedSequenceNumber{SequenceNumber: aws.String(sc.shard.GetCheckpoint())},
|
||||
}
|
||||
sc.recordProcessor.Initialize(input)
|
||||
recordCheckpointer := NewRecordProcessorCheckpoint(sc.shard, sc.checkpointer)
|
||||
|
||||
var continuationSequenceNumber *string
|
||||
refreshLeaseTimer := time.After(time.Until(sc.shard.LeaseTimeout.Add(-time.Duration(sc.kclConfig.LeaseRefreshPeriodMillis) * time.Millisecond)))
|
||||
for {
|
||||
getRecordsStartTime := time.Now()
|
||||
select {
|
||||
case <-*sc.stop:
|
||||
shutdownInput := &kcl.ShutdownInput{ShutdownReason: kcl.REQUESTED, Checkpointer: recordCheckpointer}
|
||||
sc.recordProcessor.Shutdown(shutdownInput)
|
||||
return nil
|
||||
case <-refreshLeaseTimer:
|
||||
log.Debugf("Refreshing lease on shard: %s for worker: %s", sc.shard.ID, sc.consumerID)
|
||||
err = sc.checkpointer.GetLease(sc.shard, sc.consumerID)
|
||||
if err != nil {
|
||||
if errors.As(err, &chk.ErrLeaseNotAcquired{}) {
|
||||
log.Warnf("Failed in acquiring lease on shard: %s for worker: %s", sc.shard.ID, sc.consumerID)
|
||||
return nil
|
||||
}
|
||||
log.Errorf("Error in refreshing lease on shard: %s for worker: %s. Error: %+v", sc.shard.ID, sc.consumerID, err)
|
||||
return err
|
||||
}
|
||||
refreshLeaseTimer = time.After(time.Until(sc.shard.LeaseTimeout.Add(-time.Duration(sc.kclConfig.LeaseRefreshPeriodMillis) * time.Millisecond)))
|
||||
case event, ok := <-shardSub.EventStream.Events():
|
||||
if !ok {
|
||||
// need to resubscribe to shard
|
||||
log.Debugf("Event stream ended, refreshing subscription on shard: %s for worker: %s", sc.shard.ID, sc.consumerID)
|
||||
if continuationSequenceNumber == nil || *continuationSequenceNumber == "" {
|
||||
log.Debugf("No continuation sequence number")
|
||||
return nil
|
||||
}
|
||||
shardSub, err = sc.resubscribe(shardSub, continuationSequenceNumber)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
subEvent, ok := event.(*kinesis.SubscribeToShardEvent)
|
||||
if !ok {
|
||||
log.Errorf("Received unexpected event type: %T", event)
|
||||
continue
|
||||
}
|
||||
continuationSequenceNumber = subEvent.ContinuationSequenceNumber
|
||||
sc.processRecords(getRecordsStartTime, subEvent.Records, subEvent.MillisBehindLatest, recordCheckpointer)
|
||||
|
||||
// The shard has been closed, so no new records can be read from it
|
||||
if continuationSequenceNumber == nil {
|
||||
log.Infof("Shard %s closed", sc.shard.ID)
|
||||
shutdownInput := &kcl.ShutdownInput{ShutdownReason: kcl.TERMINATE, Checkpointer: recordCheckpointer}
|
||||
sc.recordProcessor.Shutdown(shutdownInput)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (sc *FanOutShardConsumer) subscribeToShard() (*kinesis.SubscribeToShardOutput, error) {
|
||||
startPosition, err := sc.getStartingPosition()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return sc.kc.SubscribeToShard(&kinesis.SubscribeToShardInput{
|
||||
ConsumerARN: &sc.consumerARN,
|
||||
ShardId: &sc.shard.ID,
|
||||
StartingPosition: startPosition,
|
||||
})
|
||||
}
|
||||
|
||||
func (sc *FanOutShardConsumer) resubscribe(shardSub *kinesis.SubscribeToShardOutput, continuationSequence *string) (*kinesis.SubscribeToShardOutput, error) {
|
||||
err := shardSub.EventStream.Close()
|
||||
if err != nil {
|
||||
sc.kclConfig.Logger.Errorf("Unable to close event stream for %s: %v", sc.shard.ID, err)
|
||||
return nil, err
|
||||
}
|
||||
startPosition := &kinesis.StartingPosition{
|
||||
Type: aws.String("AFTER_SEQUENCE_NUMBER"),
|
||||
SequenceNumber: continuationSequence,
|
||||
}
|
||||
shardSub, err = sc.kc.SubscribeToShard(&kinesis.SubscribeToShardInput{
|
||||
ConsumerARN: &sc.consumerARN,
|
||||
ShardId: &sc.shard.ID,
|
||||
StartingPosition: startPosition,
|
||||
})
|
||||
if err != nil {
|
||||
sc.kclConfig.Logger.Errorf("Unable to resubscribe to shard %s: %v", sc.shard.ID, err)
|
||||
return nil, err
|
||||
}
|
||||
return shardSub, nil
|
||||
}
|
||||
171
clientlibrary/worker/polling-shard-consumer.go
Normal file
171
clientlibrary/worker/polling-shard-consumer.go
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
/*
|
||||
* Copyright (c) 2018 VMware, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
|
||||
* associated documentation files (the "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is furnished to do
|
||||
* so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all copies or substantial
|
||||
* portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
|
||||
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
// The implementation is derived from https://github.com/patrobinson/gokini
|
||||
//
|
||||
// Copyright 2018 Patrick robinson
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
package worker
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/service/kinesis"
|
||||
|
||||
chk "github.com/vmware/vmware-go-kcl/clientlibrary/checkpoint"
|
||||
kcl "github.com/vmware/vmware-go-kcl/clientlibrary/interfaces"
|
||||
"github.com/vmware/vmware-go-kcl/clientlibrary/metrics"
|
||||
"github.com/vmware/vmware-go-kcl/clientlibrary/utils"
|
||||
)
|
||||
|
||||
// PollingShardConsumer is responsible for polling data records from a (specified) shard.
|
||||
// Note: PollingShardConsumer only deal with one shard.
|
||||
type PollingShardConsumer struct {
|
||||
commonShardConsumer
|
||||
streamName string
|
||||
stop *chan struct{}
|
||||
consumerID string
|
||||
mService metrics.MonitoringService
|
||||
}
|
||||
|
||||
func (sc *PollingShardConsumer) getShardIterator() (*string, error) {
|
||||
startPosition, err := sc.getStartingPosition()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
shardIterArgs := &kinesis.GetShardIteratorInput{
|
||||
ShardId: &sc.shard.ID,
|
||||
ShardIteratorType: startPosition.Type,
|
||||
StartingSequenceNumber: startPosition.SequenceNumber,
|
||||
Timestamp: startPosition.Timestamp,
|
||||
StreamName: &sc.streamName,
|
||||
}
|
||||
iterResp, err := sc.kc.GetShardIterator(shardIterArgs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return iterResp.ShardIterator, nil
|
||||
}
|
||||
|
||||
// getRecords continously poll one shard for data record
|
||||
// Precondition: it currently has the lease on the shard.
|
||||
func (sc *PollingShardConsumer) getRecords() error {
|
||||
defer sc.releaseLease()
|
||||
|
||||
log := sc.kclConfig.Logger
|
||||
|
||||
// If the shard is child shard, need to wait until the parent finished.
|
||||
if err := sc.waitOnParentShard(); err != nil {
|
||||
// If parent shard has been deleted by Kinesis system already, just ignore the error.
|
||||
if err != chk.ErrSequenceIDNotFound {
|
||||
log.Errorf("Error in waiting for parent shard: %v to finish. Error: %+v", sc.shard.ParentShardId, err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
shardIterator, err := sc.getShardIterator()
|
||||
if err != nil {
|
||||
log.Errorf("Unable to get shard iterator for %s: %v", sc.shard.ID, err)
|
||||
return err
|
||||
}
|
||||
|
||||
// Start processing events and notify record processor on shard and starting checkpoint
|
||||
input := &kcl.InitializationInput{
|
||||
ShardId: sc.shard.ID,
|
||||
ExtendedSequenceNumber: &kcl.ExtendedSequenceNumber{SequenceNumber: aws.String(sc.shard.GetCheckpoint())},
|
||||
}
|
||||
sc.recordProcessor.Initialize(input)
|
||||
|
||||
recordCheckpointer := NewRecordProcessorCheckpoint(sc.shard, sc.checkpointer)
|
||||
retriedErrors := 0
|
||||
|
||||
for {
|
||||
if time.Now().UTC().After(sc.shard.LeaseTimeout.Add(-time.Duration(sc.kclConfig.LeaseRefreshPeriodMillis) * time.Millisecond)) {
|
||||
log.Debugf("Refreshing lease on shard: %s for worker: %s", sc.shard.ID, sc.consumerID)
|
||||
err = sc.checkpointer.GetLease(sc.shard, sc.consumerID)
|
||||
if err != nil {
|
||||
if errors.As(err, &chk.ErrLeaseNotAcquired{}) {
|
||||
log.Warnf("Failed in acquiring lease on shard: %s for worker: %s", sc.shard.ID, sc.consumerID)
|
||||
return nil
|
||||
}
|
||||
// log and return error
|
||||
log.Errorf("Error in refreshing lease on shard: %s for worker: %s. Error: %+v",
|
||||
sc.shard.ID, sc.consumerID, err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
getRecordsStartTime := time.Now()
|
||||
|
||||
log.Debugf("Trying to read %d record from iterator: %v", sc.kclConfig.MaxRecords, aws.StringValue(shardIterator))
|
||||
getRecordsArgs := &kinesis.GetRecordsInput{
|
||||
Limit: aws.Int64(int64(sc.kclConfig.MaxRecords)),
|
||||
ShardIterator: shardIterator,
|
||||
}
|
||||
// Get records from stream and retry as needed
|
||||
getResp, err := sc.kc.GetRecords(getRecordsArgs)
|
||||
if err != nil {
|
||||
if utils.AWSErrCode(err) == kinesis.ErrCodeProvisionedThroughputExceededException || utils.AWSErrCode(err) == kinesis.ErrCodeKMSThrottlingException {
|
||||
log.Errorf("Error getting records from shard %v: %+v", sc.shard.ID, err)
|
||||
retriedErrors++
|
||||
// exponential backoff
|
||||
// https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff
|
||||
time.Sleep(time.Duration(math.Exp2(float64(retriedErrors))*100) * time.Millisecond)
|
||||
continue
|
||||
}
|
||||
log.Errorf("Error getting records from Kinesis that cannot be retried: %+v Request: %s", err, getRecordsArgs)
|
||||
return err
|
||||
}
|
||||
// reset the retry count after success
|
||||
retriedErrors = 0
|
||||
|
||||
sc.processRecords(getRecordsStartTime, getResp.Records, getResp.MillisBehindLatest, recordCheckpointer)
|
||||
|
||||
// The shard has been closed, so no new records can be read from it
|
||||
if getResp.NextShardIterator == nil {
|
||||
log.Infof("Shard %s closed", sc.shard.ID)
|
||||
shutdownInput := &kcl.ShutdownInput{ShutdownReason: kcl.TERMINATE, Checkpointer: recordCheckpointer}
|
||||
sc.recordProcessor.Shutdown(shutdownInput)
|
||||
return nil
|
||||
}
|
||||
shardIterator = getResp.NextShardIterator
|
||||
|
||||
// Idle between each read, the user is responsible for checkpoint the progress
|
||||
// This value is only used when no records are returned; if records are returned, it should immediately
|
||||
// retrieve the next set of records.
|
||||
if len(getResp.Records) == 0 && aws.Int64Value(getResp.MillisBehindLatest) < int64(sc.kclConfig.IdleTimeBetweenReadsInMillis) {
|
||||
time.Sleep(time.Duration(sc.kclConfig.IdleTimeBetweenReadsInMillis) * time.Millisecond)
|
||||
}
|
||||
|
||||
select {
|
||||
case <-*sc.stop:
|
||||
shutdownInput := &kcl.ShutdownInput{ShutdownReason: kcl.REQUESTED, Checkpointer: recordCheckpointer}
|
||||
sc.recordProcessor.Shutdown(shutdownInput)
|
||||
return nil
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -64,14 +64,11 @@ func (pc *PreparedCheckpointer) Checkpoint() error {
|
|||
}
|
||||
|
||||
func (rc *RecordProcessorCheckpointer) Checkpoint(sequenceNumber *string) error {
|
||||
rc.shard.Mux.Lock()
|
||||
defer rc.shard.Mux.Unlock()
|
||||
|
||||
// checkpoint the last sequence of a closed shard
|
||||
if sequenceNumber == nil {
|
||||
rc.shard.Checkpoint = chk.ShardEnd
|
||||
rc.shard.SetCheckpoint(chk.ShardEnd)
|
||||
} else {
|
||||
rc.shard.Checkpoint = aws.StringValue(sequenceNumber)
|
||||
rc.shard.SetCheckpoint(aws.StringValue(sequenceNumber))
|
||||
}
|
||||
|
||||
return rc.checkpoint.CheckpointSequence(rc.shard)
|
||||
|
|
|
|||
|
|
@ -1,317 +0,0 @@
|
|||
/*
|
||||
* Copyright (c) 2018 VMware, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
|
||||
* associated documentation files (the "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is furnished to do
|
||||
* so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all copies or substantial
|
||||
* portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
|
||||
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
// The implementation is derived from https://github.com/patrobinson/gokini
|
||||
//
|
||||
// Copyright 2018 Patrick robinson
|
||||
//
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
//
|
||||
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
//
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
package worker
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"math"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/aws/awserr"
|
||||
"github.com/aws/aws-sdk-go/service/kinesis"
|
||||
"github.com/aws/aws-sdk-go/service/kinesis/kinesisiface"
|
||||
deagg "github.com/awslabs/kinesis-aggregation/go/deaggregator"
|
||||
|
||||
chk "github.com/vmware/vmware-go-kcl/clientlibrary/checkpoint"
|
||||
"github.com/vmware/vmware-go-kcl/clientlibrary/config"
|
||||
kcl "github.com/vmware/vmware-go-kcl/clientlibrary/interfaces"
|
||||
"github.com/vmware/vmware-go-kcl/clientlibrary/metrics"
|
||||
par "github.com/vmware/vmware-go-kcl/clientlibrary/partition"
|
||||
)
|
||||
|
||||
const (
|
||||
// This is the initial state of a shard consumer. This causes the consumer to remain blocked until the all
|
||||
// parent shards have been completed.
|
||||
WaitingOnParentShards ShardConsumerState = iota + 1
|
||||
|
||||
// ErrCodeKMSThrottlingException is defined in the API Reference https://docs.aws.amazon.com/sdk-for-go/api/service/kinesis/#Kinesis.GetRecords
|
||||
// But it's not a constant?
|
||||
ErrCodeKMSThrottlingException = "KMSThrottlingException"
|
||||
)
|
||||
|
||||
type ShardConsumerState int
|
||||
|
||||
// ShardConsumer is responsible for consuming data records of a (specified) shard.
|
||||
// Note: ShardConsumer only deal with one shard.
|
||||
type ShardConsumer struct {
|
||||
streamName string
|
||||
shard *par.ShardStatus
|
||||
kc kinesisiface.KinesisAPI
|
||||
checkpointer chk.Checkpointer
|
||||
recordProcessor kcl.IRecordProcessor
|
||||
kclConfig *config.KinesisClientLibConfiguration
|
||||
stop *chan struct{}
|
||||
consumerID string
|
||||
mService metrics.MonitoringService
|
||||
state ShardConsumerState
|
||||
}
|
||||
|
||||
func (sc *ShardConsumer) getShardIterator(shard *par.ShardStatus) (*string, error) {
|
||||
log := sc.kclConfig.Logger
|
||||
|
||||
// Get checkpoint of the shard from dynamoDB
|
||||
err := sc.checkpointer.FetchCheckpoint(shard)
|
||||
if err != nil && err != chk.ErrSequenceIDNotFound {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// If there isn't any checkpoint for the shard, use the configuration value.
|
||||
if shard.Checkpoint == "" {
|
||||
initPos := sc.kclConfig.InitialPositionInStream
|
||||
shardIteratorType := config.InitalPositionInStreamToShardIteratorType(initPos)
|
||||
log.Debugf("No checkpoint recorded for shard: %v, starting with: %v", shard.ID,
|
||||
aws.StringValue(shardIteratorType))
|
||||
|
||||
var shardIterArgs *kinesis.GetShardIteratorInput
|
||||
if initPos == config.AT_TIMESTAMP {
|
||||
shardIterArgs = &kinesis.GetShardIteratorInput{
|
||||
ShardId: &shard.ID,
|
||||
ShardIteratorType: shardIteratorType,
|
||||
Timestamp: sc.kclConfig.InitialPositionInStreamExtended.Timestamp,
|
||||
StreamName: &sc.streamName,
|
||||
}
|
||||
} else {
|
||||
shardIterArgs = &kinesis.GetShardIteratorInput{
|
||||
ShardId: &shard.ID,
|
||||
ShardIteratorType: shardIteratorType,
|
||||
StreamName: &sc.streamName,
|
||||
}
|
||||
}
|
||||
|
||||
iterResp, err := sc.kc.GetShardIterator(shardIterArgs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return iterResp.ShardIterator, nil
|
||||
}
|
||||
|
||||
log.Debugf("Start shard: %v at checkpoint: %v", shard.ID, shard.Checkpoint)
|
||||
shardIterArgs := &kinesis.GetShardIteratorInput{
|
||||
ShardId: &shard.ID,
|
||||
ShardIteratorType: aws.String("AFTER_SEQUENCE_NUMBER"),
|
||||
StartingSequenceNumber: &shard.Checkpoint,
|
||||
StreamName: &sc.streamName,
|
||||
}
|
||||
iterResp, err := sc.kc.GetShardIterator(shardIterArgs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return iterResp.ShardIterator, nil
|
||||
}
|
||||
|
||||
// getRecords continously poll one shard for data record
|
||||
// Precondition: it currently has the lease on the shard.
|
||||
func (sc *ShardConsumer) getRecords(shard *par.ShardStatus) error {
|
||||
defer sc.releaseLease(shard)
|
||||
|
||||
log := sc.kclConfig.Logger
|
||||
|
||||
// If the shard is child shard, need to wait until the parent finished.
|
||||
if err := sc.waitOnParentShard(shard); err != nil {
|
||||
// If parent shard has been deleted by Kinesis system already, just ignore the error.
|
||||
if err != chk.ErrSequenceIDNotFound {
|
||||
log.Errorf("Error in waiting for parent shard: %v to finish. Error: %+v", shard.ParentShardId, err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
shardIterator, err := sc.getShardIterator(shard)
|
||||
if err != nil {
|
||||
log.Errorf("Unable to get shard iterator for %s: %v", shard.ID, err)
|
||||
return err
|
||||
}
|
||||
|
||||
// Start processing events and notify record processor on shard and starting checkpoint
|
||||
input := &kcl.InitializationInput{
|
||||
ShardId: shard.ID,
|
||||
ExtendedSequenceNumber: &kcl.ExtendedSequenceNumber{SequenceNumber: aws.String(shard.Checkpoint)},
|
||||
}
|
||||
sc.recordProcessor.Initialize(input)
|
||||
|
||||
recordCheckpointer := NewRecordProcessorCheckpoint(shard, sc.checkpointer)
|
||||
retriedErrors := 0
|
||||
|
||||
for {
|
||||
if time.Now().UTC().After(shard.LeaseTimeout.Add(-time.Duration(sc.kclConfig.LeaseRefreshPeriodMillis) * time.Millisecond)) {
|
||||
log.Debugf("Refreshing lease on shard: %s for worker: %s", shard.ID, sc.consumerID)
|
||||
err = sc.checkpointer.GetLease(shard, sc.consumerID)
|
||||
if err != nil {
|
||||
if errors.As(err, &chk.ErrLeaseNotAcquired{}) {
|
||||
log.Warnf("Failed in acquiring lease on shard: %s for worker: %s", shard.ID, sc.consumerID)
|
||||
return nil
|
||||
}
|
||||
// log and return error
|
||||
log.Errorf("Error in refreshing lease on shard: %s for worker: %s. Error: %+v",
|
||||
shard.ID, sc.consumerID, err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
getRecordsStartTime := time.Now()
|
||||
|
||||
log.Debugf("Trying to read %d record from iterator: %v", sc.kclConfig.MaxRecords, aws.StringValue(shardIterator))
|
||||
getRecordsArgs := &kinesis.GetRecordsInput{
|
||||
Limit: aws.Int64(int64(sc.kclConfig.MaxRecords)),
|
||||
ShardIterator: shardIterator,
|
||||
}
|
||||
// Get records from stream and retry as needed
|
||||
getResp, err := sc.kc.GetRecords(getRecordsArgs)
|
||||
if err != nil {
|
||||
if awsErr, ok := err.(awserr.Error); ok {
|
||||
if awsErr.Code() == kinesis.ErrCodeProvisionedThroughputExceededException || awsErr.Code() == ErrCodeKMSThrottlingException {
|
||||
log.Errorf("Error getting records from shard %v: %+v", shard.ID, err)
|
||||
retriedErrors++
|
||||
// exponential backoff
|
||||
// https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff
|
||||
time.Sleep(time.Duration(math.Exp2(float64(retriedErrors))*100) * time.Millisecond)
|
||||
continue
|
||||
}
|
||||
}
|
||||
log.Errorf("Error getting records from Kinesis that cannot be retried: %+v Request: %s", err, getRecordsArgs)
|
||||
return err
|
||||
}
|
||||
|
||||
// Convert from nanoseconds to milliseconds
|
||||
getRecordsTime := time.Since(getRecordsStartTime) / 1000000
|
||||
sc.mService.RecordGetRecordsTime(shard.ID, float64(getRecordsTime))
|
||||
|
||||
// reset the retry count after success
|
||||
retriedErrors = 0
|
||||
|
||||
log.Debugf("Received %d original records.", len(getResp.Records))
|
||||
|
||||
// De-aggregate the records if they were published by the KPL.
|
||||
dars := make([]*kinesis.Record, 0)
|
||||
dars, err = deagg.DeaggregateRecords(getResp.Records)
|
||||
|
||||
if err != nil {
|
||||
// The error is caused by bad KPL publisher and just skip the bad records
|
||||
// instead of being stuck here.
|
||||
log.Errorf("Error in de-aggregating KPL records: %+v", err)
|
||||
}
|
||||
|
||||
// IRecordProcessorCheckpointer
|
||||
input := &kcl.ProcessRecordsInput{
|
||||
Records: dars,
|
||||
MillisBehindLatest: aws.Int64Value(getResp.MillisBehindLatest),
|
||||
Checkpointer: recordCheckpointer,
|
||||
}
|
||||
|
||||
recordLength := len(input.Records)
|
||||
recordBytes := int64(0)
|
||||
log.Debugf("Received %d de-aggregated records, MillisBehindLatest: %v", recordLength, input.MillisBehindLatest)
|
||||
|
||||
for _, r := range dars {
|
||||
recordBytes += int64(len(r.Data))
|
||||
}
|
||||
|
||||
if recordLength > 0 || sc.kclConfig.CallProcessRecordsEvenForEmptyRecordList {
|
||||
processRecordsStartTime := time.Now()
|
||||
|
||||
// Delivery the events to the record processor
|
||||
input.CacheEntryTime = &getRecordsStartTime
|
||||
input.CacheExitTime = &processRecordsStartTime
|
||||
sc.recordProcessor.ProcessRecords(input)
|
||||
|
||||
// Convert from nanoseconds to milliseconds
|
||||
processedRecordsTiming := time.Since(processRecordsStartTime) / 1000000
|
||||
sc.mService.RecordProcessRecordsTime(shard.ID, float64(processedRecordsTiming))
|
||||
}
|
||||
|
||||
sc.mService.IncrRecordsProcessed(shard.ID, recordLength)
|
||||
sc.mService.IncrBytesProcessed(shard.ID, recordBytes)
|
||||
sc.mService.MillisBehindLatest(shard.ID, float64(*getResp.MillisBehindLatest))
|
||||
|
||||
// Idle between each read, the user is responsible for checkpoint the progress
|
||||
// This value is only used when no records are returned; if records are returned, it should immediately
|
||||
// retrieve the next set of records.
|
||||
if recordLength == 0 && aws.Int64Value(getResp.MillisBehindLatest) < int64(sc.kclConfig.IdleTimeBetweenReadsInMillis) {
|
||||
time.Sleep(time.Duration(sc.kclConfig.IdleTimeBetweenReadsInMillis) * time.Millisecond)
|
||||
}
|
||||
|
||||
// The shard has been closed, so no new records can be read from it
|
||||
if getResp.NextShardIterator == nil {
|
||||
log.Infof("Shard %s closed", shard.ID)
|
||||
shutdownInput := &kcl.ShutdownInput{ShutdownReason: kcl.TERMINATE, Checkpointer: recordCheckpointer}
|
||||
sc.recordProcessor.Shutdown(shutdownInput)
|
||||
return nil
|
||||
}
|
||||
shardIterator = getResp.NextShardIterator
|
||||
|
||||
select {
|
||||
case <-*sc.stop:
|
||||
shutdownInput := &kcl.ShutdownInput{ShutdownReason: kcl.REQUESTED, Checkpointer: recordCheckpointer}
|
||||
sc.recordProcessor.Shutdown(shutdownInput)
|
||||
return nil
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Need to wait until the parent shard finished
|
||||
func (sc *ShardConsumer) waitOnParentShard(shard *par.ShardStatus) error {
|
||||
if len(shard.ParentShardId) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
pshard := &par.ShardStatus{
|
||||
ID: shard.ParentShardId,
|
||||
Mux: &sync.Mutex{},
|
||||
}
|
||||
|
||||
for {
|
||||
if err := sc.checkpointer.FetchCheckpoint(pshard); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Parent shard is finished.
|
||||
if pshard.Checkpoint == chk.ShardEnd {
|
||||
return nil
|
||||
}
|
||||
|
||||
time.Sleep(time.Duration(sc.kclConfig.ParentShardPollIntervalMillis) * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup the internal lease cache
|
||||
func (sc *ShardConsumer) releaseLease(shard *par.ShardStatus) {
|
||||
log := sc.kclConfig.Logger
|
||||
log.Infof("Release lease for shard %s", shard.ID)
|
||||
shard.SetLeaseOwner("")
|
||||
|
||||
// Release the lease by wiping out the lease owner for the shard
|
||||
// Note: we don't need to do anything in case of error here and shard lease will eventuall be expired.
|
||||
if err := sc.checkpointer.RemoveLeaseOwner(shard.ID); err != nil {
|
||||
log.Errorf("Failed to release shard lease or shard: %s Error: %+v", shard.ID, err)
|
||||
}
|
||||
|
||||
// reporting lease lose metrics
|
||||
sc.mService.LeaseLost(shard.ID)
|
||||
}
|
||||
88
clientlibrary/worker/worker-fan-out.go
Normal file
88
clientlibrary/worker/worker-fan-out.go
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
/*
|
||||
* Copyright (c) 2021 VMware, Inc.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
|
||||
* associated documentation files (the "Software"), to deal in the Software without restriction, including
|
||||
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is furnished to do
|
||||
* so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all copies or substantial
|
||||
* portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
|
||||
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package worker
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go/service/kinesis"
|
||||
|
||||
"github.com/vmware/vmware-go-kcl/clientlibrary/utils"
|
||||
)
|
||||
|
||||
// fetchConsumerARNWithRetry tries to fetch consumer ARN. Retries 10 times with exponential backoff in case of an error
|
||||
func (w *Worker) fetchConsumerARNWithRetry() (string, error) {
|
||||
for retry := 0; ; retry++ {
|
||||
consumerARN, err := w.fetchConsumerARN()
|
||||
if err == nil {
|
||||
return consumerARN, nil
|
||||
}
|
||||
if retry < 10 {
|
||||
sleepDuration := time.Duration(math.Exp2(float64(retry))*100) * time.Millisecond
|
||||
w.kclConfig.Logger.Errorf("Could not get consumer ARN: %v, retrying after: %s", err, sleepDuration)
|
||||
time.Sleep(sleepDuration)
|
||||
continue
|
||||
}
|
||||
return consumerARN, err
|
||||
}
|
||||
}
|
||||
|
||||
// fetchConsumerARN gets enhanced fan-out consumerARN.
|
||||
// Registers enhanced fan-out consumer if the consumer is not found
|
||||
func (w *Worker) fetchConsumerARN() (string, error) {
|
||||
log := w.kclConfig.Logger
|
||||
log.Debugf("Fetching stream consumer ARN")
|
||||
streamDescription, err := w.kc.DescribeStream(&kinesis.DescribeStreamInput{
|
||||
StreamName: &w.kclConfig.StreamName,
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorf("Could not describe stream: %v", err)
|
||||
return "", err
|
||||
}
|
||||
streamConsumerDescription, err := w.kc.DescribeStreamConsumer(&kinesis.DescribeStreamConsumerInput{
|
||||
ConsumerName: &w.kclConfig.EnhancedFanOutConsumerName,
|
||||
StreamARN: streamDescription.StreamDescription.StreamARN,
|
||||
})
|
||||
if err == nil {
|
||||
log.Infof("Enhanced fan-out consumer found, consumer status: %s", *streamConsumerDescription.ConsumerDescription.ConsumerStatus)
|
||||
if *streamConsumerDescription.ConsumerDescription.ConsumerStatus != kinesis.ConsumerStatusActive {
|
||||
return "", fmt.Errorf("consumer is not in active status yet, current status: %s", *streamConsumerDescription.ConsumerDescription.ConsumerStatus)
|
||||
}
|
||||
return *streamConsumerDescription.ConsumerDescription.ConsumerARN, nil
|
||||
}
|
||||
if utils.AWSErrCode(err) == kinesis.ErrCodeResourceNotFoundException {
|
||||
log.Infof("Enhanced fan-out consumer not found, registering new consumer with name: %s", w.kclConfig.EnhancedFanOutConsumerName)
|
||||
out, err := w.kc.RegisterStreamConsumer(&kinesis.RegisterStreamConsumerInput{
|
||||
ConsumerName: &w.kclConfig.EnhancedFanOutConsumerName,
|
||||
StreamARN: streamDescription.StreamDescription.StreamARN,
|
||||
})
|
||||
if err != nil {
|
||||
log.Errorf("Could not register enhanced fan-out consumer: %v", err)
|
||||
return "", err
|
||||
}
|
||||
if *out.Consumer.ConsumerStatus != kinesis.ConsumerStatusActive {
|
||||
return "", fmt.Errorf("consumer is not in active status yet, current status: %s", *out.Consumer.ConsumerStatus)
|
||||
}
|
||||
return *out.Consumer.ConsumerARN, nil
|
||||
}
|
||||
log.Errorf("Could not describe stream consumer: %v", err)
|
||||
return "", err
|
||||
}
|
||||
|
|
@ -51,9 +51,10 @@ import (
|
|||
* the shards).
|
||||
*/
|
||||
type Worker struct {
|
||||
streamName string
|
||||
regionName string
|
||||
workerID string
|
||||
streamName string
|
||||
regionName string
|
||||
workerID string
|
||||
consumerARN string
|
||||
|
||||
processorFactory kcl.IRecordProcessorFactory
|
||||
kclConfig *config.KinesisClientLibConfiguration
|
||||
|
|
@ -181,6 +182,24 @@ func (w *Worker) initialize() error {
|
|||
log.Infof("Use custom checkpointer implementation.")
|
||||
}
|
||||
|
||||
if w.kclConfig.EnableEnhancedFanOutConsumer {
|
||||
log.Debugf("Enhanced fan-out is enabled")
|
||||
switch {
|
||||
case w.kclConfig.EnhancedFanOutConsumerARN != "":
|
||||
w.consumerARN = w.kclConfig.EnhancedFanOutConsumerARN
|
||||
case w.kclConfig.EnhancedFanOutConsumerName != "":
|
||||
var err error
|
||||
w.consumerARN, err = w.fetchConsumerARNWithRetry()
|
||||
if err != nil {
|
||||
log.Errorf("Failed to fetch consumer ARN for: %s, %v", w.kclConfig.EnhancedFanOutConsumerName, err)
|
||||
return err
|
||||
}
|
||||
default:
|
||||
log.Errorf("Consumer Name or ARN were not specified with enhanced fan-out enabled")
|
||||
return errors.New("Consumer Name or ARN must be specified when enhanced fan-out is enabled")
|
||||
}
|
||||
}
|
||||
|
||||
err := w.mService.Init(w.kclConfig.ApplicationName, w.streamName, w.workerID)
|
||||
if err != nil {
|
||||
log.Errorf("Failed to start monitoring service: %+v", err)
|
||||
|
|
@ -204,19 +223,32 @@ func (w *Worker) initialize() error {
|
|||
return nil
|
||||
}
|
||||
|
||||
// newShardConsumer to create a shard consumer instance
|
||||
func (w *Worker) newShardConsumer(shard *par.ShardStatus) *ShardConsumer {
|
||||
return &ShardConsumer{
|
||||
streamName: w.streamName,
|
||||
// newShardConsumer creates shard consumer for the specified shard
|
||||
func (w *Worker) newShardConsumer(shard *par.ShardStatus) shardConsumer {
|
||||
common := commonShardConsumer{
|
||||
shard: shard,
|
||||
kc: w.kc,
|
||||
checkpointer: w.checkpointer,
|
||||
recordProcessor: w.processorFactory.CreateProcessor(),
|
||||
kclConfig: w.kclConfig,
|
||||
consumerID: w.workerID,
|
||||
stop: w.stop,
|
||||
mService: w.mService,
|
||||
state: WaitingOnParentShards,
|
||||
}
|
||||
if w.kclConfig.EnableEnhancedFanOutConsumer {
|
||||
w.kclConfig.Logger.Infof("Start enhanced fan-out shard consumer for shard: %v", shard.ID)
|
||||
return &FanOutShardConsumer{
|
||||
commonShardConsumer: common,
|
||||
consumerARN: w.consumerARN,
|
||||
consumerID: w.workerID,
|
||||
stop: w.stop,
|
||||
}
|
||||
}
|
||||
w.kclConfig.Logger.Infof("Start polling shard consumer for shard: %v", shard.ID)
|
||||
return &PollingShardConsumer{
|
||||
commonShardConsumer: common,
|
||||
streamName: w.streamName,
|
||||
consumerID: w.workerID,
|
||||
stop: w.stop,
|
||||
mService: w.mService,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -230,7 +262,7 @@ func (w *Worker) eventLoop() {
|
|||
// starts at the same time, this decreases the probability of them calling
|
||||
// kinesis.DescribeStream at the same time, and hit the hard-limit on aws API calls.
|
||||
// On average the period remains the same so that doesn't affect behavior.
|
||||
shardSyncSleep := w.kclConfig.ShardSyncIntervalMillis/2 + w.rng.Intn(int(w.kclConfig.ShardSyncIntervalMillis))
|
||||
shardSyncSleep := w.kclConfig.ShardSyncIntervalMillis/2 + w.rng.Intn(w.kclConfig.ShardSyncIntervalMillis)
|
||||
|
||||
err := w.syncShard()
|
||||
if err != nil {
|
||||
|
|
@ -247,7 +279,7 @@ func (w *Worker) eventLoop() {
|
|||
// Count the number of leases hold by this worker excluding the processed shard
|
||||
counter := 0
|
||||
for _, shard := range w.shardStatus {
|
||||
if shard.GetLeaseOwner() == w.workerID && shard.Checkpoint != chk.ShardEnd {
|
||||
if shard.GetLeaseOwner() == w.workerID && shard.GetCheckpoint() != chk.ShardEnd {
|
||||
counter++
|
||||
}
|
||||
}
|
||||
|
|
@ -271,7 +303,7 @@ func (w *Worker) eventLoop() {
|
|||
}
|
||||
|
||||
// The shard is closed and we have processed all records
|
||||
if shard.Checkpoint == chk.ShardEnd {
|
||||
if shard.GetCheckpoint() == chk.ShardEnd {
|
||||
continue
|
||||
}
|
||||
|
||||
|
|
@ -286,16 +318,13 @@ func (w *Worker) eventLoop() {
|
|||
|
||||
// log metrics on got lease
|
||||
w.mService.LeaseGained(shard.ID)
|
||||
|
||||
log.Infof("Start Shard Consumer for shard: %v", shard.ID)
|
||||
sc := w.newShardConsumer(shard)
|
||||
w.waitGroup.Add(1)
|
||||
go func() {
|
||||
go func(shard *par.ShardStatus) {
|
||||
defer w.waitGroup.Done()
|
||||
if err := sc.getRecords(shard); err != nil {
|
||||
if err := w.newShardConsumer(shard).getRecords(); err != nil {
|
||||
log.Errorf("Error in getRecords: %+v", err)
|
||||
}
|
||||
}()
|
||||
}(shard)
|
||||
// exit from for loop and not to grab more shard for now.
|
||||
break
|
||||
}
|
||||
|
|
@ -341,7 +370,7 @@ func (w *Worker) getShardIDs(nextToken string, shardInfo map[string]bool) error
|
|||
w.shardStatus[*s.ShardId] = &par.ShardStatus{
|
||||
ID: *s.ShardId,
|
||||
ParentShardId: aws.StringValue(s.ParentShardId),
|
||||
Mux: &sync.Mutex{},
|
||||
Mux: &sync.RWMutex{},
|
||||
StartingSequenceNumber: aws.StringValue(s.SequenceNumberRange.StartingSequenceNumber),
|
||||
EndingSequenceNumber: aws.StringValue(s.SequenceNumberRange.EndingSequenceNumber),
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,10 +27,9 @@ import (
|
|||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/aws/session"
|
||||
"github.com/aws/aws-sdk-go/service/kinesis"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
chk "github.com/vmware/vmware-go-kcl/clientlibrary/checkpoint"
|
||||
cfg "github.com/vmware/vmware-go-kcl/clientlibrary/config"
|
||||
par "github.com/vmware/vmware-go-kcl/clientlibrary/partition"
|
||||
|
|
@ -74,7 +73,7 @@ func TestWorkerInjectCheckpointer(t *testing.T) {
|
|||
// verify the checkpointer after graceful shutdown
|
||||
status := &par.ShardStatus{
|
||||
ID: shardID,
|
||||
Mux: &sync.Mutex{},
|
||||
Mux: &sync.RWMutex{},
|
||||
}
|
||||
checkpointer.FetchCheckpoint(status)
|
||||
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@ import (
|
|||
"github.com/aws/aws-sdk-go/aws/session"
|
||||
"github.com/prometheus/common/expfmt"
|
||||
"github.com/stretchr/testify/assert"
|
||||
|
||||
cfg "github.com/vmware/vmware-go-kcl/clientlibrary/config"
|
||||
"github.com/vmware/vmware-go-kcl/clientlibrary/metrics"
|
||||
"github.com/vmware/vmware-go-kcl/clientlibrary/metrics/cloudwatch"
|
||||
|
|
@ -41,9 +42,11 @@ import (
|
|||
)
|
||||
|
||||
const (
|
||||
streamName = "kcl-test"
|
||||
regionName = "us-west-2"
|
||||
workerID = "test-worker"
|
||||
appName = "appName"
|
||||
streamName = "kcl-test"
|
||||
regionName = "us-west-2"
|
||||
workerID = "test-worker"
|
||||
consumerName = "enhanced-fan-out-consumer"
|
||||
)
|
||||
|
||||
const metricsSystem = "cloudwatch"
|
||||
|
|
@ -67,7 +70,7 @@ func TestWorker(t *testing.T) {
|
|||
// Use logrus logger
|
||||
log := logger.NewLogrusLoggerWithConfig(config)
|
||||
|
||||
kclConfig := cfg.NewKinesisClientLibConfig("appName", streamName, regionName, workerID).
|
||||
kclConfig := cfg.NewKinesisClientLibConfig(appName, streamName, regionName, workerID).
|
||||
WithInitialPositionInStream(cfg.LATEST).
|
||||
WithMaxRecords(8).
|
||||
WithMaxLeasesForWorker(1).
|
||||
|
|
@ -89,7 +92,7 @@ func TestWorkerWithTimestamp(t *testing.T) {
|
|||
log := logger.NewLogrusLoggerWithConfig(config)
|
||||
|
||||
ts := time.Now().Add(time.Second * 5)
|
||||
kclConfig := cfg.NewKinesisClientLibConfig("appName", streamName, regionName, workerID).
|
||||
kclConfig := cfg.NewKinesisClientLibConfig(appName, streamName, regionName, workerID).
|
||||
WithTimestampAtInitialPositionInStream(&ts).
|
||||
WithMaxRecords(10).
|
||||
WithMaxLeasesForWorker(1).
|
||||
|
|
@ -119,7 +122,7 @@ func TestWorkerWithSigInt(t *testing.T) {
|
|||
// use zap logger
|
||||
log := zaplogger.NewZapLoggerWithConfig(config)
|
||||
|
||||
kclConfig := cfg.NewKinesisClientLibConfig("appName", streamName, regionName, workerID).
|
||||
kclConfig := cfg.NewKinesisClientLibConfig(appName, streamName, regionName, workerID).
|
||||
WithInitialPositionInStream(cfg.LATEST).
|
||||
WithMaxRecords(10).
|
||||
WithMaxLeasesForWorker(1).
|
||||
|
|
@ -137,7 +140,7 @@ func TestWorkerStatic(t *testing.T) {
|
|||
// Note: use empty string as SessionToken for long-term credentials.
|
||||
creds := credentials.NewStaticCredentials("AccessKeyId", "SecretAccessKey", "SessionToken")
|
||||
|
||||
kclConfig := cfg.NewKinesisClientLibConfigWithCredential("appName", streamName, regionName, workerID, creds).
|
||||
kclConfig := cfg.NewKinesisClientLibConfigWithCredential(appName, streamName, regionName, workerID, creds).
|
||||
WithInitialPositionInStream(cfg.LATEST).
|
||||
WithMaxRecords(10).
|
||||
WithMaxLeasesForWorker(1).
|
||||
|
|
@ -159,7 +162,7 @@ func TestWorkerAssumeRole(t *testing.T) {
|
|||
// referenced by the "myRoleARN" ARN.
|
||||
creds := stscreds.NewCredentials(sess, "arn:aws:iam::*:role/kcl-test-publisher")
|
||||
|
||||
kclConfig := cfg.NewKinesisClientLibConfigWithCredential("appName", streamName, regionName, workerID, creds).
|
||||
kclConfig := cfg.NewKinesisClientLibConfigWithCredential(appName, streamName, regionName, workerID, creds).
|
||||
WithInitialPositionInStream(cfg.LATEST).
|
||||
WithMaxRecords(10).
|
||||
WithMaxLeasesForWorker(1).
|
||||
|
|
@ -169,6 +172,67 @@ func TestWorkerAssumeRole(t *testing.T) {
|
|||
runTest(kclConfig, false, t)
|
||||
}
|
||||
|
||||
func TestEnhancedFanOutConsumer(t *testing.T) {
|
||||
// At miminal, use standard logrus logger
|
||||
// log := logger.NewLogrusLogger(logrus.StandardLogger())
|
||||
//
|
||||
// In order to have precise control over logging. Use logger with config
|
||||
config := logger.Configuration{
|
||||
EnableConsole: true,
|
||||
ConsoleLevel: logger.Debug,
|
||||
ConsoleJSONFormat: false,
|
||||
EnableFile: true,
|
||||
FileLevel: logger.Info,
|
||||
FileJSONFormat: true,
|
||||
Filename: "log.log",
|
||||
}
|
||||
// Use logrus logger
|
||||
log := logger.NewLogrusLoggerWithConfig(config)
|
||||
|
||||
kclConfig := cfg.NewKinesisClientLibConfig(appName, streamName, regionName, workerID).
|
||||
WithInitialPositionInStream(cfg.LATEST).
|
||||
WithEnhancedFanOutConsumer(consumerName).
|
||||
WithMaxRecords(10).
|
||||
WithMaxLeasesForWorker(1).
|
||||
WithShardSyncIntervalMillis(5000).
|
||||
WithFailoverTimeMillis(300000).
|
||||
WithLogger(log)
|
||||
|
||||
runTest(kclConfig, false, t)
|
||||
}
|
||||
|
||||
func TestEnhancedFanOutConsumerARN(t *testing.T) {
|
||||
t.Skip("Need to provide actual consumerARN")
|
||||
|
||||
consumerARN := "arn:aws:kinesis:*:stream/kcl-test/consumer/fanout-poc-consumer-test:*"
|
||||
// At miminal, use standard logrus logger
|
||||
// log := logger.NewLogrusLogger(logrus.StandardLogger())
|
||||
//
|
||||
// In order to have precise control over logging. Use logger with config
|
||||
config := logger.Configuration{
|
||||
EnableConsole: true,
|
||||
ConsoleLevel: logger.Debug,
|
||||
ConsoleJSONFormat: false,
|
||||
EnableFile: true,
|
||||
FileLevel: logger.Info,
|
||||
FileJSONFormat: true,
|
||||
Filename: "log.log",
|
||||
}
|
||||
// Use logrus logger
|
||||
log := logger.NewLogrusLoggerWithConfig(config)
|
||||
|
||||
kclConfig := cfg.NewKinesisClientLibConfig(appName, streamName, regionName, workerID).
|
||||
WithInitialPositionInStream(cfg.LATEST).
|
||||
WithEnhancedFanOutConsumerARN(consumerARN).
|
||||
WithMaxRecords(10).
|
||||
WithMaxLeasesForWorker(1).
|
||||
WithShardSyncIntervalMillis(5000).
|
||||
WithFailoverTimeMillis(300000).
|
||||
WithLogger(log)
|
||||
|
||||
runTest(kclConfig, false, t)
|
||||
}
|
||||
|
||||
func runTest(kclConfig *cfg.KinesisClientLibConfiguration, triggersig bool, t *testing.T) {
|
||||
assert.Equal(t, regionName, kclConfig.RegionName)
|
||||
assert.Equal(t, streamName, kclConfig.StreamName)
|
||||
|
|
|
|||
Loading…
Reference in a new issue