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.

system_app.py 8.2KB

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