feat: keep cable VLANs (NetBox Utilities) in step with the switch port
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
52680e5b7c
commit
be3a02179c
5 files changed
+82
-7
No files matched your search
@@ -89,7 +89,8 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox.
|
||||
to the ports (802.1Q mode, untagged/tagged). The interface at the other end
|
||||
of a port's cable (e.g. a router or access point) is kept in step: VLANs it
|
||||
is missing are added, VLANs the switch port no longer carries are removed;
|
||||
other VLANs there stay. After the preview the app asks before changing these
|
||||
other VLANs there stay. The same applies to the connection VLANs of the
|
||||
cable itself (NetBox Utilities plugin, `cable-vlans` API). After the preview the app asks before changing these
|
||||
far ends ("Nur Switch" syncs the switch alone)
|
||||
- Tenant required: a switch without tenant in NetBox is refused; every created
|
||||
IP address, prefix, VRF, VLAN and cable gets the switch's tenant
|
||||
|
||||
@@ -2061,7 +2061,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
except Exception as error: # noqa: BLE001
|
||||
report["errors"].append(f"IP-Adresse {address} auf {interface['name']}: {error}")
|
||||
|
||||
new_peers = {}
|
||||
new_peers, new_cables = {}, {}
|
||||
if create_cables:
|
||||
lookup = _RemoteLookup(nb)
|
||||
manual_devices = config.get("neighbor_devices") or {}
|
||||
@@ -2121,7 +2121,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
report["cables_created"] += 1
|
||||
report["changes"].append(f"Kabel {device.name} {label}")
|
||||
if not dry_run:
|
||||
nb.dcim.cables.create({
|
||||
new_cables[key] = nb.dcim.cables.create({
|
||||
"a_terminations": [{"object_type": "dcim.interface", "object_id": local.id}],
|
||||
"b_terminations": [{"object_type": "dcim.interface", "object_id": remote.id}],
|
||||
"status": "connected",
|
||||
@@ -2132,12 +2132,60 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa
|
||||
except Exception as error: # noqa: BLE001
|
||||
report["errors"].append(f"Nachbar {label}: {error}")
|
||||
if sync_peer_vlans:
|
||||
_sync_cable_vlans(nb, records, port_vlans, old_vlans, new_cables, vlan_ids, own_devices, dry_run, report)
|
||||
_sync_peer_vlans(nb, records, port_vlans, old_vlans, new_peers, vlan_ids, vlan_sites, own_devices, dry_run, report)
|
||||
if backup_config:
|
||||
_backup_config(nb, device, snapshot, dry_run, report)
|
||||
return report
|
||||
|
||||
|
||||
def _sync_cable_vlans(nb, records, port_vlans, old_vlans, new_cables, vlan_ids, own_devices, dry_run, report):
|
||||
"""Keep the connection VLANs of each port's cable (NetBox Utilities plugin) in step with the port.
|
||||
|
||||
Like the far end: the port's VLANs are added, VLANs it lost in this run are
|
||||
removed, others stay. Without the plugin (or its cable VLAN API) nothing happens.
|
||||
"""
|
||||
try:
|
||||
endpoint = nb.plugins.utilities.cable_vlans
|
||||
except AttributeError:
|
||||
return
|
||||
for key, vlans in port_vlans.items():
|
||||
record = records.get(key)
|
||||
cable_id = getattr(new_cables.get(key), "id", None) or (related_id(record, "cable") if record else None)
|
||||
if not isinstance(cable_id, int) or vlans.get("tagged_all"):
|
||||
continue
|
||||
try:
|
||||
peer = _cable_peer(nb, record) if record else None
|
||||
if peer is not None and related_id(peer, "device") in own_devices:
|
||||
continue # switch-to-switch cable: both sides sync it, VLANs would flip
|
||||
port_ids = {vlan_ids[vid] for vid in list(vlans.get("untagged", [])) + list(vlans.get("tagged", []))
|
||||
if isinstance(vlan_ids.get(vid), int)}
|
||||
removed = old_vlans.get(key, set()) - port_ids
|
||||
assignments = list(endpoint.filter(cable_id=cable_id))
|
||||
assignment = assignments[0] if assignments else None
|
||||
current = {getattr(item, "id", item) for item in (getattr(assignment, "vlans", None) or [])}
|
||||
wanted = (current - removed) | port_ids
|
||||
if wanted == current:
|
||||
continue
|
||||
texts = []
|
||||
if wanted - current:
|
||||
texts.append(f"{len(wanted - current)} VLAN(s) vom Switch-Port übernommen")
|
||||
if current - wanted:
|
||||
texts.append(f"{len(current - wanted)} VLAN(s) entfernt (am Switch-Port weggefallen)")
|
||||
name = record.name if record else key
|
||||
report["changes"].append(f"Kabel-VLANs {name}: {', '.join(texts)}")
|
||||
if dry_run:
|
||||
continue
|
||||
if assignment:
|
||||
assignment.update({"vlans": sorted(wanted)})
|
||||
else:
|
||||
endpoint.create({"cable": cable_id, "vlans": sorted(wanted)})
|
||||
except Exception as error: # noqa: BLE001
|
||||
if getattr(getattr(error, "req", None), "status_code", None) == 404:
|
||||
return # plugin version without the cable VLAN API
|
||||
report["errors"].append(f"Kabel-VLANs von {key}: {error}")
|
||||
|
||||
|
||||
def _cable_peer(nb, record):
|
||||
"""The single far-end interface of ``record``'s cable, or ``None``."""
|
||||
cable_id = related_id(record, "cable")
|
||||
|
||||
@@ -570,11 +570,11 @@ class Actions:
|
||||
if not dialog.exec():
|
||||
return
|
||||
peers = [f"{switch['name']}: {change}" for switch, report in reports
|
||||
for change in report["changes"] if change.startswith("Gegenstelle ")]
|
||||
for change in report["changes"] if change.startswith(("Gegenstelle ", "Kabel-VLANs "))]
|
||||
sync_peers = not peers or widgets.confirm(
|
||||
self.window, "Gegenstellen anpassen?",
|
||||
f"An {len(peers)} per Kabel verbundenen Schnittstelle(n) anderer Geräte weichen die VLANs vom "
|
||||
"Switch-Port ab. Sollen sie angeglichen werden (fehlende ergänzen, am Switch weggefallene "
|
||||
f"{len(peers)} Kabel bzw. per Kabel verbundene Schnittstelle(n) anderer Geräte haben andere VLANs als "
|
||||
"der Switch-Port. Sollen sie angeglichen werden (fehlende ergänzen, am Switch weggefallene "
|
||||
"entfernen)? Ohne Anpassung wird nur der Switch synchronisiert.",
|
||||
ok_text="Angleichen", cancel_text="Nur Switch", details="\n".join(peers))
|
||||
self._apply_switch_sync(nb, items, create_cables, log, update_cables, sync_peers)
|
||||
|
||||
@@ -68,7 +68,7 @@ class Endpoint:
|
||||
def create(self, payload):
|
||||
if isinstance(payload, list): # bulk create
|
||||
return [self.create(item) for item in payload]
|
||||
record = Record(self, id=next(_ids), cable=None, **payload)
|
||||
record = Record(self, **{"id": next(_ids), "cable": None, **payload})
|
||||
self.records.append(record)
|
||||
self.created.append(payload)
|
||||
return record
|
||||
|
||||
@@ -708,3 +708,29 @@ def test_far_end_of_a_cable_gets_missing_vlans_of_the_switch_port():
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert any("1 VLAN(s) entfernt" in change for change in report["changes"])
|
||||
assert peer.untagged_vlan == 120 and peer.tagged_vlans == [199] and peer.mode == "tagged"
|
||||
|
||||
|
||||
def test_cable_vlans_of_the_utilities_plugin_follow_the_switch_port():
|
||||
nb, switch, snapshot = _numbered_setup()
|
||||
nb.ipam.vlans.records += [
|
||||
Record(nb.ipam.vlans, id=120, vid=20, name="LAN", tenant=SimpleNamespace(id=7), site=None),
|
||||
Record(nb.ipam.vlans, id=136, vid=36, name="WMGMT", tenant=SimpleNamespace(id=7), site=None),
|
||||
]
|
||||
snapshot["interfaces"][1]["vlans"] = {"untagged": [20], "tagged": [36], "tagged_all": False}
|
||||
nb.dcim.interfaces.get(2).cable = SimpleNamespace(id=70)
|
||||
nb.dcim.cables.records.append(Record(nb.dcim.cables, id=70,
|
||||
a_terminations=[{"object_type": "dcim.interface", "object_id": 2}],
|
||||
b_terminations=[{"object_type": "dcim.interface", "object_id": 20}]))
|
||||
nb.plugins = SimpleNamespace(utilities=SimpleNamespace(cable_vlans=Endpoint()))
|
||||
cable_vlans = nb.plugins.utilities.cable_vlans
|
||||
report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False, dry_run=True)
|
||||
assert "Kabel-VLANs 2: 2 VLAN(s) vom Switch-Port übernommen" in report["changes"] and cable_vlans.created == []
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert cable_vlans.created == [{"cable": 70, "vlans": [120, 136]}]
|
||||
cable_vlans.records[0].cable = SimpleNamespace(id=70)
|
||||
|
||||
# VLAN 36 is removed on the switch; a VLAN set by hand on the cable stays.
|
||||
cable_vlans.records[0].vlans = [120, 136, 199]
|
||||
snapshot["interfaces"][1]["vlans"] = {"untagged": [20], "tagged": [], "tagged_all": False}
|
||||
sync_snapshot_to_netbox(nb, switch, snapshot, create_cables=False)
|
||||
assert cable_vlans.updates[-1] == (cable_vlans.records[0].id, {"vlans": [120, 199]})
|
||||
Reference in new issue
Block a user