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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
#!/usr/bin/env python3
import os
import re
import sys
import boto3
import subprocess
from datetime import datetime
def main(sample_count=5):
try:
_, from_location, to_location, hostname = sys.argv
except ValueError:
print("usage: {} <this_location> <to_location> <hostname>".format(
os.path.basename(sys.argv[0])))
sys.exit(1)
client = boto3.client("cloudwatch")
now = datetime.now()
patt = re.compile(
"round-trip min/avg/max = "
"(?P<min>[0-9]+\.[0-9]+)/(?P<avg>[0-9]+\.[0-9]+)/"
"(?P<max>[0-9]+\.[0-9]+) (?P<unit>.*)")
out = subprocess.run(
["ping", "-c", str(sample_count), hostname],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# Prevent failing with an error if the ping fails
match = patt.search(out.stdout.decode("us-ascii"))
if not match:
return 1
val = match.groupdict()
client.put_metric_data(
Namespace="VPNLatency",
MetricData=[
{
"MetricName": "PingRTT",
"Dimensions": [
{
"Name": "From Location",
"Value": from_location,
},
{
"Name": "To Location",
"Value": to_location,
}
],
"Timestamp": now,
"StatisticValues": {
"SampleCount": sample_count,
"Sum": float(val["avg"]) * sample_count,
"Minimum": float(val["min"]),
"Maximum": float(val["max"]),
},
"Unit": "Milliseconds"
},
{
"MetricName": "PingRTT",
"Dimensions": [
{
"Name": "From Location",
"Value": from_location,
},
],
"Timestamp": now,
"StatisticValues": {
"SampleCount": sample_count,
"Sum": float(val["avg"]) * sample_count,
"Minimum": float(val["min"]),
"Maximum": float(val["max"]),
},
"Unit": "Milliseconds"
},
{
"MetricName": "PingRTT",
"Dimensions": [
{
"Name": "To Location",
"Value": to_location,
}
],
"Timestamp": now,
"StatisticValues": {
"SampleCount": sample_count,
"Sum": float(val["avg"]) * sample_count,
"Minimum": float(val["min"]),
"Maximum": float(val["max"]),
},
"Unit": "Milliseconds"
},
]
)
return 0
if __name__ == "__main__":
sys.exit(main())
|