Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

system_app.py 8.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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 json
  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. try:
  147. v = REDIS_CONN.get("TASKEXE")
  148. if not v:
  149. raise Exception("No task executor running!")
  150. obj = json.loads(v)
  151. color = "green"
  152. for id in obj.keys():
  153. arr = obj[id]
  154. if len(arr) == 1:
  155. obj[id] = [0]
  156. else:
  157. obj[id] = [arr[i + 1] - arr[i] for i in range(len(arr) - 1)]
  158. elapsed = max(obj[id])
  159. if elapsed > 50:
  160. color = "yellow"
  161. if elapsed > 120:
  162. color = "red"
  163. res["task_executor"] = {"status": color, "elapsed": obj}
  164. except Exception as e:
  165. res["task_executor"] = {"status": "red", "error": str(e)}
  166. return get_json_result(data=res)
  167. @manager.route("/new_token", methods=["POST"])
  168. @login_required
  169. def new_token():
  170. """
  171. Generate a new API token.
  172. ---
  173. tags:
  174. - API Tokens
  175. security:
  176. - ApiKeyAuth: []
  177. parameters:
  178. - in: query
  179. name: name
  180. type: string
  181. required: false
  182. description: Name of the token.
  183. responses:
  184. 200:
  185. description: Token generated successfully.
  186. schema:
  187. type: object
  188. properties:
  189. token:
  190. type: string
  191. description: The generated API token.
  192. """
  193. try:
  194. tenants = UserTenantService.query(user_id=current_user.id)
  195. if not tenants:
  196. return get_data_error_result(message="Tenant not found!")
  197. tenant_id = tenants[0].tenant_id
  198. obj = {
  199. "tenant_id": tenant_id,
  200. "token": generate_confirmation_token(tenant_id),
  201. "create_time": current_timestamp(),
  202. "create_date": datetime_format(datetime.now()),
  203. "update_time": None,
  204. "update_date": None,
  205. }
  206. if not APITokenService.save(**obj):
  207. return get_data_error_result(message="Fail to new a dialog!")
  208. return get_json_result(data=obj)
  209. except Exception as e:
  210. return server_error_response(e)
  211. @manager.route("/token_list", methods=["GET"])
  212. @login_required
  213. def token_list():
  214. """
  215. List all API tokens for the current user.
  216. ---
  217. tags:
  218. - API Tokens
  219. security:
  220. - ApiKeyAuth: []
  221. responses:
  222. 200:
  223. description: List of API tokens.
  224. schema:
  225. type: object
  226. properties:
  227. tokens:
  228. type: array
  229. items:
  230. type: object
  231. properties:
  232. token:
  233. type: string
  234. description: The API token.
  235. name:
  236. type: string
  237. description: Name of the token.
  238. create_time:
  239. type: string
  240. description: Token creation time.
  241. """
  242. try:
  243. tenants = UserTenantService.query(user_id=current_user.id)
  244. if not tenants:
  245. return get_data_error_result(message="Tenant not found!")
  246. objs = APITokenService.query(tenant_id=tenants[0].tenant_id)
  247. return get_json_result(data=[o.to_dict() for o in objs])
  248. except Exception as e:
  249. return server_error_response(e)
  250. @manager.route("/token/<token>", methods=["DELETE"])
  251. @login_required
  252. def rm(token):
  253. """
  254. Remove an API token.
  255. ---
  256. tags:
  257. - API Tokens
  258. security:
  259. - ApiKeyAuth: []
  260. parameters:
  261. - in: path
  262. name: token
  263. type: string
  264. required: true
  265. description: The API token to remove.
  266. responses:
  267. 200:
  268. description: Token removed successfully.
  269. schema:
  270. type: object
  271. properties:
  272. success:
  273. type: boolean
  274. description: Deletion status.
  275. """
  276. APITokenService.filter_delete(
  277. [APIToken.tenant_id == current_user.id, APIToken.token == token]
  278. )
  279. return get_json_result(data=True)