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.

task_executor.py 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  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. # from beartype import BeartypeConf
  16. # from beartype.claw import beartype_all # <-- you didn't sign up for this
  17. # beartype_all(conf=BeartypeConf(violation_type=UserWarning)) # <-- emit warnings from all code
  18. import sys
  19. from api.utils.log_utils import initRootLogger
  20. from graphrag.utils import get_llm_cache, set_llm_cache
  21. CONSUMER_NO = "0" if len(sys.argv) < 2 else sys.argv[1]
  22. CONSUMER_NAME = "task_executor_" + CONSUMER_NO
  23. initRootLogger(CONSUMER_NAME)
  24. import logging
  25. import os
  26. from datetime import datetime
  27. import json
  28. import xxhash
  29. import copy
  30. import re
  31. import time
  32. import threading
  33. from functools import partial
  34. from io import BytesIO
  35. from multiprocessing.context import TimeoutError
  36. from timeit import default_timer as timer
  37. import tracemalloc
  38. import numpy as np
  39. from peewee import DoesNotExist
  40. from api.db import LLMType, ParserType, TaskStatus
  41. from api.db.services.dialog_service import keyword_extraction, question_proposal
  42. from api.db.services.document_service import DocumentService
  43. from api.db.services.llm_service import LLMBundle
  44. from api.db.services.task_service import TaskService
  45. from api.db.services.file2document_service import File2DocumentService
  46. from api import settings
  47. from api.versions import get_ragflow_version
  48. from api.db.db_models import close_connection
  49. from rag.app import laws, paper, presentation, manual, qa, table, book, resume, picture, naive, one, audio, \
  50. knowledge_graph, email
  51. from rag.nlp import search, rag_tokenizer
  52. from rag.raptor import RecursiveAbstractiveProcessing4TreeOrganizedRetrieval as Raptor
  53. from rag.settings import DOC_MAXIMUM_SIZE, SVR_QUEUE_NAME, print_rag_settings
  54. from rag.utils import num_tokens_from_string
  55. from rag.utils.redis_conn import REDIS_CONN, Payload
  56. from rag.utils.storage_factory import STORAGE_IMPL
  57. BATCH_SIZE = 64
  58. FACTORY = {
  59. "general": naive,
  60. ParserType.NAIVE.value: naive,
  61. ParserType.PAPER.value: paper,
  62. ParserType.BOOK.value: book,
  63. ParserType.PRESENTATION.value: presentation,
  64. ParserType.MANUAL.value: manual,
  65. ParserType.LAWS.value: laws,
  66. ParserType.QA.value: qa,
  67. ParserType.TABLE.value: table,
  68. ParserType.RESUME.value: resume,
  69. ParserType.PICTURE.value: picture,
  70. ParserType.ONE.value: one,
  71. ParserType.AUDIO.value: audio,
  72. ParserType.EMAIL.value: email,
  73. ParserType.KG.value: knowledge_graph
  74. }
  75. CONSUMER_NAME = "task_consumer_" + CONSUMER_NO
  76. PAYLOAD: Payload | None = None
  77. BOOT_AT = datetime.now().isoformat()
  78. PENDING_TASKS = 0
  79. LAG_TASKS = 0
  80. mt_lock = threading.Lock()
  81. DONE_TASKS = 0
  82. FAILED_TASKS = 0
  83. CURRENT_TASK = None
  84. class TaskCanceledException(Exception):
  85. def __init__(self, msg):
  86. self.msg = msg
  87. def set_progress(task_id, from_page=0, to_page=-1, prog=None, msg="Processing..."):
  88. global PAYLOAD
  89. if prog is not None and prog < 0:
  90. msg = "[ERROR]" + msg
  91. try:
  92. cancel = TaskService.do_cancel(task_id)
  93. except DoesNotExist:
  94. logging.warning(f"set_progress task {task_id} is unknown")
  95. if PAYLOAD:
  96. PAYLOAD.ack()
  97. PAYLOAD = None
  98. return
  99. if cancel:
  100. msg += " [Canceled]"
  101. prog = -1
  102. if to_page > 0:
  103. if msg:
  104. msg = f"Page({from_page + 1}~{to_page + 1}): " + msg
  105. d = {"progress_msg": msg}
  106. if prog is not None:
  107. d["progress"] = prog
  108. logging.info(f"set_progress({task_id}), progress: {prog}, progress_msg: {msg}")
  109. try:
  110. TaskService.update_progress(task_id, d)
  111. except DoesNotExist:
  112. logging.warning(f"set_progress task {task_id} is unknown")
  113. if PAYLOAD:
  114. PAYLOAD.ack()
  115. PAYLOAD = None
  116. return
  117. close_connection()
  118. if cancel and PAYLOAD:
  119. PAYLOAD.ack()
  120. PAYLOAD = None
  121. raise TaskCanceledException(msg)
  122. def collect():
  123. global CONSUMER_NAME, PAYLOAD, DONE_TASKS, FAILED_TASKS
  124. try:
  125. PAYLOAD = REDIS_CONN.get_unacked_for(CONSUMER_NAME, SVR_QUEUE_NAME, "rag_flow_svr_task_broker")
  126. if not PAYLOAD:
  127. PAYLOAD = REDIS_CONN.queue_consumer(SVR_QUEUE_NAME, "rag_flow_svr_task_broker", CONSUMER_NAME)
  128. if not PAYLOAD:
  129. time.sleep(1)
  130. return None
  131. except Exception:
  132. logging.exception("Get task event from queue exception")
  133. return None
  134. msg = PAYLOAD.get_message()
  135. if not msg:
  136. return None
  137. task = None
  138. canceled = False
  139. try:
  140. task = TaskService.get_task(msg["id"])
  141. if task:
  142. _, doc = DocumentService.get_by_id(task["doc_id"])
  143. canceled = doc.run == TaskStatus.CANCEL.value or doc.progress < 0
  144. except DoesNotExist:
  145. pass
  146. except Exception:
  147. logging.exception("collect get_task exception")
  148. if not task or canceled:
  149. state = "is unknown" if not task else "has been cancelled"
  150. with mt_lock:
  151. DONE_TASKS += 1
  152. logging.info(f"collect task {msg['id']} {state}")
  153. return None
  154. if msg.get("type", "") == "raptor":
  155. task["task_type"] = "raptor"
  156. return task
  157. def get_storage_binary(bucket, name):
  158. return STORAGE_IMPL.get(bucket, name)
  159. def build_chunks(task, progress_callback):
  160. if task["size"] > DOC_MAXIMUM_SIZE:
  161. set_progress(task["id"], prog=-1, msg="File size exceeds( <= %dMb )" %
  162. (int(DOC_MAXIMUM_SIZE / 1024 / 1024)))
  163. return []
  164. chunker = FACTORY[task["parser_id"].lower()]
  165. try:
  166. st = timer()
  167. bucket, name = File2DocumentService.get_storage_address(doc_id=task["doc_id"])
  168. binary = get_storage_binary(bucket, name)
  169. logging.info("From minio({}) {}/{}".format(timer() - st, task["location"], task["name"]))
  170. except TimeoutError:
  171. progress_callback(-1, "Internal server error: Fetch file from minio timeout. Could you try it again.")
  172. logging.exception("Minio {}/{} got timeout: Fetch file from minio timeout.".format(task["location"], task["name"]))
  173. raise
  174. except Exception as e:
  175. if re.search("(No such file|not found)", str(e)):
  176. progress_callback(-1, "Can not find file <%s> from minio. Could you try it again?" % task["name"])
  177. else:
  178. progress_callback(-1, "Get file from minio: %s" % str(e).replace("'", ""))
  179. logging.exception("Chunking {}/{} got exception".format(task["location"], task["name"]))
  180. raise
  181. try:
  182. cks = chunker.chunk(task["name"], binary=binary, from_page=task["from_page"],
  183. to_page=task["to_page"], lang=task["language"], callback=progress_callback,
  184. kb_id=task["kb_id"], parser_config=task["parser_config"], tenant_id=task["tenant_id"])
  185. logging.info("Chunking({}) {}/{} done".format(timer() - st, task["location"], task["name"]))
  186. except TaskCanceledException:
  187. raise
  188. except Exception as e:
  189. progress_callback(-1, "Internal server error while chunking: %s" % str(e).replace("'", ""))
  190. logging.exception("Chunking {}/{} got exception".format(task["location"], task["name"]))
  191. raise
  192. docs = []
  193. doc = {
  194. "doc_id": task["doc_id"],
  195. "kb_id": str(task["kb_id"])
  196. }
  197. if task["pagerank"]:
  198. doc["pagerank_fea"] = int(task["pagerank"])
  199. el = 0
  200. for ck in cks:
  201. d = copy.deepcopy(doc)
  202. d.update(ck)
  203. d["id"] = xxhash.xxh64((ck["content_with_weight"] + str(d["doc_id"])).encode("utf-8")).hexdigest()
  204. d["create_time"] = str(datetime.now()).replace("T", " ")[:19]
  205. d["create_timestamp_flt"] = datetime.now().timestamp()
  206. if not d.get("image"):
  207. _ = d.pop("image", None)
  208. d["img_id"] = ""
  209. docs.append(d)
  210. continue
  211. try:
  212. output_buffer = BytesIO()
  213. if isinstance(d["image"], bytes):
  214. output_buffer = BytesIO(d["image"])
  215. else:
  216. d["image"].save(output_buffer, format='JPEG')
  217. st = timer()
  218. STORAGE_IMPL.put(task["kb_id"], d["id"], output_buffer.getvalue())
  219. el += timer() - st
  220. except Exception:
  221. logging.exception("Saving image of chunk {}/{}/{} got exception".format(task["location"], task["name"], d["_id"]))
  222. raise
  223. d["img_id"] = "{}-{}".format(task["kb_id"], d["id"])
  224. del d["image"]
  225. docs.append(d)
  226. logging.info("MINIO PUT({}):{}".format(task["name"], el))
  227. if task["parser_config"].get("auto_keywords", 0):
  228. st = timer()
  229. progress_callback(msg="Start to generate keywords for every chunk ...")
  230. chat_mdl = LLMBundle(task["tenant_id"], LLMType.CHAT, llm_name=task["llm_id"], lang=task["language"])
  231. for d in docs:
  232. cached = get_llm_cache(chat_mdl.llm_name, d["content_with_weight"], "keywords",
  233. {"topn": task["parser_config"]["auto_keywords"]})
  234. if not cached:
  235. cached = keyword_extraction(chat_mdl, d["content_with_weight"],
  236. task["parser_config"]["auto_keywords"])
  237. if cached:
  238. set_llm_cache(chat_mdl.llm_name, d["content_with_weight"], cached, "keywords",
  239. {"topn": task["parser_config"]["auto_keywords"]})
  240. d["important_kwd"] = cached.split(",")
  241. d["important_tks"] = rag_tokenizer.tokenize(" ".join(d["important_kwd"]))
  242. progress_callback(msg="Keywords generation completed in {:.2f}s".format(timer() - st))
  243. if task["parser_config"].get("auto_questions", 0):
  244. st = timer()
  245. progress_callback(msg="Start to generate questions for every chunk ...")
  246. chat_mdl = LLMBundle(task["tenant_id"], LLMType.CHAT, llm_name=task["llm_id"], lang=task["language"])
  247. for d in docs:
  248. cached = get_llm_cache(chat_mdl.llm_name, d["content_with_weight"], "question",
  249. {"topn": task["parser_config"]["auto_questions"]})
  250. if not cached:
  251. cached = question_proposal(chat_mdl, d["content_with_weight"], task["parser_config"]["auto_questions"])
  252. if cached:
  253. set_llm_cache(chat_mdl.llm_name, d["content_with_weight"], cached, "question",
  254. {"topn": task["parser_config"]["auto_questions"]})
  255. d["question_kwd"] = cached.split("\n")
  256. d["question_tks"] = rag_tokenizer.tokenize("\n".join(d["question_kwd"]))
  257. progress_callback(msg="Question generation completed in {:.2f}s".format(timer() - st))
  258. return docs
  259. def init_kb(row, vector_size: int):
  260. idxnm = search.index_name(row["tenant_id"])
  261. return settings.docStoreConn.createIdx(idxnm, row.get("kb_id",""), vector_size)
  262. def embedding(docs, mdl, parser_config=None, callback=None):
  263. if parser_config is None:
  264. parser_config = {}
  265. batch_size = 16
  266. tts, cnts = [], []
  267. for d in docs:
  268. tts.append(d.get("docnm_kwd", "Title"))
  269. c = "\n".join(d.get("question_kwd", []))
  270. if not c:
  271. c = d["content_with_weight"]
  272. c = re.sub(r"</?(table|td|caption|tr|th)( [^<>]{0,12})?>", " ", c)
  273. cnts.append(c)
  274. tk_count = 0
  275. if len(tts) == len(cnts):
  276. tts_ = np.array([])
  277. for i in range(0, len(tts), batch_size):
  278. vts, c = mdl.encode(tts[i: i + batch_size])
  279. if len(tts_) == 0:
  280. tts_ = vts
  281. else:
  282. tts_ = np.concatenate((tts_, vts), axis=0)
  283. tk_count += c
  284. callback(prog=0.6 + 0.1 * (i + 1) / len(tts), msg="")
  285. tts = tts_
  286. cnts_ = np.array([])
  287. for i in range(0, len(cnts), batch_size):
  288. vts, c = mdl.encode(cnts[i: i + batch_size])
  289. if len(cnts_) == 0:
  290. cnts_ = vts
  291. else:
  292. cnts_ = np.concatenate((cnts_, vts), axis=0)
  293. tk_count += c
  294. callback(prog=0.7 + 0.2 * (i + 1) / len(cnts), msg="")
  295. cnts = cnts_
  296. title_w = float(parser_config.get("filename_embd_weight", 0.1))
  297. vects = (title_w * tts + (1 - title_w) *
  298. cnts) if len(tts) == len(cnts) else cnts
  299. assert len(vects) == len(docs)
  300. vector_size = 0
  301. for i, d in enumerate(docs):
  302. v = vects[i].tolist()
  303. vector_size = len(v)
  304. d["q_%d_vec" % len(v)] = v
  305. return tk_count, vector_size
  306. def run_raptor(row, chat_mdl, embd_mdl, callback=None):
  307. vts, _ = embd_mdl.encode(["ok"])
  308. vector_size = len(vts[0])
  309. vctr_nm = "q_%d_vec" % vector_size
  310. chunks = []
  311. for d in settings.retrievaler.chunk_list(row["doc_id"], row["tenant_id"], [str(row["kb_id"])],
  312. fields=["content_with_weight", vctr_nm]):
  313. chunks.append((d["content_with_weight"], np.array(d[vctr_nm])))
  314. raptor = Raptor(
  315. row["parser_config"]["raptor"].get("max_cluster", 64),
  316. chat_mdl,
  317. embd_mdl,
  318. row["parser_config"]["raptor"]["prompt"],
  319. row["parser_config"]["raptor"]["max_token"],
  320. row["parser_config"]["raptor"]["threshold"]
  321. )
  322. original_length = len(chunks)
  323. chunks = raptor(chunks, row["parser_config"]["raptor"]["random_seed"], callback)
  324. doc = {
  325. "doc_id": row["doc_id"],
  326. "kb_id": [str(row["kb_id"])],
  327. "docnm_kwd": row["name"],
  328. "title_tks": rag_tokenizer.tokenize(row["name"])
  329. }
  330. if row["pagerank"]:
  331. doc["pagerank_fea"] = int(row["pagerank"])
  332. res = []
  333. tk_count = 0
  334. for content, vctr in chunks[original_length:]:
  335. d = copy.deepcopy(doc)
  336. d["id"] = xxhash.xxh64((content + str(d["doc_id"])).encode("utf-8")).hexdigest()
  337. d["create_time"] = str(datetime.now()).replace("T", " ")[:19]
  338. d["create_timestamp_flt"] = datetime.now().timestamp()
  339. d[vctr_nm] = vctr.tolist()
  340. d["content_with_weight"] = content
  341. d["content_ltks"] = rag_tokenizer.tokenize(content)
  342. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  343. res.append(d)
  344. tk_count += num_tokens_from_string(content)
  345. return res, tk_count, vector_size
  346. def do_handle_task(task):
  347. task_id = task["id"]
  348. task_from_page = task["from_page"]
  349. task_to_page = task["to_page"]
  350. task_tenant_id = task["tenant_id"]
  351. task_embedding_id = task["embd_id"]
  352. task_language = task["language"]
  353. task_llm_id = task["llm_id"]
  354. task_dataset_id = task["kb_id"]
  355. task_doc_id = task["doc_id"]
  356. task_document_name = task["name"]
  357. task_parser_config = task["parser_config"]
  358. # prepare the progress callback function
  359. progress_callback = partial(set_progress, task_id, task_from_page, task_to_page)
  360. try:
  361. task_canceled = TaskService.do_cancel(task_id)
  362. except DoesNotExist:
  363. logging.warning(f"task {task_id} is unknown")
  364. return
  365. if task_canceled:
  366. progress_callback(-1, msg="Task has been canceled.")
  367. return
  368. try:
  369. # bind embedding model
  370. embedding_model = LLMBundle(task_tenant_id, LLMType.EMBEDDING, llm_name=task_embedding_id, lang=task_language)
  371. except Exception as e:
  372. error_message = f'Fail to bind embedding model: {str(e)}'
  373. progress_callback(-1, msg=error_message)
  374. logging.exception(error_message)
  375. raise
  376. # Either using RAPTOR or Standard chunking methods
  377. if task.get("task_type", "") == "raptor":
  378. try:
  379. # bind LLM for raptor
  380. chat_model = LLMBundle(task_tenant_id, LLMType.CHAT, llm_name=task_llm_id, lang=task_language)
  381. # run RAPTOR
  382. chunks, token_count, vector_size = run_raptor(task, chat_model, embedding_model, progress_callback)
  383. except TaskCanceledException:
  384. raise
  385. except Exception as e:
  386. error_message = f'Fail to bind LLM used by RAPTOR: {str(e)}'
  387. progress_callback(-1, msg=error_message)
  388. logging.exception(error_message)
  389. raise
  390. else:
  391. # Standard chunking methods
  392. start_ts = timer()
  393. chunks = build_chunks(task, progress_callback)
  394. logging.info("Build document {}: {:.2f}s".format(task_document_name, timer() - start_ts))
  395. if chunks is None:
  396. return
  397. if not chunks:
  398. progress_callback(1., msg=f"No chunk built from {task_document_name}")
  399. return
  400. # TODO: exception handler
  401. ## set_progress(task["did"], -1, "ERROR: ")
  402. progress_callback(msg="Generate {} chunks".format(len(chunks)))
  403. start_ts = timer()
  404. try:
  405. token_count, vector_size = embedding(chunks, embedding_model, task_parser_config, progress_callback)
  406. except Exception as e:
  407. error_message = "Generate embedding error:{}".format(str(e))
  408. progress_callback(-1, error_message)
  409. logging.exception(error_message)
  410. token_count = 0
  411. raise
  412. progress_message = "Embedding chunks ({:.2f}s)".format(timer() - start_ts)
  413. logging.info(progress_message)
  414. progress_callback(msg=progress_message)
  415. # logging.info(f"task_executor init_kb index {search.index_name(task_tenant_id)} embedding_model {embedding_model.llm_name} vector length {vector_size}")
  416. init_kb(task, vector_size)
  417. chunk_count = len(set([chunk["id"] for chunk in chunks]))
  418. start_ts = timer()
  419. doc_store_result = ""
  420. es_bulk_size = 4
  421. for b in range(0, len(chunks), es_bulk_size):
  422. doc_store_result = settings.docStoreConn.insert(chunks[b:b + es_bulk_size], search.index_name(task_tenant_id), task_dataset_id)
  423. if b % 128 == 0:
  424. progress_callback(prog=0.8 + 0.1 * (b + 1) / len(chunks), msg="")
  425. if doc_store_result:
  426. error_message = f"Insert chunk error: {doc_store_result}, please check log file and Elasticsearch/Infinity status!"
  427. progress_callback(-1, msg=error_message)
  428. raise Exception(error_message)
  429. chunk_ids = [chunk["id"] for chunk in chunks[:b + es_bulk_size]]
  430. chunk_ids_str = " ".join(chunk_ids)
  431. try:
  432. TaskService.update_chunk_ids(task["id"], chunk_ids_str)
  433. except DoesNotExist:
  434. logging.warning(f"do_handle_task update_chunk_ids failed since task {task['id']} is unknown.")
  435. doc_store_result = settings.docStoreConn.delete({"id": chunk_ids}, search.index_name(task_tenant_id), task_dataset_id)
  436. return
  437. logging.info("Indexing doc({}), page({}-{}), chunks({}), elapsed: {:.2f}".format(task_document_name, task_from_page, task_to_page, len(chunks), timer() - start_ts))
  438. DocumentService.increment_chunk_num(task_doc_id, task_dataset_id, token_count, chunk_count, 0)
  439. time_cost = timer() - start_ts
  440. progress_callback(prog=1.0, msg="Done ({:.2f}s)".format(time_cost))
  441. logging.info("Chunk doc({}), page({}-{}), chunks({}), token({}), elapsed:{:.2f}".format(task_document_name, task_from_page, task_to_page, len(chunks), token_count, time_cost))
  442. def handle_task():
  443. global PAYLOAD, mt_lock, DONE_TASKS, FAILED_TASKS, CURRENT_TASK
  444. task = collect()
  445. if task:
  446. try:
  447. logging.info(f"handle_task begin for task {json.dumps(task)}")
  448. with mt_lock:
  449. CURRENT_TASK = copy.deepcopy(task)
  450. do_handle_task(task)
  451. with mt_lock:
  452. DONE_TASKS += 1
  453. CURRENT_TASK = None
  454. logging.info(f"handle_task done for task {json.dumps(task)}")
  455. except TaskCanceledException:
  456. with mt_lock:
  457. DONE_TASKS += 1
  458. CURRENT_TASK = None
  459. try:
  460. set_progress(task["id"], prog=-1, msg="handle_task got TaskCanceledException")
  461. except Exception:
  462. pass
  463. logging.debug("handle_task got TaskCanceledException", exc_info=True)
  464. except Exception:
  465. with mt_lock:
  466. FAILED_TASKS += 1
  467. CURRENT_TASK = None
  468. try:
  469. set_progress(task["id"], prog=-1, msg="handle_task got exception, please check log")
  470. except Exception:
  471. pass
  472. logging.exception(f"handle_task got exception for task {json.dumps(task)}")
  473. if PAYLOAD:
  474. PAYLOAD.ack()
  475. PAYLOAD = None
  476. def report_status():
  477. global CONSUMER_NAME, BOOT_AT, PENDING_TASKS, LAG_TASKS, mt_lock, DONE_TASKS, FAILED_TASKS, CURRENT_TASK
  478. REDIS_CONN.sadd("TASKEXE", CONSUMER_NAME)
  479. while True:
  480. try:
  481. now = datetime.now()
  482. group_info = REDIS_CONN.queue_info(SVR_QUEUE_NAME, "rag_flow_svr_task_broker")
  483. if group_info is not None:
  484. PENDING_TASKS = int(group_info.get("pending", 0))
  485. LAG_TASKS = int(group_info.get("lag", 0))
  486. with mt_lock:
  487. heartbeat = json.dumps({
  488. "name": CONSUMER_NAME,
  489. "now": now.isoformat(),
  490. "boot_at": BOOT_AT,
  491. "pending": PENDING_TASKS,
  492. "lag": LAG_TASKS,
  493. "done": DONE_TASKS,
  494. "failed": FAILED_TASKS,
  495. "current": CURRENT_TASK,
  496. })
  497. REDIS_CONN.zadd(CONSUMER_NAME, heartbeat, now.timestamp())
  498. logging.info(f"{CONSUMER_NAME} reported heartbeat: {heartbeat}")
  499. expired = REDIS_CONN.zcount(CONSUMER_NAME, 0, now.timestamp() - 60 * 30)
  500. if expired > 0:
  501. REDIS_CONN.zpopmin(CONSUMER_NAME, expired)
  502. except Exception:
  503. logging.exception("report_status got exception")
  504. time.sleep(30)
  505. def analyze_heap(snapshot1: tracemalloc.Snapshot, snapshot2: tracemalloc.Snapshot, snapshot_id: int, dump_full: bool):
  506. msg = ""
  507. if dump_full:
  508. stats2 = snapshot2.statistics('lineno')
  509. msg += f"{CONSUMER_NAME} memory usage of snapshot {snapshot_id}:\n"
  510. for stat in stats2[:10]:
  511. msg += f"{stat}\n"
  512. stats1_vs_2 = snapshot2.compare_to(snapshot1, 'lineno')
  513. msg += f"{CONSUMER_NAME} memory usage increase from snapshot {snapshot_id - 1} to snapshot {snapshot_id}:\n"
  514. for stat in stats1_vs_2[:10]:
  515. msg += f"{stat}\n"
  516. msg += f"{CONSUMER_NAME} detailed traceback for the top memory consumers:\n"
  517. for stat in stats1_vs_2[:3]:
  518. msg += '\n'.join(stat.traceback.format())
  519. logging.info(msg)
  520. def main():
  521. logging.info(r"""
  522. ______ __ ______ __
  523. /_ __/___ ______/ /__ / ____/ _____ _______ __/ /_____ _____
  524. / / / __ `/ ___/ //_/ / __/ | |/_/ _ \/ ___/ / / / __/ __ \/ ___/
  525. / / / /_/ (__ ) ,< / /____> </ __/ /__/ /_/ / /_/ /_/ / /
  526. /_/ \__,_/____/_/|_| /_____/_/|_|\___/\___/\__,_/\__/\____/_/
  527. """)
  528. logging.info(f'TaskExecutor: RAGFlow version: {get_ragflow_version()}')
  529. settings.init_settings()
  530. print_rag_settings()
  531. background_thread = threading.Thread(target=report_status)
  532. background_thread.daemon = True
  533. background_thread.start()
  534. TRACE_MALLOC_DELTA = int(os.environ.get('TRACE_MALLOC_DELTA', "0"))
  535. TRACE_MALLOC_FULL = int(os.environ.get('TRACE_MALLOC_FULL', "0"))
  536. if TRACE_MALLOC_DELTA > 0:
  537. if TRACE_MALLOC_FULL < TRACE_MALLOC_DELTA:
  538. TRACE_MALLOC_FULL = TRACE_MALLOC_DELTA
  539. tracemalloc.start()
  540. snapshot1 = tracemalloc.take_snapshot()
  541. while True:
  542. handle_task()
  543. num_tasks = DONE_TASKS + FAILED_TASKS
  544. if TRACE_MALLOC_DELTA > 0 and num_tasks > 0 and num_tasks % TRACE_MALLOC_DELTA == 0:
  545. snapshot2 = tracemalloc.take_snapshot()
  546. analyze_heap(snapshot1, snapshot2, int(num_tasks / TRACE_MALLOC_DELTA), num_tasks % TRACE_MALLOC_FULL == 0)
  547. snapshot1 = snapshot2
  548. snapshot2 = None
  549. if __name__ == "__main__":
  550. main()