task_server.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. import random
  2. import threading
  3. import time
  4. from concurrent.futures import ThreadPoolExecutor
  5. from queue import Queue
  6. from typing import List, Dict, Optional
  7. import pymysql
  8. from pymysql import Connection
  9. from pymysql.cursors import DictCursor
  10. from sqlalchemy import func
  11. from pqai_agent import logging_service
  12. from pqai_agent.data_models.agent_configuration import AgentConfiguration
  13. from pqai_agent.data_models.agent_test_task import AgentTestTask
  14. from pqai_agent_server.const.status_enum import TestTaskConversationsStatus, TestTaskStatus, get_test_task_status_desc, \
  15. get_test_task_conversations_status_desc
  16. logger = logging_service.logger
  17. class Database:
  18. """数据库操作类"""
  19. def __init__(self, db_config):
  20. self.db_config = db_config
  21. self.connection_pool = Queue(maxsize=10)
  22. self._initialize_pool()
  23. def _initialize_pool(self):
  24. """初始化数据库连接池"""
  25. for _ in range(5):
  26. conn = pymysql.connect(**self.db_config)
  27. self.connection_pool.put(conn)
  28. logger.info("Database connection pool initialized with 5 connections")
  29. def get_connection(self) -> Connection:
  30. """从连接池获取数据库连接"""
  31. return self.connection_pool.get()
  32. def release_connection(self, conn: Connection):
  33. """释放数据库连接回连接池"""
  34. self.connection_pool.put(conn)
  35. def execute(self, query: str, args: tuple = (), many: bool = False) -> int:
  36. """执行SQL语句并返回影响的行数"""
  37. conn = self.get_connection()
  38. try:
  39. with conn.cursor() as cursor:
  40. if many:
  41. cursor.executemany(query, args)
  42. else:
  43. cursor.execute(query, args)
  44. conn.commit()
  45. return cursor.rowcount
  46. except Exception as e:
  47. logger.error(f"Database error: {str(e)}")
  48. conn.rollback()
  49. raise
  50. finally:
  51. self.release_connection(conn)
  52. def insert(self, insert: str, args: tuple = (), many: bool = False) -> int:
  53. """执行插入SQL语句并主键"""
  54. conn = self.get_connection()
  55. try:
  56. with conn.cursor() as cursor:
  57. if many:
  58. cursor.executemany(insert, args)
  59. else:
  60. cursor.execute(insert, args)
  61. conn.commit()
  62. return cursor.lastrowid
  63. except Exception as e:
  64. logger.error(f"Database error: {str(e)}")
  65. conn.rollback()
  66. raise
  67. finally:
  68. self.release_connection(conn)
  69. def fetch(self, query: str, args: tuple = ()) -> List[Dict]:
  70. """执行SQL查询并返回结果列表"""
  71. conn = self.get_connection()
  72. try:
  73. with conn.cursor(DictCursor) as cursor:
  74. cursor.execute(query, args)
  75. return cursor.fetchall()
  76. except Exception as e:
  77. logger.error(f"Database error: {str(e)}")
  78. raise
  79. finally:
  80. self.release_connection(conn)
  81. def fetch_one(self, query: str, args: tuple = ()) -> Optional[Dict]:
  82. """执行SQL查询并返回单行结果"""
  83. conn = self.get_connection()
  84. try:
  85. with conn.cursor(DictCursor) as cursor:
  86. cursor.execute(query, args)
  87. return cursor.fetchone()
  88. except Exception as e:
  89. logger.error(f"Database error: {str(e)}")
  90. raise
  91. finally:
  92. self.release_connection(conn)
  93. def close_all(self):
  94. """关闭所有数据库连接"""
  95. while not self.connection_pool.empty():
  96. conn = self.connection_pool.get()
  97. conn.close()
  98. logger.info("All database connections closed")
  99. class TaskManager:
  100. """任务管理器"""
  101. def __init__(self, session_maker, db_config, agent_configuration_table, test_task_table,
  102. test_task_conversations_table,
  103. max_workers: int = 10):
  104. self.session_maker = session_maker
  105. self.db = Database(db_config)
  106. self.agent_configuration_table = agent_configuration_table
  107. self.test_task_table = test_task_table
  108. self.test_task_conversations_table = test_task_conversations_table
  109. self.task_events = {} # 任务ID -> Event (用于取消任务)
  110. self.task_locks = {} # 任务ID -> Lock (用于任务状态同步)
  111. self.running_tasks = set()
  112. self.executor = ThreadPoolExecutor(max_workers=max_workers, thread_name_prefix='TaskWorker')
  113. self.task_futures = {} # 任务ID -> Future
  114. # def get_test_task_list(self, page_num: int, page_size: int) -> Dict:
  115. # fetch_query = f"""
  116. # select t1.id, t2.name, t1.create_user, t1.update_user, t1.status, t1.create_time, t1.update_time
  117. # from {self.test_task_table} t1
  118. # left join {self.agent_configuration_table} t2 on t1.agent_id = t2.id
  119. # order by create_time desc
  120. # limit %s, %s;
  121. # """
  122. # messages = self.db.fetch(fetch_query, ((page_num - 1) * page_size, page_size))
  123. # total_size = self.db.fetch_one(f"""select count(*) as `count` from {self.test_task_table}""")
  124. #
  125. # total = total_size["count"]
  126. # total_page = total // page_size + 1 if total % page_size > 0 else total // page_size
  127. # total_page = 1 if total_page <= 0 else total_page
  128. # response_data = [
  129. # {
  130. # "id": message["id"],
  131. # "agentName": message["name"],
  132. # "createUser": message["create_user"],
  133. # "updateUser": message["update_user"],
  134. # "statusName": get_test_task_status_desc(message["status"]),
  135. # "createTime": message["create_time"].strftime("%Y-%m-%d %H:%M:%S"),
  136. # "updateTime": message["update_time"].strftime("%Y-%m-%d %H:%M:%S")
  137. # }
  138. # for message in messages
  139. # ]
  140. # return {
  141. # "currentPage": page_num,
  142. # "pageSize": page_size,
  143. # "totalSize": total_page,
  144. # "total": total,
  145. # "list": response_data,
  146. # }
  147. def get_test_task_list(self, page_num: int, page_size: int) -> Dict:
  148. with self.session_maker() as session:
  149. # 计算偏移量
  150. offset = (page_num - 1) * page_size
  151. # 查询分页数据
  152. result = (session.query(AgentTestTask, AgentConfiguration)
  153. .outerjoin(AgentConfiguration, AgentTestTask.agent_id == AgentConfiguration.id)
  154. .limit(page_size).offset(offset).all())
  155. # 查询总记录数
  156. total = session.query(func.count(AgentTestTask.id)).scalar()
  157. total_page = total // page_size + 1 if total % page_size > 0 else total // page_size
  158. total_page = 1 if total_page <= 0 else total_page
  159. response_data = [
  160. {
  161. "id": agent_test_task.id,
  162. "agentName": agent_configuration.name,
  163. "createUser": agent_test_task.create_user,
  164. "updateUser": agent_test_task.update_user,
  165. "statusName": get_test_task_status_desc(agent_test_task.status),
  166. "createTime": agent_test_task.create_time.strftime("%Y-%m-%d %H:%M:%S"),
  167. "updateTime": agent_test_task.update_time.strftime("%Y-%m-%d %H:%M:%S")
  168. }
  169. for agent_test_task, agent_configuration in result
  170. ]
  171. return {
  172. "currentPage": page_num,
  173. "pageSize": page_size,
  174. "totalSize": total_page,
  175. "total": total,
  176. "list": response_data,
  177. }
  178. def get_test_task_conversations(self, task_id: int, page_num: int, page_size: int) -> Dict:
  179. fetch_query = f"""
  180. select t1.id, t2.name, t3.create_user, t1.input, t1.output, t1.score, t1.status, t1.create_time, t1.update_time
  181. from {self.test_task_conversations_table} t1
  182. left join {self.agent_configuration_table} t2 on t1.agent_id = t2.id
  183. left join {self.test_task_table} t3 on t1.task_id = t3.id
  184. where t1.task_id = %s
  185. order by create_time desc
  186. limit %s, %s;
  187. """
  188. messages = self.db.fetch(fetch_query, (task_id, (page_num - 1) * page_size, page_size))
  189. total_size = self.db.fetch_one(
  190. f"""select count(*) as `count` from {self.test_task_conversations_table} where task_id = %s""",
  191. (task_id,))
  192. total = total_size["count"]
  193. total_page = total // page_size + 1 if total % page_size > 0 else total // page_size
  194. total_page = 1 if total_page <= 0 else total_page
  195. response_data = [
  196. {
  197. "id": message["id"],
  198. "agentName": message["name"],
  199. "createUser": message["create_user"],
  200. "input": message["input"],
  201. "output": message["output"],
  202. "score": message["score"],
  203. "statusName": get_test_task_conversations_status_desc(message["status"]),
  204. "createTime": message["create_time"].strftime("%Y-%m-%d %H:%M:%S"),
  205. "updateTime": message["update_time"].strftime("%Y-%m-%d %H:%M:%S")
  206. }
  207. for message in messages
  208. ]
  209. return {
  210. "currentPage": page_num,
  211. "pageSize": page_size,
  212. "totalSize": total_page,
  213. "total": total,
  214. "list": response_data,
  215. }
  216. def create_task(self, agent_id: int, model_id: int) -> Dict:
  217. """创建新任务"""
  218. conn = self.db.get_connection()
  219. try:
  220. conn.begin()
  221. # TODO 插入任务 当前测试模拟
  222. with conn.cursor() as cursor:
  223. cursor.execute(
  224. f"""INSERT INTO {self.test_task_table} (agent_id, status, create_user, update_user) VALUES (%s, %s, %s, %s)""",
  225. (agent_id, 0, 'xueyiming', 'xueyiming')
  226. )
  227. task_id = cursor.lastrowid
  228. task_conversations = []
  229. # TODO 查询具体的数据集信息后插入
  230. i = 0
  231. for _ in range(30):
  232. i = i + 1
  233. task_conversations.append((
  234. task_id, agent_id, i, i, "输入", "输出", 0
  235. ))
  236. with conn.cursor() as cursor:
  237. cursor.executemany(
  238. f"""INSERT INTO {self.test_task_conversations_table} (task_id, agent_id, dataset_id, conversation_id, input, output, status)
  239. VALUES (%s, %s, %s, %s, %s, %s, %s)""",
  240. task_conversations
  241. )
  242. conn.commit()
  243. except Exception as e:
  244. conn.rollback()
  245. logger.error(f"Failed to create task agent_id {agent_id}: {str(e)}")
  246. raise
  247. finally:
  248. self.db.release_connection(conn)
  249. logger.info(f"Created task {task_id} with 100 task_conversations")
  250. # 异步执行任务
  251. self._execute_task(task_id)
  252. return self.get_task(task_id)
  253. def get_task(self, task_id: int) -> Optional[Dict]:
  254. """获取任务信息"""
  255. return self.db.fetch_one(f"""SELECT * FROM {self.test_task_table} WHERE id = %s""", (task_id,))
  256. def get_task_conversations(self, task_id: int) -> List[Dict]:
  257. """获取任务的所有子任务"""
  258. return self.db.fetch(f"""SELECT * FROM {self.test_task_conversations_table} WHERE task_id = %s""", (task_id,))
  259. def get_pending_task_conversations(self, task_id: int) -> List[Dict]:
  260. """获取待处理的子任务"""
  261. return self.db.fetch(
  262. f"""SELECT * FROM {self.test_task_conversations_table} WHERE task_id = %s AND status = %s""",
  263. (task_id, TestTaskConversationsStatus.PENDING.value)
  264. )
  265. def update_task_status(self, task_id: int, status: int):
  266. """更新任务状态"""
  267. self.db.execute(
  268. f"""UPDATE {self.test_task_table} SET status = %s WHERE id = %s""",
  269. (status, task_id)
  270. )
  271. def update_task_conversations_status(self, task_conversations_id: int, status: int):
  272. """更新子任务状态"""
  273. self.db.execute(
  274. f"""UPDATE {self.test_task_conversations_table} SET status = %s WHERE id = %s""",
  275. (status, task_conversations_id)
  276. )
  277. def update_task_conversations_res(self, task_conversations_id: int, status: int, score: str):
  278. """更新子任务状态"""
  279. self.db.execute(
  280. f"""UPDATE {self.test_task_conversations_table} SET status = %s, score = %s WHERE id = %s""",
  281. (status, score, task_conversations_id)
  282. )
  283. def cancel_task(self, task_id: int):
  284. """取消任务(带事务支持)"""
  285. # 设置取消事件
  286. if task_id in self.task_events:
  287. self.task_events[task_id].set()
  288. # 如果任务正在执行,尝试取消Future
  289. if task_id in self.task_futures:
  290. self.task_futures[task_id].cancel()
  291. conn = self.db.get_connection()
  292. try:
  293. conn.begin()
  294. # 更新任务状态为取消
  295. with conn.cursor() as cursor:
  296. cursor.execute(
  297. f"""UPDATE {self.test_task_table} SET status = %s WHERE id = %s""",
  298. (TestTaskStatus.CANCELLED.value, task_id)
  299. )
  300. # 取消所有待处理的子任务
  301. with conn.cursor() as cursor:
  302. cursor.execute(
  303. f"""UPDATE {self.test_task_conversations_table} SET status = %s WHERE task_id = %s AND status = %s""",
  304. (TestTaskConversationsStatus.CANCELLED.value, task_id, TestTaskConversationsStatus.PENDING.value)
  305. )
  306. conn.commit()
  307. logger.info(f"Cancelled task {task_id} and its pending {self.test_task_conversations_table}")
  308. except Exception as e:
  309. conn.rollback()
  310. logger.error(f"Failed to cancel task {task_id}: {str(e)}")
  311. finally:
  312. self.db.release_connection(conn)
  313. def resume_task(self, task_id: int) -> bool:
  314. """恢复已取消的任务"""
  315. task = self.get_task(task_id)
  316. if not task or task['status'] != TestTaskStatus.CANCELLED.value:
  317. return False
  318. conn = self.db.get_connection()
  319. try:
  320. conn.begin()
  321. # 更新任务状态为待开始
  322. with conn.cursor() as cursor:
  323. cursor.execute(
  324. f"""UPDATE {self.test_task_table} SET status = %s WHERE id = %s""",
  325. (TestTaskStatus.NOT_STARTED.value, task_id)
  326. )
  327. # 恢复所有已取消的子任务
  328. with conn.cursor() as cursor:
  329. cursor.execute(
  330. f"""UPDATE {self.test_task_conversations_table} SET status = %s WHERE task_id = %s AND status = %s""",
  331. (TestTaskConversationsStatus.PENDING.value, task_id, TestTaskConversationsStatus.CANCELLED.value)
  332. )
  333. conn.commit()
  334. logger.info(f"Cancelled task {task_id} and its pending {self.test_task_conversations_table}")
  335. except Exception as e:
  336. conn.rollback()
  337. logger.error(f"Failed to cancel task {task_id}: {str(e)}")
  338. finally:
  339. self.db.release_connection(conn)
  340. # 重新执行任务
  341. self._execute_task(task_id)
  342. logger.info(f"Resumed task {task_id}")
  343. return True
  344. def _execute_task(self, task_id: int):
  345. """提交任务到线程池执行"""
  346. # 确保任务状态一致性
  347. if task_id in self.running_tasks:
  348. return
  349. # 创建任务事件和锁
  350. if task_id not in self.task_events:
  351. self.task_events[task_id] = threading.Event()
  352. if task_id not in self.task_locks:
  353. self.task_locks[task_id] = threading.Lock()
  354. # 提交到线程池
  355. future = self.executor.submit(self._process_task, task_id)
  356. self.task_futures[task_id] = future
  357. # 标记任务为运行中
  358. with self.task_locks[task_id]:
  359. self.running_tasks.add(task_id)
  360. def _process_task(self, task_id: int):
  361. """处理任务的所有子任务"""
  362. try:
  363. # 更新任务状态为运行中
  364. self.update_task_status(task_id, TestTaskStatus.IN_PROGRESS.value)
  365. # 获取所有待处理的子任务
  366. task_conversations = self.get_pending_task_conversations(task_id)
  367. # 执行每个子任务
  368. for task_conversation in task_conversations:
  369. # 检查任务是否被取消
  370. if self.task_events[task_id].is_set():
  371. break
  372. # 更新子任务状态为运行中
  373. self.update_task_conversations_status(task_conversation['id'],
  374. TestTaskConversationsStatus.RUNNING.value)
  375. try:
  376. # 模拟任务执行 - 在实际应用中替换为实际业务逻辑
  377. # TODO 后续改成实际任务执行
  378. time.sleep(1)
  379. score = '{"score":0.05}'
  380. # 更新子任务状态为已完成
  381. self.update_task_conversations_res(task_conversation['id'],
  382. TestTaskConversationsStatus.SUCCESS.value, score)
  383. except Exception as e:
  384. logger.error(f"Error executing task {task_id}: {str(e)}")
  385. self.update_task_conversations_status(task_conversation['id'],
  386. TestTaskConversationsStatus.FAILED.value)
  387. # 检查任务是否完成
  388. task_conversations = self.get_task_conversations(task_id)
  389. all_completed = all(task_conversation['status'] in
  390. (TestTaskConversationsStatus.SUCCESS.value, TestTaskConversationsStatus.FAILED.value)
  391. for task_conversation in task_conversations)
  392. any_pending = any(task_conversation['status'] in
  393. (TestTaskConversationsStatus.PENDING.value, TestTaskConversationsStatus.RUNNING.value)
  394. for task_conversation in task_conversations)
  395. if all_completed:
  396. self.update_task_status(task_id, TestTaskStatus.COMPLETED.value)
  397. logger.info(f"Task {task_id} completed")
  398. elif not any_pending:
  399. # 没有待处理子任务但未全部完成(可能是取消了)
  400. current_status = self.get_task(task_id)['status']
  401. if current_status != TestTaskStatus.CANCELLED.value:
  402. self.update_task_status(task_id, TestTaskStatus.COMPLETED.value
  403. if all_completed else TestTaskStatus.CANCELLED.value)
  404. except Exception as e:
  405. logger.error(f"Error executing task {task_id}: {str(e)}")
  406. self.update_task_status(task_id, TestTaskStatus.COMPLETED.value)
  407. finally:
  408. # 清理资源
  409. with self.task_locks[task_id]:
  410. if task_id in self.running_tasks:
  411. self.running_tasks.remove(task_id)
  412. if task_id in self.task_events:
  413. del self.task_events[task_id]
  414. if task_id in self.task_futures:
  415. del self.task_futures[task_id]
  416. def shutdown(self):
  417. """关闭执行器"""
  418. self.executor.shutdown(wait=False)
  419. logger.info("Task executor shutdown")