Last active
December 21, 2015 10:08
-
-
Save scari/dbf045a8feaecac06eb5 to your computer and use it in GitHub Desktop.
This file contains 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
import httplib2, sys, os, base64, hashlib, hmac, time | |
import json as simplejson | |
from urllib import urlencode, quote_plus | |
aws_key = '' | |
aws_secret_key = '' | |
hostname = open('/etc/hostname').read().rstrip() | |
# XXX: For now, those two names are same. but should be distinguished. | |
instanceid = hostname | |
loadavg1, loadavg5, loadavg15 = open('/proc/loadavg').read().split(' ')[:3] | |
params = {'Namespace': 'uCloud', | |
'MetricData.member.1.MetricName': 'CPUUtilization', | |
'MetricData.member.1.Value': loadavg5, | |
'MetricData.member.1.Unit': 'Percent', | |
'MetricData.member.1.Dimensions.member.1.Name': 'InstanceID', | |
'MetricData.member.1.Dimensions.member.1.Value': instanceid, | |
'MetricData.member.1.Dimensions.member.2.Name': 'Hostname', | |
'MetricData.member.1.Dimensions.member.2.Value': hostname} | |
def getSignedURL(key, secret_key, action, parms): | |
# base url | |
base_url = "monitoring.ap-northeast-1.amazonaws.com" | |
# build the parameter dictionary | |
url_params = parms | |
url_params['AWSAccessKeyId'] = key | |
url_params['Action'] = action | |
url_params['SignatureMethod'] = 'HmacSHA256' | |
url_params['SignatureVersion'] = '2' | |
url_params['Version'] = '2010-08-01' | |
url_params['Timestamp'] = time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime()) | |
# sort and encode the parameters | |
keys = url_params.keys() | |
keys.sort() | |
values = map(url_params.get, keys) | |
url_string = urlencode(zip(keys,values)) | |
# sign, encode and quote the entire request string | |
string_to_sign = "GET\n%s\n/\n%s" % (base_url, url_string) | |
signature = hmac.new(key=secret_key, msg=string_to_sign, digestmod=hashlib.sha256).digest() | |
signature = base64.encodestring(signature).strip() | |
urlencoded_signature = quote_plus(signature) | |
url_string += "&Signature=%s" % urlencoded_signature | |
# do it | |
foo = "http://%s/?%s" % (base_url, url_string) | |
return foo | |
class Cloudwatch: | |
def __init__(self, key, secret_key): | |
self.key = os.getenv('AWS_ACCESS_KEY_ID', key) | |
self.secret_key = os.getenv('AWS_SECRET_ACCESS_KEY_ID', secret_key) | |
def putData(self, params): | |
signedURL = getSignedURL(self.key, self.secret_key, 'PutMetricData', params) | |
#print signedURL | |
h = httplib2.Http() | |
resp, content = h.request(signedURL) | |
#print resp, content | |
cw = Cloudwatch(aws_key, aws_secret_key) | |
cw.putData(params) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment