ChartPlugin.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import time
  2. import itertools
  3. import gevent
  4. from Config import config
  5. from util import helper
  6. from util.Flag import flag
  7. from Plugin import PluginManager
  8. from .ChartDb import ChartDb
  9. from .ChartCollector import ChartCollector
  10. if "db" not in locals().keys(): # Share on reloads
  11. db = ChartDb()
  12. gevent.spawn_later(10 * 60, db.archive)
  13. helper.timer(60 * 60 * 6, db.archive)
  14. collector = ChartCollector(db)
  15. @PluginManager.registerTo("SiteManager")
  16. class SiteManagerPlugin(object):
  17. def load(self, *args, **kwargs):
  18. back = super(SiteManagerPlugin, self).load(*args, **kwargs)
  19. collector.setInitialLastValues(self.sites.values())
  20. return back
  21. def delete(self, address, *args, **kwargs):
  22. db.deleteSite(address)
  23. return super(SiteManagerPlugin, self).delete(address, *args, **kwargs)
  24. @PluginManager.registerTo("UiWebsocket")
  25. class UiWebsocketPlugin(object):
  26. @flag.admin
  27. def actionChartDbQuery(self, to, query, params=None):
  28. if config.debug or config.verbose:
  29. s = time.time()
  30. rows = []
  31. try:
  32. if not query.strip().upper().startswith("SELECT"):
  33. raise Exception("Only SELECT query supported")
  34. res = db.execute(query, params)
  35. except Exception as err: # Response the error to client
  36. self.log.error("ChartDbQuery error: %s" % err)
  37. return {"error": str(err)}
  38. # Convert result to dict
  39. for row in res:
  40. rows.append(dict(row))
  41. if config.verbose and time.time() - s > 0.1: # Log slow query
  42. self.log.debug("Slow query: %s (%.3fs)" % (query, time.time() - s))
  43. return rows
  44. @flag.admin
  45. def actionChartGetPeerLocations(self, to):
  46. peers = {}
  47. for site in self.server.sites.values():
  48. peers.update(site.peers)
  49. peer_locations = self.getPeerLocations(peers)
  50. return peer_locations