Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
fix: keep other sources' links on import, and match unpadded MACs (#558)
Pouzor - Rémy Jardient374d99b80e41
diff --git a/backend/app/api/routes/proxmox.py b/backend/app/api/routes/proxmox.pyindex e2dacc6..ea22216 100644--- a/backend/app/api/routes/proxmox.py+++ b/backend/app/api/routes/proxmox.py@@ -354,7 +354,8 @@ async def _persist_pending_import(# the address that would have matched them.await reconcile_duplicates(db)- links_recorded = await _replace_links(db, edges_raw, cluster_pairs)+ imported = {n["ieee_address"] for n in nodes_raw if n.get("ieee_address")}+ links_recorded = await _replace_links(db, imported, edges_raw, cluster_pairs)await db.commit()return ProxmoxImportPendingResponse(@@ -532,17 +533,29 @@ async def _ensure_inventory_row(async def _replace_links(db: AsyncSession,+ imported: set[str],edges_raw: list[dict[str, Any]],cluster_pairs: list[tuple[str, str]],) -> int:- """Wipe all proxmox-source links and re-insert the freshly discovered set.+ """Wipe this import's proxmox-source links and re-insert the fresh set.Two link shapes: host→guest (``proxmox`` → 'virtual' edges) and host↔host(``proxmox_cluster`` → 'cluster' edges).++ Only links touching a device in ``imported`` (the ieees this import+ returned) are wiped. One import is one Proxmox endpoint, not the whole+ truth: a second standalone server imported after the first used to erase+ the first one's host→guest links, since the wipe covered every proxmox+ link in the table. A guest that moved to another host of the same cluster+ still loses its old link — its previous host is part of this import."""await db.execute(sa_delete(InventoryDeviceLink).where(- InventoryDeviceLink.discovery_source.in_([_PROXMOX_GUEST_SOURCE, _PROXMOX_CLUSTER_SOURCE])+ InventoryDeviceLink.discovery_source.in_([_PROXMOX_GUEST_SOURCE, _PROXMOX_CLUSTER_SOURCE]),+ or_(+ InventoryDeviceLink.source_ieee.in_(imported),+ InventoryDeviceLink.target_ieee.in_(imported),+ ),))recorded = 0diff --git a/backend/app/api/routes/zigbee.py b/backend/app/api/routes/zigbee.pyindex b1fe700..6835528 100644--- a/backend/app/api/routes/zigbee.py+++ b/backend/app/api/routes/zigbee.py@@ -6,7 +6,7 @@ from typing import Anyfrom fastapi import APIRouter, BackgroundTasks, Depends, HTTPExceptionfrom sqlalchemy import delete as sa_delete-from sqlalchemy import select+from sqlalchemy import or_, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.api.deps import get_current_user@@ -269,7 +269,7 @@ async def _persist_pending_import("""Upsert nodes/edges into device_inventory + device_inventory_links.Coordinator auto-approves to a canvas Node. Other devices upsert by IEEE.- All zigbee-source links are wiped and re-inserted from the new map.+ This network's zigbee-source links are wiped and re-inserted from the new map."""# Repair any pre-existing duplicate nodes (same IEEE) before upserting, so# the by-IEEE lookups below resolve to a single row.@@ -343,12 +343,20 @@ async def _persist_pending_import(passpending_updated += 1- # Replace all zigbee-source links with the freshly discovered set.+ # Replace this network's zigbee-source links with the freshly discovered+ # set. Only links touching a device this import returned: one import is one+ # Zigbee2MQTT instance, and wiping every zigbee link erased the map of a+ # second network imported earlier.+ imported = {n["ieee_address"] for n in nodes_raw if n.get("ieee_address")}await db.execute(sa_delete(InventoryDeviceLink).where(# Both sources, or mesh links would pile up import after import:# the wipe below is what keeps this a replace, not an append.- InventoryDeviceLink.discovery_source.in_(["zigbee", "zigbee_mesh"])+ InventoryDeviceLink.discovery_source.in_(["zigbee", "zigbee_mesh"]),+ or_(+ InventoryDeviceLink.source_ieee.in_(imported),+ InventoryDeviceLink.target_ieee.in_(imported),+ ),))diff --git a/backend/app/api/routes/zwave.py b/backend/app/api/routes/zwave.pyindex c23a5cb..960eb27 100644--- a/backend/app/api/routes/zwave.py+++ b/backend/app/api/routes/zwave.py@@ -6,7 +6,7 @@ from typing import Anyfrom fastapi import APIRouter, BackgroundTasks, Depends, HTTPExceptionfrom sqlalchemy import delete as sa_delete-from sqlalchemy import select+from sqlalchemy import or_, selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom app.api.deps import get_current_user@@ -203,7 +203,8 @@ async def _persist_pending_import("""Upsert nodes/edges into device_inventory + device_inventory_links.Coordinator auto-approves to a canvas Node. Other devices upsert by Z-Wave- identity. All zwave-source links are wiped and re-inserted from the new map.+ identity. This network's zwave-source links are wiped and re-inserted from+ the new map."""# Repair any pre-existing same-canvas duplicate nodes before upserting, so# the by-IEEE lookups below resolve cleanly.@@ -271,9 +272,19 @@ async def _persist_pending_import(passpending_updated += 1- # Replace all zwave-source links with the freshly discovered set.+ # Replace this network's zwave-source links with the freshly discovered+ # set. Only links touching a device this import returned: one import is one+ # controller, and wiping every zwave link erased the map of a second+ # network imported earlier.+ imported = {n["ieee_address"] for n in nodes_raw if n.get("ieee_address")}await db.execute(- sa_delete(InventoryDeviceLink).where(InventoryDeviceLink.discovery_source == "zwave")+ sa_delete(InventoryDeviceLink).where(+ InventoryDeviceLink.discovery_source == "zwave",+ or_(+ InventoryDeviceLink.source_ieee.in_(imported),+ InventoryDeviceLink.target_ieee.in_(imported),+ ),+ ))links_recorded = 0diff --git a/backend/app/services/mac_utils.py b/backend/app/services/mac_utils.pyindex b1ed5c3..84b86e5 100644--- a/backend/app/services/mac_utils.py+++ b/backend/app/services/mac_utils.py@@ -5,14 +5,29 @@ lowercase ``bc:24:11:..``, Proxmox config is often uppercase ``BC:24:11:..``).Canonicalizing on write *and* on compare lets cross-source dedup match a deviceby MAC with a plain ``==`` — the join key for merging an IP-scanned row with aProxmox-imported one.++Octets are zero-padded too: macOS ``arp -a`` drops leading zeros+(``2:c4:b5:83:1a:71``) where Proxmox reports ``02:c4:b5:83:1a:71``, and left+as they were the two never compared equal."""from __future__ import annotations+import re++_OCTET = re.compile(r"[0-9a-f]{1,2}")+def normalize_mac(mac: str | None) -> str | None:- """Canonical MAC: lowercase, ``-`` → ``:``, stripped. Blank/None → None."""+ """Canonical MAC: lowercase, ``-`` → ``:``, stripped, octets zero-padded.++ Blank/None → None. Anything that is not six colon-separated hex octets is+ returned lowercased but otherwise as given, rather than guessed at.+ """if not mac:return Nonenormalized = mac.strip().lower().replace("-", ":")+ octets = normalized.split(":")+ if len(octets) == 6 and all(_OCTET.fullmatch(o) for o in octets):+ return ":".join(o.zfill(2) for o in octets)return normalized or Nonediff --git a/backend/tests/test_mac_utils.py b/backend/tests/test_mac_utils.pyindex 465b157..77494bc 100644--- a/backend/tests/test_mac_utils.py+++ b/backend/tests/test_mac_utils.py@@ -12,6 +12,22 @@ def test_normalize_mac_lowercases_and_unifies_separators() -> None:assert normalize_mac(" BC:24:11:AA:BB:CC ") == "bc:24:11:aa:bb:cc"+def test_normalize_mac_pads_octets() -> None:+ # macOS `arp -a` drops leading zeros; Proxmox reports them.+ assert normalize_mac("2:c4:b5:83:1a:71") == "02:c4:b5:83:1a:71"+ assert normalize_mac("0:46:D8:3:93:2D") == "00:46:d8:03:93:2d"+ assert normalize_mac("50-2-91-c2-f2-91") == "50:02:91:c2:f2:91"+ assert normalize_mac("02:c4:b5:83:1a:71") == "02:c4:b5:83:1a:71"+++def test_normalize_mac_leaves_other_shapes_alone() -> None:+ # Not six hex octets: lowercased, never padded into something it is not.+ assert normalize_mac("0011.2233.4455") == "0011.2233.4455"+ assert normalize_mac("2:c4:b5:83:1a") == "2:c4:b5:83:1a"+ assert normalize_mac("2:c4:b5:83:1a:zz") == "2:c4:b5:83:1a:zz"+ assert normalize_mac("2:c4:b5:83:1a:711") == "2:c4:b5:83:1a:711"++def test_normalize_mac_blank_is_none() -> None:assert normalize_mac(None) is Noneassert normalize_mac("") is Nonediff --git a/backend/tests/test_proxmox_router.py b/backend/tests/test_proxmox_router.pyindex e7af63a..a29f873 100644--- a/backend/tests/test_proxmox_router.py+++ b/backend/tests/test_proxmox_router.py@@ -368,6 +368,27 @@ async def test_persist_merges_a_guest_that_moved_to_another_host(db_session) ->assert rows[0].ieee_address == "pve-pve2-802" # re-pointed to the new host+async def test_persist_merges_a_moved_guest_whose_mac_was_seen_unpadded(db_session) -> None:+ # A scan on macOS reads the MAC from `arp -a`, which drops leading zeros;+ # Proxmox reports them. Compared as written the two differed, so the MAC+ # fallback missed and a guest whose host was renamed was filed twice.+ await _persist_pending_import(+ db_session, [_guest_node(106, "10.0.0.5", mac="2:c4:b5:83:1a:71")], []+ )++ await _persist_pending_import(+ db_session,+ [_guest_node(106, "10.0.0.5", mac="02:C4:B5:83:1A:71", host="pve2")],+ [],+ )++ rows = (await db_session.execute(select(InventoryDevice))).scalars().all()+ assert len(rows) == 1+ assert rows[0].ieee_address == "pve-pve2-106"+ assert rows[0].mac == "02:c4:b5:83:1a:71"++@pytest.mark.asyncioasync def test_persist_never_repoints_a_mesh_ieee(db_session) -> None:# A zigbee/zwave ieee is a real hardware address. A Proxmox import that@@ -633,6 +654,73 @@ async def test_link_survives_and_resolves_onto_second_design(db_session) -> Noneassert (await db_session.execute(select(InventoryDeviceLink))).scalars().one()+def _server(host: str, vmid: int, ip: str) -> tuple[list[dict], list[dict]]:+ """One standalone Proxmox server: a host and one guest, as an import returns them."""+ host_ieee = f"pve-node-{host}"+ nodes = [+ {**_host_node(), "id": host_ieee, "ieee_address": host_ieee, "hostname": host, "label": host},+ _guest_node(vmid, ip, host=host),+ ]+ return nodes, [{"source": host_ieee, "target": f"pve-{host}-{vmid}"}]+++async def _proxmox_links(db_session) -> set[tuple[str, str, str]]:+ links = (await db_session.execute(select(InventoryDeviceLink))).scalars().all()+ return {(ln.source_ieee, ln.target_ieee, ln.discovery_source) for ln in links}+++async def test_importing_a_second_server_keeps_the_first_servers_links(db_session) -> None:+ # Regression (#502): two standalone servers imported in turn. The link wipe+ # covered every proxmox link, so importing B erased A's host→guest link.+ await _persist_pending_import(db_session, *_server("alpha", 101, "10.0.0.5"))+ await _persist_pending_import(db_session, *_server("beta", 201, "10.0.1.5"))++ assert await _proxmox_links(db_session) == {+ ("pve-node-alpha", "pve-alpha-101", "proxmox"),+ ("pve-node-beta", "pve-beta-201", "proxmox"),+ }+++async def test_importing_a_second_server_keeps_the_first_clusters_links(db_session) -> None:+ cluster = [+ {**_host_node(), "id": "pve-node-a", "ieee_address": "pve-node-a", "hostname": "a", "label": "a"},+ {**_host_node(), "id": "pve-node-b", "ieee_address": "pve-node-b", "hostname": "b", "label": "b"},+ ]+ await _persist_pending_import(db_session, cluster, [])+ await _persist_pending_import(db_session, *_server("beta", 201, "10.0.1.5"))++ assert ("pve-node-a", "pve-node-b", "proxmox_cluster") in await _proxmox_links(db_session)+ assert await _is_proxmox_cluster_member(db_session, "pve-node-a") is True+++async def test_reimport_still_drops_a_link_the_server_no_longer_reports(db_session) -> None:+ # The wipe is narrower, not gone: within one endpoint a re-import is still+ # the full truth. vm101 moved from host a to host b of the same cluster.+ hosts = [+ {**_host_node(), "id": "pve-node-a", "ieee_address": "pve-node-a", "hostname": "a", "label": "a"},+ {**_host_node(), "id": "pve-node-b", "ieee_address": "pve-node-b", "hostname": "b", "label": "b"},+ ]+ mac = "bc:24:11:00:00:01"+ await _persist_pending_import(+ db_session,+ [*hosts, _guest_node(101, "10.0.0.5", mac=mac, host="a")],+ [{"source": "pve-node-a", "target": "pve-a-101"}],+ )+ await _persist_pending_import(+ db_session,+ [*hosts, _guest_node(101, "10.0.0.5", mac=mac, host="b")],+ [{"source": "pve-node-b", "target": "pve-b-101"}],+ )++ assert await _proxmox_links(db_session) == {+ ("pve-node-a", "pve-node-b", "proxmox_cluster"),+ ("pve-node-b", "pve-b-101", "proxmox"),+ }++@pytest.mark.asyncioasync def test_persist_never_deletes(db_session) -> None:await _persist_pending_import(db_session, [_guest_node(101, "10.0.0.5")], [])diff --git a/backend/tests/test_zigbee_router.py b/backend/tests/test_zigbee_router.pyindex fc9688e..7cb5687 100644--- a/backend/tests/test_zigbee_router.py+++ b/backend/tests/test_zigbee_router.py@@ -528,6 +528,37 @@ async def test_persist_pending_import_wipes_mesh_links_too(db_session) -> None:assert rows[0].discovery_source == "zigbee"+async def test_importing_a_second_network_keeps_the_first_networks_links(db_session) -> None:+ """Regression: the wipe covered every zigbee link, so a second Zigbee2MQTT+ instance imported after the first erased the first one's map."""+ from sqlalchemy import select++ from app.api.routes.zigbee import _persist_pending_import+ from app.db.models import InventoryDeviceLink++ first_edges = [+ {"source": "0xCOORD", "target": "0xR1", "kind": "tree"},+ {"source": "0xR1", "target": "0xE1", "kind": "mesh"},+ ]+ await _persist_pending_import(db_session, _PENDING_NODES, first_edges)++ other = [+ {**_PENDING_NODES[0], "id": "0xCOORD2", "ieee_address": "0xCOORD2"},+ {**_PENDING_NODES[1], "id": "0xR9", "ieee_address": "0xR9"},+ ]+ await _persist_pending_import(+ db_session, other, [{"source": "0xCOORD2", "target": "0xR9", "kind": "tree"}]+ )++ rows = (await db_session.execute(select(InventoryDeviceLink))).scalars().all()+ assert {(r.source_ieee, r.target_ieee, r.discovery_source) for r in rows} == {+ ("0xCOORD", "0xR1", "zigbee"),+ ("0xR1", "0xE1", "zigbee_mesh"),+ ("0xCOORD2", "0xR9", "zigbee"),+ }++@pytest.mark.asyncioasync def test_persist_pending_import_sets_coordinator_pending_fields(db_session) -> None:"""Coordinator lands in pending carrying its vendor/model metadata."""diff --git a/backend/tests/test_zwave_router.py b/backend/tests/test_zwave_router.pyindex 96712cc..5fe1780 100644--- a/backend/tests/test_zwave_router.py+++ b/backend/tests/test_zwave_router.py@@ -343,6 +343,34 @@ async def test_persist_replaces_links(db_session) -> None:assert (rows[0].source_ieee, rows[0].target_ieee) == ("zwave-0xh-1", "zwave-0xh-2")+async def test_importing_a_second_network_keeps_the_first_networks_links(db_session) -> None:+ """Regression: the wipe covered every zwave link, so a second controller+ imported after the first erased the first one's map."""+ from sqlalchemy import select++ from app.api.routes.zwave import _persist_pending_import+ from app.db.models import InventoryDeviceLink++ await _persist_pending_import(+ db_session, _PENDING_NODES[:2], [{"source": "zwave-0xh-1", "target": "zwave-0xh-2"}]+ )++ other = [+ {**_PENDING_NODES[0], "id": "zwave-0xb-1", "ieee_address": "zwave-0xb-1"},+ {**_PENDING_NODES[1], "id": "zwave-0xb-2", "ieee_address": "zwave-0xb-2"},+ ]+ await _persist_pending_import(+ db_session, other, [{"source": "zwave-0xb-1", "target": "zwave-0xb-2"}]+ )++ rows = (await db_session.execute(select(InventoryDeviceLink))).scalars().all()+ assert {(r.source_ieee, r.target_ieee) for r in rows} == {+ ("zwave-0xh-1", "zwave-0xh-2"),+ ("zwave-0xb-1", "zwave-0xb-2"),+ }++@pytest.mark.asyncioasync def test_persist_sets_coordinator_pending_fields(db_session) -> None:"""Coordinator lands in pending carrying its vendor/model metadata."""