blob: 5c8e9895a1454d61118e7fe2eedc0314aa6d1f05 [file] [log] [blame]
koder aka kdanilov36e3a6e2015-04-25 21:21:58 +03001import time
2import random
3import os.path
4import logging
5import calendar
6import datetime
7import threading
8
9import cherrypy
10from cherrypy import tools
11
12import wally
13
14logger = logging.getLogger("wally.webui")
15
16
17def to_timestamp(str_datetime):
18 dt, str_gmt_offset = str_datetime.split("GMT", 1)
19 dt = dt.strip().split(" ", 1)[1]
20 dto = datetime.datetime.strptime(dt, "%b %d %Y %H:%M:%S")
21 timestamp = calendar.timegm(dto.timetuple())
22 str_gmt_offset = str_gmt_offset.strip().split(" ", 1)[0]
23 gmt_offset = int(str_gmt_offset)
24 gmt_offset_sec = gmt_offset // 100 * 3600 + (gmt_offset % 100) * 60
25 return timestamp - gmt_offset_sec
26
27
28def backfill_thread(dstore):
29 with dstore.lock:
30 for i in range(600):
31 dstore.data['disk_io'].append(int(random.random() * 100))
32 dstore.data['net_io'].append(int(random.random() * 100))
33
34 while True:
35 time.sleep(1)
36 with dstore.lock:
37 dstore.data['disk_io'].append(int(random.random() * 100))
38 dstore.data['net_io'].append(int(random.random() * 100))
39
40
41class WebWally(object):
42
43 def __init__(self, sensors_data_storage):
44 self.storage = sensors_data_storage
45
46 @cherrypy.expose
47 @tools.json_out()
48 def sensors(self, start, stop, step, name):
49 try:
50 start = to_timestamp(start)
51 stop = to_timestamp(stop)
52
53 with self.storage.lock:
54 data = self.storage.data[name]
55 except Exception:
56 logger.exception("During parse input data")
57 raise cherrypy.HTTPError("Wrong date format")
58
59 if step != 1000:
60 raise cherrypy.HTTPError("Step must be equals to 1s")
61
62 num = stop - start
63
64 if len(data) > num:
65 data = data[-num:]
66 else:
67 data = [0] * (num - len(data)) + data
68
69 return data
70
71 @cherrypy.expose
72 def index(self):
73 idx = os.path.dirname(wally.__file__)
74 idx = os.path.join(idx, "sensors.html")
75 return open(idx).read()
76
77
78def web_main_thread(sensors_data_storage):
79
80 cherrypy.config.update({'environment': 'embedded',
81 'server.socket_port': 8089,
82 'engine.autoreload_on': False})
83
84 th = threading.Thread(None, backfill_thread, "backfill_thread",
85 (sensors_data_storage,))
86 th.daemon = True
87 th.start()
88
89 cherrypy.quickstart(WebWally(sensors_data_storage), '/')
90
91
92def web_main_stop():
93 cherrypy.engine.stop()