From dfe985bb9e98ef5e9b12a8d13ace3581b6a349a7 Mon Sep 17 00:00:00 2001 From: Louis Date: Wed, 4 Nov 2026 10:47:33 +0100 Subject: [PATCH] fix: assign only VLANs of the device's site; show notes prominently - VLANs of another site stay in the label but are not assigned to ports (NetBox rejects them); one note per device and VLAN instead of an error per port - Preview shows a notes badge and expands switches with notes; notes are also written to the log after the transfer Co-Authored-By: Claude Opus 5.5 --- netbox_sync/core/switches.py | 38 ++++++++++++++++++++++++++++++------ netbox_sync/ui/actions.py | 2 ++ netbox_sync/ui/dialogs.py | 9 +++++++-- tests/test_switch_sync.py | 16 +++++++++++++++ 4 files changed, 57 insertions(+), 8 deletions(-) diff --git a/netbox_sync/core/switches.py b/netbox_sync/core/switches.py index 0db0e93..63ecad0 100644 --- a/netbox_sync/core/switches.py +++ b/netbox_sync/core/switches.py @@ -1571,8 +1571,12 @@ def _sync_prefixes(nb, config, snapshot, tenant_id, vrf_ids, dry_run, report): report["errors"].append(f"Prefix {network}: {error}") -def _sync_vlans(nb, config, snapshot, tenant_id, site_id, dry_run, report): - """``{VLAN ID: NetBox ID}``; missing VLANs are only created when approved.""" +def _sync_vlans(nb, config, snapshot, tenant_id, site_id, dry_run, report, sites=None): + """``{VLAN ID: NetBox ID}``; missing VLANs are only created when approved. + + ``sites`` receives ``{VLAN ID: (site ID or None, name)}`` for the site check of the ports. + """ + sites = {} if sites is None else sites _vlans, matches = _switch_vlan_matches(nb, config, snapshot, tenant_id, site_id) approved = {int(vid) for vid, choice in (config.get("vlan_map") or {}).items() if choice.get("action") == "new"} approved |= {int(vid) for vid in config.get("create_vlans") or []} # profiles of version 4.4.0 @@ -1580,6 +1584,7 @@ def _sync_vlans(nb, config, snapshot, tenant_id, site_id, dry_run, report): for vid, (record, method, name) in matches.items(): if record is not None: present[vid] = record.id + sites[vid] = (related_id(record, "site"), getattr(record, "name", "") or str(vid)) continue if method != "new" or vid not in approved: continue @@ -1592,6 +1597,7 @@ def _sync_vlans(nb, config, snapshot, tenant_id, site_id, dry_run, report): if site_id: payload["site"] = site_id present[vid] = _NEW if dry_run else nb.ipam.vlans.create(payload).id + sites[vid] = (site_id, name) except Exception as error: # noqa: BLE001 report["errors"].append(f"VLAN {vid}: {error}") return present @@ -1676,6 +1682,24 @@ def _sync_switch_stack(nb, device, members, dry_run, report): report["errors"].append(f"Switch-Stack (NetBox Utilities): {error}") +def _vlans_for_site(vlan_ids, vlan_sites, site_id, owner, reported, report): + """VLANs a port of ``owner`` may use: NetBox only allows global VLANs or VLANs of the device's site. + + Other VLANs stay in the label; each is reported once per device. + """ + allowed = {} + for vid, netbox_id in vlan_ids.items(): + vlan_site, name = vlan_sites.get(vid, (None, str(vid))) + if vlan_site in (None, site_id): + allowed[vid] = netbox_id + elif (owner.id, vid) not in reported: + reported.add((owner.id, vid)) + report["notes"].append(f"VLAN {vid} „{name}“ gehört zu einem anderen Standort als {owner.name} – " + f"nur im Label vermerkt, nicht am Port zugewiesen (VLAN global machen, " + f"um es zuzuweisen)") + return allowed + + def _sync_lag_members(snapshot, owners, records, dry_run, report): """Assign member ports to their LAG interface (NetBox field ``lag``).""" names = {interface_key(item["name"]): item["name"] for item in snapshot["interfaces"]} @@ -1811,7 +1835,8 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa device_id = device.id vrf_ids = _sync_vrfs(nb, config, snapshot, tenant_id, dry_run, report) _sync_prefixes(nb, config, snapshot, tenant_id, vrf_ids, dry_run, report) - vlan_ids = _sync_vlans(nb, config, snapshot, tenant_id, related_id(device, "site"), dry_run, report) + vlan_sites = {} + vlan_ids = _sync_vlans(nb, config, snapshot, tenant_id, related_id(device, "site"), dry_run, report, vlan_sites) ignored = ignored_vlans(config.get("vlan_map")) members = stack_devices(nb, config, snapshot, device) owners = _interface_owners(snapshot, members, device) @@ -1823,7 +1848,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa and stack_member(name, snapshot.get("platform")) == member) report["notes"].append(f"Stack-Mitglied {member}: kein NetBox-Gerät gewählt – {skipped} Ports übersprungen") _sync_switch_stack(nb, device, members, dry_run, report) - records = {} + records, foreign = {}, set() for interface in snapshot["interfaces"]: key = interface_key(interface["name"]) @@ -1834,6 +1859,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa where = f" auf {owner.name}" if owner.id != device_id else "" port = dict(interface, vlans=without_vlans(interface.get("vlans"), ignored)) label = port_label(port["vlans"], interface.get("lag")) + owner_vlans = _vlans_for_site(vlan_ids, vlan_sites, related_id(owner, "site"), owner, foreign, report) try: if record: changes = {} @@ -1843,7 +1869,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa # routed ports and snapshots without configuration. if label and (getattr(record, "label", "") or "") != label: changes["label"] = label - changes.update(_vlan_assignment(port, vlan_ids, record)) + changes.update(_vlan_assignment(port, owner_vlans, record)) if changes: report["interfaces_updated"] += 1 texts = [] @@ -1868,7 +1894,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa } if label: payload["label"] = label - payload.update(_vlan_assignment(port, vlan_ids)) + payload.update(_vlan_assignment(port, owner_vlans)) if interface.get("description"): payload["description"] = interface["description"][:200] report["interfaces_created"] += 1 diff --git a/netbox_sync/ui/actions.py b/netbox_sync/ui/actions.py index 835faf9..c84cab3 100644 --- a/netbox_sync/ui/actions.py +++ b/netbox_sync/ui/actions.py @@ -530,6 +530,8 @@ class Actions: update_cables=update_cables) for error in report["errors"]: ctx.log(f"{switch['name']}: {error}", "error") + for note in report.get("notes", []): + ctx.log(f"{switch['name']}: {note}", "warning") reports.append((switch, report)) return reports diff --git a/netbox_sync/ui/dialogs.py b/netbox_sync/ui/dialogs.py index a20b4ac..78f9900 100644 --- a/netbox_sync/ui/dialogs.py +++ b/netbox_sync/ui/dialogs.py @@ -551,6 +551,9 @@ class SyncPreviewDialog(_Dialog): errors = sum(len(report["errors"]) for _switch, report in reports) if errors: items.append((f"{errors} Probleme", "error")) + notes = sum(len(report.get("notes", [])) for _switch, report in reports) + if notes: + items.append((f"{notes} Hinweis(e)", "warning")) for text, kind in items: summary.addWidget(Badge(text, kind)) summary.addStretch(1) @@ -566,7 +569,9 @@ class SyncPreviewDialog(_Dialog): changes = report["changes"] total_changes += len(changes) unchanged = report["interfaces_unchanged"] - top = QTreeWidgetItem([f"{switch['name']} — {len(changes)} Änderung(en), {unchanged} Interface(s) unverändert"]) + hints = len(report.get("notes", [])) + top = QTreeWidgetItem([f"{switch['name']} — {len(changes)} Änderung(en), {unchanged} Interface(s) unverändert" + + (f", {hints} Hinweis(e)" if hints else "")]) top.setIcon(0, icon("network", theme.color("accent"))) font = top.font(0) font.setBold(True) @@ -595,7 +600,7 @@ class SyncPreviewDialog(_Dialog): top.addChild(member) member.setExpanded(True) tree.addTopLevelItem(top) - top.setExpanded(len(reports) == 1 or bool(report["errors"])) + top.setExpanded(len(reports) == 1 or bool(report["errors"]) or bool(hints)) self.root.addWidget(tree, 1) if total_changes == 0: self.root.addWidget(Banner("NetBox ist bereits auf dem aktuellen Stand – es gibt nichts zu übertragen.", "success")) diff --git a/tests/test_switch_sync.py b/tests/test_switch_sync.py index 8d97387..e4b73a1 100644 --- a/tests/test_switch_sync.py +++ b/tests/test_switch_sync.py @@ -596,3 +596,19 @@ def test_cables_to_patch_panels_and_busy_far_ends_are_kept(): report = sync_snapshot_to_netbox(nb, switch, snapshot, update_cables=True) assert nb.dcim.cables.updates == [] assert any("Gegenstelle hat bereits ein anderes Kabel" in note for note in report["notes"]) + + +def test_vlans_of_another_site_are_only_labelled(): + nb, switch, snapshot = _numbered_setup() + nb.dcim.devices.get(1).site = SimpleNamespace(id=2) + nb.ipam.vlans.records += [ + Record(nb.ipam.vlans, id=110, vid=10, name="MOBILE", tenant=SimpleNamespace(id=7), site=SimpleNamespace(id=1)), + Record(nb.ipam.vlans, id=120, vid=20, name="CLIENTS", tenant=SimpleNamespace(id=7), site=None), + ] + report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False) + assert report["errors"] == [] + assert nb.dcim.interfaces.get(1).label == "10" and getattr(nb.dcim.interfaces.get(1), "untagged_vlan", None) is None + assert nb.dcim.interfaces.get(2).untagged_vlan == 120, "global VLANs are always assigned" + assert [note for note in report["notes"] if "VLAN 10" in note] == [ + "VLAN 10 „MOBILE“ gehört zu einem anderen Standort als access-01 – nur im Label vermerkt, nicht am Port " + "zugewiesen (VLAN global machen, um es zuzuweisen)"]