Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8159566ff4 | ||
|
|
b80a3950ac | ||
|
|
cae4859383 |
No files matched your search
@@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.12.0] - 2026-11-26
|
||||
|
||||
### Fixed
|
||||
- `get_vm_status(vmid)` reports the VM's real state (#72): it reads
|
||||
`GET /nodes/{node}/qemu/{vmid}/status/current` and answers `running`, `stopped`, or
|
||||
`paused` for a `qmpstatus` of paused or suspended, the same as `get_vms()`. It used to say
|
||||
`running` for every VM whose config could be read, so a caller waiting for a clean shutdown
|
||||
never saw the VM stop (NetOrk/netork's workflow step "Shut down Proxmox VM" always ran into
|
||||
its timeout). The guest agent is asked for an address only while the VM runs, and
|
||||
`wait_for_ip=True` ends with a `RuntimeError` at once when the VM is stopped or paused,
|
||||
rather than waiting out its timeout for an address that cannot come.
|
||||
|
||||
## [0.11.0] - 2026-11-25
|
||||
|
||||
### Added
|
||||
|
||||
@@ -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.
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "napalm-proxmox"
|
||||
version = "0.11.0"
|
||||
version = "0.12.0"
|
||||
description = "NAPALM drivers for Proxmox VE (classic Linux networking, SDN, OVS) and Proxmox Backup Server"
|
||||
readme = "README.md"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vm_interfaces": 37,
|
||||
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vms": 21,
|
||||
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.create_vm_from_cloud_init": 18,
|
||||
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.get_vm_status": 16
|
||||
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.get_vm_status": 12
|
||||
},
|
||||
"function_lines": {
|
||||
"napalm_proxmox/interfaces_mixin.py::ProxmoxInterfaceMixin.get_mac_address_table": 71,
|
||||
@@ -34,7 +34,7 @@
|
||||
"napalm_proxmox/vm_mixin.py::ProxmoxVMMixin.get_vms": 114,
|
||||
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.create_vm_from_cloud_init": 220,
|
||||
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.destroy_vm": 56,
|
||||
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.get_vm_status": 92
|
||||
"napalm_proxmox/vm_provision_mixin.py::ProxmoxVMProvisionMixin.get_vm_status": 63
|
||||
},
|
||||
"mypy_relaxed": [
|
||||
"napalm_proxmox.config_mixin",
|
||||
|
||||
@@ -201,7 +201,7 @@ class TestLoopbackIsNeverTheVmsAddress:
|
||||
mixin = ProxmoxVMProvisionMixin()
|
||||
node = MagicMock()
|
||||
mixin._node_api = MagicMock(return_value=node)
|
||||
node.qemu.return_value.config.get.return_value = {"net0": "virtio,bridge=vmbr0"}
|
||||
node.qemu.return_value.status.current.get.return_value = {"status": "running"}
|
||||
node.qemu.return_value.agent.return_value.get.return_value = {"result": interfaces}
|
||||
with patch("time.sleep"):
|
||||
return mixin.get_vm_status("101", wait_for_ip=True, timeout=30, poll_interval=1)
|
||||
|
||||
@@ -336,7 +336,7 @@ def test_get_vm_status_with_wait_for_ip():
|
||||
# Mock VM config
|
||||
mock_vm = MagicMock()
|
||||
mock_node.qemu.return_value = mock_vm
|
||||
mock_vm.config.get.return_value = {"net0": "virtio,bridge=vmbr0,tag=10"}
|
||||
mock_vm.status.current.get.return_value = _RUNNING
|
||||
|
||||
# The real Proxmox REST path is "network-get-interfaces" (hyphens),
|
||||
# reached via agent(...) as a callable resource, not dotted attribute
|
||||
@@ -375,7 +375,7 @@ def test_get_vm_status_skips_loopback_interface():
|
||||
|
||||
mock_vm = MagicMock()
|
||||
mock_node.qemu.return_value = mock_vm
|
||||
mock_vm.config.get.return_value = {"net0": "virtio,bridge=vmbr0"}
|
||||
mock_vm.status.current.get.return_value = _RUNNING
|
||||
|
||||
mock_agent_call = MagicMock()
|
||||
mock_vm.agent.return_value = mock_agent_call
|
||||
@@ -410,7 +410,7 @@ def test_get_vm_status_timeout_waiting_for_ip():
|
||||
# Mock VM config
|
||||
mock_vm = MagicMock()
|
||||
mock_node.qemu.return_value = mock_vm
|
||||
mock_vm.config.get.return_value = {"net0": "virtio,bridge=vmbr0"}
|
||||
mock_vm.status.current.get.return_value = _RUNNING
|
||||
|
||||
# Mock guest-agent that never returns IP
|
||||
mock_agent_call = MagicMock()
|
||||
@@ -424,6 +424,114 @@ def test_get_vm_status_timeout_waiting_for_ip():
|
||||
mixin.get_vm_status("101", wait_for_ip=True, timeout=1, poll_interval=0.5)
|
||||
|
||||
|
||||
_RUNNING = {"status": "running", "qmpstatus": "running"}
|
||||
_ETH0 = {
|
||||
"name": "eth0",
|
||||
"hardware-address": "aa:bb:cc:dd:ee:00",
|
||||
"ip-addresses": [{"ip-address": "10.0.0.100", "ip-address-type": "ipv4"}],
|
||||
}
|
||||
|
||||
|
||||
def _status_of(current, interfaces=()):
|
||||
"""A mixin whose VM 101 answers ``status/current`` with *current*."""
|
||||
mixin = ProxmoxVMProvisionMixin()
|
||||
node = MagicMock()
|
||||
mixin._node_api = MagicMock(return_value=node)
|
||||
vm = node.qemu.return_value
|
||||
if isinstance(current, list):
|
||||
vm.status.current.get.side_effect = current
|
||||
else:
|
||||
vm.status.current.get.return_value = current
|
||||
vm.agent.return_value.get.return_value = {"result": list(interfaces)}
|
||||
return mixin, vm
|
||||
|
||||
|
||||
class TestTheStatusIsWhatProxmoxSays:
|
||||
"""``status/current``, not whether the config reads (NAPALM/napalm-proxmox#72).
|
||||
|
||||
The guest agent is asked for an address only while the VM runs.
|
||||
"""
|
||||
|
||||
def test_a_stopped_vm_is_stopped(self):
|
||||
mixin, vm = _status_of({"status": "stopped", "qmpstatus": "stopped"})
|
||||
|
||||
assert mixin.get_vm_status("101") == {"status": "stopped"}
|
||||
vm.status.current.get.assert_called_once_with()
|
||||
vm.agent.assert_not_called()
|
||||
|
||||
@pytest.mark.parametrize("qmpstatus", ["paused", "suspended"])
|
||||
def test_a_paused_vm_is_paused(self, qmpstatus):
|
||||
mixin, vm = _status_of({"status": "running", "qmpstatus": qmpstatus})
|
||||
|
||||
assert mixin.get_vm_status("101") == {"status": "paused"}
|
||||
vm.agent.assert_not_called()
|
||||
|
||||
def test_a_running_vm_is_running_with_its_address(self):
|
||||
mixin, _vm = _status_of(_RUNNING, [_ETH0])
|
||||
|
||||
assert mixin.get_vm_status("101") == {
|
||||
"status": "running",
|
||||
"ip_address": "10.0.0.100",
|
||||
"hostname": "eth0",
|
||||
"mac_address": "aa:bb:cc:dd:ee:00",
|
||||
}
|
||||
|
||||
def test_a_running_vm_whose_agent_does_not_answer_is_running(self):
|
||||
mixin, vm = _status_of(_RUNNING)
|
||||
vm.agent.return_value.get.side_effect = Exception("QEMU guest agent is not running")
|
||||
|
||||
assert mixin.get_vm_status("101") == {"status": "running"}
|
||||
|
||||
def test_a_vm_proxmox_does_not_have_is_unknown(self):
|
||||
mixin, vm = _status_of({})
|
||||
vm.status.current.get.side_effect = Exception("Configuration file does not exist")
|
||||
|
||||
assert mixin.get_vm_status("999") == {"status": "unknown"}
|
||||
|
||||
def test_waiting_for_an_address_ends_when_the_vm_stops(self):
|
||||
"""A VM that stopped will report no address: the wait ends with an error at once."""
|
||||
mixin, vm = _status_of([_RUNNING, {"status": "stopped"}])
|
||||
|
||||
with pytest.raises(RuntimeError, match="stopped"):
|
||||
with patch("time.sleep"):
|
||||
mixin.get_vm_status("101", wait_for_ip=True, timeout=300, poll_interval=1)
|
||||
assert vm.agent.return_value.get.call_count == 1
|
||||
|
||||
def test_waiting_for_an_address_of_a_paused_vm_does_not_ask_the_agent(self):
|
||||
mixin, vm = _status_of({"status": "running", "qmpstatus": "paused"})
|
||||
|
||||
with pytest.raises(RuntimeError, match="paused"):
|
||||
mixin.get_vm_status("101", wait_for_ip=True, timeout=300, poll_interval=1)
|
||||
vm.agent.assert_not_called()
|
||||
|
||||
def test_waiting_reads_the_status_again_on_each_round(self):
|
||||
mixin, vm = _status_of([_RUNNING, _RUNNING, _RUNNING])
|
||||
vm.agent.return_value.get.side_effect = [
|
||||
{"result": []},
|
||||
{"result": []},
|
||||
{"result": [_ETH0]},
|
||||
]
|
||||
|
||||
with patch("time.sleep"):
|
||||
result = mixin.get_vm_status("101", wait_for_ip=True, timeout=300, poll_interval=1)
|
||||
|
||||
assert result["ip_address"] == "10.0.0.100"
|
||||
assert vm.status.current.get.call_count == 3
|
||||
|
||||
def test_a_status_that_does_not_read_while_waiting_keeps_the_wait_going(self):
|
||||
mixin, vm = _status_of([_RUNNING, Exception("timed out"), _RUNNING])
|
||||
vm.agent.return_value.get.side_effect = [
|
||||
{"result": []},
|
||||
{"result": []},
|
||||
{"result": [_ETH0]},
|
||||
]
|
||||
|
||||
with patch("time.sleep"):
|
||||
result = mixin.get_vm_status("101", wait_for_ip=True, timeout=300, poll_interval=1)
|
||||
|
||||
assert result["ip_address"] == "10.0.0.100"
|
||||
|
||||
|
||||
def test_destroy_vm_success():
|
||||
"""destroy_vm stops running VM, deletes it, cleans up snippets."""
|
||||
mixin = ProxmoxVMProvisionMixin()
|
||||
|
||||
Reference in new issue
Block a user