ext_app_metrics.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import json
  2. import os
  3. import threading
  4. from flask import Response
  5. from configs import dify_config
  6. from dify_app import DifyApp
  7. def init_app(app: DifyApp):
  8. @app.after_request
  9. def after_request(response):
  10. """Add Version headers to the response."""
  11. response.headers.add("X-Version", dify_config.CURRENT_VERSION)
  12. response.headers.add("X-Env", dify_config.DEPLOY_ENV)
  13. return response
  14. @app.route("/health")
  15. def health():
  16. return Response(
  17. json.dumps({"pid": os.getpid(), "status": "ok", "version": dify_config.CURRENT_VERSION}),
  18. status=200,
  19. content_type="application/json",
  20. )
  21. @app.route("/threads")
  22. def threads():
  23. num_threads = threading.active_count()
  24. threads = threading.enumerate()
  25. thread_list = []
  26. for thread in threads:
  27. thread_name = thread.name
  28. thread_id = thread.ident
  29. is_alive = thread.is_alive()
  30. thread_list.append(
  31. {
  32. "name": thread_name,
  33. "id": thread_id,
  34. "is_alive": is_alive,
  35. }
  36. )
  37. return {
  38. "pid": os.getpid(),
  39. "thread_num": num_threads,
  40. "threads": thread_list,
  41. }
  42. @app.route("/db-pool-stat")
  43. def pool_stat():
  44. from extensions.ext_database import db
  45. engine = db.engine
  46. # TODO: Fix the type error
  47. # FIXME maybe its sqlalchemy issue
  48. return {
  49. "pid": os.getpid(),
  50. "pool_size": engine.pool.size(), # type: ignore
  51. "checked_in_connections": engine.pool.checkedin(), # type: ignore
  52. "checked_out_connections": engine.pool.checkedout(), # type: ignore
  53. "overflow_connections": engine.pool.overflow(), # type: ignore
  54. "connection_timeout": engine.pool.timeout(), # type: ignore
  55. "recycle_time": db.engine.pool._recycle, # type: ignore
  56. }