#!/usr/bin/env python3 """Explicit Proxmox operations with confirmation and task completion checks.""" from __future__ import annotations import argparse import json import os import ssl import time import urllib.error import urllib.parse import urllib.request from typing import Any PVE_HOST = os.environ.get("PVE_HOST", "").strip() TOKEN_ID = os.environ.get("PVE_TOKEN_ID", "") TOKEN_SECRET = os.environ.get("PVE_TOKEN_SECRET", "") class OpsError(RuntimeError): """An explicit operation could not be completed.""" def tls_context() -> ssl.SSLContext: """Build a verified TLS context after required configuration is present.""" ca_file = os.environ.get("PVE_CA_FILE", "").strip() try: return ssl.create_default_context(cafile=ca_file or None) except (OSError, ValueError, ssl.SSLError) as exc: raise OpsError("PVE_CA_FILE could not be loaded") from exc def api_url(path: str) -> str: """Use the standard Proxmox port unless PVE_HOST includes an explicit port.""" host = PVE_HOST if host.startswith("[") and "]:" not in host: host = f"{host}:8006" elif not host.startswith("[") and host.count(":") != 1: host = f"{host}:8006" return f"https://{host}/api2/json{path}" def tls_error(exc: BaseException) -> OpsError: """Turn transport failures into a concise error without request headers.""" reason = exc.reason if isinstance(exc, urllib.error.URLError) else exc if isinstance(reason, ssl.SSLCertVerificationError): return OpsError("TLS certificate verification failed") if isinstance(reason, ssl.SSLError): return OpsError("TLS connection failed") return OpsError("connection failed") def request(method: str, path: str, data: dict[str, Any] | None = None) -> Any: """Send one API request after the caller has selected a named action.""" if not PVE_HOST or not TOKEN_ID or not TOKEN_SECRET: raise OpsError("PVE_HOST, PVE_TOKEN_ID, and PVE_TOKEN_SECRET are required") body = urllib.parse.urlencode(data).encode() if data else None req = urllib.request.Request( api_url(path), method=method, data=body, headers={"Authorization": f"PVEAPIToken={TOKEN_ID}={TOKEN_SECRET}"}, ) try: with urllib.request.urlopen(req, context=tls_context(), timeout=60) as response: return json.loads(response.read().decode()).get("data") except urllib.error.HTTPError as exc: raise OpsError(f"HTTP {exc.code} {method} {path}: {exc.read().decode(errors='replace')[:300]}") from exc except (urllib.error.URLError, OSError, ValueError) as exc: raise tls_error(exc) from exc def wait_task(node: str, upid: str, *, timeout_seconds: int = 3600) -> bool: """Poll a submitted Proxmox task to a real terminal result.""" print(f" task: {upid}") started = time.monotonic() while time.monotonic() - started < timeout_seconds: quoted = urllib.parse.quote(upid, safe="") status = request("GET", f"/nodes/{node}/tasks/{quoted}/status") or {} if status.get("status") == "stopped": outcome = status.get("exitstatus", "?") ok = outcome == "OK" print(f" terminal state: {outcome} {'SUCCESS' if ok else 'FAILED'}") return ok time.sleep(3) print(f" terminal state: TIMEOUT after {timeout_seconds}s") return False def find_node(vmid: str) -> str: """Find a guest's current node before submitting an operation.""" for guest in request("GET", "/cluster/resources?type=vm") or []: if str(guest.get("vmid")) == str(vmid) and guest.get("node"): return str(guest["node"]) raise OpsError(f"guest {vmid} was not found") def backup(args: argparse.Namespace) -> bool: """Start a snapshot backup after printing its exact target and mode.""" node = find_node(args.vmid) print(f"WILL BACK UP guest {args.vmid} on {node} in snapshot mode to {args.storage}.") if not args.confirm: print("DRY RUN. Re-run with --confirm to submit the backup.") return True upid = request("POST", f"/nodes/{node}/vzdump", {"vmid": args.vmid, "storage": args.storage, "mode": "snapshot", "compress": "zstd"}) return wait_task(node, str(upid)) def migrate(args: argparse.Namespace) -> bool: """Move a guest only after an explicit preview and confirmation.""" source = find_node(args.vmid) print(f"WILL MIGRATE guest {args.vmid} from {source} to {args.target}.") if not args.confirm: print("DRY RUN. Re-run with --confirm to submit the migration.") return True upid = request("POST", f"/nodes/{source}/qemu/{args.vmid}/migrate", {"target": args.target, "online": 1}) return wait_task(source, str(upid)) def status(_args: argparse.Namespace) -> bool: """Show guest placement without making any change.""" for guest in request("GET", "/cluster/resources?type=vm") or []: print(f"{guest.get('vmid')} {guest.get('name')} {guest.get('node')} {guest.get('status')}") return True def parser() -> argparse.ArgumentParser: result = argparse.ArgumentParser(description=__doc__) sub = result.add_subparsers(dest="action", required=True) view = sub.add_parser("status", help="read-only placement summary") view.set_defaults(func=status) for name, func in (("backup", backup), ("migrate", migrate)): command = sub.add_parser(name) command.add_argument("vmid") command.add_argument("--confirm", action="store_true") if name == "backup": command.add_argument("--storage", required=True) else: command.add_argument("--target", required=True) command.set_defaults(func=func) return result if __name__ == "__main__": arguments = parser().parse_args() try: raise SystemExit(0 if arguments.func(arguments) else 1) except OpsError as exc: print(f"OPERATION FAILED: {exc}") raise SystemExit(2)