仓库模块完了
This commit is contained in:
@@ -1,12 +1,11 @@
|
||||
from fastapi import APIRouter
|
||||
from app.routes import user, algorithm, api_key, history, gateway, monitoring, openai, deployment
|
||||
from app.routes import user, algorithm, history, gateway, monitoring, openai, deployment
|
||||
|
||||
api_router = APIRouter()
|
||||
|
||||
# 注册路由
|
||||
api_router.include_router(user.router, prefix="/users", tags=["users"])
|
||||
api_router.include_router(algorithm.router, prefix="/algorithms", tags=["algorithms"])
|
||||
api_router.include_router(api_key.router, prefix="/api-keys", tags=["api-keys"])
|
||||
api_router.include_router(history.router, prefix="/history", tags=["history"])
|
||||
api_router.include_router(gateway.router, prefix="/gateway", tags=["gateway"])
|
||||
api_router.include_router(monitoring.router, prefix="/monitoring", tags=["monitoring"])
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List
|
||||
|
||||
from app.models.database import get_db
|
||||
from app.schemas.user import APIKeyCreate, APIKeyResponse, APIKeyListResponse
|
||||
from app.models.models import APIKey
|
||||
from app.services.user import APIKeyService
|
||||
from app.dependencies import get_current_active_user
|
||||
|
||||
# 创建路由器
|
||||
router = APIRouter(prefix="/api-keys", tags=["api-keys"])
|
||||
|
||||
|
||||
@router.post("", response_model=APIKeyResponse)
|
||||
async def create_api_key(
|
||||
api_key_create: APIKeyCreate,
|
||||
current_user: dict = Depends(get_current_active_user),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""创建API密钥"""
|
||||
# 只有管理员或用户本人可以为自己创建API密钥
|
||||
if current_user.role != "admin" and current_user.id != api_key_create.user_id:
|
||||
raise HTTPException(status_code=403, detail="Not enough permissions")
|
||||
|
||||
# 创建API密钥
|
||||
api_key = APIKeyService.create_api_key(db, api_key_create)
|
||||
|
||||
return api_key
|
||||
|
||||
|
||||
@router.get("", response_model=APIKeyListResponse)
|
||||
async def get_api_keys(
|
||||
current_user: dict = Depends(get_current_active_user),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""获取API密钥列表"""
|
||||
# 管理员可以查看所有API密钥,普通用户只能查看自己的
|
||||
if current_user.role == "admin":
|
||||
# 这里可以添加分页和过滤,暂时返回所有
|
||||
api_keys = db.query(APIKey).all()
|
||||
else:
|
||||
api_keys = APIKeyService.get_api_keys_by_user_id(db, current_user.id)
|
||||
|
||||
return {"api_keys": api_keys, "total": len(api_keys)}
|
||||
|
||||
|
||||
@router.get("/{api_key_id}", response_model=APIKeyResponse)
|
||||
async def get_api_key(
|
||||
api_key_id: str,
|
||||
current_user: dict = Depends(get_current_active_user),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""获取API密钥详情"""
|
||||
# 获取API密钥
|
||||
api_key = APIKeyService.get_api_key_by_id(db, api_key_id)
|
||||
if not api_key:
|
||||
raise HTTPException(status_code=404, detail="API key not found")
|
||||
|
||||
# 管理员可以查看所有API密钥,普通用户只能查看自己的
|
||||
if current_user.role != "admin" and current_user.id != api_key.user_id:
|
||||
raise HTTPException(status_code=403, detail="Not enough permissions")
|
||||
|
||||
return api_key
|
||||
|
||||
|
||||
@router.delete("/{api_key_id}", response_model=dict)
|
||||
async def revoke_api_key(
|
||||
api_key_id: str,
|
||||
current_user: dict = Depends(get_current_active_user),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""撤销API密钥"""
|
||||
# 获取API密钥
|
||||
api_key = APIKeyService.get_api_key_by_id(db, api_key_id)
|
||||
if not api_key:
|
||||
raise HTTPException(status_code=404, detail="API key not found")
|
||||
|
||||
# 管理员可以撤销所有API密钥,普通用户只能撤销自己的
|
||||
if current_user.role != "admin" and current_user.id != api_key.user_id:
|
||||
raise HTTPException(status_code=403, detail="Not enough permissions")
|
||||
|
||||
# 撤销API密钥
|
||||
result = APIKeyService.revoke_api_key(db, api_key_id)
|
||||
if not result:
|
||||
raise HTTPException(status_code=400, detail="Failed to revoke API key")
|
||||
|
||||
return {"message": "API key revoked successfully"}
|
||||
@@ -243,22 +243,3 @@ async def get_user_role_based_permissions(
|
||||
}
|
||||
|
||||
|
||||
@router.get("/check-api-key-access")
|
||||
async def check_api_key_access(
|
||||
api_key_value: str,
|
||||
algorithm_id: str,
|
||||
current_user: dict = Depends(get_current_active_user),
|
||||
db = Depends(get_db)
|
||||
):
|
||||
"""检查API密钥对算法的访问权限"""
|
||||
# 只有管理员可以检查任意API密钥的权限
|
||||
if current_user.get("role") != "admin":
|
||||
raise HTTPException(status_code=403, detail="Only admins can check API key access")
|
||||
|
||||
has_access = permission_manager.check_api_key_access(db, api_key_value, algorithm_id)
|
||||
|
||||
return {
|
||||
"api_key_valid": True, # 如果到达这里,说明API密钥存在且活跃
|
||||
"has_algorithm_access": has_access,
|
||||
"algorithm_id": algorithm_id
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import uuid
|
||||
from app.models.models import AlgorithmRepository
|
||||
from app.models.database import SessionLocal
|
||||
from app.routes.user import get_current_active_user
|
||||
from app.schemas.user import UserResponse
|
||||
from app.gitea.service import gitea_service
|
||||
|
||||
router = APIRouter(prefix="/repositories", tags=["repositories"])
|
||||
@@ -38,11 +39,11 @@ class UpdateRepositoryRequest(BaseModel):
|
||||
@router.post("", status_code=status.HTTP_201_CREATED)
|
||||
async def create_repository(
|
||||
request: CreateRepositoryRequest,
|
||||
current_user: dict = Depends(get_current_active_user)
|
||||
current_user: UserResponse = Depends(get_current_active_user)
|
||||
):
|
||||
"""创建算法仓库"""
|
||||
# 检查用户权限
|
||||
if current_user.role != "admin":
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
# 创建数据库会话
|
||||
@@ -92,11 +93,11 @@ async def create_repository(
|
||||
@router.get("")
|
||||
async def list_repositories(
|
||||
algorithm_id: Optional[str] = None,
|
||||
current_user: dict = Depends(get_current_active_user)
|
||||
current_user: UserResponse = Depends(get_current_active_user)
|
||||
):
|
||||
"""获取算法仓库列表"""
|
||||
# 检查用户权限
|
||||
if current_user.role != "admin":
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
# 创建数据库会话
|
||||
@@ -139,11 +140,11 @@ async def list_repositories(
|
||||
@router.get("/{repo_id}")
|
||||
async def get_repository(
|
||||
repo_id: str,
|
||||
current_user: dict = Depends(get_current_active_user)
|
||||
current_user: UserResponse = Depends(get_current_active_user)
|
||||
):
|
||||
"""获取单个算法仓库"""
|
||||
# 检查用户权限
|
||||
if current_user.role != "admin":
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
# 创建数据库会话
|
||||
@@ -179,11 +180,11 @@ async def get_repository(
|
||||
async def update_repository(
|
||||
repo_id: str,
|
||||
request: UpdateRepositoryRequest,
|
||||
current_user: dict = Depends(get_current_active_user)
|
||||
current_user: UserResponse = Depends(get_current_active_user)
|
||||
):
|
||||
"""更新算法仓库"""
|
||||
# 检查用户权限
|
||||
if current_user.role != "admin":
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
# 创建数据库会话
|
||||
@@ -239,11 +240,11 @@ async def update_repository(
|
||||
@router.delete("/{repo_id}")
|
||||
async def delete_repository(
|
||||
repo_id: str,
|
||||
current_user: dict = Depends(get_current_active_user)
|
||||
current_user: UserResponse = Depends(get_current_active_user)
|
||||
):
|
||||
"""删除算法仓库"""
|
||||
# 检查用户权限
|
||||
if current_user.role != "admin":
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
# 创建数据库会话
|
||||
|
||||
@@ -6,9 +6,10 @@ from pydantic import BaseModel
|
||||
import uuid
|
||||
import os
|
||||
|
||||
from app.models.models import AlgorithmService
|
||||
from app.models.models import AlgorithmService, ServiceGroup, AlgorithmRepository
|
||||
from app.models.database import SessionLocal
|
||||
from app.routes.user import get_current_active_user
|
||||
from app.schemas.user import UserResponse
|
||||
from app.services.project_analyzer import ProjectAnalyzer
|
||||
from app.services.service_generator import ServiceGenerator
|
||||
from app.services.service_orchestrator import ServiceOrchestrator
|
||||
@@ -83,6 +84,46 @@ class RepositoryAlgorithmsResponse(BaseModel):
|
||||
algorithms: List[Dict[str, Any]]
|
||||
|
||||
|
||||
class ServiceGroupRequest(BaseModel):
|
||||
"""服务分组请求"""
|
||||
name: str
|
||||
description: str = ""
|
||||
|
||||
|
||||
class ServiceGroupResponse(BaseModel):
|
||||
"""服务分组响应"""
|
||||
id: str
|
||||
name: str
|
||||
description: str
|
||||
status: str
|
||||
created_at: str
|
||||
updated_at: str
|
||||
|
||||
|
||||
class ServiceGroupListResponse(BaseModel):
|
||||
"""服务分组列表响应"""
|
||||
success: bool
|
||||
groups: List[ServiceGroupResponse]
|
||||
|
||||
|
||||
class ServiceGroupDetailResponse(BaseModel):
|
||||
"""服务分组详情响应"""
|
||||
success: bool
|
||||
group: ServiceGroupResponse
|
||||
|
||||
|
||||
class BatchOperationRequest(BaseModel):
|
||||
"""批量操作请求"""
|
||||
service_ids: List[str]
|
||||
|
||||
|
||||
class BatchOperationResponse(BaseModel):
|
||||
"""批量操作响应"""
|
||||
success: bool
|
||||
message: str
|
||||
results: List[Dict[str, Any]]
|
||||
|
||||
|
||||
# 初始化服务组件
|
||||
project_analyzer = ProjectAnalyzer()
|
||||
service_generator = ServiceGenerator()
|
||||
@@ -92,19 +133,23 @@ service_orchestrator = ServiceOrchestrator()
|
||||
@router.post("/register", status_code=status.HTTP_201_CREATED)
|
||||
async def register_service(
|
||||
request: RegisterServiceRequest,
|
||||
current_user: dict = Depends(get_current_active_user)
|
||||
current_user: UserResponse = Depends(get_current_active_user)
|
||||
):
|
||||
"""注册新服务"""
|
||||
# 检查用户权限
|
||||
if current_user.role != "admin":
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
# 创建数据库会话
|
||||
db = SessionLocal()
|
||||
try:
|
||||
# 1. 获取仓库信息
|
||||
# 注意:在实际实现中,应该从数据库中获取仓库信息
|
||||
# 这里简化处理,假设仓库存在
|
||||
repo = db.query(AlgorithmRepository).filter(AlgorithmRepository.id == request.repository_id).first()
|
||||
if not repo:
|
||||
raise HTTPException(status_code=404, detail="仓库不存在")
|
||||
|
||||
# 记录仓库信息
|
||||
print(f"仓库信息: {repo.name}, {repo.description}, {repo.repo_url}")
|
||||
|
||||
# 2. 分析项目
|
||||
repo_path = f"/tmp/repository_{request.repository_id}"
|
||||
@@ -157,7 +202,7 @@ def main(data):
|
||||
id=str(uuid.uuid4()),
|
||||
service_id=service_id,
|
||||
name=request.name,
|
||||
algorithm_name="algorithm", # 注意:在实际实现中,应该从仓库信息中获取
|
||||
algorithm_name=repo.name, # 使用仓库名称作为算法名称
|
||||
version=request.version,
|
||||
host=request.host,
|
||||
port=request.port,
|
||||
@@ -200,11 +245,11 @@ def main(data):
|
||||
|
||||
@router.get("", response_model=ServiceListResponse)
|
||||
async def list_services(
|
||||
current_user: dict = Depends(get_current_active_user)
|
||||
current_user: UserResponse = Depends(get_current_active_user)
|
||||
):
|
||||
"""获取服务列表"""
|
||||
# 检查用户权限
|
||||
if current_user.role != "admin":
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
# 创建数据库会话
|
||||
@@ -241,11 +286,11 @@ async def list_services(
|
||||
@router.get("/{service_id}", response_model=ServiceDetailResponse)
|
||||
async def get_service(
|
||||
service_id: str,
|
||||
current_user: dict = Depends(get_current_active_user)
|
||||
current_user: UserResponse = Depends(get_current_active_user)
|
||||
):
|
||||
"""获取服务详情"""
|
||||
# 检查用户权限
|
||||
if current_user.role != "admin":
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
# 创建数据库会话
|
||||
@@ -281,11 +326,11 @@ async def get_service(
|
||||
@router.post("/{service_id}/start")
|
||||
async def start_service(
|
||||
service_id: str,
|
||||
current_user: dict = Depends(get_current_active_user)
|
||||
current_user: UserResponse = Depends(get_current_active_user)
|
||||
):
|
||||
"""启动服务"""
|
||||
# 检查用户权限
|
||||
if current_user.role != "admin":
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
# 创建数据库会话
|
||||
@@ -325,11 +370,11 @@ async def start_service(
|
||||
@router.post("/{service_id}/stop")
|
||||
async def stop_service(
|
||||
service_id: str,
|
||||
current_user: dict = Depends(get_current_active_user)
|
||||
current_user: UserResponse = Depends(get_current_active_user)
|
||||
):
|
||||
"""停止服务"""
|
||||
# 检查用户权限
|
||||
if current_user.role != "admin":
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
# 创建数据库会话
|
||||
@@ -369,11 +414,11 @@ async def stop_service(
|
||||
@router.post("/{service_id}/restart")
|
||||
async def restart_service(
|
||||
service_id: str,
|
||||
current_user: dict = Depends(get_current_active_user)
|
||||
current_user: UserResponse = Depends(get_current_active_user)
|
||||
):
|
||||
"""重启服务"""
|
||||
# 检查用户权限
|
||||
if current_user.role != "admin":
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
# 创建数据库会话
|
||||
@@ -413,11 +458,11 @@ async def restart_service(
|
||||
@router.delete("/{service_id}")
|
||||
async def delete_service(
|
||||
service_id: str,
|
||||
current_user: dict = Depends(get_current_active_user)
|
||||
current_user: UserResponse = Depends(get_current_active_user)
|
||||
):
|
||||
"""删除服务"""
|
||||
# 检查用户权限
|
||||
if current_user.role != "admin":
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
# 创建数据库会话
|
||||
@@ -456,11 +501,11 @@ async def delete_service(
|
||||
@router.get("/{service_id}/status")
|
||||
async def get_service_status(
|
||||
service_id: str,
|
||||
current_user: dict = Depends(get_current_active_user)
|
||||
current_user: UserResponse = Depends(get_current_active_user)
|
||||
):
|
||||
"""获取服务状态"""
|
||||
# 检查用户权限
|
||||
if current_user.role != "admin":
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
# 创建数据库会话
|
||||
@@ -496,11 +541,11 @@ async def get_service_status(
|
||||
async def get_service_logs(
|
||||
service_id: str,
|
||||
lines: int = 100,
|
||||
current_user: dict = Depends(get_current_active_user)
|
||||
current_user: UserResponse = Depends(get_current_active_user)
|
||||
):
|
||||
"""获取服务日志"""
|
||||
# 检查用户权限
|
||||
if current_user.role != "admin":
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
# 创建数据库会话
|
||||
@@ -534,11 +579,11 @@ async def get_service_logs(
|
||||
@router.get("/repository/algorithms")
|
||||
async def get_repository_algorithms(
|
||||
repository_id: str,
|
||||
current_user: dict = Depends(get_current_active_user)
|
||||
current_user: UserResponse = Depends(get_current_active_user)
|
||||
):
|
||||
"""获取仓库中的算法列表"""
|
||||
# 检查用户权限
|
||||
if current_user.role != "admin":
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
try:
|
||||
@@ -567,3 +612,453 @@ async def get_repository_algorithms(
|
||||
)
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
# 服务分组管理API
|
||||
|
||||
@router.post("/groups", status_code=status.HTTP_201_CREATED)
|
||||
async def create_service_group(
|
||||
request: ServiceGroupRequest,
|
||||
current_user: UserResponse = Depends(get_current_active_user)
|
||||
):
|
||||
"""创建服务分组"""
|
||||
# 检查用户权限
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
# 创建数据库会话
|
||||
db = SessionLocal()
|
||||
try:
|
||||
# 生成唯一ID
|
||||
group_id = str(uuid.uuid4())
|
||||
|
||||
# 创建分组实例
|
||||
group = ServiceGroup(
|
||||
id=group_id,
|
||||
name=request.name,
|
||||
description=request.description
|
||||
)
|
||||
|
||||
# 保存到数据库
|
||||
db.add(group)
|
||||
db.commit()
|
||||
db.refresh(group)
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"message": "服务分组创建成功",
|
||||
"group": {
|
||||
"id": group.id,
|
||||
"name": group.name,
|
||||
"description": group.description,
|
||||
"status": group.status,
|
||||
"created_at": group.created_at.isoformat(),
|
||||
"updated_at": group.updated_at.isoformat()
|
||||
}
|
||||
}
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@router.get("/groups", response_model=ServiceGroupListResponse)
|
||||
async def list_service_groups(
|
||||
current_user: UserResponse = Depends(get_current_active_user)
|
||||
):
|
||||
"""获取服务分组列表"""
|
||||
# 检查用户权限
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
# 创建数据库会话
|
||||
db = SessionLocal()
|
||||
try:
|
||||
# 查询分组列表
|
||||
groups = db.query(ServiceGroup).all()
|
||||
|
||||
# 转换为响应格式
|
||||
group_list = []
|
||||
for group in groups:
|
||||
group_list.append(ServiceGroupResponse(
|
||||
id=group.id,
|
||||
name=group.name,
|
||||
description=group.description,
|
||||
status=group.status,
|
||||
created_at=group.created_at.isoformat(),
|
||||
updated_at=group.updated_at.isoformat()
|
||||
))
|
||||
|
||||
return ServiceGroupListResponse(
|
||||
success=True,
|
||||
groups=group_list
|
||||
)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@router.get("/groups/{group_id}", response_model=ServiceGroupDetailResponse)
|
||||
async def get_service_group(
|
||||
group_id: str,
|
||||
current_user: UserResponse = Depends(get_current_active_user)
|
||||
):
|
||||
"""获取服务分组详情"""
|
||||
# 检查用户权限
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
# 创建数据库会话
|
||||
db = SessionLocal()
|
||||
try:
|
||||
# 查询分组
|
||||
group = db.query(ServiceGroup).filter(ServiceGroup.id == group_id).first()
|
||||
|
||||
if not group:
|
||||
raise HTTPException(status_code=404, detail="Service group not found")
|
||||
|
||||
return ServiceGroupDetailResponse(
|
||||
success=True,
|
||||
group=ServiceGroupResponse(
|
||||
id=group.id,
|
||||
name=group.name,
|
||||
description=group.description,
|
||||
status=group.status,
|
||||
created_at=group.created_at.isoformat(),
|
||||
updated_at=group.updated_at.isoformat()
|
||||
)
|
||||
)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@router.put("/groups/{group_id}")
|
||||
async def update_service_group(
|
||||
group_id: str,
|
||||
request: ServiceGroupRequest,
|
||||
current_user: UserResponse = Depends(get_current_active_user)
|
||||
):
|
||||
"""更新服务分组"""
|
||||
# 检查用户权限
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
# 创建数据库会话
|
||||
db = SessionLocal()
|
||||
try:
|
||||
# 查询分组
|
||||
group = db.query(ServiceGroup).filter(ServiceGroup.id == group_id).first()
|
||||
|
||||
if not group:
|
||||
raise HTTPException(status_code=404, detail="Service group not found")
|
||||
|
||||
# 更新分组信息
|
||||
group.name = request.name
|
||||
group.description = request.description
|
||||
|
||||
# 保存到数据库
|
||||
db.commit()
|
||||
db.refresh(group)
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"message": "服务分组更新成功",
|
||||
"group": {
|
||||
"id": group.id,
|
||||
"name": group.name,
|
||||
"description": group.description,
|
||||
"status": group.status,
|
||||
"created_at": group.created_at.isoformat(),
|
||||
"updated_at": group.updated_at.isoformat()
|
||||
}
|
||||
}
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@router.delete("/groups/{group_id}")
|
||||
async def delete_service_group(
|
||||
group_id: str,
|
||||
current_user: UserResponse = Depends(get_current_active_user)
|
||||
):
|
||||
"""删除服务分组"""
|
||||
# 检查用户权限
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
# 创建数据库会话
|
||||
db = SessionLocal()
|
||||
try:
|
||||
# 查询分组
|
||||
group = db.query(ServiceGroup).filter(ServiceGroup.id == group_id).first()
|
||||
|
||||
if not group:
|
||||
raise HTTPException(status_code=404, detail="Service group not found")
|
||||
|
||||
# 检查分组是否有服务
|
||||
services_count = db.query(AlgorithmService).filter(AlgorithmService.group_id == group_id).count()
|
||||
if services_count > 0:
|
||||
raise HTTPException(status_code=400, detail=f"该分组下还有{services_count}个服务,无法删除")
|
||||
|
||||
# 删除分组
|
||||
db.delete(group)
|
||||
db.commit()
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"message": "服务分组删除成功",
|
||||
"group_id": group_id
|
||||
}
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
# 批量服务操作API
|
||||
|
||||
@router.post("/batch/start")
|
||||
async def batch_start_services(
|
||||
request: BatchOperationRequest,
|
||||
current_user: UserResponse = Depends(get_current_active_user)
|
||||
):
|
||||
"""批量启动服务"""
|
||||
# 检查用户权限
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
# 创建数据库会话
|
||||
db = SessionLocal()
|
||||
try:
|
||||
results = []
|
||||
success_count = 0
|
||||
|
||||
for service_id in request.service_ids:
|
||||
# 查询服务
|
||||
service = db.query(AlgorithmService).filter(AlgorithmService.service_id == service_id).first()
|
||||
|
||||
if not service:
|
||||
results.append({
|
||||
"service_id": service_id,
|
||||
"success": False,
|
||||
"message": "服务不存在"
|
||||
})
|
||||
continue
|
||||
|
||||
# 获取容器ID
|
||||
container_id = service.config.get("container_id")
|
||||
if not container_id:
|
||||
results.append({
|
||||
"service_id": service_id,
|
||||
"success": False,
|
||||
"message": "容器ID不存在"
|
||||
})
|
||||
continue
|
||||
|
||||
# 启动服务
|
||||
start_result = service_orchestrator.start_service(service_id, container_id)
|
||||
if start_result["success"]:
|
||||
# 更新服务状态
|
||||
service.status = start_result["status"]
|
||||
db.commit()
|
||||
success_count += 1
|
||||
results.append({
|
||||
"service_id": service_id,
|
||||
"success": True,
|
||||
"message": "服务启动成功"
|
||||
})
|
||||
else:
|
||||
results.append({
|
||||
"service_id": service_id,
|
||||
"success": False,
|
||||
"message": f"服务启动失败: {start_result['error']}"
|
||||
})
|
||||
|
||||
return BatchOperationResponse(
|
||||
success=True,
|
||||
message=f"批量启动完成,成功{success_count}个,失败{len(request.service_ids) - success_count}个",
|
||||
results=results
|
||||
)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@router.post("/batch/stop")
|
||||
async def batch_stop_services(
|
||||
request: BatchOperationRequest,
|
||||
current_user: UserResponse = Depends(get_current_active_user)
|
||||
):
|
||||
"""批量停止服务"""
|
||||
# 检查用户权限
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
# 创建数据库会话
|
||||
db = SessionLocal()
|
||||
try:
|
||||
results = []
|
||||
success_count = 0
|
||||
|
||||
for service_id in request.service_ids:
|
||||
# 查询服务
|
||||
service = db.query(AlgorithmService).filter(AlgorithmService.service_id == service_id).first()
|
||||
|
||||
if not service:
|
||||
results.append({
|
||||
"service_id": service_id,
|
||||
"success": False,
|
||||
"message": "服务不存在"
|
||||
})
|
||||
continue
|
||||
|
||||
# 获取容器ID
|
||||
container_id = service.config.get("container_id")
|
||||
if not container_id:
|
||||
results.append({
|
||||
"service_id": service_id,
|
||||
"success": False,
|
||||
"message": "容器ID不存在"
|
||||
})
|
||||
continue
|
||||
|
||||
# 停止服务
|
||||
stop_result = service_orchestrator.stop_service(service_id, container_id)
|
||||
if stop_result["success"]:
|
||||
# 更新服务状态
|
||||
service.status = stop_result["status"]
|
||||
db.commit()
|
||||
success_count += 1
|
||||
results.append({
|
||||
"service_id": service_id,
|
||||
"success": True,
|
||||
"message": "服务停止成功"
|
||||
})
|
||||
else:
|
||||
results.append({
|
||||
"service_id": service_id,
|
||||
"success": False,
|
||||
"message": f"服务停止失败: {stop_result['error']}"
|
||||
})
|
||||
|
||||
return BatchOperationResponse(
|
||||
success=True,
|
||||
message=f"批量停止完成,成功{success_count}个,失败{len(request.service_ids) - success_count}个",
|
||||
results=results
|
||||
)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@router.post("/batch/restart")
|
||||
async def batch_restart_services(
|
||||
request: BatchOperationRequest,
|
||||
current_user: UserResponse = Depends(get_current_active_user)
|
||||
):
|
||||
"""批量重启服务"""
|
||||
# 检查用户权限
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
# 创建数据库会话
|
||||
db = SessionLocal()
|
||||
try:
|
||||
results = []
|
||||
success_count = 0
|
||||
|
||||
for service_id in request.service_ids:
|
||||
# 查询服务
|
||||
service = db.query(AlgorithmService).filter(AlgorithmService.service_id == service_id).first()
|
||||
|
||||
if not service:
|
||||
results.append({
|
||||
"service_id": service_id,
|
||||
"success": False,
|
||||
"message": "服务不存在"
|
||||
})
|
||||
continue
|
||||
|
||||
# 获取容器ID
|
||||
container_id = service.config.get("container_id")
|
||||
if not container_id:
|
||||
results.append({
|
||||
"service_id": service_id,
|
||||
"success": False,
|
||||
"message": "容器ID不存在"
|
||||
})
|
||||
continue
|
||||
|
||||
# 重启服务
|
||||
restart_result = service_orchestrator.restart_service(service_id, container_id)
|
||||
if restart_result["success"]:
|
||||
# 更新服务状态
|
||||
service.status = restart_result["status"]
|
||||
db.commit()
|
||||
success_count += 1
|
||||
results.append({
|
||||
"service_id": service_id,
|
||||
"success": True,
|
||||
"message": "服务重启成功"
|
||||
})
|
||||
else:
|
||||
results.append({
|
||||
"service_id": service_id,
|
||||
"success": False,
|
||||
"message": f"服务重启失败: {restart_result['error']}"
|
||||
})
|
||||
|
||||
return BatchOperationResponse(
|
||||
success=True,
|
||||
message=f"批量重启完成,成功{success_count}个,失败{len(request.service_ids) - success_count}个",
|
||||
results=results
|
||||
)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@router.post("/batch/delete")
|
||||
async def batch_delete_services(
|
||||
request: BatchOperationRequest,
|
||||
current_user: UserResponse = Depends(get_current_active_user)
|
||||
):
|
||||
"""批量删除服务"""
|
||||
# 检查用户权限
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Insufficient permissions")
|
||||
|
||||
# 创建数据库会话
|
||||
db = SessionLocal()
|
||||
try:
|
||||
results = []
|
||||
success_count = 0
|
||||
|
||||
for service_id in request.service_ids:
|
||||
# 查询服务
|
||||
service = db.query(AlgorithmService).filter(AlgorithmService.service_id == service_id).first()
|
||||
|
||||
if not service:
|
||||
results.append({
|
||||
"service_id": service_id,
|
||||
"success": False,
|
||||
"message": "服务不存在"
|
||||
})
|
||||
continue
|
||||
|
||||
# 获取容器ID和镜像名称
|
||||
container_id = service.config.get("container_id")
|
||||
image_name = f"algorithm-service-{service_id}:{service.version}"
|
||||
|
||||
# 删除服务
|
||||
delete_result = service_orchestrator.delete_service(service_id, container_id, image_name)
|
||||
|
||||
# 删除数据库记录
|
||||
db.delete(service)
|
||||
db.commit()
|
||||
success_count += 1
|
||||
results.append({
|
||||
"service_id": service_id,
|
||||
"success": True,
|
||||
"message": "服务删除成功"
|
||||
})
|
||||
|
||||
return BatchOperationResponse(
|
||||
success=True,
|
||||
message=f"批量删除完成,成功{success_count}个,失败{len(request.service_ids) - success_count}个",
|
||||
results=results
|
||||
)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
@@ -2,9 +2,12 @@ from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List
|
||||
from jose import JWTError, jwt
|
||||
|
||||
from app.config.settings import settings
|
||||
from app.models.database import get_db
|
||||
from app.schemas.user import UserCreate, UserUpdate, UserResponse, UserListResponse, Token, LoginRequest
|
||||
from app.models.models import User, Role
|
||||
from app.schemas.user import UserCreate, UserUpdate, UserResponse, UserListResponse, Token, LoginRequest, RoleCreate, RoleResponse
|
||||
from app.services.user import UserService
|
||||
|
||||
# 创建路由器
|
||||
@@ -16,16 +19,72 @@ oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/users/login")
|
||||
|
||||
async def get_current_active_user(db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)):
|
||||
"""获取当前活跃用户"""
|
||||
user = UserService.get_current_user(db, token)
|
||||
if not user:
|
||||
try:
|
||||
# 检查令牌是否在黑名单中
|
||||
if UserService.is_token_blacklisted(token):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
# 解码令牌
|
||||
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
|
||||
username: str = payload.get("sub")
|
||||
if username is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
# 使用UserService获取用户信息,避免直接使用User模型
|
||||
user = UserService.get_user_by_username(db, username)
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
# 检查用户是否活跃
|
||||
if user.status != "active":
|
||||
raise HTTPException(status_code=400, detail="Inactive user")
|
||||
|
||||
# 使用UserService获取角色信息
|
||||
role = UserService.get_role_by_id(db, user.role_id)
|
||||
|
||||
# 构建角色响应
|
||||
role_response = None
|
||||
if role:
|
||||
role_response = RoleResponse(
|
||||
id=role.id,
|
||||
name=role.name,
|
||||
description=role.description,
|
||||
created_at=role.created_at,
|
||||
updated_at=role.updated_at
|
||||
)
|
||||
|
||||
# 构建用户响应
|
||||
user_response = UserResponse(
|
||||
id=user.id,
|
||||
username=user.username,
|
||||
email=user.email,
|
||||
role_id=user.role_id,
|
||||
status=user.status,
|
||||
created_at=user.created_at,
|
||||
updated_at=user.updated_at,
|
||||
role=role_response,
|
||||
role_name=role.name if role else None
|
||||
)
|
||||
|
||||
return user_response
|
||||
except JWTError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
if user.status != "active":
|
||||
raise HTTPException(status_code=400, detail="Inactive user")
|
||||
return user
|
||||
|
||||
|
||||
from app.schemas.user import LoginRequest
|
||||
@@ -60,6 +119,10 @@ async def register(user: UserCreate, db: Session = Depends(get_db)):
|
||||
if UserService.get_user_by_email(db, user.email):
|
||||
raise HTTPException(status_code=400, detail="Email already registered")
|
||||
|
||||
# 检查角色是否存在
|
||||
if not UserService.get_role_by_id(db, user.role_id):
|
||||
raise HTTPException(status_code=400, detail="Role not found")
|
||||
|
||||
# 创建用户
|
||||
db_user = UserService.create_user(db, user)
|
||||
|
||||
@@ -81,7 +144,7 @@ async def get_users(
|
||||
):
|
||||
"""获取用户列表"""
|
||||
# 只有管理员可以查看用户列表
|
||||
if current_user.role != "admin":
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Not enough permissions")
|
||||
|
||||
users = UserService.get_users(db, skip=skip, limit=limit)
|
||||
@@ -96,7 +159,7 @@ async def get_user(
|
||||
):
|
||||
"""获取用户信息"""
|
||||
# 只有管理员或用户本人可以查看用户信息
|
||||
if current_user.role != "admin" and current_user.id != user_id:
|
||||
if current_user.role_name != "admin" and current_user.id != user_id:
|
||||
raise HTTPException(status_code=403, detail="Not enough permissions")
|
||||
|
||||
user = UserService.get_user_by_id(db, user_id)
|
||||
@@ -115,15 +178,98 @@ async def update_user(
|
||||
):
|
||||
"""更新用户信息"""
|
||||
# 只有管理员或用户本人可以更新用户信息
|
||||
if current_user.role != "admin" and current_user.id != user_id:
|
||||
if current_user.role_name != "admin" and current_user.id != user_id:
|
||||
raise HTTPException(status_code=403, detail="Not enough permissions")
|
||||
|
||||
# 非管理员只能更新自己的信息,不能更新角色
|
||||
if current_user.role != "admin" and "role" in user_update.dict():
|
||||
if current_user.role_name != "admin" and "role_id" in user_update.dict():
|
||||
raise HTTPException(status_code=403, detail="Cannot update role")
|
||||
|
||||
# 检查角色是否存在
|
||||
if "role_id" in user_update.dict():
|
||||
if not UserService.get_role_by_id(db, user_update.role_id):
|
||||
raise HTTPException(status_code=400, detail="Role not found")
|
||||
|
||||
user = UserService.update_user(db, user_id, user_update)
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
return user
|
||||
|
||||
|
||||
@router.delete("/{user_id}")
|
||||
async def delete_user(
|
||||
user_id: str,
|
||||
current_user: UserResponse = Depends(get_current_active_user),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""删除用户"""
|
||||
# 只有管理员可以删除用户
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Not enough permissions")
|
||||
|
||||
# 检查用户是否存在
|
||||
user = UserService.get_user_by_id(db, user_id)
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
# 删除用户
|
||||
db.delete(user)
|
||||
db.commit()
|
||||
|
||||
return {"message": "User deleted successfully"}
|
||||
|
||||
|
||||
# 角色管理API
|
||||
@router.post("/roles", response_model=RoleResponse)
|
||||
async def create_role(
|
||||
role: RoleCreate,
|
||||
current_user: UserResponse = Depends(get_current_active_user),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""创建角色"""
|
||||
# 只有管理员可以创建角色
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Not enough permissions")
|
||||
|
||||
# 检查角色名称是否已存在
|
||||
if UserService.get_role_by_name(db, role.name):
|
||||
raise HTTPException(status_code=400, detail="Role name already exists")
|
||||
|
||||
# 创建角色
|
||||
db_role = UserService.create_role(db, role)
|
||||
|
||||
return db_role
|
||||
|
||||
|
||||
@router.get("/roles", response_model=List[RoleResponse])
|
||||
async def get_roles(
|
||||
current_user: UserResponse = Depends(get_current_active_user),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""获取角色列表"""
|
||||
# 只有管理员可以查看所有角色
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Not enough permissions")
|
||||
|
||||
roles = UserService.get_roles(db)
|
||||
|
||||
return roles
|
||||
|
||||
|
||||
@router.get("/roles/{role_id}", response_model=RoleResponse)
|
||||
async def get_role(
|
||||
role_id: str,
|
||||
current_user: UserResponse = Depends(get_current_active_user),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""获取角色详情"""
|
||||
# 只有管理员可以查看角色详情
|
||||
if current_user.role_name != "admin":
|
||||
raise HTTPException(status_code=403, detail="Not enough permissions")
|
||||
|
||||
role = UserService.get_role_by_id(db, role_id)
|
||||
if not role:
|
||||
raise HTTPException(status_code=404, detail="Role not found")
|
||||
|
||||
return role
|
||||
|
||||
Reference in New Issue
Block a user