This repository was archived by the owner on Mar 5, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
163 lines (128 loc) · 4.42 KB
/
api.py
File metadata and controls
163 lines (128 loc) · 4.42 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
"""HTTP API implementation."""
import csv
import json
import logging
import time
import webapp2
import models
def Multiplex(iterators, selection_func):
"""Iterate over multiple sources and multiplex values.
Args:
iterators: list of source iterators
selection_func: takes a list of values, selects one and returns its index
Yields:
Each value from the source iterators, in the order determined by
selection_func.
"""
iterators = list(iterators)
for i, obj in reversed(list(enumerate(iterators))):
try:
iterators[i] = [obj, obj.next()]
except StopIteration:
del iterators[i]
while iterators:
i = selection_func([x[1] for x in iterators])
yield iterators[i][1]
try:
iterators[i][1] = iterators[i][0].next()
except StopIteration:
del iterators[i]
class Get(webapp2.RequestHandler):
"""Fetch values from one or more timeseries.
HTTP parameters:
expr=<string>
format={csv,json}
resolution={full,minute,hour,day}
start=<unix_timestamp>
end=<unix_timestamp>
"""
def get(self):
output_format = self.request.get('format', 'json')
assert output_format in ('csv', 'json')
resolution = self.request.get('resolution', 'full')
resolution = models.Values.RESOLUTION_NAMES[resolution]
start = self.request.get('start', None)
if start:
start = int(start)
if start < 0:
start = int(time.time()) + start
end = self.request.get('end', None)
if end:
end = int(end)
if end < 0:
end = int(time.time()) + end
expr = self.request.get('expr')
data = models.TimeSeries.FromExpr(expr)
if output_format == 'csv':
self.response.content_type = 'text/csv'
fh = csv.writer(self.response.out)
# CSV requires us to pre-determine column names
try:
group = data.iterkeys().next()
except StopIteration:
return
group_columns = [x.tag_key for x in group]
fh.writerow(['timestamp'] + group_columns + ['value'])
elif output_format == 'json':
self.response.content_type = 'application/json'
ret = []
def SelectMinTime(values):
return min(range(len(values)), key=lambda x: values[x][0])
streams = {}
# Get all datastore queries running in parallel first
for groupings, timeseries in data.iteritems():
streams[groupings] = [
x.GetValues(start=start, end=end, resolution=resolution)
for x in timeseries
]
for groupings in sorted(data.keys()):
group_values = dict((x.tag_key, x.tag_value) for x in sorted(groupings))
values = Multiplex(streams[groupings], SelectMinTime)
if output_format == 'csv':
group_constants = [group_values[x] for x in group_columns]
for timestamp, value in values:
fh.writerow([timestamp] + group_constants + [value])
elif output_format == 'json':
ret.append({
'tags': group_values,
'timestamps_values': list(values),
})
if output_format == 'json':
json.dump(ret, self.response.out, separators=(',', ':'))
class Put(webapp2.RequestHandler):
"""Add a value to a timeseries.
HTTP parameters:
tag=<key>=<value> (repeated)
value=<integer>
"""
def _HandleBlock(self, block):
if 'timestamps_values' not in block:
now = int(time.time())
block['timestamps_values'] = [[now, x] for x in block['values']]
if 'client_timestamp' in block:
server_timestamp = int(time.time())
offset = server_timestamp - block['client_timestamp']
for pair in block['timestamps_values']:
pair[0] += offset
tags = [models.Tag.FromStr(x, create=True)
for x in block['tags']]
timeseries = models.TimeSeries.GetOrCreate(tags)
timeseries.AddValues(block['timestamps_values'],
offset=block.get('offset', False))
def post(self):
content_type = self.request.headers['Content-Type'].split(';', 1)[0]
if content_type == 'application/x-www-form-urlencoded':
self._HandleBlock({
'offset': bool(self.request.get('offset', 0)),
'tags': self.request.get_all('tag'),
'values': [int(x) for x in self.request.get_all('value')],
})
elif content_type == 'application/json':
for block in json.loads(self.request.body):
self._HandleBlock(block)
else:
assert False, content_type
app = webapp2.WSGIApplication([
('/api/get', Get),
('/api/put', Put),
])