vm-bench/backend/app.py
Claus Lohmar 10199f896b fix: escape f-string braces in backend route decorators
{job_id} in f-strings was interpreted as Python variable instead
of FastAPI path parameter. Double braces {{job_id}} produce
literal {job_id} in the route string.
2026-07-21 18:17:41 +00:00

137 lines
4.3 KiB
Python

"""
Backend API — Proxmox Image Conversion Engine
Runs on the Proxmox host (srv2) at http://10.2.0.2:9000
All API routes live under /api/v1/.
Matches open-api.yaml v1.1.0 spec exactly.
"""
from __future__ import annotations
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from models import (
JobSubmissionRequest,
JobStatusResponse,
CleanupRequest,
CleanupResponse,
AnalyzeRequest,
AnalyzeResponse,
HealthResponse,
ErrorResponse,
)
from converter import extract_if_needed, discover_disk, detect_os, detect_efi
from provisioner import submit_job, get_job_status, cleanup_staging
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
STAGING_IN = "/mnt/converter/in"
API_PREFIX = "/api/v1"
# ---------------------------------------------------------------------------
# App
# ---------------------------------------------------------------------------
app = FastAPI(
title="Proxmox Image Conversion Engine",
version="1.1.0",
docs_url="/docs",
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _validate_filename(filename: str) -> None:
"""Reject filenames that attempt path traversal."""
if ".." in filename or filename.startswith("/"):
raise HTTPException(status_code=400, detail="Invalid filename: path traversal not allowed")
# ---------------------------------------------------------------------------
# Routes — all under /api/v1/
# ---------------------------------------------------------------------------
@app.get(f"{API_PREFIX}/health", response_model=HealthResponse)
def health() -> HealthResponse:
"""Health check."""
return HealthResponse(status="ok")
@app.post(f"{API_PREFIX}/analyze", response_model=AnalyzeResponse)
def analyze(req: AnalyzeRequest) -> AnalyzeResponse:
"""Analyze a source file: extract if archive, find disk, detect OS + EFI."""
_validate_filename(req.source_filename)
try:
source = extract_if_needed(req.source_filename)
except Exception as exc:
raise HTTPException(status_code=400, detail=str(exc))
try:
disk = discover_disk(source)
except Exception as exc:
raise HTTPException(status_code=400, detail=f"Disk discovery failed: {exc}")
extract_dir = source if source.is_dir() else source.parent
os_type = detect_os(disk.path, extract_dir)
efi = detect_efi(disk.path)
return AnalyzeResponse(
vmid=req.vmid,
filename=disk.path.name,
disk_format=disk.format,
disk_size_gb=disk.size_gb,
os_type=os_type,
efi_detectable=efi,
)
@app.post(f"{API_PREFIX}/jobs", response_model=JobStatusResponse, status_code=202)
def create_job(req: JobSubmissionRequest) -> JobStatusResponse:
"""Submit a conversion + provisioning job."""
try:
return submit_job(req)
except Exception as exc:
raise HTTPException(status_code=400, detail=str(exc))
@app.get(f"{API_PREFIX}/jobs/{{job_id}}", response_model=JobStatusResponse)
def job_status(job_id: str) -> JobStatusResponse:
"""Get current status of a conversion job."""
try:
return get_job_status(job_id)
except Exception:
raise HTTPException(status_code=404, detail=f"Job not found: {job_id}")
@app.post(f"{API_PREFIX}/jobs/{{job_id}}/cleanup", response_model=CleanupResponse)
def cleanup_job(job_id: str, req: CleanupRequest) -> CleanupResponse:
"""Delete or preserve staging files for a job."""
try:
vmid = int(job_id.split("_")[1])
except (IndexError, ValueError):
vmid = 0
result = cleanup_staging(vmid, req.delete_staging_files)
return CleanupResponse(
job_id=result["job_id"],
action_taken=result["action_taken"],
message=result["message"],
)
# ---------------------------------------------------------------------------
# Run
# ---------------------------------------------------------------------------
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=9000)