def incoming_cloudwatch_alarm()

in source/msam/chalicelib/cloudwatch.py [0:0]


def incoming_cloudwatch_alarm(event, _):
    """
    Standard AWS Lambda entry point for receiving CloudWatch alarm notifications.
    """
    print(event)
    try:
        updated_timestamp = int(time.time())
        ddb_table_name = ALARMS_TABLE_NAME
        ddb_resource = boto3.resource('dynamodb', config=MSAM_BOTO3_CONFIG)
        ddb_table = ddb_resource.Table(ddb_table_name)
        for record in event["Records"]:
            region = (record["Sns"]["TopicArn"]).split(":")[3]
            alarm = json.loads(record["Sns"]["Message"])
            alarm_name = [
                match.value for match in parse('$..AlarmName').find(alarm)
            ]
            # look up the resources with this region alarm name
            # metric = [match.value for match in parse('$..MetricName').find(alarm)]
            namespace = [
                match.value for match in parse('$..Namespace').find(alarm)
            ]
            state = [
                match.value for match in parse('$..NewStateValue').find(alarm)
            ]
            updated = [
                match.value
                for match in parse('$..StateChangeTime').find(alarm)
            ]
            region_alarm_name = "{}:{}".format(
                region, alarm_name[0] if alarm_name else None)
            subscribers = subscribers_to_alarm(
                alarm_name[0] if alarm_name else None, region)
            for resource_arn in subscribers:
                item = {
                    "RegionAlarmName":
                    region_alarm_name,
                    "ResourceArn":
                    resource_arn,
                    "Namespace":
                    namespace[0] if namespace else None,
                    "StateUpdated":
                    int(
                        datetime.datetime.strptime(
                            updated[0], '%Y-%m-%dT%H:%M:%S.%f%z').timestamp())
                    if updated else None,
                    "StateValue":
                    state[0] if state else None,
                    "Updated":
                    updated_timestamp
                }
                ddb_table.put_item(Item=item)
                print("{} updated via alarm notification".format(resource_arn))
    except ClientError as error:
        print(error)
    return True