koder aka kdanilov | 36e3a6e | 2015-04-25 21:21:58 +0300 | [diff] [blame] | 1 | import time |
| 2 | import random |
| 3 | import os.path |
| 4 | import logging |
| 5 | import calendar |
| 6 | import datetime |
| 7 | import threading |
| 8 | |
| 9 | import cherrypy |
| 10 | from cherrypy import tools |
| 11 | |
| 12 | import wally |
| 13 | |
| 14 | logger = logging.getLogger("wally.webui") |
| 15 | |
| 16 | |
| 17 | def 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 | |
| 28 | def 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 | |
| 41 | class 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 | |
| 78 | def 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 | |
| 92 | def web_main_stop(): |
| 93 | cherrypy.engine.stop() |