-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhandler.py
70 lines (53 loc) · 1.84 KB
/
handler.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 os
import time
import boto3
import logging
import sys, os # noqa
# get this file's directory independent of where it's run from
here = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(here, "vendored"))
import requests # noqa
from raven.contrib.awslambda import LambdaClient # noqa
raven_client = LambdaClient()
logger = logging.getLogger()
logger.setLevel(logging.INFO)
boto_client = None
def current_time_in_seconds():
return time.time()
def response_with_message(message):
logger.info(message)
return {"statusCode": 200, "body": json.dumps({"message": message})}
def publish_elapsed_time_for_host(elapsed_time, host):
global boto_client
if not boto_client:
boto_client = boto3.client('cloudwatch')
boto_client.put_metric_data(
Namespace=os.environ.get('PING_ALARM_NAMESPACE'),
MetricData=[
{
'MetricName': os.environ.get('PING_METRIC_NAME'),
'Dimensions': [
{
'Name': 'Host',
'Value': host
},
],
'Value': elapsed_time,
'Unit': 'Seconds'
},
]
)
@raven_client.capture_exceptions
def ping(event, context):
ping_host = os.environ.get('PING_HOST')
start = current_time_in_seconds()
try:
response = requests.get(ping_host)
response.raise_for_status()
except requests.RequestException as e:
publish_elapsed_time_for_host(0, ping_host)
return response_with_message("Checked failed for {}, {}".format(ping_host, str(e)))
elapsed_time = current_time_in_seconds() - start
publish_elapsed_time_for_host(elapsed_time, ping_host)
return response_with_message("Pinged: {} Duration: {}".format(ping_host, elapsed_time))