-
Notifications
You must be signed in to change notification settings - Fork 4
/
post_traffic_hook.py
70 lines (61 loc) · 2.45 KB
/
post_traffic_hook.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import json
import logging
import os
import boto3
from botocore.exceptions import ClientError
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
sm = boto3.client("sagemaker")
s3 = boto3.client("s3")
cd = boto3.client("codedeploy")
def get_bucket_prefix(url):
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse
a = urlparse(url)
return a.netloc, a.path.lstrip("/") + "/"
def lambda_handler(event, context):
logger.debug("event %s", json.dumps(event))
endpoint_name = os.environ["ENDPOINT_NAME"]
logger.info("post traffic for endpoint: %s", endpoint_name)
data_capture_uri = os.environ.get("DATA_CAPTURE_URI", "")
logger.info("data capture uri: %s", data_capture_uri)
error_message = None
try:
if data_capture_uri:
# List objects under data capture logs director
bucket, prefix = get_bucket_prefix(data_capture_uri)
contents = s3.list_objects(Bucket=bucket, Prefix=prefix).get("Contents")
if contents != None and contents:
logger.info("Found %d data capture logs", len(contents))
else:
error_message = "No data capture logs found"
logger.error(error_message)
except ClientError as e:
error_message = e.response["Error"]["Message"]
logger.error("Error checking logs %s", error_message)
try:
if error_message != None:
logger.info("put codepipeline failed: %s", error_message)
response = cd.put_lifecycle_event_hook_execution_status(
deploymentId=event["DeploymentId"],
lifecycleEventHookExecutionId=event["LifecycleEventHookExecutionId"],
status="Failed",
)
return {"statusCode": 400, "message": error_message}
else:
logger.info("put codepipeline success")
response = cd.put_lifecycle_event_hook_execution_status(
deploymentId=event["DeploymentId"],
lifecycleEventHookExecutionId=event["LifecycleEventHookExecutionId"],
status="Succeeded",
)
return {
"statusCode": 200,
}
except ClientError as e:
# Error attempting to update the cloud formation
logger.error("Unexpected codepipeline error")
logger.error(e)
return {"statusCode": 500, "message": e.response["Error"]["Message"]}