feat: HA state, backups and votes in get_clusters(); migrate_vm, preflight, maintenance
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

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).
This commit is contained in:
Christian Manivong committed 2026-11-01 22:15:01 +01:00
1 parent cb29a42c31
commit 0704d9a102
11 files changed
+1653 -17

No files matched your search

+151
View File
@@ -0,0 +1,151 @@
"""get_clusters() for Proxmox VE: the backup jobs, and the backups on the storages.
Read from:
- ``GET /cluster/backup``: each vzdump job. ``enabled`` absent means enabled;
old jobs carry ``starttime``/``dow`` instead of ``schedule``, which PVE itself
turns into ``"<dow> <starttime>"`` (``PVE/API2/Backup.pm``). ``storage`` and
``mode`` are None where the job does not set them: a node's
``/etc/vzdump.conf`` then decides.
- a pool job's guests: ``GET /pools?poolid=<pool>`` (PVE 8.1 and later), else
``GET /pools/<pool>``, which older releases have;
- ``GET /nodes/<node>/storage/<storage>/content?content=backup`` for each storage
that holds backups (PBS answers the same): a shared one once, on the own node
if it sees it, else on the next node that does; a local one on every node
that has it.
Each list is best-effort: when part of it cannot be read it is None, because
half a list would say a guest has no backup, or a job no guest, when it may.
"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any
from napalm_proxmox.pve_values import split_list, to_flag, to_int, vmid_list
if TYPE_CHECKING:
# Type-only: newer than the napalm_device_types floor in pyproject.toml.
from napalm_device_types import BackupDict, BackupJobDict, ClusterStorageDict
logger = logging.getLogger(__name__)
_JsonDict = dict[str, Any]
_ALL_DAYS = "mon,tue,wed,thu,fri,sat,sun"
_GUEST_TYPES = ("qemu", "lxc")
def _schedule(job: _JsonDict) -> str | None:
if job.get("schedule"):
return str(job["schedule"])
start = job.get("starttime")
if not start:
return None
dow = ",".join(split_list(job.get("dow")))
return str(start) if dow in ("", _ALL_DAYS) else f"{dow} {start}"
def _pool_info(api: Any, pool: str) -> _JsonDict:
try:
for entry in api.pools.get(poolid=pool) or []:
if entry.get("poolid") == pool:
return dict(entry)
except Exception as exc:
logger.debug("GET /pools?poolid=%s failed, trying /pools/%s: %s", pool, pool, exc)
return dict(api.pools(pool).get() or {})
def _pool_members(api: Any, pool: str) -> list[int]:
members = _pool_info(api, pool).get("members") or []
return [
int(m["vmid"])
for m in members
if m.get("type") in _GUEST_TYPES and m.get("vmid") is not None
]
def _job(api: Any, job: _JsonDict) -> BackupJobDict:
pool = job.get("pool") or None
return {
"id": str(job.get("id") or ""),
"enabled": to_flag(job.get("enabled", 1)),
"schedule": _schedule(job),
"storage": job.get("storage") or None,
"mode": job.get("mode") or None,
"all": to_flag(job.get("all")),
"vmids": _pool_members(api, str(pool)) if pool else vmid_list(job.get("vmid")),
"exclude": vmid_list(job.get("exclude")),
"pool": pool,
"node": job.get("node") or None,
}
def read_backup_jobs(api: Any) -> list[BackupJobDict] | None:
"""The cluster's backup jobs; None when they, or a pool's guests, cannot be read."""
try:
return [_job(api, job) for job in api.cluster.backup.get() or []]
except Exception as exc:
logger.debug("Cannot read the backup jobs: %s", exc)
return None
def _content(api: Any, node: str, storage: str) -> list[_JsonDict]:
return list(api.nodes(node).storage(storage).content.get(content="backup") or [])
def _first_answer(api: Any, storage: str, nodes: list[str]) -> list[_JsonDict]:
error: Exception | None = None
for node in nodes:
try:
return _content(api, node, storage)
except Exception as exc:
logger.debug("Cannot read backups on %s from %s: %s", storage, node, exc)
error = exc
if error is not None:
raise error
return []
def _storage_rows(api: Any, storage: ClusterStorageDict, local_node: str) -> list[_JsonDict]:
nodes = storage["nodes"]
if storage["shared"]:
return _first_answer(api, storage["name"], sorted(nodes, key=lambda n: n != local_node))
return [row for node in nodes for row in _content(api, node, storage["name"])]
def _merge(rows: list[_JsonDict], storage: str, merged: dict[tuple[int, str], BackupDict]) -> None:
for row in rows:
if row.get("vmid") is None or row.get("ctime") is None:
continue # not a vzdump/PBS backup of a guest
key, ctime = (int(row["vmid"]), storage), int(row["ctime"])
entry = merged.get(key)
if entry is None:
merged[key] = {
"vmid": key[0],
"storage": storage,
"time": ctime,
"size": to_int(row.get("size")),
"count": 1,
}
continue
entry["count"] += 1
if ctime > entry["time"]:
entry["time"], entry["size"] = ctime, to_int(row.get("size"))
def read_backups(
api: Any, storages: list[ClusterStorageDict], local_node: str
) -> list[BackupDict] | None:
"""One entry per guest and storage with its newest backup; None if a storage
that holds backups cannot be read."""
merged: dict[tuple[int, str], BackupDict] = {}
try:
for storage in storages:
if "backup" in storage["content"]:
_merge(_storage_rows(api, storage, local_node), storage["name"], merged)
except Exception as exc:
logger.debug("Cannot read the backups: %s", exc)
return None
return [merged[key] for key in sorted(merged, key=lambda k: (k[1], k[0]))]
+105
View File
@@ -0,0 +1,105 @@
"""get_clusters() for Proxmox VE: quorum votes and the guests the HA manager keeps.
Read from:
- ``GET /cluster/config/nodes``: corosync's nodelist, ``quorum_votes`` per node;
- ``GET /cluster/ha/resources``: each HA resource's ``sid`` (``vm:100``,
``ct:101``), requested ``state`` and, on PVE 8, ``group``;
- ``GET /cluster/ha/status/current``: per ``service`` entry the ``node`` and the
CRM's ``crm_state`` (only the verbose ``state`` while the CRM has not taken it
up yet);
- ``GET /cluster/ha/rules`` (PVE 9): each rule's ``rule`` id and its
``resources``, a comma-separated list of sids. PVE 8 has no such endpoint.
Each read is best-effort: what cannot be read is None, never a guess.
"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any
from napalm_proxmox.pve_values import split_list
if TYPE_CHECKING:
# Type-only: newer than the napalm_device_types floor in pyproject.toml.
from napalm_device_types import HAResourceDict
logger = logging.getLogger(__name__)
_JsonDict = dict[str, Any]
#: HA resource type prefix -> guest kind.
_KINDS = {"vm": "qemu", "ct": "lxc"}
#: corosync counts a node without ``quorum_votes`` as one vote.
_DEFAULT_VOTES = 1
#: What HA keeps a resource at when its config names no state.
_DEFAULT_REQUESTED = "started"
def read_votes(api: Any) -> dict[str, int] | None:
"""Quorum votes per node name; None when the nodelist cannot be read."""
try:
rows = api.cluster.config.nodes.get() or []
except Exception as exc:
logger.debug("Cannot read the corosync nodelist: %s", exc)
return None
return {
str(row.get("node") or row.get("name")): int(row.get("quorum_votes", _DEFAULT_VOTES))
for row in rows
if row.get("node") or row.get("name")
}
def _services(api: Any) -> dict[str, _JsonDict] | None:
try:
rows = api.cluster.ha.status.current.get() or []
except Exception as exc:
logger.debug("Cannot read the HA status: %s", exc)
return None
return {str(r["sid"]): r for r in rows if r.get("type") == "service" and r.get("sid")}
def _rules(api: Any) -> dict[str, list[str]]:
"""Rule ids per sid. PVE 8 answers with an error: no rules there."""
try:
rows = api.cluster.ha.rules.get() or []
except Exception as exc:
logger.debug("No HA rules (PVE 8 has none): %s", exc)
return {}
by_sid: dict[str, list[str]] = {}
for rule in rows:
for sid in split_list(rule.get("resources")):
by_sid.setdefault(sid, []).append(str(rule.get("rule")))
return by_sid
def _resource(
row: _JsonDict, services: dict[str, _JsonDict] | None, rules: dict[str, list[str]]
) -> HAResourceDict | None:
sid = str(row.get("sid") or "")
prefix, _, vmid = sid.partition(":")
if prefix not in _KINDS or not vmid.isdigit():
return None
service = (services or {}).get(sid, {})
return {
"vmid": int(vmid),
"kind": _KINDS[prefix],
"requested": str(row.get("state") or _DEFAULT_REQUESTED),
"status": service.get("crm_state") or service.get("state") or None,
"node": service.get("node") or None,
"group": row.get("group") or None,
"rules": rules.get(sid, []),
}
def read_ha_resources(api: Any) -> list[HAResourceDict] | None:
"""Every guest HA manages, by vmid; None when the HA resources cannot be read."""
try:
rows = api.cluster.ha.resources.get() or []
except Exception as exc:
logger.debug("Cannot read the HA resources: %s", exc)
return None
services, rules = _services(api), _rules(api)
resources = [_resource(row, services, rules) for row in rows]
return sorted((r for r in resources if r is not None), key=lambda r: r["vmid"])
+22 -17
View File
@@ -13,7 +13,10 @@ cluster of one, without a name). Read from:
- ``GET /nodes/{node}/network`` of each online node: its bridges;
- ``GET /cluster/sdn/vnets`` and ``/cluster/sdn/zones``: the vnets, on the nodes
of their zone;
- ``GET /cluster/ha/status/manager_status``: which node is in maintenance.
- ``GET /cluster/ha/status/manager_status``: which node is in maintenance;
- quorum votes and HA resources: see ``cluster_ha``; backup jobs and backups:
see ``cluster_backups``. Each of those is best-effort and None when it cannot
be read, without failing the rest of the report.
"""
from __future__ import annotations
@@ -21,7 +24,12 @@ from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any, NamedTuple
from napalm_proxmox.cluster_backups import read_backup_jobs, read_backups
from napalm_proxmox.cluster_ha import read_ha_resources, read_votes
from napalm_proxmox.network_targets import bridge_targets, vnet_target
from napalm_proxmox.pve_values import split_list as _list
from napalm_proxmox.pve_values import to_flag as _flag
from napalm_proxmox.pve_values import to_int as _int
from napalm_proxmox.utils import cpu_flags
if TYPE_CHECKING:
@@ -51,22 +59,10 @@ class _Cpu(NamedTuple):
flags: list[str] | None = None
def _int(value: Any) -> int | None:
return None if value is None else int(value)
def _float(value: Any) -> float | None:
return None if value is None else float(value)
def _flag(value: Any) -> bool:
return bool(int(value or 0))
def _list(value: Any) -> list[str]:
return [part.strip() for part in str(value or "").split(",") if part.strip()]
def _size(rows: list[_JsonDict], key: str, shared: bool) -> int | None:
"""One storage's size over the nodes in *rows*: summed unless it is shared."""
values = [row.get(key) for row in rows]
@@ -151,14 +147,18 @@ class ProxmoxClusterMixin:
resources = self._api.cluster.resources.get() or []
head = next((s for s in status if s.get("type") == "cluster"), None)
members = self._members(status if head else [])
storages = _storages(resources)
return [
{
"id": None,
"name": (head.get("name") or None) if head else None,
"quorate": _flag(head.get("quorate")) if head else None,
"nodes": self._cluster_nodes(members, resources),
"storages": _storages(resources),
"storages": storages,
"networks": self._networks(members),
"ha_resources": read_ha_resources(self._api),
"backup_jobs": read_backup_jobs(self._api),
"backups": read_backups(self._api, storages, self._node_name),
}
]
@@ -166,8 +166,8 @@ class ProxmoxClusterMixin:
self, members: list[_Member], resources: list[_JsonDict]
) -> list[ClusterNodeDict]:
rows = {r.get("node"): r for r in resources if r.get("type") == "node"}
maintenance = self._maintenance()
return [self._cluster_node(m, rows.get(m.name, {}), maintenance) for m in members]
maintenance, votes = self._maintenance(), read_votes(self._api)
return [self._cluster_node(m, rows.get(m.name, {}), maintenance, votes) for m in members]
def _networks(self, members: list[_Member]) -> list[ClusterNetworkDict]:
online = [m for m in members if m.online]
@@ -225,7 +225,11 @@ class ProxmoxClusterMixin:
)
def _cluster_node(
self, member: _Member, row: _JsonDict, maintenance: dict[str, bool] | None
self,
member: _Member,
row: _JsonDict,
maintenance: dict[str, bool] | None,
votes: dict[str, int] | None,
) -> ClusterNodeDict:
if not member.online:
row, cpu = {}, _Cpu()
@@ -243,6 +247,7 @@ class ProxmoxClusterMixin:
"cpu_usage": _float(row.get("cpu")),
"memory_total": _int(row.get("maxmem")),
"memory_used": _int(row.get("mem")),
"votes": None if votes is None else votes.get(member.name),
}
def _vnets(self, members: list[str]) -> list[ClusterNetworkDict]:
+2
View File
@@ -63,6 +63,7 @@ from napalm_proxmox.routing_mixin import ProxmoxRoutingMixin
from napalm_proxmox.sdn_mixin import ProxmoxSDNMixin
from napalm_proxmox.system_mixin import ProxmoxSystemMixin
from napalm_proxmox.vm_contract_mixin import ProxmoxVMContractMixin
from napalm_proxmox.vm_migrate_mixin import ProxmoxVMMigrateMixin
from napalm_proxmox.vm_mixin import ProxmoxVMMixin
from napalm_proxmox.vm_provision_mixin import ProxmoxVMProvisionMixin
from napalm_proxmox.vm_snapshot_mixin import ProxmoxVMSnapshotMixin
@@ -89,6 +90,7 @@ class ProxmoxDriver(
ProxmoxVMSnapshotMixin,
ProxmoxVMProvisionMixin,
ProxmoxClusterMixin,
ProxmoxVMMigrateMixin,
ProxmoxRoutingMixin,
ProxmoxSystemMixin,
KernelFactsMixin,
+115
View File
@@ -0,0 +1,115 @@
"""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
+27
View File
@@ -0,0 +1,27 @@
"""How the Proxmox VE API writes plain values: numbers as strings, flags as 0/1, lists
as comma-separated strings."""
from __future__ import annotations
import re
from typing import Any
_LIST_SEPARATORS = re.compile(r"[\s,;\0]+")
def to_int(value: Any) -> int | None:
return None if value is None else int(value)
def to_flag(value: Any) -> bool:
return bool(int(value or 0))
def split_list(value: Any) -> list[str]:
"""``"a,b"`` -> ``["a", "b"]``; PVE also separates with ``;``, blanks or NUL."""
return [part for part in _LIST_SEPARATORS.split(str(value or "")) if part]
def vmid_list(value: Any) -> list[int]:
"""``"100,101"`` -> ``[100, 101]``; what is not a number is left out."""
return [int(part) for part in split_list(value) if part.isdigit()]
+255
View File
@@ -0,0 +1,255 @@
"""HypervisorDriver migration methods for Proxmox VE: preflight, migrate, HA maintenance.
A guest is addressed like every other VM method of this driver: by vmid or name,
on the node the driver is connected to (``_resolve_vm``).
- ``get_vm_migration_preflight``: a VM asks ``GET .../qemu/{vmid}/migrate``; a
container has no such endpoint, so the online members are its candidates.
A member the cluster calls offline is refused (``"node offline"``) for both,
also where the VM endpoint would list it as allowed.
- ``migrate_vm``: ``POST .../{qemu|lxc}/{vmid}/migrate`` and the task is followed
to its end; a failure raises with the task log's ``ERROR:`` lines. A guest HA
manages migrates through a ``hamigrate`` task that only hands the request to
the HA manager; the driver then follows ``/cluster/ha/status/current`` until
the guest is on the target, and on a failure reads the migration task's log.
- ``set_node_maintenance``: PVE has no REST endpoint for it; it runs
``ha-manager crm-command node-maintenance`` over the driver's SSH session.
The HA manager moves the node's HA guests away after the command returned.
"""
from __future__ import annotations
import logging
import shlex
from time import monotonic, sleep
from typing import TYPE_CHECKING, Any
from napalm_proxmox.migration import lxc_local, qemu_local, refusal, task_errors, upid_field
from napalm_proxmox.pve_values import to_flag
if TYPE_CHECKING:
# Type-only: newer than the napalm_device_types floor in pyproject.toml.
from napalm_device_types import MigrationPreflightDict
logger = logging.getLogger(__name__)
_JsonDict = dict[str, Any]
#: Enough to reach the ERROR lines at the end of a long storage migration's log.
_TASK_LOG_LINES = 50000
_HA_POLL_SECONDS = 5
#: CRM states while the HA manager is moving a guest.
_HA_MOVING = frozenset({"migrate", "relocate"})
class ProxmoxVMMigrateMixin:
"""Relies on the driver, ``_resolve_vm``/``_guest_api``, ``_members`` and
``_wait_for_task``/``_run_node_command``/``_node_ssh``."""
_api: Any
_node_name: str
hostname: str
timeout: int
_node_api: Any
_resolve_vm: Any
_guest_api: Any
_members: Any
_wait_for_task: Any
_node_ssh: Any
_run_node_command: Any
# -- cluster membership -------------------------------------------------------
def _cluster_members(self) -> list[Any]:
status = self._api.cluster.status.get() or []
clustered = any(s.get("type") == "cluster" for s in status)
return list(self._members(status if clustered else []))
def _other_member(self, node: str) -> None:
names = [m.name for m in self._cluster_members()]
if node == self._node_name or node not in names:
raise ValueError(
f"{node!r} is not another member of the cluster of {self._node_name!r} "
f"(members: {', '.join(names)})"
)
def _storage_sharing(self) -> dict[str, bool]:
rows = self._api.cluster.resources.get(type="storage") or []
sharing: dict[str, bool] = {}
for row in rows:
if row.get("type") == "storage" and row.get("storage"):
name = str(row["storage"])
sharing[name] = sharing.get(name, False) or to_flag(row.get("shared"))
return sharing
# -- preflight ----------------------------------------------------------------
def get_vm_migration_preflight(self, name: str) -> MigrationPreflightDict:
"""Where the guest could move to within its cluster, and what blocks it."""
vmid, vm_type = self._resolve_vm(name)
others = [m for m in self._cluster_members() if m.name != self._node_name]
offline = [m.name for m in others if not m.online]
if vm_type == "vm":
return self._qemu_preflight(vmid, offline)
return self._lxc_preflight(vmid, [m.name for m in others if m.online], offline)
def _qemu_preflight(self, vmid: int, offline: list[str]) -> MigrationPreflightDict:
answer = self._guest_api(vmid, "vm").migrate.get() or {}
refused = {
str(node): refusal(blockers)
for node, blockers in (answer.get("not_allowed_nodes") or {}).items()
}
for node in offline:
refused[node] = "; ".join(filter(None, ["node offline", refused.get(node)]))
disks, resources = qemu_local(answer)
return {
"running": to_flag(answer.get("running")),
"allowed_nodes": [
str(n) for n in answer.get("allowed_nodes") or [] if n not in offline
],
"refused_nodes": refused,
"local_disks": disks,
"local_resources": resources,
}
def _lxc_running(self, vmid: int) -> bool:
status = self._guest_api(vmid, "container").status.current.get() or {}
return bool(status.get("status") == "running")
def _lxc_preflight(
self, vmid: int, online: list[str], offline: list[str]
) -> MigrationPreflightDict:
config = self._guest_api(vmid, "container").config.get() or {}
disks, resources = lxc_local(config, self._storage_sharing())
return {
"running": self._lxc_running(vmid),
"allowed_nodes": online,
"refused_nodes": {n: "node offline" for n in offline},
"local_disks": disks,
"local_resources": resources,
}
# -- migration ----------------------------------------------------------------
def migrate_vm(
self,
name: str,
target_node: str,
online: bool = True,
target_storage: str | None = None,
timeout: int = 3600,
) -> None:
"""Move the guest to *target_node*; block until Proxmox VE finished."""
vmid, vm_type = self._resolve_vm(name)
self._other_member(target_node)
deadline = monotonic() + timeout
params = self._qemu_params(vmid, online) if vm_type == "vm" else self._lxc_params(vmid)
if target_storage:
params["targetstorage" if vm_type == "vm" else "target-storage"] = target_storage
try:
upid = str(self._guest_api(vmid, vm_type).migrate.post(target=target_node, **params))
except Exception as exc:
raise RuntimeError(
f"Migration of {vm_type} {vmid} to {target_node!r} refused: {exc}"
) from exc
self._follow_task(upid, vmid, timeout)
if upid_field(upid, 5) == "hamigrate":
self._follow_ha(vmid, vm_type, target_node, deadline, upid)
def _qemu_params(self, vmid: int, online: bool) -> dict[str, Any]:
answer = self._guest_api(vmid, "vm").migrate.get() or {}
params: dict[str, Any] = {}
if online and to_flag(answer.get("running")):
params["online"] = 1
if qemu_local(answer)[0]:
params["with-local-disks"] = 1
return params
def _lxc_params(self, vmid: int) -> dict[str, Any]:
# A container cannot move while running; restart mode stops and restarts it.
return {"restart": 1} if self._lxc_running(vmid) else {}
def _task_errors(self, upid: str) -> list[str]:
try:
log = self._node_api().tasks(upid).log.get(limit=_TASK_LOG_LINES) or []
except Exception as exc:
logger.debug("Cannot read the log of task %s: %s", upid, exc)
return []
return task_errors(log)
def _follow_task(self, upid: str, vmid: int, timeout: int) -> None:
try:
self._wait_for_task(upid, timeout=timeout)
except RuntimeError as exc:
errors = self._task_errors(upid)
if not errors:
raise
raise RuntimeError(f"Migration of guest {vmid} failed: {'; '.join(errors)}") from exc
# -- a guest HA manages -------------------------------------------------------
def _ha_state(self, sid: str) -> tuple[str | None, str | None]:
rows = self._api.cluster.ha.status.current.get() or []
service: _JsonDict = next((r for r in rows if r.get("sid") == sid), {})
return service.get("node"), service.get("crm_state") or service.get("state")
def _follow_ha(
self, vmid: int, vm_type: str, target: str, deadline: float, ha_upid: str
) -> None:
sid = f"{'vm' if vm_type == 'vm' else 'ct'}:{vmid}"
moving_seen = False
while True:
node, state = self._ha_state(sid)
if node == target and state not in _HA_MOVING:
return
if state == "error":
self._ha_failed(vmid, vm_type, ha_upid, f"HA manager put {sid} into error state")
if state in _HA_MOVING:
moving_seen = True
elif moving_seen:
self._ha_failed(
vmid, vm_type, ha_upid, f"HA manager left {sid} on {node} ({state})"
)
if monotonic() > deadline:
raise RuntimeError(
f"Migration of {sid} to {target!r} timed out on {node} ({state})"
)
sleep(_HA_POLL_SECONDS)
def _ha_failed(self, vmid: int, vm_type: str, ha_upid: str, what: str) -> None:
"""Raise *what* with the ERROR lines of the migration the HA manager ran."""
errors: list[str] = []
kind = "qmigrate" if vm_type == "vm" else "vzmigrate"
try:
tasks = self._node_api().tasks.get(vmid=vmid, typefilter=kind, limit=1) or []
since = int(upid_field(ha_upid, 4) or "0", 16)
if tasks and int(tasks[0].get("starttime") or 0) >= since:
errors = self._task_errors(str(tasks[0].get("upid")))
except Exception as exc:
logger.debug("Cannot find the migration task of guest %s: %s", vmid, exc)
raise RuntimeError(f"{what}: {'; '.join(errors)}" if errors else what)
# -- HA maintenance -----------------------------------------------------------
def set_node_maintenance(self, node: str, enabled: bool) -> None:
"""Switch HA maintenance mode of a cluster node, over SSH (no REST endpoint)."""
names = [m.name for m in self._cluster_members()]
if node not in names:
raise ValueError(
f"{node!r} is not a member of the cluster (members: {', '.join(names)})"
)
action = "enable" if enabled else "disable"
try:
self._node_ssh()
except Exception as exc:
raise RuntimeError(
f"Cannot {action} HA maintenance of node {node!r}: SSH to {self.hostname} "
f"is not available ({exc})"
) from exc
command = f"ha-manager crm-command node-maintenance {action} {shlex.quote(node)}"
try:
self._run_node_command(command, timeout=self.timeout)
except Exception as exc:
raise RuntimeError(
f"ha-manager refused to {action} maintenance of {node!r}: {exc}"
) from exc