-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcadence.py
executable file
·88 lines (67 loc) · 2.23 KB
/
cadence.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
81
82
83
84
85
86
87
88
#!/usr/bin/env python3
from flask import Flask, jsonify, request
import os
import requests
import sys
import time
from timeseries import TimeSeries
class MetricsClient(object):
def __init__(self, host, max_size=10_000):
self.host = host
self.max_size = max_size
self.backlog = []
def get_all(self):
url = os.path.join(self.host, f"metrics")
response = requests.get(url)
return (response.json)
def get(self, name: str):
url = os.path.join(self.host, f"metric/{name}")
response = requests.get(url)
return (response.json)
def post(self, name: str, data: dict):
data.setdefault('time', time.time())
self.backlog.append((name, data))
error = False
for _ in range(len(self.backlog)):
(_name, _data) = self.backlog.pop(0)
try:
self._post(_name, _data)
except e:
error = True
self.backlog.append((_name, _data))
if error:
print(f"Failed to post (backlog={len(self.backlog)})")
def _post(self, name, data):
url = os.path.join(self.host, f"metric/{name}")
response = requests.post(url, json=data)
response.raise_for_status()
class MetricsServer(object):
def __init__(self):
pass
def main():
app = Flask(__name__)
metrics = {}
@app.route("/status")
def status():
return ("OK", 200)
@app.route("/metrics")
def get_metrics():
return (jsonify(list(metrics.keys())), 200)
@app.route("/metric/<name>", methods=["GET"])
def get_metric(name: str):
if name in metrics:
start = request.args.get('start', default=None, type=float)
end = request.args.get('end', default=None, type=float)
return jsonify(metrics[name].select(start, end))
else:
return ("Metric not found", 404)
@app.route("/metric/<name>", methods=["POST"])
def post_metric(name: str):
if name not in metrics:
metrics[name] = TimeSeries()
metrics[name].add(request.get_json(force=True))
return ("OK", 201)
app.run(host="0.0.0.0")
if __name__ == "__main__":
ret = main()
sys.exit(ret)