Archived
73 lines
2.5 KiB
Python
73 lines
2.5 KiB
Python
import logging
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, status
|
|
from sqlalchemy import select
|
|
from sqlalchemy.exc import IntegrityError
|
|
from sqlalchemy.orm import Session
|
|
|
|
from .. import models, schemas
|
|
from ..database import get_db
|
|
from ..deps import get_current_user, require_admin
|
|
from ..proxmox_templates import list_templates as discover_templates
|
|
|
|
logger = logging.getLogger(__name__)
|
|
router = APIRouter(prefix="/templates", tags=["templates"])
|
|
|
|
|
|
@router.get("", response_model=list[schemas.TemplateOut])
|
|
def list_templates(
|
|
db: Session = Depends(get_db),
|
|
_: models.User = Depends(get_current_user),
|
|
):
|
|
"""Возвращает только активные шаблоны панели."""
|
|
return list(
|
|
db.scalars(
|
|
select(models.Template)
|
|
.where(models.Template.is_active.is_(True))
|
|
.order_by(models.Template.created_at.desc())
|
|
)
|
|
)
|
|
|
|
|
|
@router.get("/from-proxmox")
|
|
def list_proxmox_templates(_: models.User = Depends(require_admin)):
|
|
"""Находит VM templates и CT templates на настроенной ноде Proxmox."""
|
|
try:
|
|
return discover_templates()
|
|
except Exception:
|
|
logger.exception("Не удалось получить список шаблонов Proxmox")
|
|
raise HTTPException(status_code=502, detail="Proxmox временно недоступен")
|
|
|
|
|
|
@router.post("", response_model=schemas.TemplateOut, status_code=status.HTTP_201_CREATED)
|
|
def create_template(
|
|
payload: schemas.TemplateCreate,
|
|
db: Session = Depends(get_db),
|
|
_: models.User = Depends(require_admin),
|
|
):
|
|
"""Создаёт шаблон только от имени администратора."""
|
|
template = models.Template(**payload.model_dump())
|
|
db.add(template)
|
|
try:
|
|
db.commit()
|
|
except IntegrityError:
|
|
db.rollback()
|
|
raise HTTPException(status_code=409, detail="Шаблон с таким именем уже существует")
|
|
db.refresh(template)
|
|
return template
|
|
|
|
|
|
@router.delete("/{template_id}")
|
|
def deactivate_template(
|
|
template_id: int,
|
|
db: Session = Depends(get_db),
|
|
_: models.User = Depends(require_admin),
|
|
):
|
|
"""Деактивирует шаблон без удаления связанных инстансов."""
|
|
template = db.get(models.Template, template_id)
|
|
if template is None:
|
|
raise HTTPException(status_code=404, detail="Шаблон не найден")
|
|
template.is_active = False
|
|
db.commit()
|
|
return {"ok": True}
|