-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstart.py
80 lines (56 loc) · 2.07 KB
/
start.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import whisper
import time
import re
import os.path
import json
from urlparse import parse_qs
def application(environ, start_response):
server = Server(environ)
response = server.run()
return response.display(start_response)
class Server:
def __init__(self, environ):
self.environ = environ
def run(self):
query = parse_qs(self.environ['QUERY_STRING'])
if not 'metric' in query:
return Response(400, "Should contain at least one metric name")
if 'from' in query:
from_ = int(query['from'][0])
else:
from_ = int(time.time()) - 60 * 60 * 24
if 'until' in query:
until = int(query['until'][0])
else:
until = int(time.time())
datas = {}
for metric in query['metric']:
filteredMetric = re.sub('[^\w\d/]', '', metric)
filename = '/opt/graphite/storage/whisper/'+filteredMetric+'.wsp'
if not os.path.exists(filename):
print "Metric not found", metric
datas[metric] = None
continue
(timeInfo, values) = whisper.fetch(filename, from_, until)
(start,end,step) = timeInfo
datas[metric] = {
'start': start,
'end': end,
'step': step,
'values': values
}
response = Response(200, "callback("+json.dumps(datas)+");")
response.set_content_type('application/json')
return response
class Response:
descriptions = {400: 'Bad request', 200: 'OK'}
def __init__(self, code, body):
self.code = code
self.body = body
self.content_type = 'text/plain'
def set_content_type(self, type):
self.content_type = type
def display(self, start_response):
description = Response.descriptions[self.code] if self.code in Response.descriptions else ''
start_response(str(self.code) + description, [("Content-Type", self.content_type), ("Content-Length", str(len(self.body)))])
return [self.body]