node_config_tools.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. # app/services/agent/tools/builtin/node_config_tools.py
  2. from typing import Optional, Dict, Any, List
  3. from sqlalchemy.ext.asyncio import AsyncSession
  4. from app.models.user import VasUser
  5. from app.services.node_configuration_service import NodeConfigurationService
  6. from app.services.agent.tools.registry import agent_tool
  7. ADMIN_CHECK_MSG = "权限不足:该运维操作仅系统管理员(admin)可执行"
  8. @agent_tool(
  9. name="list_node_configurations",
  10. description="查询爬虫节点配置列表(booker/sentinel/standalone),支持按 identifier 标识与启用状态筛选(管理员专有)",
  11. )
  12. async def list_node_configurations(
  13. entry_type: str = "booker",
  14. identifier: Optional[str] = None,
  15. enable: Optional[bool] = None,
  16. page: int = 1,
  17. page_size: int = 10,
  18. *,
  19. db: AsyncSession,
  20. current_user: VasUser,
  21. ) -> Dict[str, Any]:
  22. """查询爬虫节点配置列表"""
  23. if current_user.role != "admin":
  24. return {"error": ADMIN_CHECK_MSG}
  25. clean_type = entry_type.strip().lower()
  26. enable_int = 1 if enable is True else (0 if enable is False else None)
  27. try:
  28. total, entries = await NodeConfigurationService.list_entries(
  29. db=db,
  30. entry_type=clean_type,
  31. page=page,
  32. page_size=min(page_size, 30),
  33. identifier=identifier.strip() if identifier else None,
  34. enable=enable_int,
  35. )
  36. items = []
  37. for e in entries:
  38. items.append({
  39. "id": e.id,
  40. "node_id": e.node_id,
  41. "identifier": e.identifier,
  42. "enable": bool(e.enable),
  43. "debug": bool(e.debug),
  44. "proxy_cd": getattr(e, "proxy_cd", None),
  45. "session_max_life": getattr(e, "session_max_life", None),
  46. "version": e.version,
  47. "updated_by": e.updated_by,
  48. "updated_at": e.updated_at.strftime("%Y-%m-%d %H:%M:%S") if e.updated_at else None,
  49. })
  50. return {
  51. "entry_type": clean_type,
  52. "total": total,
  53. "page": page,
  54. "items": items,
  55. }
  56. except Exception as e:
  57. return {"error": f"查询节点配置失败: {str(e)}"}
  58. @agent_tool(
  59. name="get_node_configuration_detail",
  60. description="获取指定爬虫节点配置的完整详情(含代理池、时间窗、Plugin配置等,管理员专有)",
  61. )
  62. async def get_node_configuration_detail(
  63. entry_type: str,
  64. entry_id: int,
  65. *,
  66. db: AsyncSession,
  67. current_user: VasUser,
  68. ) -> Dict[str, Any]:
  69. """获取单个节点配置完整详情"""
  70. if current_user.role != "admin":
  71. return {"error": ADMIN_CHECK_MSG}
  72. try:
  73. entry = await NodeConfigurationService.get_entry(db, entry_type.strip().lower(), entry_id)
  74. snapshot = NodeConfigurationService._to_snapshot(entry)
  75. return {
  76. "entry_type": entry_type,
  77. "entry_id": entry_id,
  78. "configuration": snapshot,
  79. }
  80. except Exception as e:
  81. return {"error": f"获取节点配置详情失败: {str(e)}"}
  82. @agent_tool(
  83. name="toggle_node_configuration",
  84. description="一键启用或禁用指定的爬虫节点配置(管理员专有)",
  85. is_dangerous=True,
  86. )
  87. async def toggle_node_configuration(
  88. entry_type: str,
  89. entry_id: int,
  90. enable: bool,
  91. *,
  92. db: AsyncSession,
  93. current_user: VasUser,
  94. ) -> Dict[str, Any]:
  95. """启停节点配置"""
  96. if current_user.role != "admin":
  97. return {"error": ADMIN_CHECK_MSG}
  98. operator = current_user.email or current_user.nickname or current_user.id
  99. try:
  100. updated = await NodeConfigurationService.toggle_enable(
  101. db=db,
  102. entry_type=entry_type.strip().lower(),
  103. entry_id=entry_id,
  104. enable=enable,
  105. operator=operator,
  106. )
  107. return {
  108. "success": True,
  109. "entry_type": entry_type,
  110. "entry_id": entry_id,
  111. "identifier": updated.identifier,
  112. "enable": bool(updated.enable),
  113. "version": updated.version,
  114. "message": f"节点 {updated.identifier} 已成功{'启用' if enable else '禁用'}",
  115. }
  116. except Exception as e:
  117. return {"error": f"启停节点配置失败: {str(e)}"}
  118. @agent_tool(
  119. name="update_node_configuration_settings",
  120. description="调整指定爬虫节点的关键运维参数,如 proxy_cd(秒), session_max_life(秒), debug模式(管理员专有)",
  121. is_dangerous=True,
  122. )
  123. async def update_node_configuration_settings(
  124. entry_type: str,
  125. entry_id: int,
  126. proxy_cd: Optional[int] = None,
  127. session_max_life: Optional[int] = None,
  128. debug: Optional[int] = None,
  129. *,
  130. db: AsyncSession,
  131. current_user: VasUser,
  132. ) -> Dict[str, Any]:
  133. """修改节点配置关键参数"""
  134. if current_user.role != "admin":
  135. return {"error": ADMIN_CHECK_MSG}
  136. set_data = {}
  137. if proxy_cd is not None:
  138. set_data["proxy_cd"] = proxy_cd
  139. if session_max_life is not None:
  140. set_data["session_max_life"] = session_max_life
  141. if debug is not None:
  142. set_data["debug"] = 1 if debug else 0
  143. if not set_data:
  144. return {"message": "未传入需要更新的参数"}
  145. operator = current_user.email or current_user.nickname or current_user.id
  146. try:
  147. updated = await NodeConfigurationService.sparse_update_entry(
  148. db=db,
  149. entry_type=entry_type.strip().lower(),
  150. entry_id=entry_id,
  151. set_data=set_data,
  152. operator=operator,
  153. )
  154. return {
  155. "success": True,
  156. "entry_type": entry_type,
  157. "entry_id": entry_id,
  158. "identifier": updated.identifier,
  159. "updated_fields": set_data,
  160. "version": updated.version,
  161. "message": f"节点 {updated.identifier} 配置更新成功",
  162. }
  163. except Exception as e:
  164. return {"error": f"更新节点配置参数失败: {str(e)}"}
  165. @agent_tool(
  166. name="list_node_configuration_revisions",
  167. description="查询指定节点配置的历史版本审计记录,用于排错与回滚(管理员专有)",
  168. )
  169. async def list_node_configuration_revisions(
  170. entry_type: str,
  171. entry_id: int,
  172. *,
  173. db: AsyncSession,
  174. current_user: VasUser,
  175. ) -> Dict[str, Any]:
  176. """查询节点配置历史版本"""
  177. if current_user.role != "admin":
  178. return {"error": ADMIN_CHECK_MSG}
  179. try:
  180. revisions = await NodeConfigurationService.get_revisions(
  181. db=db,
  182. entry_type=entry_type.strip().lower(),
  183. entry_id=entry_id,
  184. )
  185. items = []
  186. for r in revisions[:15]:
  187. items.append({
  188. "revision_id": r.id,
  189. "version": r.version,
  190. "action": r.action,
  191. "updated_by": r.updated_by,
  192. "created_at": r.created_at.strftime("%Y-%m-%d %H:%M:%S") if r.created_at else None,
  193. })
  194. return {
  195. "entry_type": entry_type,
  196. "entry_id": entry_id,
  197. "count": len(items),
  198. "revisions": items,
  199. }
  200. except Exception as e:
  201. return {"error": f"查询版本记录失败: {str(e)}"}
  202. @agent_tool(
  203. name="rollback_node_configuration",
  204. description="将节点配置紧急回滚到指定的历史版本 revision_id(管理员专有)",
  205. is_dangerous=True,
  206. )
  207. async def rollback_node_configuration(
  208. entry_type: str,
  209. entry_id: int,
  210. revision_id: int,
  211. *,
  212. db: AsyncSession,
  213. current_user: VasUser,
  214. ) -> Dict[str, Any]:
  215. """回滚节点配置"""
  216. if current_user.role != "admin":
  217. return {"error": ADMIN_CHECK_MSG}
  218. operator = current_user.email or current_user.nickname or current_user.id
  219. try:
  220. rolled = await NodeConfigurationService.rollback_revision(
  221. db=db,
  222. entry_type=entry_type.strip().lower(),
  223. entry_id=entry_id,
  224. revision_id=revision_id,
  225. operator=operator,
  226. )
  227. return {
  228. "success": True,
  229. "entry_type": entry_type,
  230. "entry_id": entry_id,
  231. "identifier": rolled.identifier,
  232. "current_version": rolled.version,
  233. "message": f"节点 {rolled.identifier} 已成功回滚至历史版本 #{revision_id}",
  234. }
  235. except Exception as e:
  236. return {"error": f"回滚节点配置失败: {str(e)}"}