This repository has been archived by the owner on Feb 2, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #1 from alphagov/add-email-alert-monitoring
Add `email_alert_notifications`
- Loading branch information
Showing
1 changed file
with
44 additions
and
0 deletions.
There are no files selected for viewing
44 changes: 44 additions & 0 deletions
44
email_alert_notifications/rename_email_files_with_request_id.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
import boto3 | ||
import urllib | ||
import re | ||
import uuid | ||
from botocore.exceptions import ClientError | ||
|
||
S3 = boto3.client('s3') | ||
|
||
REQUEST_ID_REGEX = re.compile(r'data-govuk-request-id=(?:3D){,1}"([0-9\-\.]+)"') | ||
|
||
def lambda_handler(event, context): | ||
bucket_name = source_bucket_name(event) | ||
key = source_key(event) | ||
request_id = parse_request_id(bucket_name, key) | ||
prefix = file_prefix(event, request_id) | ||
move_file(bucket_name, key, request_id, prefix) | ||
|
||
def source_bucket_name(event): | ||
return event['Records'][0]['s3']['bucket']['name'] | ||
|
||
def source_key(event): | ||
return urllib.unquote_plus(event['Records'][0]['s3']['object']['key']).decode('utf8') | ||
|
||
def parse_request_id(bucket_name, key): | ||
m = REQUEST_ID_REGEX.search(email_body(bucket_name, key)) | ||
if m: | ||
return m.group(1) | ||
|
||
def email_body(bucket_name, key): | ||
response = S3.get_object(Bucket=bucket_name, Key=key) | ||
return response["Body"].read() | ||
|
||
def move_file(bucket_name, key, request_id, prefix): | ||
S3.copy_object( | ||
Bucket=bucket_name, | ||
CopySource='%s/%s' % (bucket_name, key), | ||
Key='%s/%s.msg' % (prefix, request_id or uuid.uuid4())) | ||
S3.delete_object(Bucket=bucket_name, Key=key) | ||
|
||
def file_prefix(event, request_id): | ||
if request_id: | ||
return "travel-advice-alerts" | ||
else: | ||
return "no-request-id" |