|
| 1 | +# Copyright 2015-2016 Rackspace US, Inc. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import time |
| 16 | +import boto3 |
| 17 | +import botocore |
| 18 | +import logging |
| 19 | + |
| 20 | +LOG = logging.getLogger(__name__) |
| 21 | + |
| 22 | + |
| 23 | +class KinesisSubscriber(object): |
| 24 | + ''' Invokes the lambda function on events from the Kinesis streams ''' |
| 25 | + def __init__(self, config, profile_name, |
| 26 | + function_name, stream_name, batch_size): |
| 27 | + self._aws_session = boto3.session.Session(region_name=config.region, |
| 28 | + profile_name=profile_name) |
| 29 | + self._lambda_client = self._aws_session.client('lambda') |
| 30 | + self.function_name = function_name |
| 31 | + self.stream_name = stream_name |
| 32 | + self.batch_size = batch_size |
| 33 | + |
| 34 | + def subscribe(self): |
| 35 | + ''' Subscribes the lambda to the Kinesis stream ''' |
| 36 | + try: |
| 37 | + LOG.debug('Creating Kinesis subscription') |
| 38 | + self._lambda_client \ |
| 39 | + .create_event_source_mapping(EventSourceArn=self.stream_name, |
| 40 | + FunctionName=self.function_name, |
| 41 | + BatchSize=self.batch_size, |
| 42 | + StartingPosition='TRIM_HORIZON') |
| 43 | + LOG.debug('Subscription created') |
| 44 | + except botocore.exceptions.ClientError as ex: |
| 45 | + response_code = ex.response['Error']['Code'] |
| 46 | + if response_code == 'InvalidParameterValueException': |
| 47 | + LOG.debug('Retrying subscription') |
| 48 | + time.sleep(3) |
| 49 | + elif response_code == 'ResourceConflictException': |
| 50 | + LOG.debug('Subscription exists') |
| 51 | + else: |
| 52 | + LOG.error('Subscription failed, error=%s' % str(ex)) |
| 53 | + raise ex |
| 54 | + |
| 55 | + |
| 56 | +def create_subscriptions(config, profile_name): |
| 57 | + ''' Adds supported subscriptions ''' |
| 58 | + if 'kinesis' in config.subscription.keys(): |
| 59 | + data = config.subscription['kinesis'] |
| 60 | + function_name = config.name |
| 61 | + stream_name = data['stream'] |
| 62 | + batch_size = data['batch_size'] |
| 63 | + s = KinesisSubscriber(config, profile_name, |
| 64 | + function_name, stream_name, batch_size) |
| 65 | + s.subscribe() |
0 commit comments