app.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. import os
  2. from configs import dify_config
  3. if not dify_config.DEBUG:
  4. from gevent import monkey
  5. monkey.patch_all()
  6. import grpc.experimental.gevent
  7. grpc.experimental.gevent.init_gevent()
  8. import json
  9. import threading
  10. import time
  11. import warnings
  12. from flask import Response
  13. from app_factory import create_app
  14. # DO NOT REMOVE BELOW
  15. from events import event_handlers # noqa: F401
  16. from extensions.ext_database import db
  17. # TODO: Find a way to avoid importing models here
  18. from models import account, dataset, model, source, task, tool, tools, web # noqa: F401
  19. # DO NOT REMOVE ABOVE
  20. warnings.simplefilter("ignore", ResourceWarning)
  21. os.environ["TZ"] = "UTC"
  22. # windows platform not support tzset
  23. if hasattr(time, "tzset"):
  24. time.tzset()
  25. # create app
  26. app = create_app()
  27. celery = app.extensions["celery"]
  28. if dify_config.TESTING:
  29. print("App is running in TESTING mode")
  30. @app.after_request
  31. def after_request(response):
  32. """Add Version headers to the response."""
  33. response.set_cookie("remember_token", "", expires=0)
  34. response.headers.add("X-Version", dify_config.CURRENT_VERSION)
  35. response.headers.add("X-Env", dify_config.DEPLOY_ENV)
  36. return response
  37. @app.route("/health")
  38. def health():
  39. return Response(
  40. json.dumps({"pid": os.getpid(), "status": "ok", "version": dify_config.CURRENT_VERSION}),
  41. status=200,
  42. content_type="application/json",
  43. )
  44. @app.route("/threads")
  45. def threads():
  46. num_threads = threading.active_count()
  47. threads = threading.enumerate()
  48. thread_list = []
  49. for thread in threads:
  50. thread_name = thread.name
  51. thread_id = thread.ident
  52. is_alive = thread.is_alive()
  53. thread_list.append(
  54. {
  55. "name": thread_name,
  56. "id": thread_id,
  57. "is_alive": is_alive,
  58. }
  59. )
  60. return {
  61. "pid": os.getpid(),
  62. "thread_num": num_threads,
  63. "threads": thread_list,
  64. }
  65. @app.route("/db-pool-stat")
  66. def pool_stat():
  67. engine = db.engine
  68. return {
  69. "pid": os.getpid(),
  70. "pool_size": engine.pool.size(),
  71. "checked_in_connections": engine.pool.checkedin(),
  72. "checked_out_connections": engine.pool.checkedout(),
  73. "overflow_connections": engine.pool.overflow(),
  74. "connection_timeout": engine.pool.timeout(),
  75. "recycle_time": db.engine.pool._recycle,
  76. }
  77. if __name__ == "__main__":
  78. app.run(host="0.0.0.0", port=5001)