py149 lines5.8 KB
| 1 | #!/usr/bin/env python3 |
| 2 | """Explicit Proxmox operations with confirmation and task completion checks.""" |
| 3 | |
| 4 | from __future__ import annotations |
| 5 | |
| 6 | import argparse |
| 7 | import json |
| 8 | import os |
| 9 | import ssl |
| 10 | import time |
| 11 | import urllib.error |
| 12 | import urllib.parse |
| 13 | import urllib.request |
| 14 | from typing import Any |
| 15 | |
| 16 | PVE_HOST = os.environ.get("PVE_HOST", "").strip() |
| 17 | TOKEN_ID = os.environ.get("PVE_TOKEN_ID", "") |
| 18 | TOKEN_SECRET = os.environ.get("PVE_TOKEN_SECRET", "") |
| 19 | |
| 20 | |
| 21 | class OpsError(RuntimeError): |
| 22 | """An explicit operation could not be completed.""" |
| 23 | |
| 24 | |
| 25 | def tls_context() -> ssl.SSLContext: |
| 26 | """Build a verified TLS context after required configuration is present.""" |
| 27 | ca_file = os.environ.get("PVE_CA_FILE", "").strip() |
| 28 | try: |
| 29 | return ssl.create_default_context(cafile=ca_file or None) |
| 30 | except (OSError, ValueError, ssl.SSLError) as exc: |
| 31 | raise OpsError("PVE_CA_FILE could not be loaded") from exc |
| 32 | |
| 33 | |
| 34 | def api_url(path: str) -> str: |
| 35 | """Use the standard Proxmox port unless PVE_HOST includes an explicit port.""" |
| 36 | host = PVE_HOST |
| 37 | if host.startswith("[") and "]:" not in host: |
| 38 | host = f"{host}:8006" |
| 39 | elif not host.startswith("[") and host.count(":") != 1: |
| 40 | host = f"{host}:8006" |
| 41 | return f"https://{host}/api2/json{path}" |
| 42 | |
| 43 | |
| 44 | def tls_error(exc: BaseException) -> OpsError: |
| 45 | """Turn transport failures into a concise error without request headers.""" |
| 46 | reason = exc.reason if isinstance(exc, urllib.error.URLError) else exc |
| 47 | if isinstance(reason, ssl.SSLCertVerificationError): |
| 48 | return OpsError("TLS certificate verification failed") |
| 49 | if isinstance(reason, ssl.SSLError): |
| 50 | return OpsError("TLS connection failed") |
| 51 | return OpsError("connection failed") |
| 52 | |
| 53 | |
| 54 | def request(method: str, path: str, data: dict[str, Any] | None = None) -> Any: |
| 55 | """Send one API request after the caller has selected a named action.""" |
| 56 | if not PVE_HOST or not TOKEN_ID or not TOKEN_SECRET: |
| 57 | raise OpsError("PVE_HOST, PVE_TOKEN_ID, and PVE_TOKEN_SECRET are required") |
| 58 | body = urllib.parse.urlencode(data).encode() if data else None |
| 59 | req = urllib.request.Request( |
| 60 | api_url(path), method=method, data=body, |
| 61 | headers={"Authorization": f"PVEAPIToken={TOKEN_ID}={TOKEN_SECRET}"}, |
| 62 | ) |
| 63 | try: |
| 64 | with urllib.request.urlopen(req, context=tls_context(), timeout=60) as response: |
| 65 | return json.loads(response.read().decode()).get("data") |
| 66 | except urllib.error.HTTPError as exc: |
| 67 | raise OpsError(f"HTTP {exc.code} {method} {path}: {exc.read().decode(errors='replace')[:300]}") from exc |
| 68 | except (urllib.error.URLError, OSError, ValueError) as exc: |
| 69 | raise tls_error(exc) from exc |
| 70 | |
| 71 | |
| 72 | def wait_task(node: str, upid: str, *, timeout_seconds: int = 3600) -> bool: |
| 73 | """Poll a submitted Proxmox task to a real terminal result.""" |
| 74 | print(f" task: {upid}") |
| 75 | started = time.monotonic() |
| 76 | while time.monotonic() - started < timeout_seconds: |
| 77 | quoted = urllib.parse.quote(upid, safe="") |
| 78 | status = request("GET", f"/nodes/{node}/tasks/{quoted}/status") or {} |
| 79 | if status.get("status") == "stopped": |
| 80 | outcome = status.get("exitstatus", "?") |
| 81 | ok = outcome == "OK" |
| 82 | print(f" terminal state: {outcome} {'SUCCESS' if ok else 'FAILED'}") |
| 83 | return ok |
| 84 | time.sleep(3) |
| 85 | print(f" terminal state: TIMEOUT after {timeout_seconds}s") |
| 86 | return False |
| 87 | |
| 88 | |
| 89 | def find_node(vmid: str) -> str: |
| 90 | """Find a guest's current node before submitting an operation.""" |
| 91 | for guest in request("GET", "/cluster/resources?type=vm") or []: |
| 92 | if str(guest.get("vmid")) == str(vmid) and guest.get("node"): |
| 93 | return str(guest["node"]) |
| 94 | raise OpsError(f"guest {vmid} was not found") |
| 95 | |
| 96 | |
| 97 | def backup(args: argparse.Namespace) -> bool: |
| 98 | """Start a snapshot backup after printing its exact target and mode.""" |
| 99 | node = find_node(args.vmid) |
| 100 | print(f"WILL BACK UP guest {args.vmid} on {node} in snapshot mode to {args.storage}.") |
| 101 | if not args.confirm: |
| 102 | print("DRY RUN. Re-run with --confirm to submit the backup.") |
| 103 | return True |
| 104 | upid = request("POST", f"/nodes/{node}/vzdump", {"vmid": args.vmid, "storage": args.storage, "mode": "snapshot", "compress": "zstd"}) |
| 105 | return wait_task(node, str(upid)) |
| 106 | |
| 107 | |
| 108 | def migrate(args: argparse.Namespace) -> bool: |
| 109 | """Move a guest only after an explicit preview and confirmation.""" |
| 110 | source = find_node(args.vmid) |
| 111 | print(f"WILL MIGRATE guest {args.vmid} from {source} to {args.target}.") |
| 112 | if not args.confirm: |
| 113 | print("DRY RUN. Re-run with --confirm to submit the migration.") |
| 114 | return True |
| 115 | upid = request("POST", f"/nodes/{source}/qemu/{args.vmid}/migrate", {"target": args.target, "online": 1}) |
| 116 | return wait_task(source, str(upid)) |
| 117 | |
| 118 | |
| 119 | def status(_args: argparse.Namespace) -> bool: |
| 120 | """Show guest placement without making any change.""" |
| 121 | for guest in request("GET", "/cluster/resources?type=vm") or []: |
| 122 | print(f"{guest.get('vmid')} {guest.get('name')} {guest.get('node')} {guest.get('status')}") |
| 123 | return True |
| 124 | |
| 125 | |
| 126 | def parser() -> argparse.ArgumentParser: |
| 127 | result = argparse.ArgumentParser(description=__doc__) |
| 128 | sub = result.add_subparsers(dest="action", required=True) |
| 129 | view = sub.add_parser("status", help="read-only placement summary") |
| 130 | view.set_defaults(func=status) |
| 131 | for name, func in (("backup", backup), ("migrate", migrate)): |
| 132 | command = sub.add_parser(name) |
| 133 | command.add_argument("vmid") |
| 134 | command.add_argument("--confirm", action="store_true") |
| 135 | if name == "backup": |
| 136 | command.add_argument("--storage", required=True) |
| 137 | else: |
| 138 | command.add_argument("--target", required=True) |
| 139 | command.set_defaults(func=func) |
| 140 | return result |
| 141 | |
| 142 | |
| 143 | if __name__ == "__main__": |
| 144 | arguments = parser().parse_args() |
| 145 | try: |
| 146 | raise SystemExit(0 if arguments.func(arguments) else 1) |
| 147 | except OpsError as exc: |
| 148 | print(f"OPERATION FAILED: {exc}") |
| 149 | raise SystemExit(2) |