fix(vm): get_vm_status reads status/current (NetOrk/netork#2696)
get_vm_status answered "running" for every VM whose config could be read and never asked Proxmox for the VM's state, so a caller waiting for a clean shutdown never saw the VM stop. It now reads status/current and maps it with qemu_status, the mapping get_vms() uses: running, stopped, or paused for a qmpstatus of paused or suspended. The guest agent is asked for an address only while the VM runs; wait_for_ip ends at once with a RuntimeError when the VM is stopped or paused. Closes #72
This commit is contained in:
1 parent
ad3b5b29a9
commit
cae4859383
5 files changed
+190
-58
No files matched your search
@@ -29,6 +29,7 @@ from napalm_device_types.provisioning import (
|
||||
from napalm_proxmox.image_names import cache_name, import_volume_name, split_checksum
|
||||
from napalm_proxmox.network_targets import bridge_targets, vnet_target
|
||||
from napalm_proxmox.utils import cpu_flags
|
||||
from napalm_proxmox.vm_mixin import qemu_status
|
||||
|
||||
if TYPE_CHECKING:
|
||||
# Type-only: VMCpuTypeDict is newer than the napalm_device_types floor in
|
||||
@@ -874,6 +875,11 @@ class ProxmoxVMProvisionMixin:
|
||||
"""
|
||||
Get the runtime status of a virtual machine.
|
||||
|
||||
The status is what ``GET /nodes/{node}/qemu/{vmid}/status/current`` says:
|
||||
``running``, ``stopped``, or ``paused`` where its ``qmpstatus`` is paused or
|
||||
suspended (``qemu_status``, as ``get_vms()`` lists it). Only a running VM's
|
||||
guest agent is asked for an address (NAPALM/napalm-proxmox#72).
|
||||
|
||||
Optionally waits for the guest-agent to report an IP address on the
|
||||
management NIC (net0), useful after provisioning.
|
||||
|
||||
@@ -885,70 +891,36 @@ class ProxmoxVMProvisionMixin:
|
||||
|
||||
Returns:
|
||||
{"status": str, "ip_address": str, "hostname": str, "mac_address": str}
|
||||
(ip_address, hostname, mac_address only if VM is running and has network info)
|
||||
(ip_address, hostname, mac_address only if VM is running and has network
|
||||
info); {"status": "unknown"} when Proxmox gives no status for the vmid.
|
||||
|
||||
Raises:
|
||||
RuntimeError: VM doesn't exist or wait_for_ip times out
|
||||
RuntimeError: wait_for_ip times out, or the VM is not running while
|
||||
waiting (a stopped or paused VM reports no address)
|
||||
"""
|
||||
try:
|
||||
vmid_int = int(vmid)
|
||||
vm = self._node_api().qemu(int(vmid))
|
||||
_logger.debug(f"Getting status for VM {vmid}")
|
||||
|
||||
# VM must exist / be readable before we start polling.
|
||||
try:
|
||||
self._node_api().qemu(vmid_int).config.get()
|
||||
except Exception:
|
||||
# VM may not exist yet or config not readable
|
||||
# The VM must exist / be readable before we start polling.
|
||||
status = self._qemu_current_status(vm, vmid)
|
||||
if status is None:
|
||||
return {"status": "unknown"}
|
||||
|
||||
# Polling loop
|
||||
start_time = time.time()
|
||||
while True:
|
||||
elapsed = time.time() - start_time
|
||||
if wait_for_ip and elapsed > timeout:
|
||||
if status != "running":
|
||||
if wait_for_ip:
|
||||
raise RuntimeError(f"VM {vmid} is {status}: it reports no IP address")
|
||||
return {"status": status}
|
||||
if wait_for_ip and time.time() - start_time > timeout:
|
||||
raise RuntimeError(f"VM {vmid} failed to acquire IP within {timeout}s")
|
||||
|
||||
try:
|
||||
# Query guest-agent network interfaces. Proxmox's REST path is
|
||||
# "network-get-interfaces" (hyphens) — it must be passed as a
|
||||
# resource id via __call__, not dotted attribute access (which
|
||||
# would silently build a non-existent "network_get_interfaces"
|
||||
# path and 404 on every poll).
|
||||
agent_info = (
|
||||
self._node_api().qemu(vmid_int).agent("network-get-interfaces").get()
|
||||
)
|
||||
interfaces = (agent_info or {}).get("result", [])
|
||||
|
||||
# The guest agent does not report interfaces in a fixed order —
|
||||
# loopback commonly comes first, named "lo" on Linux and
|
||||
# "lo0" on the BSDs. Skip loopback addresses, whatever the
|
||||
# interface is called, and take the first IPv4 address.
|
||||
for iface in interfaces:
|
||||
name = iface.get("name", "")
|
||||
if not name:
|
||||
continue
|
||||
for addr in iface.get("ip-addresses", []):
|
||||
if addr.get("ip-address-type") != "ipv4":
|
||||
continue
|
||||
ip_addr = addr.get("ip-address", "")
|
||||
if ip_addr and not ipaddress.ip_address(ip_addr).is_loopback:
|
||||
_logger.info(f"VM {vmid} acquired IP {ip_addr}")
|
||||
return {
|
||||
"status": "running",
|
||||
"ip_address": ip_addr,
|
||||
"hostname": name,
|
||||
"mac_address": iface.get("hardware-address", ""),
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
_logger.debug(f"Error querying guest-agent for VM {vmid}: {e}")
|
||||
|
||||
address = self._guest_agent_address(vm, vmid)
|
||||
if address is not None:
|
||||
return {"status": "running", **address}
|
||||
if not wait_for_ip:
|
||||
# Return immediate status without IP
|
||||
return {"status": "running"}
|
||||
|
||||
# Wait before next poll
|
||||
time.sleep(poll_interval)
|
||||
# A status that does not read this round keeps the last one.
|
||||
status = self._qemu_current_status(vm, vmid) or status
|
||||
|
||||
except RuntimeError:
|
||||
raise
|
||||
@@ -956,6 +928,48 @@ class ProxmoxVMProvisionMixin:
|
||||
_logger.exception(f"Error getting status for VM {vmid}: {e}")
|
||||
raise RuntimeError(f"Failed to get VM {vmid} status: {e}") from e
|
||||
|
||||
@staticmethod
|
||||
def _qemu_current_status(vm: Any, vmid: str) -> str | None:
|
||||
"""The VM's status from ``status/current``; None when it does not read."""
|
||||
try:
|
||||
return qemu_status(vm.status.current.get() or {})
|
||||
except Exception as e:
|
||||
_logger.debug(f"Could not read the status of VM {vmid}: {e}")
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _guest_agent_address(vm: Any, vmid: str) -> dict[str, str] | None:
|
||||
"""The first non-loopback IPv4 address the guest agent reports, or None."""
|
||||
try:
|
||||
# Proxmox's REST path is "network-get-interfaces" (hyphens) — it must
|
||||
# be passed as a resource id via __call__, not dotted attribute access
|
||||
# (which would silently build a non-existent "network_get_interfaces"
|
||||
# path and 404 on every poll).
|
||||
agent_info = vm.agent("network-get-interfaces").get()
|
||||
except Exception as e:
|
||||
_logger.debug(f"Error querying guest-agent for VM {vmid}: {e}")
|
||||
return None
|
||||
# The guest agent does not report interfaces in a fixed order — loopback
|
||||
# commonly comes first, named "lo" on Linux and "lo0" on the BSDs. Skip
|
||||
# loopback addresses, whatever the interface is called, and take the first
|
||||
# IPv4 address.
|
||||
for iface in (agent_info or {}).get("result", []):
|
||||
name = iface.get("name", "")
|
||||
if not name:
|
||||
continue
|
||||
for addr in iface.get("ip-addresses", []):
|
||||
if addr.get("ip-address-type") != "ipv4":
|
||||
continue
|
||||
ip_addr = addr.get("ip-address", "")
|
||||
if ip_addr and not ipaddress.ip_address(ip_addr).is_loopback:
|
||||
_logger.info(f"VM {vmid} acquired IP {ip_addr}")
|
||||
return {
|
||||
"ip_address": ip_addr,
|
||||
"hostname": name,
|
||||
"mac_address": iface.get("hardware-address", ""),
|
||||
}
|
||||
return None
|
||||
|
||||
def get_network_targets(self) -> list[NetworkTargetDict]:
|
||||
"""
|
||||
List selectable network targets (bridges + SDN vnets) for a new VM's NIC.
|
||||
|
||||
Reference in new issue
Block a user