import logging from typing import List from fastapi import APIRouter, Depends from sqlalchemy.orm import Session from .. import models, schemas, proxmox_client as pve from ..database import get_db from ..deps import get_current_user, require_admin 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), _=Depends(get_current_user)): """Возвращает активные шаблоны, сохранённые в панели.""" return db.query(models.Template).filter(models.Template.is_active == True).all() # noqa: E712 @router.post("", response_model=schemas.TemplateOut) def create_template( payload: schemas.TemplateCreate, db: Session = Depends(get_db), _=Depends(require_admin), ): """Добавляет шаблон в каталог панели.""" tpl = models.Template(**payload.model_dump()) db.add(tpl) db.commit() db.refresh(tpl) return tpl def _list_lxc_container_templates(node: str = None) -> list: """Возвращает LXC-контейнеры, отмеченные в Proxmox как template=1.""" node = node or pve.settings.pve_node px = pve._client() result = [] for container in px.nodes(node).lxc.get(): if container.get("template") != 1: continue vmid = int(container["vmid"]) config = px.nodes(node).lxc(vmid).config.get() result.append({ "vmid": vmid, "name": container.get("hostname") or config.get("hostname") or f"lxc-{vmid}", "cores": int(config.get("cores", 1)), "memory_mb": int(config.get("memory", 1024)), "disk_gb": 8, "source_kind": "vmid", }) return result @router.get("/from-proxmox") def list_proxmox_templates(_=Depends(require_admin)): """Ищет VM, LXC-контейнеры и архивы LXC на Proxmox-ноде.""" try: vm_templates = pve.list_vm_templates() except Exception as exc: logger.warning("Ошибка получения VM-шаблонов из Proxmox: %s", exc) vm_templates = [] try: lxc_templates = _list_lxc_container_templates() except Exception as exc: logger.warning("Ошибка получения LXC-шаблонов-контейнеров из Proxmox: %s", exc) lxc_templates = [] try: archive_templates = pve.list_lxc_templates() except Exception as exc: logger.warning("Ошибка получения архивов LXC-шаблонов из Proxmox: %s", exc) archive_templates = [] for template in archive_templates: template["source_kind"] = "archive" return { "vm_templates": vm_templates, "lxc_templates": lxc_templates + archive_templates, } @router.delete("/{template_id}") def deactivate_template( template_id: int, db: Session = Depends(get_db), _=Depends(require_admin) ): """Деактивирует шаблон в каталоге панели.""" tpl = db.query(models.Template).filter(models.Template.id == template_id).first() if tpl: tpl.is_active = False db.commit() return {"ok": True}