diff --git a/HyperMake b/HyperMake index a34630e..aa75a30 100644 --- a/HyperMake +++ b/HyperMake @@ -88,5 +88,5 @@ settings: default-targets: - ci 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 diff --git a/clientlibrary/checkpoint/checkpointer.go b/clientlibrary/checkpoint/checkpointer.go new file mode 100644 index 0000000..1f48349 --- /dev/null +++ b/clientlibrary/checkpoint/checkpointer.go @@ -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") diff --git a/clientlibrary/worker/checkpointer.go b/clientlibrary/checkpoint/dynamodb-checkpointer.go similarity index 90% rename from clientlibrary/worker/checkpointer.go rename to clientlibrary/checkpoint/dynamodb-checkpointer.go index 9d15fa1..0b00b6b 100644 --- a/clientlibrary/worker/checkpointer.go +++ b/clientlibrary/checkpoint/dynamodb-checkpointer.go @@ -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 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 ( "errors" @@ -40,36 +40,14 @@ import ( log "github.com/sirupsen/logrus" "github.com/vmware/vmware-go-kcl/clientlibrary/config" + 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" // 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" ) -// 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 type DynamoCheckpoint struct { TableName string @@ -104,7 +82,7 @@ func (checkpointer *DynamoCheckpoint) Init() error { } // 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() newLeaseTimeoutString := newLeaseTimeout.Format(time.RFC3339) currentCheckpoint, err := checkpointer.getItem(shard.ID) @@ -177,16 +155,16 @@ func (checkpointer *DynamoCheckpoint) GetLease(shard *shardStatus, newAssignTo s return err } - shard.mux.Lock() + shard.Mux.Lock() shard.AssignedTo = newAssignTo shard.LeaseTimeout = newLeaseTimeout - shard.mux.Unlock() + shard.Mux.Unlock() return nil } // 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) marshalledCheckpoint := map[string]*dynamodb.AttributeValue{ LEASE_KEY_KEY: { @@ -211,7 +189,7 @@ func (checkpointer *DynamoCheckpoint) CheckpointSequence(shard *shardStatus) err } // 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) if err != nil { return err @@ -222,8 +200,8 @@ func (checkpointer *DynamoCheckpoint) FetchCheckpoint(shard *shardStatus) error return ErrSequenceIDNotFound } log.Debugf("Retrieved Shard Iterator %s", *sequenceID.S) - shard.mux.Lock() - defer shard.mux.Unlock() + shard.Mux.Lock() + defer shard.Mux.Unlock() shard.Checkpoint = *sequenceID.S if assignedTo, ok := checkpoint[LEASE_OWNER_KEY]; ok { diff --git a/clientlibrary/partition/partition.go b/clientlibrary/partition/partition.go new file mode 100644 index 0000000..c261672 --- /dev/null +++ b/clientlibrary/partition/partition.go @@ -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 +} diff --git a/clientlibrary/worker/record-processor-checkpointer.go b/clientlibrary/worker/record-processor-checkpointer.go index 0562a3c..ec44eb0 100644 --- a/clientlibrary/worker/record-processor-checkpointer.go +++ b/clientlibrary/worker/record-processor-checkpointer.go @@ -21,7 +21,9 @@ package worker import ( "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" + par "github.com/vmware/vmware-go-kcl/clientlibrary/partition" ) type ( @@ -41,12 +43,12 @@ type ( * RecordProcessor instance. Amazon Kinesis Client Library will create one instance per shard assignment. */ RecordProcessorCheckpointer struct { - shard *shardStatus - checkpoint Checkpointer + shard *par.ShardStatus + checkpoint chk.Checkpointer } ) -func NewRecordProcessorCheckpoint(shard *shardStatus, checkpoint Checkpointer) kcl.IRecordProcessorCheckpointer { +func NewRecordProcessorCheckpoint(shard *par.ShardStatus, checkpoint chk.Checkpointer) kcl.IRecordProcessorCheckpointer { return &RecordProcessorCheckpointer{ shard: shard, checkpoint: checkpoint, @@ -62,16 +64,16 @@ func (pc *PreparedCheckpointer) Checkpoint() error { } func (rc *RecordProcessorCheckpointer) Checkpoint(sequenceNumber *string) error { - rc.shard.mux.Lock() + rc.shard.Mux.Lock() // checkpoint the last sequence of a closed shard if sequenceNumber == nil { - rc.shard.Checkpoint = SHARD_END + rc.shard.Checkpoint = chk.SHARD_END } else { rc.shard.Checkpoint = aws.StringValue(sequenceNumber) } - rc.shard.mux.Unlock() + rc.shard.Mux.Unlock() return rc.checkpoint.CheckpointSequence(rc.shard) } diff --git a/clientlibrary/worker/shard-consumer.go b/clientlibrary/worker/shard-consumer.go index 9b54425..7899a67 100644 --- a/clientlibrary/worker/shard-consumer.go +++ b/clientlibrary/worker/shard-consumer.go @@ -38,9 +38,11 @@ import ( "github.com/aws/aws-sdk-go/service/kinesis" "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" 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 ( @@ -71,9 +73,9 @@ type ShardConsumerState int // Note: ShardConsumer only deal with one shard. type ShardConsumer struct { streamName string - shard *shardStatus + shard *par.ShardStatus kc kinesisiface.KinesisAPI - checkpointer Checkpointer + checkpointer chk.Checkpointer recordProcessor kcl.IRecordProcessor kclConfig *config.KinesisClientLibConfiguration stop *chan struct{} @@ -83,10 +85,10 @@ type ShardConsumer struct { 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 err := sc.checkpointer.FetchCheckpoint(shard) - if err != nil && err != ErrSequenceIDNotFound { + if err != nil && err != chk.ErrSequenceIDNotFound { return nil, err } @@ -123,14 +125,14 @@ func (sc *ShardConsumer) getShardIterator(shard *shardStatus) (*string, error) { // getRecords continously poll one shard for data record // 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.releaseLease(shard) // 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 != ErrSequenceIDNotFound { + if err != chk.ErrSequenceIDNotFound { log.Errorf("Error in waiting for parent shard: %v to finish. Error: %+v", shard.ParentShardId, 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) err = sc.checkpointer.GetLease(shard, sc.consumerID) 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) return nil } @@ -255,14 +257,14 @@ func (sc *ShardConsumer) getRecords(shard *shardStatus) error { } // 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 { return nil } - pshard := &shardStatus{ + pshard := &par.ShardStatus{ ID: shard.ParentShardId, - mux: &sync.Mutex{}, + Mux: &sync.Mutex{}, } for { @@ -271,7 +273,7 @@ func (sc *ShardConsumer) waitOnParentShard(shard *shardStatus) error { } // Parent shard is finished. - if pshard.Checkpoint == SHARD_END { + if pshard.Checkpoint == chk.SHARD_END { return nil } @@ -280,9 +282,9 @@ func (sc *ShardConsumer) waitOnParentShard(shard *shardStatus) error { } // 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) - shard.setLeaseOwner("") + shard.SetLeaseOwner("") // reporting lease lose metrics sc.mService.LeaseLost(shard.ID) } diff --git a/clientlibrary/worker/worker-custom.go b/clientlibrary/worker/worker-custom.go new file mode 100644 index 0000000..580a416 --- /dev/null +++ b/clientlibrary/worker/worker-custom.go @@ -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 +} diff --git a/clientlibrary/worker/worker.go b/clientlibrary/worker/worker.go index 33551c3..8c3bedd 100644 --- a/clientlibrary/worker/worker.go +++ b/clientlibrary/worker/worker.go @@ -40,40 +40,16 @@ import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/dynamodb" - "github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface" "github.com/aws/aws-sdk-go/service/kinesis" "github.com/aws/aws-sdk-go/service/kinesis/kinesisiface" + 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 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 * 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 kclConfig *config.KinesisClientLibConfiguration kc kinesisiface.KinesisAPI - dynamo dynamodbiface.DynamoDBAPI - checkpointer Checkpointer + checkpointer chk.Checkpointer stop *chan struct{} waitGroup *sync.WaitGroup sigs *chan os.Signal - shardStatus map[string]*shardStatus + shardStatus map[string]*par.ShardStatus metricsConfig *metrics.MonitoringConfiguration 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) } - w.dynamo = dynamodb.New(s) - w.checkpointer = NewDynamoCheckpoint(w.dynamo, kclConfig) + w.checkpointer = chk.NewDynamoCheckpoint(dynamodb.New(s), kclConfig) if w.metricsConfig == nil { // "" means noop monitor service. i.e. not emitting any metrics. @@ -209,7 +183,7 @@ func (w *Worker) initialize() error { return err } - w.shardStatus = make(map[string]*shardStatus) + w.shardStatus = make(map[string]*par.ShardStatus) sigs := make(chan os.Signal, 1) w.sigs = &sigs @@ -227,7 +201,7 @@ func (w *Worker) initialize() error { } // newShardConsumer to create a shard consumer instance -func (w *Worker) newShardConsumer(shard *shardStatus) *ShardConsumer { +func (w *Worker) newShardConsumer(shard *par.ShardStatus) *ShardConsumer { return &ShardConsumer{ streamName: w.streamName, shard: shard, @@ -258,7 +232,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 != SHARD_END { + if shard.GetLeaseOwner() == w.workerID && shard.Checkpoint != chk.SHARD_END { counter++ } } @@ -267,14 +241,14 @@ func (w *Worker) eventLoop() { if counter < w.kclConfig.MaxLeasesForWorker { for _, shard := range w.shardStatus { // already owner of the shard - if shard.getLeaseOwner() == w.workerID { + if shard.GetLeaseOwner() == w.workerID { continue } err := w.checkpointer.FetchCheckpoint(shard) if err != nil { // checkpoint may not existed yet is not an error condition. - if err != ErrSequenceIDNotFound { + if err != chk.ErrSequenceIDNotFound { log.Errorf(" Error: %+v", err) // move on to next shard continue @@ -282,14 +256,14 @@ func (w *Worker) eventLoop() { } // The shard is closed and we have processed all records - if shard.Checkpoint == SHARD_END { + if shard.Checkpoint == chk.SHARD_END { continue } err = w.checkpointer.GetLease(shard, w.workerID) if err != nil { // cannot get lease on the shard - if err.Error() != ErrLeaseNotAquired { + if err.Error() != chk.ErrLeaseNotAquired { log.Error(err) } continue @@ -351,10 +325,10 @@ func (w *Worker) getShardIDs(startShardID string, shardInfo map[string]bool) err // found new shard if _, ok := w.shardStatus[*s.ShardId]; !ok { log.Infof("Found new shard with id %s", *s.ShardId) - w.shardStatus[*s.ShardId] = &shardStatus{ + w.shardStatus[*s.ShardId] = &par.ShardStatus{ ID: *s.ShardId, ParentShardId: aws.StringValue(s.ParentShardId), - mux: &sync.Mutex{}, + Mux: &sync.Mutex{}, StartingSequenceNumber: aws.StringValue(s.SequenceNumberRange.StartingSequenceNumber), EndingSequenceNumber: aws.StringValue(s.SequenceNumberRange.EndingSequenceNumber), } diff --git a/clientlibrary/worker/worker_custom_test.go b/clientlibrary/worker/worker_custom_test.go new file mode 100644 index 0000000..a02ba33 --- /dev/null +++ b/clientlibrary/worker/worker_custom_test.go @@ -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() +} diff --git a/support/toolchain/HyperMake b/support/toolchain/HyperMake index e02ea28..1dcd569 100644 --- a/support/toolchain/HyperMake +++ b/support/toolchain/HyperMake @@ -25,4 +25,4 @@ settings: default-targets: - rebuild-toolchain docker: - image: 'vmware/go-kcl-toolchain:0.1.1' + image: 'vmware/go-kcl-toolchain:0.1.2' diff --git a/support/toolchain/docker/Dockerfile b/support/toolchain/docker/Dockerfile index eefbe9f..1e66efe 100644 --- a/support/toolchain/docker/Dockerfile +++ b/support/toolchain/docker/Dockerfile @@ -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 GOPATH /go:/src RUN go get -v github.com/alecthomas/gometalinter && \