Add support for providing custom checkpointer (#17)

* Add credential configuration for resources

Add credentials for Kinesis, DynamoDB and Cloudwatch. See the worker_test.go
to see how to use it.

Signed-off-by: Tao Jiang <taoj@vmware.com>

* Add support for providing custom checkpointer

Provide a new constructor for adding checkpointer instead of alway using
default dynamodb checkpointer.

The next step is to abstract out the Kinesis into a generic stream API and
this will be bigger change and will be addressed in different PR.

Test:
  Use the new construtor to inject dynamodb checkpointer and run the existing
  tests.

Signed-off-by: Tao Jiang <taoj@vmware.com>

* Add support for providing custom checkpointer

Provide a new constructor for adding checkpointer instead of alway using
default dynamodb checkpointer.

The next step is to abstract out the Kinesis into a generic stream API and
this will be bigger change and will be addressed in different PR.

Fix checkfmt error.

Test:
  Use the new construtor to inject dynamodb checkpointer and run the existing
  tests.

Signed-off-by: Tao Jiang <taoj@vmware.com>
This commit is contained in:
Tao Jiang 2019-04-22 15:55:39 -05:00
parent c634c75ebc
commit 2ca82c25ca
11 changed files with 321 additions and 93 deletions

View file

@ -88,5 +88,5 @@ settings:
default-targets: default-targets:
- ci - ci
docker: docker:
image: 'vmware/go-kcl-toolchain:latest' image: 'vmware/go-kcl-toolchain:0.1.2'
src-volume: /go/src/github.com/vmware/vmware-go-kcl src-volume: /go/src/github.com/vmware/vmware-go-kcl

View file

@ -0,0 +1,59 @@
/*
* 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 checkpoint
import (
"errors"
par "github.com/vmware/vmware-go-kcl/clientlibrary/partition"
)
const (
LEASE_KEY_KEY = "ShardID"
LEASE_OWNER_KEY = "AssignedTo"
LEASE_TIMEOUT_KEY = "LeaseTimeout"
CHECKPOINT_SEQUENCE_NUMBER_KEY = "Checkpoint"
PARENT_SHARD_ID_KEY = "ParentShardId"
// We've completely processed all records in this shard.
SHARD_END = "SHARD_END"
// ErrLeaseNotAquired is returned when we failed to get a lock on the shard
ErrLeaseNotAquired = "Lease is already held by another node"
)
// Checkpointer handles checkpointing when a record has been processed
type Checkpointer interface {
Init() error
GetLease(*par.ShardStatus, string) error
CheckpointSequence(*par.ShardStatus) error
FetchCheckpoint(*par.ShardStatus) error
RemoveLeaseInfo(string) error
}
// ErrSequenceIDNotFound is returned by FetchCheckpoint when no SequenceID is found
var ErrSequenceIDNotFound = errors.New("SequenceIDNotFoundForShard")

View file

@ -25,7 +25,7 @@
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // 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 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 package checkpoint
import ( import (
"errors" "errors"
@ -40,36 +40,14 @@ import (
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
"github.com/vmware/vmware-go-kcl/clientlibrary/config" "github.com/vmware/vmware-go-kcl/clientlibrary/config"
par "github.com/vmware/vmware-go-kcl/clientlibrary/partition"
) )
const ( const (
LEASE_KEY_KEY = "ShardID"
LEASE_OWNER_KEY = "AssignedTo"
LEASE_TIMEOUT_KEY = "LeaseTimeout"
CHECKPOINT_SEQUENCE_NUMBER_KEY = "Checkpoint"
PARENT_SHARD_ID_KEY = "ParentShardId"
// We've completely processed all records in this shard.
SHARD_END = "SHARD_END"
// ErrLeaseNotAquired is returned when we failed to get a lock on the shard
ErrLeaseNotAquired = "Lease is already held by another node"
// ErrInvalidDynamoDBSchema is returned when there are one or more fields missing from the table // ErrInvalidDynamoDBSchema is returned when there are one or more fields missing from the table
ErrInvalidDynamoDBSchema = "The DynamoDB schema is invalid and may need to be re-created" ErrInvalidDynamoDBSchema = "The DynamoDB schema is invalid and may need to be re-created"
) )
// Checkpointer handles checkpointing when a record has been processed
type Checkpointer interface {
Init() error
GetLease(*shardStatus, string) error
CheckpointSequence(*shardStatus) error
FetchCheckpoint(*shardStatus) error
RemoveLeaseInfo(string) error
}
// ErrSequenceIDNotFound is returned by FetchCheckpoint when no SequenceID is found
var ErrSequenceIDNotFound = errors.New("SequenceIDNotFoundForShard")
// DynamoCheckpoint implements the Checkpoint interface using DynamoDB as a backend // DynamoCheckpoint implements the Checkpoint interface using DynamoDB as a backend
type DynamoCheckpoint struct { type DynamoCheckpoint struct {
TableName string TableName string
@ -104,7 +82,7 @@ func (checkpointer *DynamoCheckpoint) Init() error {
} }
// GetLease attempts to gain a lock on the given shard // GetLease attempts to gain a lock on the given shard
func (checkpointer *DynamoCheckpoint) GetLease(shard *shardStatus, newAssignTo string) error { func (checkpointer *DynamoCheckpoint) GetLease(shard *par.ShardStatus, newAssignTo string) error {
newLeaseTimeout := time.Now().Add(time.Duration(checkpointer.LeaseDuration) * time.Millisecond).UTC() newLeaseTimeout := time.Now().Add(time.Duration(checkpointer.LeaseDuration) * time.Millisecond).UTC()
newLeaseTimeoutString := newLeaseTimeout.Format(time.RFC3339) newLeaseTimeoutString := newLeaseTimeout.Format(time.RFC3339)
currentCheckpoint, err := checkpointer.getItem(shard.ID) currentCheckpoint, err := checkpointer.getItem(shard.ID)
@ -177,16 +155,16 @@ func (checkpointer *DynamoCheckpoint) GetLease(shard *shardStatus, newAssignTo s
return err return err
} }
shard.mux.Lock() shard.Mux.Lock()
shard.AssignedTo = newAssignTo shard.AssignedTo = newAssignTo
shard.LeaseTimeout = newLeaseTimeout shard.LeaseTimeout = newLeaseTimeout
shard.mux.Unlock() shard.Mux.Unlock()
return nil return nil
} }
// CheckpointSequence writes a checkpoint at the designated sequence ID // CheckpointSequence writes a checkpoint at the designated sequence ID
func (checkpointer *DynamoCheckpoint) CheckpointSequence(shard *shardStatus) error { func (checkpointer *DynamoCheckpoint) CheckpointSequence(shard *par.ShardStatus) error {
leaseTimeout := shard.LeaseTimeout.UTC().Format(time.RFC3339) leaseTimeout := shard.LeaseTimeout.UTC().Format(time.RFC3339)
marshalledCheckpoint := map[string]*dynamodb.AttributeValue{ marshalledCheckpoint := map[string]*dynamodb.AttributeValue{
LEASE_KEY_KEY: { LEASE_KEY_KEY: {
@ -211,7 +189,7 @@ func (checkpointer *DynamoCheckpoint) CheckpointSequence(shard *shardStatus) err
} }
// FetchCheckpoint retrieves the checkpoint for the given shard // FetchCheckpoint retrieves the checkpoint for the given shard
func (checkpointer *DynamoCheckpoint) FetchCheckpoint(shard *shardStatus) error { func (checkpointer *DynamoCheckpoint) FetchCheckpoint(shard *par.ShardStatus) error {
checkpoint, err := checkpointer.getItem(shard.ID) checkpoint, err := checkpointer.getItem(shard.ID)
if err != nil { if err != nil {
return err return err
@ -222,8 +200,8 @@ func (checkpointer *DynamoCheckpoint) FetchCheckpoint(shard *shardStatus) error
return ErrSequenceIDNotFound return ErrSequenceIDNotFound
} }
log.Debugf("Retrieved Shard Iterator %s", *sequenceID.S) log.Debugf("Retrieved Shard Iterator %s", *sequenceID.S)
shard.mux.Lock() shard.Mux.Lock()
defer shard.mux.Unlock() defer shard.Mux.Unlock()
shard.Checkpoint = *sequenceID.S shard.Checkpoint = *sequenceID.S
if assignedTo, ok := checkpoint[LEASE_OWNER_KEY]; ok { if assignedTo, ok := checkpoint[LEASE_OWNER_KEY]; ok {

View file

@ -0,0 +1,58 @@
/*
* 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 (
"sync"
"time"
)
type ShardStatus struct {
ID string
ParentShardId string
Checkpoint string
AssignedTo string
Mux *sync.Mutex
LeaseTimeout time.Time
// Shard Range
StartingSequenceNumber string
// child shard doesn't have end sequence number
EndingSequenceNumber string
}
func (ss *ShardStatus) GetLeaseOwner() string {
ss.Mux.Lock()
defer ss.Mux.Unlock()
return ss.AssignedTo
}
func (ss *ShardStatus) SetLeaseOwner(owner string) {
ss.Mux.Lock()
defer ss.Mux.Unlock()
ss.AssignedTo = owner
}

View file

@ -21,7 +21,9 @@ package worker
import ( import (
"github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws"
chk "github.com/vmware/vmware-go-kcl/clientlibrary/checkpoint"
kcl "github.com/vmware/vmware-go-kcl/clientlibrary/interfaces" kcl "github.com/vmware/vmware-go-kcl/clientlibrary/interfaces"
par "github.com/vmware/vmware-go-kcl/clientlibrary/partition"
) )
type ( type (
@ -41,12 +43,12 @@ type (
* RecordProcessor instance. Amazon Kinesis Client Library will create one instance per shard assignment. * RecordProcessor instance. Amazon Kinesis Client Library will create one instance per shard assignment.
*/ */
RecordProcessorCheckpointer struct { RecordProcessorCheckpointer struct {
shard *shardStatus shard *par.ShardStatus
checkpoint Checkpointer checkpoint chk.Checkpointer
} }
) )
func NewRecordProcessorCheckpoint(shard *shardStatus, checkpoint Checkpointer) kcl.IRecordProcessorCheckpointer { func NewRecordProcessorCheckpoint(shard *par.ShardStatus, checkpoint chk.Checkpointer) kcl.IRecordProcessorCheckpointer {
return &RecordProcessorCheckpointer{ return &RecordProcessorCheckpointer{
shard: shard, shard: shard,
checkpoint: checkpoint, checkpoint: checkpoint,
@ -62,16 +64,16 @@ func (pc *PreparedCheckpointer) Checkpoint() error {
} }
func (rc *RecordProcessorCheckpointer) Checkpoint(sequenceNumber *string) error { func (rc *RecordProcessorCheckpointer) Checkpoint(sequenceNumber *string) error {
rc.shard.mux.Lock() rc.shard.Mux.Lock()
// checkpoint the last sequence of a closed shard // checkpoint the last sequence of a closed shard
if sequenceNumber == nil { if sequenceNumber == nil {
rc.shard.Checkpoint = SHARD_END rc.shard.Checkpoint = chk.SHARD_END
} else { } else {
rc.shard.Checkpoint = aws.StringValue(sequenceNumber) rc.shard.Checkpoint = aws.StringValue(sequenceNumber)
} }
rc.shard.mux.Unlock() rc.shard.Mux.Unlock()
return rc.checkpoint.CheckpointSequence(rc.shard) return rc.checkpoint.CheckpointSequence(rc.shard)
} }

View file

@ -38,9 +38,11 @@ import (
"github.com/aws/aws-sdk-go/service/kinesis" "github.com/aws/aws-sdk-go/service/kinesis"
"github.com/aws/aws-sdk-go/service/kinesis/kinesisiface" "github.com/aws/aws-sdk-go/service/kinesis/kinesisiface"
chk "github.com/vmware/vmware-go-kcl/clientlibrary/checkpoint"
"github.com/vmware/vmware-go-kcl/clientlibrary/config" "github.com/vmware/vmware-go-kcl/clientlibrary/config"
kcl "github.com/vmware/vmware-go-kcl/clientlibrary/interfaces" kcl "github.com/vmware/vmware-go-kcl/clientlibrary/interfaces"
"github.com/vmware/vmware-go-kcl/clientlibrary/metrics" "github.com/vmware/vmware-go-kcl/clientlibrary/metrics"
par "github.com/vmware/vmware-go-kcl/clientlibrary/partition"
) )
const ( const (
@ -71,9 +73,9 @@ type ShardConsumerState int
// Note: ShardConsumer only deal with one shard. // Note: ShardConsumer only deal with one shard.
type ShardConsumer struct { type ShardConsumer struct {
streamName string streamName string
shard *shardStatus shard *par.ShardStatus
kc kinesisiface.KinesisAPI kc kinesisiface.KinesisAPI
checkpointer Checkpointer checkpointer chk.Checkpointer
recordProcessor kcl.IRecordProcessor recordProcessor kcl.IRecordProcessor
kclConfig *config.KinesisClientLibConfiguration kclConfig *config.KinesisClientLibConfiguration
stop *chan struct{} stop *chan struct{}
@ -83,10 +85,10 @@ type ShardConsumer struct {
state ShardConsumerState state ShardConsumerState
} }
func (sc *ShardConsumer) getShardIterator(shard *shardStatus) (*string, error) { func (sc *ShardConsumer) getShardIterator(shard *par.ShardStatus) (*string, error) {
// Get checkpoint of the shard from dynamoDB // Get checkpoint of the shard from dynamoDB
err := sc.checkpointer.FetchCheckpoint(shard) err := sc.checkpointer.FetchCheckpoint(shard)
if err != nil && err != ErrSequenceIDNotFound { if err != nil && err != chk.ErrSequenceIDNotFound {
return nil, err return nil, err
} }
@ -123,14 +125,14 @@ func (sc *ShardConsumer) getShardIterator(shard *shardStatus) (*string, error) {
// getRecords continously poll one shard for data record // getRecords continously poll one shard for data record
// Precondition: it currently has the lease on the shard. // Precondition: it currently has the lease on the shard.
func (sc *ShardConsumer) getRecords(shard *shardStatus) error { func (sc *ShardConsumer) getRecords(shard *par.ShardStatus) error {
defer sc.waitGroup.Done() defer sc.waitGroup.Done()
defer sc.releaseLease(shard) defer sc.releaseLease(shard)
// If the shard is child shard, need to wait until the parent finished. // If the shard is child shard, need to wait until the parent finished.
if err := sc.waitOnParentShard(shard); err != nil { if err := sc.waitOnParentShard(shard); err != nil {
// If parent shard has been deleted by Kinesis system already, just ignore the error. // If parent shard has been deleted by Kinesis system already, just ignore the error.
if err != ErrSequenceIDNotFound { if err != chk.ErrSequenceIDNotFound {
log.Errorf("Error in waiting for parent shard: %v to finish. Error: %+v", shard.ParentShardId, err) log.Errorf("Error in waiting for parent shard: %v to finish. Error: %+v", shard.ParentShardId, err)
return err return err
} }
@ -158,7 +160,7 @@ func (sc *ShardConsumer) getRecords(shard *shardStatus) error {
log.Debugf("Refreshing lease on shard: %s for worker: %s", shard.ID, sc.consumerID) log.Debugf("Refreshing lease on shard: %s for worker: %s", shard.ID, sc.consumerID)
err = sc.checkpointer.GetLease(shard, sc.consumerID) err = sc.checkpointer.GetLease(shard, sc.consumerID)
if err != nil { if err != nil {
if err.Error() == ErrLeaseNotAquired { if err.Error() == chk.ErrLeaseNotAquired {
log.Warnf("Failed in acquiring lease on shard: %s for worker: %s", shard.ID, sc.consumerID) log.Warnf("Failed in acquiring lease on shard: %s for worker: %s", shard.ID, sc.consumerID)
return nil return nil
} }
@ -255,14 +257,14 @@ func (sc *ShardConsumer) getRecords(shard *shardStatus) error {
} }
// Need to wait until the parent shard finished // Need to wait until the parent shard finished
func (sc *ShardConsumer) waitOnParentShard(shard *shardStatus) error { func (sc *ShardConsumer) waitOnParentShard(shard *par.ShardStatus) error {
if len(shard.ParentShardId) == 0 { if len(shard.ParentShardId) == 0 {
return nil return nil
} }
pshard := &shardStatus{ pshard := &par.ShardStatus{
ID: shard.ParentShardId, ID: shard.ParentShardId,
mux: &sync.Mutex{}, Mux: &sync.Mutex{},
} }
for { for {
@ -271,7 +273,7 @@ func (sc *ShardConsumer) waitOnParentShard(shard *shardStatus) error {
} }
// Parent shard is finished. // Parent shard is finished.
if pshard.Checkpoint == SHARD_END { if pshard.Checkpoint == chk.SHARD_END {
return nil return nil
} }
@ -280,9 +282,9 @@ func (sc *ShardConsumer) waitOnParentShard(shard *shardStatus) error {
} }
// Cleanup the internal lease cache // Cleanup the internal lease cache
func (sc *ShardConsumer) releaseLease(shard *shardStatus) { func (sc *ShardConsumer) releaseLease(shard *par.ShardStatus) {
log.Infof("Release lease for shard %s", shard.ID) log.Infof("Release lease for shard %s", shard.ID)
shard.setLeaseOwner("") shard.SetLeaseOwner("")
// reporting lease lose metrics // reporting lease lose metrics
sc.mService.LeaseLost(shard.ID) sc.mService.LeaseLost(shard.ID)
} }

View file

@ -0,0 +1,66 @@
/*
* Copyright (c) 2019 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 (
log "github.com/sirupsen/logrus"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/kinesis"
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"
)
// NewCustomWorker constructs a Worker instance for processing Kinesis stream data by directly inject custom cjheckpointer.
func NewCustomWorker(factory kcl.IRecordProcessorFactory, kclConfig *config.KinesisClientLibConfiguration,
checkpointer chk.Checkpointer, metricsConfig *metrics.MonitoringConfiguration) *Worker {
w := &Worker{
streamName: kclConfig.StreamName,
regionName: kclConfig.RegionName,
workerID: kclConfig.WorkerID,
processorFactory: factory,
kclConfig: kclConfig,
checkpointer: checkpointer,
metricsConfig: metricsConfig,
}
// create session for Kinesis
log.Info("Creating Kinesis session")
s, err := session.NewSession(&aws.Config{
Region: aws.String(w.regionName),
Endpoint: &kclConfig.KinesisEndpoint,
Credentials: kclConfig.KinesisCredentials,
})
if err != nil {
// no need to move forward
log.Fatalf("Failed in getting Kinesis session for creating Worker: %+v", err)
}
w.kc = kinesis.New(s)
if w.metricsConfig == nil {
// "" means noop monitor service. i.e. not emitting any metrics.
w.metricsConfig = &metrics.MonitoringConfiguration{MonitoringService: ""}
}
return w
}

View file

@ -40,40 +40,16 @@ import (
"github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb" "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"
"github.com/aws/aws-sdk-go/service/kinesis/kinesisiface" "github.com/aws/aws-sdk-go/service/kinesis/kinesisiface"
chk "github.com/vmware/vmware-go-kcl/clientlibrary/checkpoint"
"github.com/vmware/vmware-go-kcl/clientlibrary/config" "github.com/vmware/vmware-go-kcl/clientlibrary/config"
kcl "github.com/vmware/vmware-go-kcl/clientlibrary/interfaces" kcl "github.com/vmware/vmware-go-kcl/clientlibrary/interfaces"
"github.com/vmware/vmware-go-kcl/clientlibrary/metrics" "github.com/vmware/vmware-go-kcl/clientlibrary/metrics"
par "github.com/vmware/vmware-go-kcl/clientlibrary/partition"
) )
type shardStatus struct {
ID string
ParentShardId string
Checkpoint string
AssignedTo string
mux *sync.Mutex
LeaseTimeout time.Time
// Shard Range
StartingSequenceNumber string
// child shard doesn't have end sequence number
EndingSequenceNumber string
}
func (ss *shardStatus) getLeaseOwner() string {
ss.mux.Lock()
defer ss.mux.Unlock()
return ss.AssignedTo
}
func (ss *shardStatus) setLeaseOwner(owner string) {
ss.mux.Lock()
defer ss.mux.Unlock()
ss.AssignedTo = owner
}
/** /**
* Worker is the high level class that Kinesis applications use to start processing data. It initializes and oversees * Worker is the high level class that Kinesis applications use to start processing data. It initializes and oversees
* different components (e.g. syncing shard and lease information, tracking shard assignments, and processing data from * different components (e.g. syncing shard and lease information, tracking shard assignments, and processing data from
@ -87,14 +63,13 @@ type Worker struct {
processorFactory kcl.IRecordProcessorFactory processorFactory kcl.IRecordProcessorFactory
kclConfig *config.KinesisClientLibConfiguration kclConfig *config.KinesisClientLibConfiguration
kc kinesisiface.KinesisAPI kc kinesisiface.KinesisAPI
dynamo dynamodbiface.DynamoDBAPI checkpointer chk.Checkpointer
checkpointer Checkpointer
stop *chan struct{} stop *chan struct{}
waitGroup *sync.WaitGroup waitGroup *sync.WaitGroup
sigs *chan os.Signal sigs *chan os.Signal
shardStatus map[string]*shardStatus shardStatus map[string]*par.ShardStatus
metricsConfig *metrics.MonitoringConfiguration metricsConfig *metrics.MonitoringConfiguration
mService metrics.MonitoringService mService metrics.MonitoringService
@ -139,8 +114,7 @@ func NewWorker(factory kcl.IRecordProcessorFactory, kclConfig *config.KinesisCli
log.Fatalf("Failed in getting DynamoDB session for creating Worker: %+v", err) log.Fatalf("Failed in getting DynamoDB session for creating Worker: %+v", err)
} }
w.dynamo = dynamodb.New(s) w.checkpointer = chk.NewDynamoCheckpoint(dynamodb.New(s), kclConfig)
w.checkpointer = NewDynamoCheckpoint(w.dynamo, kclConfig)
if w.metricsConfig == nil { if w.metricsConfig == nil {
// "" means noop monitor service. i.e. not emitting any metrics. // "" means noop monitor service. i.e. not emitting any metrics.
@ -209,7 +183,7 @@ func (w *Worker) initialize() error {
return err return err
} }
w.shardStatus = make(map[string]*shardStatus) w.shardStatus = make(map[string]*par.ShardStatus)
sigs := make(chan os.Signal, 1) sigs := make(chan os.Signal, 1)
w.sigs = &sigs w.sigs = &sigs
@ -227,7 +201,7 @@ func (w *Worker) initialize() error {
} }
// newShardConsumer to create a shard consumer instance // newShardConsumer to create a shard consumer instance
func (w *Worker) newShardConsumer(shard *shardStatus) *ShardConsumer { func (w *Worker) newShardConsumer(shard *par.ShardStatus) *ShardConsumer {
return &ShardConsumer{ return &ShardConsumer{
streamName: w.streamName, streamName: w.streamName,
shard: shard, shard: shard,
@ -258,7 +232,7 @@ func (w *Worker) eventLoop() {
// Count the number of leases hold by this worker excluding the processed shard // Count the number of leases hold by this worker excluding the processed shard
counter := 0 counter := 0
for _, shard := range w.shardStatus { for _, shard := range w.shardStatus {
if shard.getLeaseOwner() == w.workerID && shard.Checkpoint != SHARD_END { if shard.GetLeaseOwner() == w.workerID && shard.Checkpoint != chk.SHARD_END {
counter++ counter++
} }
} }
@ -267,14 +241,14 @@ func (w *Worker) eventLoop() {
if counter < w.kclConfig.MaxLeasesForWorker { if counter < w.kclConfig.MaxLeasesForWorker {
for _, shard := range w.shardStatus { for _, shard := range w.shardStatus {
// already owner of the shard // already owner of the shard
if shard.getLeaseOwner() == w.workerID { if shard.GetLeaseOwner() == w.workerID {
continue continue
} }
err := w.checkpointer.FetchCheckpoint(shard) err := w.checkpointer.FetchCheckpoint(shard)
if err != nil { if err != nil {
// checkpoint may not existed yet is not an error condition. // checkpoint may not existed yet is not an error condition.
if err != ErrSequenceIDNotFound { if err != chk.ErrSequenceIDNotFound {
log.Errorf(" Error: %+v", err) log.Errorf(" Error: %+v", err)
// move on to next shard // move on to next shard
continue continue
@ -282,14 +256,14 @@ func (w *Worker) eventLoop() {
} }
// The shard is closed and we have processed all records // The shard is closed and we have processed all records
if shard.Checkpoint == SHARD_END { if shard.Checkpoint == chk.SHARD_END {
continue continue
} }
err = w.checkpointer.GetLease(shard, w.workerID) err = w.checkpointer.GetLease(shard, w.workerID)
if err != nil { if err != nil {
// cannot get lease on the shard // cannot get lease on the shard
if err.Error() != ErrLeaseNotAquired { if err.Error() != chk.ErrLeaseNotAquired {
log.Error(err) log.Error(err)
} }
continue continue
@ -351,10 +325,10 @@ func (w *Worker) getShardIDs(startShardID string, shardInfo map[string]bool) err
// found new shard // found new shard
if _, ok := w.shardStatus[*s.ShardId]; !ok { if _, ok := w.shardStatus[*s.ShardId]; !ok {
log.Infof("Found new shard with id %s", *s.ShardId) log.Infof("Found new shard with id %s", *s.ShardId)
w.shardStatus[*s.ShardId] = &shardStatus{ w.shardStatus[*s.ShardId] = &par.ShardStatus{
ID: *s.ShardId, ID: *s.ShardId,
ParentShardId: aws.StringValue(s.ParentShardId), ParentShardId: aws.StringValue(s.ParentShardId),
mux: &sync.Mutex{}, Mux: &sync.Mutex{},
StartingSequenceNumber: aws.StringValue(s.SequenceNumberRange.StartingSequenceNumber), StartingSequenceNumber: aws.StringValue(s.SequenceNumberRange.StartingSequenceNumber),
EndingSequenceNumber: aws.StringValue(s.SequenceNumberRange.EndingSequenceNumber), EndingSequenceNumber: aws.StringValue(s.SequenceNumberRange.EndingSequenceNumber),
} }

View file

@ -0,0 +1,89 @@
/*
* 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.
*/
package worker
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"os"
"testing"
"time"
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"
"github.com/vmware/vmware-go-kcl/clientlibrary/utils"
)
func TestCustomWorker(t *testing.T) {
kclConfig := cfg.NewKinesisClientLibConfig("appName", streamName, regionName, workerID).
WithInitialPositionInStream(cfg.LATEST).
WithMaxRecords(10).
WithMaxLeasesForWorker(1).
WithShardSyncIntervalMillis(5000).
WithFailoverTimeMillis(300000).
WithMetricsBufferTimeMillis(10000).
WithMetricsMaxQueueSize(20)
log.SetOutput(os.Stdout)
log.SetLevel(log.DebugLevel)
assert.Equal(t, regionName, kclConfig.RegionName)
assert.Equal(t, streamName, kclConfig.StreamName)
// configure cloudwatch as metrics system
metricsConfig := getMetricsConfig(kclConfig, metricsSystem)
// create dynamodb checkpointer.
s, err := session.NewSession(&aws.Config{
Region: aws.String(regionName),
Endpoint: &kclConfig.DynamoDBEndpoint,
Credentials: kclConfig.DynamoDBCredentials,
})
if err != nil {
// no need to move forward
log.Fatalf("Failed in getting DynamoDB session for creating Worker: %+v", err)
}
checkpointer := chk.NewDynamoCheckpoint(dynamodb.New(s), kclConfig)
worker := NewCustomWorker(recordProcessorFactory(t), kclConfig, checkpointer, metricsConfig)
assert.Equal(t, regionName, worker.regionName)
assert.Equal(t, streamName, worker.streamName)
err = worker.Start()
assert.Nil(t, err)
// Put some data into stream.
for i := 0; i < 100; i++ {
// Use random string as partition key to ensure even distribution across shards
err := worker.Publish(streamName, utils.RandStringBytesMaskImpr(10), []byte(specstr))
if err != nil {
t.Errorf("Errorin Publish. %+v", err)
}
}
// wait a few seconds before shutdown processing
time.Sleep(10 * time.Second)
worker.Shutdown()
}

View file

@ -25,4 +25,4 @@ settings:
default-targets: default-targets:
- rebuild-toolchain - rebuild-toolchain
docker: docker:
image: 'vmware/go-kcl-toolchain:0.1.1' image: 'vmware/go-kcl-toolchain:0.1.2'

View file

@ -1,4 +1,4 @@
FROM golang:1.11 FROM golang:1.12
ENV PATH /go/bin:/src/bin:/root/go/bin:/usr/local/go/bin:$PATH ENV PATH /go/bin:/src/bin:/root/go/bin:/usr/local/go/bin:$PATH
ENV GOPATH /go:/src ENV GOPATH /go:/src
RUN go get -v github.com/alecthomas/gometalinter && \ RUN go get -v github.com/alecthomas/gometalinter && \