Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

system_app.py 8.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. import logging
  17. from datetime import datetime
  18. from flask_login import login_required, current_user
  19. from api.db.db_models import APIToken
  20. from api.db.services.api_service import APITokenService
  21. from api.db.services.knowledgebase_service import KnowledgebaseService
  22. from api.db.services.user_service import UserTenantService
  23. from api import settings
  24. from api.utils import current_timestamp, datetime_format
  25. from api.utils.api_utils import (
  26. get_json_result,
  27. get_data_error_result,
  28. server_error_response,
  29. generate_confirmation_token,
  30. )
  31. from api.versions import get_ragflow_version
  32. from rag.utils.storage_factory import STORAGE_IMPL, STORAGE_IMPL_TYPE
  33. from timeit import default_timer as timer
  34. from rag.utils.redis_conn import REDIS_CONN
  35. @manager.route("/version", methods=["GET"])
  36. @login_required
  37. def version():
  38. """
  39. Get the current version of the application.
  40. ---
  41. tags:
  42. - System
  43. security:
  44. - ApiKeyAuth: []
  45. responses:
  46. 200:
  47. description: Version retrieved successfully.
  48. schema:
  49. type: object
  50. properties:
  51. version:
  52. type: string
  53. description: Version number.
  54. """
  55. return get_json_result(data=get_ragflow_version())
  56. @manager.route("/status", methods=["GET"])
  57. @login_required
  58. def status():
  59. """
  60. Get the system status.
  61. ---
  62. tags:
  63. - System
  64. security:
  65. - ApiKeyAuth: []
  66. responses:
  67. 200:
  68. description: System is operational.
  69. schema:
  70. type: object
  71. properties:
  72. es:
  73. type: object
  74. description: Elasticsearch status.
  75. storage:
  76. type: object
  77. description: Storage status.
  78. database:
  79. type: object
  80. description: Database status.
  81. 503:
  82. description: Service unavailable.
  83. schema:
  84. type: object
  85. properties:
  86. error:
  87. type: string
  88. description: Error message.
  89. """
  90. res = {}
  91. st = timer()
  92. try:
  93. res["doc_store"] = settings.docStoreConn.health()
  94. res["doc_store"]["elapsed"] = "{:.1f}".format((timer() - st) * 1000.0)
  95. except Exception as e:
  96. res["doc_store"] = {
  97. "type": "unknown",
  98. "status": "red",
  99. "elapsed": "{:.1f}".format((timer() - st) * 1000.0),
  100. "error": str(e),
  101. }
  102. st = timer()
  103. try:
  104. STORAGE_IMPL.health()
  105. res["storage"] = {
  106. "storage": STORAGE_IMPL_TYPE.lower(),
  107. "status": "green",
  108. "elapsed": "{:.1f}".format((timer() - st) * 1000.0),
  109. }
  110. except Exception as e:
  111. res["storage"] = {
  112. "storage": STORAGE_IMPL_TYPE.lower(),
  113. "status": "red",
  114. "elapsed": "{:.1f}".format((timer() - st) * 1000.0),
  115. "error": str(e),
  116. }
  117. st = timer()
  118. try:
  119. KnowledgebaseService.get_by_id("x")
  120. res["database"] = {
  121. "database": settings.DATABASE_TYPE.lower(),
  122. "status": "green",
  123. "elapsed": "{:.1f}".format((timer() - st) * 1000.0),
  124. }
  125. except Exception as e:
  126. res["database"] = {
  127. "database": settings.DATABASE_TYPE.lower(),
  128. "status": "red",
  129. "elapsed": "{:.1f}".format((timer() - st) * 1000.0),
  130. "error": str(e),
  131. }
  132. st = timer()
  133. try:
  134. if not REDIS_CONN.health():
  135. raise Exception("Lost connection!")
  136. res["redis"] = {
  137. "status": "green",
  138. "elapsed": "{:.1f}".format((timer() - st) * 1000.0),
  139. }
  140. except Exception as e:
  141. res["redis"] = {
  142. "status": "red",
  143. "elapsed": "{:.1f}".format((timer() - st) * 1000.0),
  144. "error": str(e),
  145. }
  146. task_executor_heartbeats = {}
  147. try:
  148. task_executors = REDIS_CONN.smembers("TASKEXE")
  149. now = datetime.now().timestamp()
  150. for task_executor_id in task_executors:
  151. heartbeats = REDIS_CONN.zrangebyscore(task_executor_id, now - 60*30, now)
  152. task_executor_heartbeats[task_executor_id] = heartbeats
  153. except Exception:
  154. logging.exception("get task executor heartbeats failed!")
  155. res["task_executor_heartbeats"] = task_executor_heartbeats
  156. return get_json_result(data=res)
  157. @manager.route("/new_token", methods=["POST"])
  158. @login_required
  159. def new_token():
  160. """
  161. Generate a new API token.
  162. ---
  163. tags:
  164. - API Tokens
  165. security:
  166. - ApiKeyAuth: []
  167. parameters:
  168. - in: query
  169. name: name
  170. type: string
  171. required: false
  172. description: Name of the token.
  173. responses:
  174. 200:
  175. description: Token generated successfully.
  176. schema:
  177. type: object
  178. properties:
  179. token:
  180. type: string
  181. description: The generated API token.
  182. """
  183. try:
  184. tenants = UserTenantService.query(user_id=current_user.id)
  185. if not tenants:
  186. return get_data_error_result(message="Tenant not found!")
  187. tenant_id = tenants[0].tenant_id
  188. obj = {
  189. "tenant_id": tenant_id,
  190. "token": generate_confirmation_token(tenant_id),
  191. "create_time": current_timestamp(),
  192. "create_date": datetime_format(datetime.now()),
  193. "update_time": None,
  194. "update_date": None,
  195. }
  196. if not APITokenService.save(**obj):
  197. return get_data_error_result(message="Fail to new a dialog!")
  198. return get_json_result(data=obj)
  199. except Exception as e:
  200. return server_error_response(e)
  201. @manager.route("/token_list", methods=["GET"])
  202. @login_required
  203. def token_list():
  204. """
  205. List all API tokens for the current user.
  206. ---
  207. tags:
  208. - API Tokens
  209. security:
  210. - ApiKeyAuth: []
  211. responses:
  212. 200:
  213. description: List of API tokens.
  214. schema:
  215. type: object
  216. properties:
  217. tokens:
  218. type: array
  219. items:
  220. type: object
  221. properties:
  222. token:
  223. type: string
  224. description: The API token.
  225. name:
  226. type: string
  227. description: Name of the token.
  228. create_time:
  229. type: string
  230. description: Token creation time.
  231. """
  232. try:
  233. tenants = UserTenantService.query(user_id=current_user.id)
  234. if not tenants:
  235. return get_data_error_result(message="Tenant not found!")
  236. objs = APITokenService.query(tenant_id=tenants[0].tenant_id)
  237. return get_json_result(data=[o.to_dict() for o in objs])
  238. except Exception as e:
  239. return server_error_response(e)
  240. @manager.route("/token/<token>", methods=["DELETE"])
  241. @login_required
  242. def rm(token):
  243. """
  244. Remove an API token.
  245. ---
  246. tags:
  247. - API Tokens
  248. security:
  249. - ApiKeyAuth: []
  250. parameters:
  251. - in: path
  252. name: token
  253. type: string
  254. required: true
  255. description: The API token to remove.
  256. responses:
  257. 200:
  258. description: Token removed successfully.
  259. schema:
  260. type: object
  261. properties:
  262. success:
  263. type: boolean
  264. description: Deletion status.
  265. """
  266. APITokenService.filter_delete(
  267. [APIToken.tenant_id == current_user.id, APIToken.token == token]
  268. )
  269. return get_json_result(data=True)