Files
napalm-proxmox/napalm_proxmox/migration.py
T
Christian Manivong 0704d9a102
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 13s
driver / types (pull_request) Successful in 1m3s
driver / test (3.12) (pull_request) Successful in 1m10s
driver / test (3.13) (pull_request) Successful in 1m3s
driver / lowest (pull_request) Successful in 33s
driver / build (pull_request) Successful in 33s
driver / security (pull_request) Successful in 1m27s
CI / driver (pull_request) Successful in 3m4s
driver / publish (pull_request) Skipped
feat: HA state, backups and votes in get_clusters(); migrate_vm, preflight, maintenance
get_clusters() reads /cluster/ha/* (PVE 8 and 9), /cluster/backup with pool
members, the newest backup per guest on each backup storage (PBS included) and
/cluster/config/nodes votes; each read is best-effort. migrate_vm() moves a
guest of the connected node and follows the task (HA-managed guests through
the HA manager), raising with the task log's ERROR lines;
get_vm_migration_preflight() maps PVE's own pre-flight; set_node_maintenance()
runs ha-manager over SSH.

Part of NetOrk/netork#1820 (stage 7: #759, #760, #761).
2026-11-01 22:15:01 +01:00

116 lines
4.4 KiB
Python

"""Reading Proxmox VE's answers about a guest's migration: refusal reasons, local
volumes and resources, task log errors.
- ``GET /nodes/{node}/qemu/{vmid}/migrate`` (qemu-server's
``migrate_vm_precondition``): ``not_allowed_nodes`` maps a node to its
blockers -- ``unavailable_storages``, ``unavailable-resources`` (mappings the
node lacks), ``blocking-ha-resources`` (PVE 9 HA rules); ``local_disks`` lists
volumes on non-shared storage, CD drives included; ``local_resources``
(``hostpci0``, ``usb0``, ``clipboard=vnc``) block the migration.
- A container has no such endpoint; its config says what it keeps locally
(``PVE/LXC/Migrate.pm``): a bind or device mount point that is not marked
``shared`` stops the migration, a volume on non-shared storage is copied.
- A task log is rows of ``{"n": <line>, "t": <text>}``; a failure writes
``ERROR: ...`` lines.
"""
from __future__ import annotations
import re
from typing import Any
from napalm_proxmox.pve_values import to_flag
_JsonDict = dict[str, Any]
_ERROR = re.compile(r"\bERROR: (.*\S)")
#: The cloud-init drive is a CD drive the migration regenerates on the target.
_CLOUDINIT = re.compile(r"vm-\d+-cloudinit")
_CT_VOLUME_KEY = re.compile(r"^(rootfs|mp\d+|unused\d+)$")
def task_errors(log: list[_JsonDict]) -> list[str]:
"""The ``ERROR:`` lines of a task log, without their timestamps, each once."""
errors: list[str] = []
for row in log:
match = _ERROR.search(str(row.get("t") or ""))
if match and match.group(1) not in errors:
errors.append(match.group(1))
return errors
def upid_field(upid: str, index: int) -> str:
"""A field of ``UPID:node:pid:pstart:starttime:type:id:user:``; "" if absent."""
parts = upid.split(":")
return parts[index] if len(parts) > index else ""
def _names(kind: str, items: list[Any]) -> str:
names = ", ".join(str(item) for item in items)
return f"{kind} {names} is" if len(items) == 1 else f"{kind}s {names} are"
def _ha_block(item: Any) -> str:
if not isinstance(item, dict):
return f"HA resource {item} blocks it"
cause = f" ({item['cause']} rule)" if item.get("cause") else ""
return f"HA resource {item.get('sid')} blocks it{cause}"
def _reason(key: str, value: Any) -> str:
items = value if isinstance(value, list) else [value]
if key == "unavailable_storages":
return f"{_names('storage', items)} not available there"
if key == "unavailable-resources":
return f"{_names('mapped resource', items)} not available there"
if key == "blocking-ha-resources":
return "; ".join(_ha_block(item) for item in items)
return f"{key}: {', '.join(str(item) for item in items)}"
def refusal(blockers: Any) -> str:
"""One node's ``not_allowed_nodes`` entry in plain words."""
if not isinstance(blockers, dict) or not blockers:
return "refused by Proxmox VE"
return "; ".join(_reason(key, blockers[key]) for key in sorted(blockers))
def qemu_local(answer: _JsonDict) -> tuple[list[str], list[str]]:
"""``(local_disks, local_resources)`` of a VM's migrate precondition answer.
A local ISO in a CD drive stops the migration, so it is a resource
(``cdrom=<volid>``, after PVE's own ``clipboard=vnc``), not a disk.
"""
disks: list[str] = []
resources = [str(r) for r in answer.get("local_resources") or []]
for disk in answer.get("local_disks") or []:
volid = str(disk.get("volid") or "")
if not volid or _CLOUDINIT.search(volid):
continue
if to_flag(disk.get("cdrom")):
resources.append(f"cdrom={volid}")
else:
disks.append(volid)
return sorted(disks), resources
def lxc_local(config: _JsonDict, shared: dict[str, bool]) -> tuple[list[str], list[str]]:
"""``(local_disks, local_resources)`` of a container's config.
*shared* says per storage whether it is shared; a storage it does not know is
taken as local, which blocks nothing.
"""
disks: list[str] = []
resources: list[str] = []
for key in sorted(config):
if not _CT_VOLUME_KEY.match(key):
continue
volume, *options = str(config[key]).split(",")
volume = volume.removeprefix("volume=")
if volume.startswith("/"):
if "shared=1" not in options:
resources.append(key)
elif not shared.get(volume.split(":", 1)[0], False):
disks.append(volume)
return sorted(disks), resources