vm-bench/backend/app.py

114 lines
3.4 KiB
Python

"""
Backend API — Proxmox Image Conversion Engine
Runs on the Proxmox host (srv2) at http://10.2.0.2:9000/api/v1
Matches open-api.yaml v1.1.0 spec exactly.
"""
from __future__ import annotations
from pathlib import Path
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from models import (
JobSubmissionRequest,
JobStatusResponse,
CleanupRequest,
AnalyzeRequest,
AnalyzeResponse,
ErrorResponse,
)
from converter import extract_if_needed, discover_disk, detect_os
from provisioner import submit_job, get_job_status, cleanup_staging
# ---------------------------------------------------------------------------
# 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=["*"],
)
# ---------------------------------------------------------------------------
# Routes — matching open-api.yaml
# ---------------------------------------------------------------------------
@app.get("/health")
def health() -> dict:
return {"status": "ok"}
@app.post("/analyze", response_model=AnalyzeResponse)
def analyze(req: AnalyzeRequest) -> AnalyzeResponse:
"""Analyze a source file: extract if archive, find disk, detect OS."""
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}")
# Determine extract_dir for OS detection
extract_dir = source if source.is_dir() else source.parent
os_type = detect_os(disk.path, extract_dir)
efi = disk.format in ("raw", "qcow2") # qemu-img can probe EFI partition
return AnalyzeResponse(
os_type=os_type,
disk_size_gb=disk.size_gb,
disk_format=disk.format,
bootable=True,
efi_detectable=efi,
filename=disk.path.name,
)
@app.post("/api/v1/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("/api/v1/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("/api/v1/jobs/{job_id}/cleanup")
def cleanup_job(job_id: str, req: CleanupRequest) -> dict:
"""Delete or preserve staging files for a job."""
# Extract vmid from job_id (format: job_{vmid}_{timestamp})
try:
vmid = int(job_id.split("_")[1])
except (IndexError, ValueError):
vmid = 0
return cleanup_staging(vmid, req.delete_staging_files)
# ---------------------------------------------------------------------------
# Run
# ---------------------------------------------------------------------------
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=9000)