main.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. from flask import Flask, request
  2. from prometheus_client import Counter, Gauge, Info, start_http_server
  3. import json
  4. app = Flask(__name__)
  5. class TelemetryInfo:
  6. def __init__(self, data):
  7. self.node_id = data['chain']['node_id']
  8. self.num_peers = data['chain']['num_peers']
  9. self.status = data['chain']['status']
  10. self.cpu_usage = data['system']['cpu_usage']
  11. self.memory_usage = data['system']['memory_usage']
  12. self.bandwidth_upload = data['system']['bandwidth_upload']
  13. self.bandwidth_download = data['system']['bandwidth_download']
  14. class Node:
  15. def __init__(self, node_id):
  16. def _(s): return f"{s}_{node_id}"
  17. self.updates = Counter(_('updates'), 'Total updates received')
  18. self.num_peers = Gauge(_('num_peers'), 'Number of active peers')
  19. self.cpu_usage = Gauge(_('cpu_usage'), "CPU usage")
  20. self.memory_usage = Gauge(_('memory_usage'), "Memory usage")
  21. self.bandwidth_upload = Gauge(
  22. _('bandwidth_upload'), "Bandwidth upload in bytes")
  23. self.bandwidth_download = Gauge(
  24. _('bandwidth_download'), "Bandwidth download in bytes"
  25. )
  26. self.status = Info(_('status'), "Node status")
  27. def submit(self, info: TelemetryInfo):
  28. self.updates.inc()
  29. self.num_peers.set(info.num_peers)
  30. self.cpu_usage.set(info.cpu_usage)
  31. self.memory_usage.set(info.memory_usage)
  32. self.bandwidth_upload.set(info.bandwidth_upload)
  33. self.bandwidth_download.set(info.bandwidth_download)
  34. self.status.info({'status': info.status})
  35. class Prometheus:
  36. def __init__(self):
  37. self.dic = {}
  38. def get(self, node_id):
  39. if not node_id in self.dic:
  40. self.dic[node_id] = Node(node_id)
  41. return self.dic[node_id]
  42. def submit(self, data):
  43. self.get(data.node_id).submit(data)
  44. prom = Prometheus()
  45. @app.route('/', methods=['POST'])
  46. def hello_world():
  47. data = json.loads(request.data.decode())
  48. info = TelemetryInfo(data)
  49. print("Received data from:", info.node_id)
  50. prom.submit(info)
  51. return ''
  52. if __name__ == 'main':
  53. print("Starting prometheus server")
  54. start_http_server(3389)