Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions proxbox_api/routes/virtualization/virtual_machines/CLAUDE.md
Original file line number Diff line number Diff line change
@@ -1 +1,16 @@
@AGENTS.md

## LXC DHCP runtime address discovery

LXC interfaces now use the read-only Proxmox
`GET /nodes/{node}/lxc/{vmid}/interfaces` endpoint in full VM network sync,
interface-only sync, and IP-only sync. Unlike QEMU, containers do not require
a guest agent. `services/proxmox_helpers.py` validates responses with the pinned
proxmox-sdk models and adapts both `ip-addresses` and legacy `inet`/`inet6` CIDRs
to the existing guest-interface shape. Existing MAC/name matching, IP filtering,
NetBox interface ownership, and core IP reconciliation remain authoritative.
Unavailable or malformed runtime data logs a secret-free warning and preserves
static-config fallback; cancellation propagates. No new API parameters, settings,
database migrations, or netbox-proxbox compatibility-floor changes are required.
Regression coverage: `tests/test_lxc_runtime_interfaces.py` and the LXC cases in
`tests/test_qemu_guest_agent_sync.py`.
29 changes: 16 additions & 13 deletions proxbox_api/routes/virtualization/virtual_machines/sync_vm.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,9 @@
)
from proxbox_api.services.proxmox.tag_styles import fetch_tag_color_map
from proxbox_api.services.proxmox_helpers import (
fetch_lxc_network_interfaces,
fetch_qemu_guest_agent_network_interfaces,
get_lxc_network_interfaces,
get_qemu_guest_agent_hostname,
get_qemu_guest_agent_network_interfaces,
sanitize_dns_hostname,
Expand Down Expand Up @@ -4291,7 +4293,7 @@ async def _vm_task_guest_interfaces(
vm_name: str,
timing_key: str,
) -> list[dict]:
if vm_type != "qemu" or not vm_config_obj.qemu_agent_enabled:
if vm_type != "lxc" and (vm_type != "qemu" or not vm_config_obj.qemu_agent_enabled):
return []
proxmox_session = next(
(
Expand All @@ -4303,7 +4305,12 @@ async def _vm_task_guest_interfaces(
)
if proxmox_session is None:
return []
result = await fetch_qemu_guest_agent_network_interfaces(
fetch_interfaces = (
fetch_lxc_network_interfaces
if vm_type == "lxc"
else fetch_qemu_guest_agent_network_interfaces
)
result = await fetch_interfaces(
proxmox_session,
node=str(resource.get("node")),
vmid=int(resource.get("vmid")),
Expand Down Expand Up @@ -5341,10 +5348,12 @@ async def _fetch_vm_interface_guest_data(
vmid: object,
vm_config: dict[str, object],
) -> list[dict[str, object]]:
if vm_type != "qemu" or not _parse_proxmox_kv_flag(vm_config.get("agent")):
return []
if not proxmox_session or not resource_node:
return []
if vm_type == "lxc":
return await get_lxc_network_interfaces(proxmox_session, resource_node, int(vmid))
if vm_type != "qemu" or not _parse_proxmox_kv_flag(vm_config.get("agent")):
return []
return (
await get_qemu_guest_agent_network_interfaces(
proxmox_session, resource_node, int(cast("int | str", vmid))
Expand Down Expand Up @@ -6211,15 +6220,9 @@ async def _sync_vm_ips(
"Could not fetch VM config for IP sync %s (vmid=%s): %s", vm_name, vmid, exc
)

guest_agent_interfaces: list[dict[str, object]] = []
if vm_type == "qemu" and _parse_proxmox_kv_flag(vm_config.get("agent")):
if proxmox_session and resource_node:
guest_agent_interfaces = (
await get_qemu_guest_agent_network_interfaces(
proxmox_session, resource_node, int(vmid)
)
or []
)
guest_agent_interfaces = await _fetch_vm_interface_guest_data(
proxmox_session, resource_node, vm_type, vmid, vm_config
)

guest_by_name = {
str(iface.get("name", "")).strip().lower(): iface for iface in guest_agent_interfaces
Expand Down
15 changes: 15 additions & 0 deletions proxbox_api/services/CLAUDE.md
Original file line number Diff line number Diff line change
@@ -1 +1,16 @@
@AGENTS.md

## LXC DHCP runtime address discovery

LXC interfaces now use the read-only Proxmox
`GET /nodes/{node}/lxc/{vmid}/interfaces` endpoint in full VM network sync,
interface-only sync, and IP-only sync. Unlike QEMU, containers do not require
a guest agent. `services/proxmox_helpers.py` validates responses with the pinned
proxmox-sdk models and adapts both `ip-addresses` and legacy `inet`/`inet6` CIDRs
to the existing guest-interface shape. Existing MAC/name matching, IP filtering,
NetBox interface ownership, and core IP reconciliation remain authoritative.
Unavailable or malformed runtime data logs a secret-free warning and preserves
static-config fallback; cancellation propagates. No new API parameters, settings,
database migrations, or netbox-proxbox compatibility-floor changes are required.
Regression coverage: `tests/test_lxc_runtime_interfaces.py` and the LXC cases in
`tests/test_qemu_guest_agent_sync.py`.
66 changes: 66 additions & 0 deletions proxbox_api/services/proxmox_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import asyncio
import functools
import ipaddress
import re
from collections.abc import Callable, Sequence
from contextlib import contextmanager
Expand Down Expand Up @@ -685,6 +686,71 @@ async def get_qemu_guest_agent_network_interfaces(
return result.interfaces


def _normalize_lxc_interfaces(payload: object) -> list[dict[str, object]]:
"""Adapt validated LXC runtime addresses to the shared guest-interface shape."""
model = generated_models.GetNodesNodeLxcVmidInterfacesResponse.model_validate(payload)
interfaces = []
for item in model.root:
interface = _model_dump(item)
interface["hardware-address"] = item.hardware_address or item.hwaddr
# Older PVE versions expose only one CIDR per family, without ip-addresses.
if not item.ip_addresses:
addresses = []
for cidr in (item.inet, item.inet6):
if not cidr:
continue
try:
address = ipaddress.ip_interface(cidr)
except ValueError:
continue
addresses.append(
{
"ip-address": str(address.ip),
"prefix": address.network.prefixlen,
"ip-address-type": "ipv4" if address.version == 4 else "ipv6",
}
)
interface["ip-addresses"] = addresses
interfaces.append(interface)
return _normalize_guest_agent_interfaces(interfaces)


@_dual_mode
async def fetch_lxc_network_interfaces(
session: ProxmoxSession,
node: str,
vmid: int,
) -> GuestAgentFetchResult:
"""Read live container addresses, including DHCP, without a QEMU guest agent."""
try:
payload = await resolve_async(session.session.nodes(node).lxc(vmid).interfaces.get())
return GuestAgentFetchResult(interfaces=_normalize_lxc_interfaces(payload), diagnostic=None)
except Exception as error:
# Stopped containers and restricted tokens may not expose runtime interfaces.
# Never log upstream exception text, which can contain credential material.
logger.warning(
"Unable to fetch LXC runtime interfaces for node=%s vmid=%s (%s)",
node,
vmid,
type(error).__name__,
)
return GuestAgentFetchResult(
interfaces=[],
diagnostic="LXC runtime interfaces unavailable; check container state and API permissions.",
)


@_dual_mode
async def get_lxc_network_interfaces(
session: ProxmoxSession,
node: str,
vmid: int,
) -> list[dict[str, object]]:
"""Return normalized LXC runtime interfaces, or config fallback on failure."""
result = await fetch_lxc_network_interfaces(session, node, vmid)
return result.interfaces


def sanitize_dns_hostname(value: object) -> str | None:
"""Normalize a guest hostname into a NetBox-acceptable dns_name.

Expand Down
84 changes: 84 additions & 0 deletions tests/test_lxc_runtime_interfaces.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
"""LXC runtime discovery supplies DHCP IPs without a QEMU guest agent."""

import asyncio
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock

import pytest

from proxbox_api.services.proxmox_helpers import (
fetch_lxc_network_interfaces,
get_lxc_network_interfaces,
)
from proxbox_api.services.sync.vm_helpers import all_guest_agent_ips


def _session(payload=None, error=None):
get = AsyncMock(return_value=payload, side_effect=error)
lxc = Mock(return_value=SimpleNamespace(interfaces=SimpleNamespace(get=get)))
nodes = Mock(return_value=SimpleNamespace(lxc=lxc))
return SimpleNamespace(session=SimpleNamespace(nodes=nodes)), nodes, lxc, get


@pytest.mark.parametrize("legacy", [False, True])
async def test_lxc_runtime_addresses_normalize_and_filter(legacy):
interface = {
"name": "eth0",
"hwaddr": "02:00:00:00:00:01",
"inet": "192.0.2.10/24",
"inet6": "fe80::1/64",
}
if not legacy:
interface["hardware-address"] = interface["hwaddr"]
interface["ip-addresses"] = [
{"ip-address": "192.0.2.10", "prefix": 24, "ip-address-type": "inet"},
{"ip-address": "2001:db8::10", "prefix": 64, "ip-address-type": "inet6"},
{"ip-address": "fe80::1", "prefix": 64, "ip-address-type": "inet6"},
]
session, nodes, lxc, get = _session(
[
{"name": "lo", "inet": "127.0.0.1/8", "inet6": "::1/128"},
interface,
]
)
result = await fetch_lxc_network_interfaces(session, "pve01", 110)
assert result.diagnostic is None
nodes.assert_called_once_with("pve01")
lxc.assert_called_once_with(110)
get.assert_awaited_once_with()
assert result.interfaces[1]["mac_address"] == "02:00:00:00:00:01"
expected = ["192.0.2.10/24"] if legacy else ["192.0.2.10/24", "2001:db8::10/64"]
assert all_guest_agent_ips(result.interfaces[1], True) == expected
assert all_guest_agent_ips(result.interfaces[0], True) == []


@pytest.mark.parametrize("payload", [[], [{"name": "eth0", "inet": "invalid"}]])
async def test_lxc_runtime_empty_or_invalid_address_does_not_invent_ip(payload):
session, *_ = _session(payload)
interfaces = await get_lxc_network_interfaces(session, "pve01", 110)
assert all(not iface["ip_addresses"] for iface in interfaces)


@pytest.mark.parametrize("payload", [{"unexpected": []}, ["invalid-interface"]])
async def test_lxc_runtime_invalid_collection_reports_unavailable(payload):
session, *_ = _session(payload)
result = await fetch_lxc_network_interfaces(session, "pve01", 110)
assert result.interfaces == []
assert result.diagnostic


async def test_lxc_runtime_failure_preserves_config_fallback_and_redacts_error(monkeypatch):
warning = Mock()
monkeypatch.setattr("proxbox_api.services.proxmox_helpers.logger.warning", warning)
session, *_ = _session(error=PermissionError("synthetic-secret-canary"))
result = await fetch_lxc_network_interfaces(session, "pve01", 110)
assert result.interfaces == []
assert result.diagnostic
assert "synthetic-secret-canary" not in str(warning.call_args)
assert "synthetic-secret-canary" not in result.diagnostic


async def test_lxc_runtime_cancellation_propagates():
session, *_ = _session(error=asyncio.CancelledError())
with pytest.raises(asyncio.CancelledError):
await fetch_lxc_network_interfaces(session, "pve01", 110)
30 changes: 25 additions & 5 deletions tests/test_qemu_guest_agent_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -370,13 +370,17 @@ async def _fake_role_scan(nb: object) -> VMRoleSnapshotScan:
assert len(scan_calls) == 1


def test_vm_sync_prefers_guest_agent_ip(monkeypatch):
@pytest.mark.parametrize("vm_type", ["qemu", "lxc"])
def test_vm_sync_prefers_guest_agent_ip(monkeypatch, vm_type):
data = _vm_sync_inputs(
{
"agent": 1,
"net0": "virtio=AA:BB:CC:DD:EE:FF,bridge=vmbr0,ip=10.0.0.20/24",
}
)
data["cluster_resources"][0]["lab"][0]["type"] = vm_type
if vm_type == "lxc":
data["vm_config"] = {"net0": "name=eth0,hwaddr=AA:BB:CC:DD:EE:FF,ip=dhcp"}
ip_payloads: list[dict] = []
_install_common_sync_patches(monkeypatch, vm_config=data["vm_config"], ip_payloads=ip_payloads)

Expand All @@ -395,8 +399,14 @@ async def _fake_guest_ifaces_with_ip(*args, **kwargs):
)

monkeypatch.setattr(
"proxbox_api.routes.virtualization.virtual_machines.sync_vm.fetch_qemu_guest_agent_network_interfaces",
"proxbox_api.routes.virtualization.virtual_machines.sync_vm."
+ (
"fetch_qemu_guest_agent_network_interfaces"
if vm_type == "qemu"
else "fetch_lxc_network_interfaces"
),
_fake_guest_ifaces_with_ip,
raising=False,
)

result = asyncio.run(
Expand Down Expand Up @@ -1204,13 +1214,17 @@ async def _fake_load_snapshot(nb):
assert primary_ip_calls[0]["primary_ip_id"] == 77


def test_vm_only_ip_sync_prefers_ipv4_primary_when_guest_reports_ipv6_first(monkeypatch):
@pytest.mark.parametrize("vm_type", ["qemu", "lxc"])
def test_vm_only_ip_sync_prefers_ipv4_primary_when_guest_reports_ipv6_first(monkeypatch, vm_type):
data = _vm_sync_inputs(
{
"agent": 1,
"net0": "virtio=AA:BB:CC:DD:EE:FF,bridge=vmbr0",
}
)
data["cluster_resources"][0]["lab"][0]["type"] = vm_type
if vm_type == "lxc":
data["vm_config"] = {"net0": "name=eth0,hwaddr=AA:BB:CC:DD:EE:FF,ip=dhcp"}
primary_ip_calls: list[dict[str, object]] = []

def _fake_get_vm_config(*args, **kwargs):
Expand Down Expand Up @@ -1246,7 +1260,7 @@ async def _fake_bulk_reconcile_ips(nb, payloads, **_kwargs):
]

async def _fake_rest_list(*args, **kwargs):
return [{"id": 66, "name": "net0", "virtual_machine": 55}]
return [{"id": 66, "name": "eth0" if vm_type == "lxc" else "net0", "virtual_machine": 55}]

async def _fake_rest_first(*args, **kwargs):
query = kwargs.get("query") or {}
Expand Down Expand Up @@ -1287,8 +1301,14 @@ async def _fake_load_snapshot(nb):
_fake_get_vm_config,
)
monkeypatch.setattr(
"proxbox_api.routes.virtualization.virtual_machines.sync_vm.get_qemu_guest_agent_network_interfaces",
"proxbox_api.routes.virtualization.virtual_machines.sync_vm."
+ (
"get_qemu_guest_agent_network_interfaces"
if vm_type == "qemu"
else "get_lxc_network_interfaces"
),
_fake_guest_ifaces,
raising=False,
)
monkeypatch.setattr(
"proxbox_api.routes.virtualization.virtual_machines.sync_vm.resolve_vm_sync_concurrency",
Expand Down