| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259 |
- import json
- from datetime import datetime
- from typing import Optional, Dict, Any, List
- from fastapi import APIRouter, Depends, Query, Body
- from sqlalchemy.ext.asyncio import AsyncSession
- from redis.asyncio import Redis
- from app.core.database import get_db
- from app.core.redis import get_redis_client
- from app.core.auth import get_current_user
- from app.models.user import VasUser
- from app.utils.response import success
- from app.schemas.common import ApiResponse
- from app.schemas.node_configuration import (
- NodeConfigurationSparseUpdateRequest,
- NodeConfigurationEnableRequest,
- NodeConfigurationRollbackRequest,
- NodeConfigurationListResponse,
- )
- from app.services.node_configuration_service import NodeConfigurationService
- public_router = APIRouter()
- protected_router = APIRouter()
- admin_required_router = APIRouter(prefix="/node-configurations", tags=["节点配置管理"])
- @admin_required_router.get(
- "/runtime-status",
- summary="获取各Worker节点实时上报状态与心跳",
- response_model=ApiResponse[Dict[str, Any]],
- )
- async def get_runtime_status(
- role: Optional[str] = Query(None, description="角色筛选: standalone / booker / sentinel"),
- node_id: Optional[str] = Query(None, description="节点 ID 筛选"),
- redis_client: Redis = Depends(get_redis_client),
- ):
- pattern = f"vs:status:{role or '*'}:{node_id or '*'}"
- keys = await redis_client.keys(pattern)
- nodes = []
- now = datetime.utcnow()
- for k in keys:
- try:
- raw = await redis_client.get(k)
- if not raw:
- continue
- data = json.loads(raw)
- collected_at_str = data.get("collected_at", "")
- is_online = False
- age_sec = 999999
- if collected_at_str:
- try:
- dt = datetime.strptime(collected_at_str, "%Y-%m-%d %H:%M:%S")
- age_sec = max(0, int((now - dt).total_seconds()))
- is_online = age_sec <= 60
- except Exception:
- is_online = True
- nodes.append({
- "role": data.get("role") or (k.split(":")[2] if len(k.split(":")) > 2 else ""),
- "node_id": data.get("node_id") or (k.split(":")[3] if len(k.split(":")) > 3 else ""),
- "is_online": is_online,
- "age_sec": age_sec,
- "installed_plugins": data.get("installed_plugins", []),
- "groups": data.get("groups", []),
- "collected_at": collected_at_str,
- })
- except Exception:
- continue
- nodes.sort(key=lambda x: (x.get("role", ""), x.get("node_id", "")))
- return success(data={"nodes": nodes, "timestamp": now.strftime("%Y-%m-%d %H:%M:%S")})
- @admin_required_router.get(
- "/{entry_type}",
- summary="分页查询配置条目列表",
- response_model=ApiResponse[NodeConfigurationListResponse],
- )
- async def list_node_configurations(
- entry_type: str,
- page: int = Query(1, ge=1, description="页码"),
- pageSize: int = Query(20, ge=1, le=100, description="每页数量", alias="pageSize"),
- identifier: Optional[str] = Query(None, description="任务标识模糊搜索"),
- node_id: Optional[str] = Query(None, description="节点唯一标识精确搜索"),
- order_id: Optional[str] = Query(None, description="订单ID (仅 standalone)"),
- db: AsyncSession = Depends(get_db),
- ):
- total, items = await NodeConfigurationService.list_entries(
- db=db,
- entry_type=entry_type,
- page=page,
- page_size=pageSize,
- identifier=identifier,
- node_id=node_id,
- order_id=order_id,
- )
- return success(
- data={
- "total": total,
- "page": page,
- "page_size": pageSize,
- "items": items,
- }
- )
- @admin_required_router.get(
- "/{entry_type}/{entry_id}",
- summary="获取指定配置条目详情",
- response_model=ApiResponse[Dict[str, Any]],
- )
- async def get_node_configuration_detail(
- entry_type: str,
- entry_id: int,
- db: AsyncSession = Depends(get_db),
- ):
- entry = await NodeConfigurationService.get_entry(
- db=db, entry_type=entry_type, entry_id=entry_id
- )
- return success(data=entry)
- @admin_required_router.post(
- "/{entry_type}",
- summary="新建配置条目 (默认停用落库)",
- response_model=ApiResponse[Dict[str, Any]],
- )
- async def create_node_configuration(
- entry_type: str,
- data: Dict[str, Any] = Body(...),
- current_user: Optional[VasUser] = Depends(get_current_user),
- db: AsyncSession = Depends(get_db),
- ):
- operator = (
- current_user.email or current_user.nickname if current_user else "admin"
- )
- entry = await NodeConfigurationService.create_entry(
- db=db,
- entry_type=entry_type,
- data=data,
- operator=operator,
- )
- return success(data=entry, message="Node configuration created successfully")
- @admin_required_router.put(
- "/{entry_type}/{entry_id}",
- summary="稀疏更新配置条目 (支持点路径更新与字段清空)",
- response_model=ApiResponse[Dict[str, Any]],
- )
- async def sparse_update_node_configuration(
- entry_type: str,
- entry_id: int,
- payload: NodeConfigurationSparseUpdateRequest = Body(...),
- current_user: Optional[VasUser] = Depends(get_current_user),
- db: AsyncSession = Depends(get_db),
- ):
- operator = (
- current_user.email or current_user.nickname if current_user else "admin"
- )
- entry = await NodeConfigurationService.sparse_update_entry(
- db=db,
- entry_type=entry_type,
- entry_id=entry_id,
- set_data=payload.set,
- clear_fields=payload.clear,
- base_version=payload.base_version,
- operator=operator,
- )
- return success(data=entry, message="Node configuration updated successfully")
- @admin_required_router.put(
- "/{entry_type}/{entry_id}/enable",
- summary="启用 / 停用配置条目",
- response_model=ApiResponse[Dict[str, Any]],
- )
- async def toggle_node_configuration_enable(
- entry_type: str,
- entry_id: int,
- payload: NodeConfigurationEnableRequest = Body(...),
- current_user: Optional[VasUser] = Depends(get_current_user),
- db: AsyncSession = Depends(get_db),
- ):
- operator = (
- current_user.email or current_user.nickname if current_user else "admin"
- )
- entry = await NodeConfigurationService.toggle_enable(
- db=db,
- entry_type=entry_type,
- entry_id=entry_id,
- enable=payload.enable,
- base_version=payload.base_version,
- operator=operator,
- )
- return success(data=entry, message="Node configuration status toggled")
- @admin_required_router.delete(
- "/{entry_type}/{entry_id}",
- summary="删除配置条目 (最后一条需 confirm_purge=true)",
- response_model=ApiResponse[bool],
- )
- async def delete_node_configuration(
- entry_type: str,
- entry_id: int,
- confirm_purge: bool = Query(False, description="最后一条数据确认删除标记"),
- db: AsyncSession = Depends(get_db),
- ):
- await NodeConfigurationService.delete_entry(
- db=db,
- entry_type=entry_type,
- entry_id=entry_id,
- confirm_purge=confirm_purge,
- )
- return success(data=True, message="Node configuration deleted successfully")
- @admin_required_router.get(
- "/{entry_type}/{entry_id}/revisions",
- summary="获取配置条目修订历史记录",
- response_model=ApiResponse[List[Dict[str, Any]]],
- )
- async def get_node_configuration_revisions(
- entry_type: str,
- entry_id: int,
- db: AsyncSession = Depends(get_db),
- ):
- revisions = await NodeConfigurationService.get_revisions(
- db=db, entry_type=entry_type, entry_id=entry_id
- )
- return success(data=revisions)
- @admin_required_router.post(
- "/{entry_type}/{entry_id}/rollback",
- summary="回滚配置条目至指定历史修订版本",
- response_model=ApiResponse[Dict[str, Any]],
- )
- async def rollback_node_configuration(
- entry_type: str,
- entry_id: int,
- payload: NodeConfigurationRollbackRequest = Body(...),
- current_user: Optional[VasUser] = Depends(get_current_user),
- db: AsyncSession = Depends(get_db),
- ):
- operator = (
- current_user.email or current_user.nickname if current_user else "admin"
- )
- entry = await NodeConfigurationService.rollback_revision(
- db=db,
- entry_type=entry_type,
- entry_id=entry_id,
- revision_id=payload.revision_id,
- base_version=payload.base_version,
- operator=operator,
- )
- return success(data=entry, message="Node configuration rolled back successfully")
|