main.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import os
  2. import sys
  3. import requests
  4. from flask import Flask, jsonify
  5. from flask_cors import CORS, cross_origin
  6. from prometheus_client.parser import text_string_to_metric_families
  7. app = Flask(__name__)
  8. app.config["JSON_SORT_KEYS"] = False
  9. cors = CORS(app)
  10. app.config["CORS_HEADERS"] = "Content-Type"
  11. def query_uptimekuma():
  12. # Prepare
  13. host = os.getenv("UKH_HOST", None)
  14. api_key = os.getenv("UKH_API_KEY", None)
  15. if host is None or api_key is None:
  16. raise Exception("Missing credentials")
  17. if not host.endswith("/"):
  18. host = f"{host}/"
  19. host_metrics = f"{host}metrics"
  20. # Query
  21. r = requests.get(host_metrics, auth=("", api_key))
  22. if r.status_code != 200:
  23. raise Exception("Failed to fetch")
  24. # Parse
  25. services = {
  26. "total": 0,
  27. "up": 0,
  28. "down": 0,
  29. "pending": 0,
  30. "maintenance": 0,
  31. }
  32. for family in text_string_to_metric_families(r.text):
  33. if family.name != "monitor_status":
  34. continue
  35. for sample in family.samples:
  36. value = int(sample.value)
  37. services["total"] += 1
  38. # (1 = UP, 0= DOWN, 2= PENDING, 3= MAINTENANCE)
  39. if value == 0:
  40. services["down"] += 1
  41. elif value == 1:
  42. services["up"] += 1
  43. elif value == 2:
  44. services["pending"] += 1
  45. elif value == 3:
  46. services["maintenance"] += 1
  47. assert services["total"] == (
  48. services["down"]
  49. + services["up"]
  50. + services["pending"]
  51. + services["maintenance"]
  52. )
  53. # Prepare output
  54. ret = {}
  55. if services["down"] > 0:
  56. ret["style"] = "is-danger"
  57. ret["title"] = "Service disruption"
  58. else:
  59. ret["style"] = "is-success"
  60. ret["title"] = "Everything is up and running"
  61. ret["content"] = (
  62. f"<b>Online {services['up']} / {services['total']}. Check <a href={host} target=_blank>here</a> for more info. </br> <p>"
  63. )
  64. return ret
  65. @app.route("/endpoint/", methods=["GET"])
  66. @cross_origin()
  67. def status():
  68. return jsonify(query_uptimekuma())
  69. if __name__ == "__main__":
  70. port = int(os.getenv("UKH_PORT", 8099))
  71. app.run(host="0.0.0.0", port=port)