You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ragflow_server.py 5.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # from beartype import BeartypeConf
  17. # from beartype.claw import beartype_all # <-- you didn't sign up for this
  18. # beartype_all(conf=BeartypeConf(violation_type=UserWarning)) # <-- emit warnings from all code
  19. from api.utils.log_utils import init_root_logger
  20. from plugin import GlobalPluginManager
  21. init_root_logger("ragflow_server")
  22. import logging
  23. import os
  24. import signal
  25. import sys
  26. import time
  27. import traceback
  28. import threading
  29. import uuid
  30. from werkzeug.serving import run_simple
  31. from api import settings
  32. from api.apps import app, smtp_mail_server
  33. from api.db.runtime_config import RuntimeConfig
  34. from api.db.services.document_service import DocumentService
  35. from api import utils
  36. from api.db.db_models import init_database_tables as init_web_db
  37. from api.db.init_data import init_web_data
  38. from api.versions import get_ragflow_version
  39. from api.utils import show_configs
  40. from rag.settings import print_rag_settings
  41. from rag.utils.mcp_tool_call_conn import shutdown_all_mcp_sessions
  42. from rag.utils.redis_conn import RedisDistributedLock
  43. stop_event = threading.Event()
  44. RAGFLOW_DEBUGPY_LISTEN = int(os.environ.get('RAGFLOW_DEBUGPY_LISTEN', "0"))
  45. def update_progress():
  46. lock_value = str(uuid.uuid4())
  47. redis_lock = RedisDistributedLock("update_progress", lock_value=lock_value, timeout=60)
  48. logging.info(f"update_progress lock_value: {lock_value}")
  49. while not stop_event.is_set():
  50. try:
  51. if redis_lock.acquire():
  52. DocumentService.update_progress()
  53. redis_lock.release()
  54. except Exception:
  55. logging.exception("update_progress exception")
  56. finally:
  57. try:
  58. redis_lock.release()
  59. except Exception:
  60. logging.exception("update_progress exception")
  61. stop_event.wait(6)
  62. def signal_handler(sig, frame):
  63. logging.info("Received interrupt signal, shutting down...")
  64. shutdown_all_mcp_sessions()
  65. stop_event.set()
  66. time.sleep(1)
  67. sys.exit(0)
  68. if __name__ == '__main__':
  69. logging.info(r"""
  70. ____ ___ ______ ______ __
  71. / __ \ / | / ____// ____// /____ _ __
  72. / /_/ // /| | / / __ / /_ / // __ \| | /| / /
  73. / _, _// ___ |/ /_/ // __/ / // /_/ /| |/ |/ /
  74. /_/ |_|/_/ |_|\____//_/ /_/ \____/ |__/|__/
  75. """)
  76. logging.info(
  77. f'RAGFlow version: {get_ragflow_version()}'
  78. )
  79. logging.info(
  80. f'project base: {utils.file_utils.get_project_base_directory()}'
  81. )
  82. show_configs()
  83. settings.init_settings()
  84. print_rag_settings()
  85. if RAGFLOW_DEBUGPY_LISTEN > 0:
  86. logging.info(f"debugpy listen on {RAGFLOW_DEBUGPY_LISTEN}")
  87. import debugpy
  88. debugpy.listen(("0.0.0.0", RAGFLOW_DEBUGPY_LISTEN))
  89. # init db
  90. init_web_db()
  91. init_web_data()
  92. # init runtime config
  93. import argparse
  94. parser = argparse.ArgumentParser()
  95. parser.add_argument(
  96. "--version", default=False, help="RAGFlow version", action="store_true"
  97. )
  98. parser.add_argument(
  99. "--debug", default=False, help="debug mode", action="store_true"
  100. )
  101. args = parser.parse_args()
  102. if args.version:
  103. print(get_ragflow_version())
  104. sys.exit(0)
  105. RuntimeConfig.DEBUG = args.debug
  106. if RuntimeConfig.DEBUG:
  107. logging.info("run on debug mode")
  108. RuntimeConfig.init_env()
  109. RuntimeConfig.init_config(JOB_SERVER_HOST=settings.HOST_IP, HTTP_PORT=settings.HOST_PORT)
  110. GlobalPluginManager.load_plugins()
  111. signal.signal(signal.SIGINT, signal_handler)
  112. signal.signal(signal.SIGTERM, signal_handler)
  113. def delayed_start_update_progress():
  114. logging.info("Starting update_progress thread (delayed)")
  115. t = threading.Thread(target=update_progress, daemon=True)
  116. t.start()
  117. if RuntimeConfig.DEBUG:
  118. if os.environ.get("WERKZEUG_RUN_MAIN") == "true":
  119. threading.Timer(1.0, delayed_start_update_progress).start()
  120. else:
  121. threading.Timer(1.0, delayed_start_update_progress).start()
  122. # init smtp server
  123. if settings.SMTP_CONF:
  124. app.config["MAIL_SERVER"] = settings.MAIL_SERVER
  125. app.config["MAIL_PORT"] = settings.MAIL_PORT
  126. app.config["MAIL_USE_SSL"] = settings.MAIL_USE_SSL
  127. app.config["MAIL_USE_TLS"] = settings.MAIL_USE_TLS
  128. app.config["MAIL_USERNAME"] = settings.MAIL_USERNAME
  129. app.config["MAIL_PASSWORD"] = settings.MAIL_PASSWORD
  130. app.config["MAIL_DEFAULT_SENDER"] = settings.MAIL_DEFAULT_SENDER
  131. smtp_mail_server.init_app(app)
  132. # start http server
  133. try:
  134. logging.info("RAGFlow HTTP server start...")
  135. run_simple(
  136. hostname=settings.HOST_IP,
  137. port=settings.HOST_PORT,
  138. application=app,
  139. threaded=True,
  140. use_reloader=RuntimeConfig.DEBUG,
  141. use_debugger=RuntimeConfig.DEBUG,
  142. )
  143. except Exception:
  144. traceback.print_exc()
  145. stop_event.set()
  146. time.sleep(1)
  147. os.kill(os.getpid(), signal.SIGKILL)