Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

system_app.py 8.6KB

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