"""Lambda s3_event_forwarder function module.""" from dateutil import parser from lambdacommon.common_config import logger from lambdacommon import util import config util.init_sentry_for_lambda() def handler(event, context): """Lambda entry point.""" try: for record in event['Records']: event_name = record['eventName'] match event_name: case 'Replication:OperationFailedReplication': handle_operation_failed_replication_event(record) case _: raise Exception(f'Event {event_name} not supported.') except Exception as e: logger.exception(str(e)) raise e def handle_operation_failed_replication_event(record): """Handle OperationFailedReplication events.""" bucket_name = record['s3']['bucket']['name'] aws_account = record['s3']['bucket']['ownerIdentity']['principalId'] object_key = record['s3']['object']['key'] object_version = record['s3']['object']['versionId'] replication_event_data = record['replicationEventData'] replication_rule_id = replication_event_data['replicationRuleId'] destination_bucket = replication_event_data['destinationBucket'] s3_operation = replication_event_data['s3Operation'] failure_reason = replication_event_data['failureReason'] request_time = parser.parse(replication_event_data['requestTime']) with util.datadog_connection( api_key=config.DD_API_KEY, app_key=config.DD_APP_KEY) as datadog: datadog.Event.create( attach_host_name=False, title=f'Replication failure for bucket {bucket_name}', text=f'Object {object_key} failed to replicate to ' f'{destination_bucket}. Failure reason: {failure_reason}. ' f'Object version: {object_version}.', alert_type='error', date_happened=int(request_time.timestamp()), source_type_name='amazon s3', tags=[ f'aws_account:{aws_account}', f'bucket_name:{bucket_name}', f'destination_bucket:{destination_bucket}', f'failure_reason:{failure_reason}', f'replication_rule_id:{replication_rule_id}', f's3_operation:{s3_operation}', ] )