Last active
October 8, 2018 06:54
-
-
Save gergnz/d653a99b2c68446329aa6a4ff18ce4b4 to your computer and use it in GitHub Desktop.
push docker data used to cloudwatch custom metric
This file contains hidden or 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
#!/usr/bin/env python | |
import subprocess | |
import json | |
import boto3 | |
import urllib2 | |
instanceid = urllib2.urlopen('http://169.254.169.254/latest/meta-data/instance-id').read() | |
region = urllib2.urlopen('http://169.254.169.254/latest/meta-data/placement/availability-zone').read()[:-1] | |
def multiply(multiplier, value): | |
if multiplier == 'KB': | |
return value * 1024 | |
if multiplier == 'MB': | |
return value * 1024 * 1024 | |
if multiplier == 'GB': | |
return value * 1024 * 1024 * 1024 | |
if multiplier == 'TB': | |
return value * 1024 * 1024 * 1024 * 1024 | |
if multiplier == 'PB': | |
return value * 1024 * 1024 * 1024 * 1024 * 1024 | |
raw_output = subprocess.check_output("/usr/bin/docker info --format '{{json .}}'", shell=True) | |
docker_info = json.loads(raw_output) | |
for item in docker_info['DriverStatus']: | |
if item[0] == 'Data Space Used': | |
raw_used=item[1] | |
if item[0] == 'Data Space Total': | |
raw_total=item[1] | |
total = raw_total[:-2] | |
used = raw_used[:-2] | |
total_multiplier = raw_total[-2:] | |
used_multiplier = raw_used[-2:] | |
total = multiply(total_multiplier, float(total)) | |
used = multiply(used_multiplier, float(used)) | |
data_used_percent = used/total*100 | |
ec2 = boto3.client('ec2', region_name=region) | |
response = ec2.describe_tags( | |
Filters=[ | |
{ | |
'Name': 'resource-id', | |
'Values': [ instanceid ], | |
} | |
] | |
) | |
asgname='default' | |
for tag in response['Tags']: | |
if tag['Key'] != 'aws:autoscaling:groupName': | |
continue | |
asgname = tag['Value'] | |
cw = boto3.client('cloudwatch', region_name=region) | |
response = cw.put_metric_data( | |
Namespace='Docker', | |
MetricData=[ | |
{ | |
'MetricName': 'data_used_percent', | |
'Dimensions': [ | |
{ 'Name': 'AutoScalingGroupName', 'Value': asgname } | |
], | |
'Value': data_used_percent, | |
'Unit': 'Percent', | |
}, | |
], | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment