main.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import os
  2. import requests
  3. from flask import Flask
  4. from flask import jsonify
  5. from flask_cors import CORS, cross_origin
  6. def get_result():
  7. services_up = 0
  8. failure_list = []
  9. returnResponse = {"style": "", "title": "", "content": ""}
  10. statping_endpoint = os.getenv("STATPING_ENDPOINT")
  11. try:
  12. print("%sapi/services/" % statping_endpoint)
  13. response = requests.get("%sapi/services/" % statping_endpoint, verify=False)
  14. # If we get a response
  15. if response.status_code == 200:
  16. # Get the total number of services returned
  17. total_services = len(response.json())
  18. # Iterate through the response
  19. for key in response.json():
  20. # If the service is online, incrememnt the up count
  21. if key["online"] == True:
  22. services_up += 1
  23. # Otherwise append the name to the naughty list
  24. else:
  25. failure_list.append(key["name"])
  26. # Check the number of up services is equal to the total number of services
  27. if total_services == services_up:
  28. # if so, return a success object
  29. returnResponse["style"] = "is-success"
  30. returnResponse["title"] = "Everything is up and running"
  31. returnResponse["content"] = (
  32. "<b>Online %s / %s. Check <a href=%s target=_blank>here</a> for more info. </br> <p>"
  33. % (services_up, total_services, statping_endpoint)
  34. )
  35. return returnResponse
  36. else:
  37. # return a numpty message
  38. returnResponse["style"] = "is-danger"
  39. returnResponse["title"] = "Service disruption"
  40. # need to build the return message to include the failures as a formatted list
  41. numptyList = "<ul>"
  42. for i in failure_list:
  43. numptyList += "<li>" + i + "</li>"
  44. numptyList += "</ul>"
  45. returnResponse["content"] = (
  46. "<b>Online %s / %s. Check <a href=%s target=_blank>here</a> for more info. </br> <p> <br>These are reported down:</br> %s"
  47. % (services_up, total_services, statping_endpoint, numptyList)
  48. )
  49. return returnResponse
  50. except:
  51. returnResponse["style"] = "is-danger"
  52. returnResponse["title"] = "Issue with upstream"
  53. returnResponse["content"] = "Statping is unreachable, check your endpoint: %s" % statping_endpoint
  54. return returnResponse
  55. app = Flask(__name__)
  56. app.config["JSON_SORT_KEYS"] = False
  57. cors = CORS(app)
  58. app.config["CORS_HEADERS"] = "Content-Type"
  59. @app.route("/endpoint/", methods=["GET"])
  60. @cross_origin()
  61. def welcome():
  62. return jsonify(get_result())
  63. if __name__ == "__main__":
  64. app.run(host="0.0.0.0", port=8099)