blob: 11e985135753bf9f8e73ca9d378b451ebd6c21ba [file] [log] [blame]
Sapan Bhatia56410d52014-12-16 01:08:23 -05001#!/usr/bin/python
2# -*- coding: utf-8 -*-
3
4from ceilometerclient import client
5from os import environ as env
6import keystoneclient.v2_0.client as ksclient
7import re
8import datetime
9import time
10from monitor.monitordriver import *
11
12
13def cli_to_array(cli_query):
14 '''This converts from the cli list of queries to what is required
15 by the python api.
16 so from:
17 "this<=34;that=foo"
18 to
19 "[{field=this,op=le,value=34},{field=that,op=eq,value=foo}]"
20 '''
21 if cli_query is None:
22 return None
23
24 op_lookup = {'!=': 'ne',
25 '>=': 'ge',
26 '<=': 'le',
27 '>': 'gt',
28 '<': 'lt',
29 '=': 'eq'}
30
31 def split_by_op(string):
32 # two character split (<=,!=)
33 frags = re.findall(r'([[a-zA-Z0-9_.]+)([><!]=)([^ -,\t\n\r\f\v]+)',
34 string)
35 if len(frags) == 0:
36 #single char split (<,=)
37 frags = re.findall(r'([a-zA-Z0-9_.]+)([><=])([^ -,\t\n\r\f\v]+)',
38 string)
39 return frags
40
41 opts = []
42 queries = cli_query.split(';')
43 for q in queries:
44 frag = split_by_op(q)
45 if len(frag) > 1:
46 raise ValueError('incorrect seperator %s in query "%s"' %
47 ('(should be ";")', q))
48 if len(frag) == 0:
49 raise ValueError('invalid query %s' % q)
50 query = frag[0]
51 opt = {}
52 opt['field'] = query[0]
53 opt['op'] = op_lookup[query[1]]
54 opt['value'] = query[2]
55 opts.append(opt)
56 return opts
57
58def meters_to_stats(meters):
59 stats = DashboardStatistics()
60 for m in meters:
61 timestamp = datetime.datetime.strptime(m.duration_start,'%Y-%m-%dT%H:%M:%S')
62 stats.stat_list.append({'timestamp':timestamp, 'value':m.sum})
63 stats.sum+=m.sum
64 stats.average+=m.sum
65 stats.unit = 'ns'
66
67 stats.average/=len(meters)
68 return stats
69
70
71
72class CeilometerDriver(MonitorDriver):
73 def get_meter(self, meter, object_filter, keystone):
74 if (not keystone):
75 keystone = {}
76 keystone['username']=env['OS_USERNAME']
77 keystone['password']=env['OS_PASSWORD']
78 keystone['auth_url']=env['OS_AUTH_URL']
79 keystone['tenant_name']=env['OS_TENANT_NAME']
80
81 ceilometer_client = client._get_ksclient(**keystone)
82 token = ceilometer_client.auth_token
83
84 ceilo_endpoint = client._get_endpoint(ceilometer_client, **keystone)
85
86 ceilometer = client.Client('2',endpoint = ceilo_endpoint, token = lambda: token)
87
88 cur_ts = datetime.datetime.fromtimestamp(time.time()-86400)
89 str_ts = cur_ts.strftime('%Y-%m-%dT%H:%M:%S')
90
91 filter=';'.join([object_filter,'timestamp>%s'%str_ts])
92 #query = cli_to_array("project_id=124de34266b24f57957345cdb43cc9ff;timestamp>2014-12-11T00:00:00")
93 query = cli_to_array(filter)
94
95 meters = ceilometer.statistics.list(meter,q=query,period=3600)
96
97 stats = meters_to_stats(meters)
98 return stats
99