vm-bench/backend/app.py
Claus Lohmar 42d3cdf1fe fix: add logging to backend — analyze, job submit, status, cleanup
Backend had zero logging. Frontend logs were fine (logging.basicConfig
in app.py). Now both services write structured logs to systemd journal:

  journalctl -u vm-bench -f            # frontend (LXC)
  journalctl -u vm-bench-backend -f    # backend (srv2)
2026-07-21 18:46:12 +00:00

162 lines
5.5 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
import logging
from fastapi import FastAPI, HTTPException, Request
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
# ---------------------------------------------------------------------------
# Logging
# ---------------------------------------------------------------------------
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
)
logger = logging.getLogger("backend")
# ---------------------------------------------------------------------------
# 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)
logger.info("Analyze request: vmid=%d file=%s", req.vmid, req.source_filename)
try:
source = extract_if_needed(req.source_filename)
logger.info("Source ready: %s", source)
except Exception as exc:
logger.error("Extraction failed: %s", exc)
raise HTTPException(status_code=400, detail=str(exc))
try:
disk = discover_disk(source)
logger.info("Disk found: %s (format=%s, size=%.1f GiB)", disk.path, disk.format, disk.size_gb)
except Exception as exc:
logger.error("Disk discovery failed: %s", 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)
logger.info("Analysis result: os=%s efi=%s", os_type, efi)
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."""
logger.info("Job submit: vmid=%d name=%s disk=%s storage=%s",
req.vmid, req.vm_name,
req.boot_disk.source_filename, req.target_storage)
try:
result = submit_job(req)
logger.info("Job queued: %s", result.job_id)
return result
except Exception as exc:
logger.error("Job submission failed: %s", 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:
result = get_job_status(job_id)
return result
except Exception:
logger.warning("Job not found: %s", job_id)
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
logger.info("Cleanup: job=%s vmid=%d delete=%s", job_id, vmid, req.delete_staging_files)
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)