Skip to content
Snippets Groups Projects
ceilometer-curl-test 5.12 KiB
Newer Older
#!/usr/bin/env python

import calendar
import ConfigParser
import httplib
import json
import math
import optparse
import os
import sys
import time

from filelock import FileLock

class api_response():

    __status = None
    __data = None
    __msg = None

    def __init__(self, status, data, msg):
        self.setStatus(status)
        self.setData(data)
        self.setMsg(msg)

    def setStatus(self, status):
        self.__status = status

    def getStatus(self):
        return self.__status

    def setData(self, data):
        self.__data = data

    def getData(self):
        return self.__data

    def setMsg(self, msg):
        self.__msg = msg

    def getMsg(self):
        return self.__msg

class api_request():
    @staticmethod
    def httpGet(url, host, port, header):
        conn = httplib.HTTPConnection(host, port)
        conn.request("GET", url, headers = header)
        res = conn.getresponse()
        response = api_response(res.status, res.read(), res.msg)
        return response
    @staticmethod
    def httpsGet(url, host, port, header):
        conn = httplib.HTTPSConnection(host, port)
        conn.request("GET", url, headers = header)
        res = conn.getresponse()
        response = api_response(res.status, res.read(), res.msg)
        return response
    @staticmethod
    def httpPost(url, host, port, params, headers):
        conn = httplib.HTTPConnection(host, port)
        conn.request("POST", url, params, headers)
        res = conn.getresponse()
        response = api_response(res.status, res.read(), res.msg)
        return response
    @staticmethod
    def httpsPost(url, host, port, params, headers):
        conn = httplib.HTTPSConnection(host, port)
        conn.request("POST", url, params, headers)
        res = conn.getresponse()
        response = api_response(res.status, res.read(), res.msg)
        return response

def getToken(protocol, server, port, tenant, username, password):
    token_file_path = os.path.join(os.path.dirname(__file__), 'token_backup')
    parser_token = ConfigParser.SafeConfigParser()

    with FileLock(token_file_path):
        parser_token.readfp(open(token_file_path))

    if (not parser_token.get('token', 'expires')) or (int(float(parser_token.get('token', 'expires')) - time.time()) <= 0):
        auth = '{"auth": {"tenantName": "%s", "passwordCredentials": {"username": "%s", "password": "%s"}}}' % (tenant, username, password)
        header = {"Content-Type": "application/json", "Accept": "application/json"}
        if protocol == 'http':
            res = api_request.httpPost('/v2.0/tokens', server, port, auth, header)
        else:
            res = api_request.httpsPost('/v2.0/tokens', server, port, auth, header)

        res_json = json.loads(res.getData())

        timestamp = calendar.timegm(time.strptime(res_json['access']['token']['expires'],"%Y-%m-%dT%H:%M:%SZ"))

        parser_token.set('token', 'id', res_json['access']['token']['id'])
        parser_token.set('token', 'expires', str(timestamp))

        with FileLock(token_file_path):
            with open(token_file_path, 'w') as configfile:
                parser_token.write(configfile)

    return parser_token.get('token', 'id')

def getMeter(protocol, server, port, token_id, meter, resource_id):
    if meter in ('cpu', 'cpu_util', 'disk.ephemeral.size', 'disk.root.size', 'memory', 'vcpus'):
        url = "/v2/meters/%s?q.field=resource_id&q.op=eq&q.value=%s&limit=1" % (meter, resource_id)
    elif meter in ('network.incoming.bytes', 'network.outgoing.bytes'):
        url = "/v2/meters/%s?q.field=metadata.instance_id&q.op=eq&q.value=%s&limit=1" % (meter, resource_id)
    else:
        return "Sorry, Unknown Meter"

    if protocol == 'http':
        res_json = json.loads(api_request.httpGet(url, server, port, {"X-Auth-Token": token_id}).getData())
    else:
        res_json = json.loads(api_request.httpsGet(url, server, port, {"X-Auth-Token": token_id}).getData())

    if res_json:
        return res_json[0]['counter_volume']
    else:
        return 'Sorry, Sample Not Found'

def main():
    config_file_path = os.path.join(os.path.dirname(__file__), 'proxy.conf')
    parser_config = ConfigParser.SafeConfigParser()
    parser_config.readfp(open(config_file_path))

    token_id = getToken(
        parser_config.get('keystone', 'protocol'),
        parser_config.get('keystone', 'server'),
        parser_config.get('keystone', 'port'),
        parser_config.get('keystone', 'tenant'),
        parser_config.get('keystone', 'username'),
        parser_config.get('keystone', 'password')
    )

#    print getMeter(
#        parser_config.get('ceilometer', 'protocol'),
#        parser_config.get('ceilometer', 'server'),
#        parser_config.get('ceilometer', 'port'),
#        token_id,
#        sys.argv[1],
#        sys.argv[2]
#    )

    server = '141.250.2.118'
    protocol = 'http'
    port = '8774'

    url = "/v2/ea26dfda4a1c43a79c94a0720510c308/os-fping/ded7f200-fb21-4577-acd3-d16e2260207b"

    res_json = json.loads(api_request.httpGet(url, server, port, {"X-Auth-Token": token_id}).getData())
    print json.dumps(res_json, sort_keys=True, indent=4, separators=(',', ': '))

if __name__ == "__main__":
    main()