Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
fix(proxmox): match a guest by its own identity, not a shared IP
Pouzor29525bca8761
diff --git a/backend/app/api/routes/proxmox.py b/backend/app/api/routes/proxmox.pyindex fb8ab44..078f914 100644--- a/backend/app/api/routes/proxmox.py+++ b/backend/app/api/routes/proxmox.py@@ -52,6 +52,9 @@ router = APIRouter()# 'virtual' edges; host↔host cluster links render as 'cluster' edges._PROXMOX_GUEST_SOURCE = "proxmox"_PROXMOX_CLUSTER_SOURCE = "proxmox_cluster"+# Every imported guest/host carries a synthetic ieee under this prefix+# (``pve-node-{host}`` / ``pve-{host}-{vmid}``), built in proxmox_service.+_PVE_IEEE_PREFIX = "pve-"def _resolve_credentials(payload: ProxmoxConnectionRequest) -> tuple[str, str]:@@ -255,10 +258,12 @@ async def _persist_pending_import() -> ProxmoxImportPendingResponse:"""Upsert Proxmox nodes/edges into device_inventory + device_inventory_links.- Two-tier identity (order matters):- 1. Match an existing canvas Node or pending row by **IP** (merge into a- device previously found by a scan) — never duplicate.- 2. Else match by synthetic ``ieee_address`` (``pve-...``).+ Two-tier identity (order matters) — see ``_find_pending``:+ 1. Match by the synthetic ``ieee_address`` (``pve-{host}-{vmid}``), the+ only key that identifies a guest.+ 2. Else match an existing pending row by MAC, then IP, to merge into a+ device a scan found first — never duplicate. Rows already claimed by+ another Proxmox guest are excluded.Update-in-place only. Nothing is ever deleted; hidden rows stay hidden."""@@ -330,14 +335,45 @@ async def _persist_pending_import(async def _find_pending(db: AsyncSession, ieee: str, ip: str | None, mac: str | None) -> InventoryDevice | None:- filters = [InventoryDevice.ieee_address == ieee]- if ip:- filters.append(InventoryDevice.ip == ip)- if mac:- filters.append(InventoryDevice.mac == mac)- return (- await db.execute(select(InventoryDevice).where(or_(*filters)))+ """The inventory row this guest *is*, in strict precedence order.++ 1. The synthetic ``ieee_address`` (``pve-{host}-{vmid}``). Unique per guest+ and the only key that identifies one.+ 2. Else MAC, else IP — merging into a row an IP/ARP scan found first.++ An IP is not an identity: a duplicated static lease, a re-used DHCP address,+ two guests behind one NAT, or a container-bridge address several guests+ report to the agent all make one address describe several machines. So the+ fallback skips any row already claimed by a *different* Proxmox guest —+ matching one used to overwrite that guest's hostname, VMID and specs, and+ non-deterministically, since one flat OR with no ordering returned whichever+ row the database yielded first. Oldest row wins, so a re-import is stable.+ """+ exact = (+ await db.execute(+ select(InventoryDevice).where(InventoryDevice.ieee_address == ieee)+ )).scalars().first()+ if exact is not None:+ return exact++ unclaimed = or_(+ InventoryDevice.ieee_address.is_(None),+ ~InventoryDevice.ieee_address.startswith(_PVE_IEEE_PREFIX),+ )+ for column, value in ((InventoryDevice.mac, mac), (InventoryDevice.ip, ip)):+ if not value:+ continue+ row = (+ await db.execute(+ select(InventoryDevice)+ .where(column == value, unclaimed)+ .order_by(InventoryDevice.discovered_at, InventoryDevice.id)+ )+ ).scalars().first()+ if row is not None:+ return row+ return Nonedef _new_pending(@@ -380,7 +416,7 @@ def _sources_after_merge(row: InventoryDevice) -> list[str]:device (no ``pve-`` ieee) was found by a scan; keep an IP-scan source."""sources = add_source(row.discovery_sources, row.discovery_source)- was_scanned = not (row.ieee_address or "").startswith("pve-")+ was_scanned = not (row.ieee_address or "").startswith(_PVE_IEEE_PREFIX)if was_scanned and row.ip and not any(s in ("arp", "mdns") for s in sources):sources = add_source(sources, "arp")return add_source(sources, _PROXMOX_GUEST_SOURCE)diff --git a/backend/app/services/proxmox_service.py b/backend/app/services/proxmox_service.pyindex 9f62662..e0de8a1 100644--- a/backend/app/services/proxmox_service.py+++ b/backend/app/services/proxmox_service.py@@ -93,24 +93,52 @@ def _guest_type_to_homelable(kind: str) -> str:return "vm" if kind == "qemu" else "lxc"-def _extract_qemu_ip(agent_payload: dict[str, Any] | None) -> str | None:- """Pull the first non-loopback IPv4 from a qemu guest-agent interfaces reply."""+def _iface_ipv4(iface: Any) -> str | None:+ """First non-loopback IPv4 of one guest-agent interface entry."""+ if not isinstance(iface, dict):+ return None+ for addr in iface.get("ip-addresses") or []:+ if not isinstance(addr, dict):+ continue+ if addr.get("ip-address-type") != "ipv4":+ continue+ ip = addr.get("ip-address")+ if isinstance(ip, str) and ip and not ip.startswith("127."):+ return ip+ return None+++def _extract_qemu_ip(+ agent_payload: dict[str, Any] | None, mac: str | None = None+) -> str | None:+ """The guest's LAN IPv4 from a qemu guest-agent interfaces reply.++ Prefer the interface whose ``hardware-address`` is the NIC MAC from the+ guest ``/config`` — the agent lists every interface, and on a guest running+ Docker/k8s the bridge (``cni0``, ``flannel``, ``docker0``) can come first.+ Those addresses repeat across guests, and a shared address is what let one+ guest's import land on another's inventory row. Fall back to the first+ non-loopback IPv4 when no MAC is known or none matches.+ """if not agent_payload:return Noneresult = agent_payload.get("result")if not isinstance(result, list):return None- for iface in result:- if not isinstance(iface, dict):- continue- for addr in iface.get("ip-addresses") or []:- if not isinstance(addr, dict):+ wanted = normalize_mac(mac)+ if wanted:+ for iface in result:+ if not isinstance(iface, dict):continue- if addr.get("ip-address-type") != "ipv4":+ if normalize_mac(iface.get("hardware-address")) != wanted:continue- ip = addr.get("ip-address")- if isinstance(ip, str) and ip and not ip.startswith("127."):+ ip = _iface_ipv4(iface)+ if ip:return ip+ for iface in result:+ ip = _iface_ipv4(iface)+ if ip:+ return ipreturn None@@ -374,7 +402,7 @@ async def _resolve_guest_net(data = await _get_json(client, f"/nodes/{host_name}/qemu/{vmid}/agent/network-get-interfaces")- ip = _extract_qemu_ip(data)+ ip = _extract_qemu_ip(data, mac)else:config = await _get_json(client, f"/nodes/{host_name}/lxc/{vmid}/config")ip = _extract_lxc_ip(config)diff --git a/backend/tests/test_proxmox_router.py b/backend/tests/test_proxmox_router.pyindex 5fb5368..c3eafd3 100644--- a/backend/tests/test_proxmox_router.py+++ b/backend/tests/test_proxmox_router.py@@ -3,6 +3,7 @@from __future__ import annotationsimport uuid+from datetime import datetime, timezonefrom types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMock, patch@@ -273,6 +274,73 @@ async def test_persist_merges_pending_scan_row_by_mac(db_session) -> None:assert set(row.discovery_sources) == {"arp", "proxmox"} # shows in both filters+async def test_persist_never_overwrites_another_guest_row_on_a_shared_ip(db_session) -> None:+ # Issue #419: two guests report the same address (duplicate lease, re-used+ # DHCP, or a container bridge address the agent lists first). Importing 812+ # used to match 802's row on that IP and overwrite its hostname and specs,+ # leaving no row for the original guest.+ db_session.add(InventoryDevice(+ id=str(uuid.uuid4()), ieee_address="pve-pve1-802", ip="10.0.0.5",+ hostname="vm802", suggested_type="vm", status="pending",+ cpu_count=8, ram_gb=32.0, disk_gb=500.0,+ discovery_source="proxmox", discovery_sources=["proxmox"],+ ))+ await db_session.commit()++ await _persist_pending_import(db_session, [_guest_node(812, "10.0.0.5")], [])++ rows = (await db_session.execute(select(InventoryDevice))).scalars().all()+ assert len(rows) == 2 # 802 still its own row+ kept = next(r for r in rows if r.ieee_address == "pve-pve1-802")+ assert kept.hostname == "vm802" # not stomped by 812+ assert (kept.cpu_count, kept.ram_gb, kept.disk_gb) == (8, 32.0, 500.0)+ added = next(r for r in rows if r.ieee_address == "pve-pve1-812")+ assert added.hostname == "vm812"+++async def test_persist_matches_ieee_before_a_shared_ip(db_session) -> None:+ # Both rows exist and share an IP. The guest's own ieee wins over the other+ # row's matching address, whichever order the database yields them in.+ for vmid, hostname in ((802, "vm802"), (812, "stale")):+ db_session.add(InventoryDevice(+ id=str(uuid.uuid4()), ieee_address=f"pve-pve1-{vmid}", ip="10.0.0.5",+ hostname=hostname, suggested_type="vm", status="pending",+ discovery_source="proxmox", discovery_sources=["proxmox"],+ ))+ await db_session.commit()++ await _persist_pending_import(db_session, [_guest_node(812, "10.0.0.5")], [])++ rows = (await db_session.execute(select(InventoryDevice))).scalars().all()+ assert len(rows) == 2+ assert next(r for r in rows if r.ieee_address == "pve-pve1-802").hostname == "vm802"+ assert next(r for r in rows if r.ieee_address == "pve-pve1-812").hostname == "vm812"+++async def test_persist_merges_the_oldest_scan_row_when_two_share_an_ip(db_session) -> None:+ # Unclaimed scan rows on one address: pick deterministically (oldest), so a+ # re-import lands on the same row instead of whichever comes back first.+ for offset, mac in ((2, "aa:bb:cc:00:00:01"), (1, "aa:bb:cc:00:00:02")):+ db_session.add(InventoryDevice(+ id=str(uuid.uuid4()), ip="10.0.0.5", mac=mac,+ suggested_type="generic", status="pending",+ discovered_at=datetime(2026, 1, offset, tzinfo=timezone.utc),+ discovery_source="arp", discovery_sources=["arp"],+ ))+ await db_session.commit()++ for _ in range(2):+ await _persist_pending_import(db_session, [_guest_node(101, "10.0.0.5")], [])++ rows = (await db_session.execute(select(InventoryDevice))).scalars().all()+ assert len(rows) == 2 # merged, never a third+ merged = next(r for r in rows if r.ieee_address == "pve-pve1-101")+ assert merged.mac == "aa:bb:cc:00:00:02" # the older row++@pytest.mark.asyncioasync def test_persist_preserves_ip_tag_for_legacy_null_source_row(db_session) -> None:# Legacy inventory row from an old IP scan, before discovery_source(s) werediff --git a/backend/tests/test_proxmox_service.py b/backend/tests/test_proxmox_service.pyindex 321a6be..273df95 100644--- a/backend/tests/test_proxmox_service.py+++ b/backend/tests/test_proxmox_service.py@@ -30,6 +30,28 @@ def test_extract_qemu_ip_skips_loopback() -> None:assert svc._extract_qemu_ip({"result": []}) is None+def test_extract_qemu_ip_prefers_the_configured_nic() -> None:+ # A guest running k8s/Docker: the agent lists the CNI bridge first, and that+ # address repeats across guests. Pick the interface holding the NIC MAC from+ # /config instead (issue #419).+ payload = {+ "result": [+ {+ "name": "cni0", "hardware-address": "0a:58:0a:2a:00:01",+ "ip-addresses": [{"ip-address-type": "ipv4", "ip-address": "10.42.0.1"}],+ },+ {+ "name": "eth0", "hardware-address": "BC:24:11:AA:BB:CC",+ "ip-addresses": [{"ip-address-type": "ipv4", "ip-address": "192.168.1.20"}],+ },+ ]+ }+ assert svc._extract_qemu_ip(payload, "bc:24:11:aa:bb:cc") == "192.168.1.20"+ # No MAC known, or none matching: first non-loopback IPv4, as before.+ assert svc._extract_qemu_ip(payload) == "10.42.0.1"+ assert svc._extract_qemu_ip(payload, "de:ad:be:ef:00:00") == "10.42.0.1"++def test_extract_lxc_ip_parses_net0_static() -> None:cfg = {"net0": "name=eth0,bridge=vmbr0,ip=192.168.1.30/24,gw=192.168.1.1"}assert svc._extract_lxc_ip(cfg) == "192.168.1.30"