Skip to content

Instantly share code, notes, and snippets.

@gergnz
Last active October 8, 2018 06:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gergnz/d653a99b2c68446329aa6a4ff18ce4b4 to your computer and use it in GitHub Desktop.
Save gergnz/d653a99b2c68446329aa6a4ff18ce4b4 to your computer and use it in GitHub Desktop.
push docker data used to cloudwatch custom metric
#!/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