node_configuration_service.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. import json
  2. import hashlib
  3. from typing import Optional, List, Tuple, Any
  4. from sqlalchemy import select, func, desc, delete
  5. from sqlalchemy.ext.asyncio import AsyncSession
  6. from app.core.biz_exception import NotFoundError, BizLogicError
  7. from app.core.logger import logger
  8. from app.models.node_configuration import NodeConfiguration, NodeConfigAuditLog
  9. from app.schemas.node_configuration import (
  10. NodeConfigurationSaveRequest,
  11. NodeConfigurationToggleRequest,
  12. NodeConfigurationCloneRequest,
  13. NodeConfigurationDeleteRequest,
  14. )
  15. def calculate_config_hash(content: Any) -> str:
  16. """
  17. 使用 Canonical JSON (键排序、紧凑分隔符) 统一计算 MD5 哈希
  18. 保证与 Python Coordinate 节点客户端计算完全一致
  19. """
  20. if isinstance(content, str):
  21. try:
  22. content = json.loads(content)
  23. except Exception:
  24. pass
  25. canonical_json_str = json.dumps(content, sort_keys=True, separators=(',', ':'), ensure_ascii=False)
  26. return hashlib.md5(canonical_json_str.encode('utf-8')).hexdigest()
  27. class NodeConfigurationService:
  28. @staticmethod
  29. def compute_hash(content: Any) -> str:
  30. return calculate_config_hash(content)
  31. @classmethod
  32. async def get_detail(
  33. cls,
  34. db: AsyncSession,
  35. role: str,
  36. node_id: str,
  37. ) -> NodeConfiguration:
  38. """
  39. 获取指定角色与节点的配置详情(供 Worker 轮询与详情展示)
  40. """
  41. stmt = select(NodeConfiguration).where(
  42. NodeConfiguration.role == role,
  43. NodeConfiguration.node_id == node_id,
  44. )
  45. res = (await db.execute(stmt)).scalar_one_or_none()
  46. if not res:
  47. raise NotFoundError(f"Node configuration for role='{role}' and node_id='{node_id}' not found")
  48. return res
  49. @classmethod
  50. async def list_configs(
  51. cls,
  52. db: AsyncSession,
  53. role: Optional[str] = None,
  54. node_id: Optional[str] = None,
  55. is_enabled: Optional[int] = None,
  56. page: int = 1,
  57. page_size: int = 20,
  58. ) -> Tuple[int, List[NodeConfiguration]]:
  59. """
  60. 分页查询配置列表
  61. """
  62. stmt = select(NodeConfiguration)
  63. count_stmt = select(func.count(NodeConfiguration.id))
  64. if role:
  65. stmt = stmt.where(NodeConfiguration.role == role)
  66. count_stmt = count_stmt.where(NodeConfiguration.role == role)
  67. if node_id:
  68. stmt = stmt.where(NodeConfiguration.node_id.like(f"%{node_id}%"))
  69. count_stmt = count_stmt.where(NodeConfiguration.node_id.like(f"%{node_id}%"))
  70. if is_enabled is not None:
  71. stmt = stmt.where(NodeConfiguration.is_enabled == is_enabled)
  72. count_stmt = count_stmt.where(NodeConfiguration.is_enabled == is_enabled)
  73. total = (await db.execute(count_stmt)).scalar() or 0
  74. offset = max(0, (page - 1) * page_size)
  75. stmt = stmt.order_by(desc(NodeConfiguration.updated_at), desc(NodeConfiguration.id)).offset(offset).limit(page_size)
  76. result = (await db.execute(stmt)).scalars().all()
  77. return total, list(result)
  78. @classmethod
  79. async def save_config(
  80. cls,
  81. db: AsyncSession,
  82. req: NodeConfigurationSaveRequest,
  83. operator: Optional[str] = None,
  84. ) -> NodeConfiguration:
  85. """
  86. 新增或更新节点配置,并自动写入审计日志
  87. """
  88. op_user = operator or req.operator or "system"
  89. calculated_hash = calculate_config_hash(req.config_content)
  90. stmt = select(NodeConfiguration).where(
  91. NodeConfiguration.role == req.role,
  92. NodeConfiguration.node_id == req.node_id,
  93. )
  94. existing = (await db.execute(stmt)).scalar_one_or_none()
  95. if existing:
  96. action = "UPDATE"
  97. before_hash = existing.config_hash
  98. after_hash = calculated_hash
  99. existing.config_content = req.config_content
  100. existing.config_hash = calculated_hash
  101. if req.is_enabled is not None:
  102. existing.is_enabled = req.is_enabled
  103. if req.description is not None:
  104. existing.description = req.description
  105. existing.updated_by = op_user
  106. target_obj = existing
  107. else:
  108. action = "CREATE"
  109. before_hash = None
  110. after_hash = calculated_hash
  111. target_obj = NodeConfiguration(
  112. role=req.role,
  113. node_id=req.node_id,
  114. config_content=req.config_content,
  115. config_hash=calculated_hash,
  116. is_enabled=req.is_enabled if req.is_enabled is not None else 1,
  117. description=req.description or "",
  118. created_by=op_user,
  119. updated_by=op_user,
  120. )
  121. db.add(target_obj)
  122. audit_log = NodeConfigAuditLog(
  123. role=req.role,
  124. node_id=req.node_id,
  125. action=action,
  126. before_hash=before_hash,
  127. after_hash=after_hash,
  128. operator=op_user,
  129. remark=req.remark or f"{action} configuration for {req.role}:{req.node_id}",
  130. )
  131. db.add(audit_log)
  132. await db.commit()
  133. await db.refresh(target_obj)
  134. logger.info(f"✅ Node configuration saved: role={req.role}, node_id={req.node_id}, hash={calculated_hash}, action={action}")
  135. return target_obj
  136. @classmethod
  137. async def toggle_config(
  138. cls,
  139. db: AsyncSession,
  140. req: NodeConfigurationToggleRequest,
  141. operator: Optional[str] = None,
  142. ) -> NodeConfiguration:
  143. """
  144. 切换启用/禁用状态
  145. """
  146. op_user = operator or req.operator or "system"
  147. stmt = select(NodeConfiguration).where(
  148. NodeConfiguration.role == req.role,
  149. NodeConfiguration.node_id == req.node_id,
  150. )
  151. existing = (await db.execute(stmt)).scalar_one_or_none()
  152. if not existing:
  153. raise NotFoundError(f"Node configuration for role='{req.role}' and node_id='{req.node_id}' not found")
  154. old_status = existing.is_enabled
  155. existing.is_enabled = 1 if req.is_enabled else 0
  156. existing.updated_by = op_user
  157. audit_log = NodeConfigAuditLog(
  158. role=req.role,
  159. node_id=req.node_id,
  160. action="TOGGLE",
  161. before_hash=existing.config_hash,
  162. after_hash=existing.config_hash,
  163. operator=op_user,
  164. remark=req.remark or f"Toggle is_enabled from {old_status} to {existing.is_enabled}",
  165. )
  166. db.add(audit_log)
  167. await db.commit()
  168. await db.refresh(existing)
  169. return existing
  170. @classmethod
  171. async def clone_config(
  172. cls,
  173. db: AsyncSession,
  174. req: NodeConfigurationCloneRequest,
  175. operator: Optional[str] = None,
  176. ) -> NodeConfiguration:
  177. """
  178. 从源节点复制配置到目标节点
  179. """
  180. op_user = operator or req.operator or "system"
  181. stmt = select(NodeConfiguration).where(
  182. NodeConfiguration.role == req.source_role,
  183. NodeConfiguration.node_id == req.source_node_id,
  184. )
  185. source = (await db.execute(stmt)).scalar_one_or_none()
  186. if not source:
  187. raise NotFoundError(f"Source configuration for role='{req.source_role}' and node_id='{req.source_node_id}' not found")
  188. save_req = NodeConfigurationSaveRequest(
  189. role=req.target_role,
  190. node_id=req.target_node_id,
  191. config_content=source.config_content,
  192. is_enabled=source.is_enabled,
  193. description=f"Cloned from {req.source_role}:{req.source_node_id}. {source.description or ''}".strip(),
  194. operator=op_user,
  195. remark=req.remark or f"Cloned from {req.source_role}:{req.source_node_id}",
  196. )
  197. return await cls.save_config(db, save_req, operator=op_user)
  198. @classmethod
  199. async def delete_config(
  200. cls,
  201. db: AsyncSession,
  202. req: NodeConfigurationDeleteRequest,
  203. operator: Optional[str] = None,
  204. ) -> bool:
  205. """
  206. 删除节点配置,并记录审计日志
  207. """
  208. op_user = operator or req.operator or "system"
  209. stmt = select(NodeConfiguration).where(
  210. NodeConfiguration.role == req.role,
  211. NodeConfiguration.node_id == req.node_id,
  212. )
  213. existing = (await db.execute(stmt)).scalar_one_or_none()
  214. if not existing:
  215. raise NotFoundError(f"Node configuration for role='{req.role}' and node_id='{req.node_id}' not found")
  216. audit_log = NodeConfigAuditLog(
  217. role=req.role,
  218. node_id=req.node_id,
  219. action="DELETE",
  220. before_hash=existing.config_hash,
  221. after_hash=None,
  222. operator=op_user,
  223. remark=req.remark or f"Deleted configuration for {req.role}:{req.node_id}",
  224. )
  225. db.add(audit_log)
  226. await db.delete(existing)
  227. await db.commit()
  228. return True
  229. @classmethod
  230. async def get_audit_logs(
  231. cls,
  232. db: AsyncSession,
  233. role: Optional[str] = None,
  234. node_id: Optional[str] = None,
  235. page: int = 1,
  236. page_size: int = 20,
  237. ) -> Tuple[int, List[NodeConfigAuditLog]]:
  238. """
  239. 查询审计日志
  240. """
  241. stmt = select(NodeConfigAuditLog)
  242. count_stmt = select(func.count(NodeConfigAuditLog.id))
  243. if role:
  244. stmt = stmt.where(NodeConfigAuditLog.role == role)
  245. count_stmt = count_stmt.where(NodeConfigAuditLog.role == role)
  246. if node_id:
  247. stmt = stmt.where(NodeConfigAuditLog.node_id == node_id)
  248. count_stmt = count_stmt.where(NodeConfigAuditLog.node_id == node_id)
  249. total = (await db.execute(count_stmt)).scalar() or 0
  250. offset = max(0, (page - 1) * page_size)
  251. stmt = stmt.order_by(desc(NodeConfigAuditLog.created_at), desc(NodeConfigAuditLog.id)).offset(offset).limit(page_size)
  252. result = (await db.execute(stmt)).scalars().all()
  253. return total, list(result)