diff --git a/README.md b/README.md index de629ac..85055d6 100644 --- a/README.md +++ b/README.md @@ -104,7 +104,15 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox. only added when the configuration changed (SHA-256 in the description). Older plugin versions (parent on the attachment) and newer ones (separate assignments) are supported; without the plugin the step is skipped with a note -- Cables from LLDP/CDP, also with FQDN system names or via the management IP +- Cables from LLDP/CDP, also with FQDN system names or via the management IP. + Neighbors that report their MAC address as port ID (e.g. access points) are + matched by MAC, and a device with a single physical port is cabled there +- Existing cables are checked against LLDP/CDP: a different far end is reported + as a note. Only with the optional "Bestehende Kabel anpassen" (confirmed with + a warning, NetBox is the source of truth) the cable is moved to the reported + neighbor; such changes are marked with ⚠ in the preview. Cables to patch + panels (front/rear ports) and far ends that already have another cable are + never changed - The switch configuration is only changed when "Enable LLDP if needed" is explicitly switched on diff --git a/netbox_sync/core/switches.py b/netbox_sync/core/switches.py index 25d8893..0db0e93 100644 --- a/netbox_sync/core/switches.py +++ b/netbox_sync/core/switches.py @@ -10,7 +10,7 @@ from pathlib import Path import paramiko -from netbox_sync.core.netbox import assign_mac, related_id +from netbox_sync.core.netbox import assign_mac, normalize_mac, related_id PLATFORMS = { "auto": "Automatisch erkennen", @@ -1474,7 +1474,17 @@ class _RemoteLookup: if _physical_record(record) and _port_number(record.name) == number] if len(found) == 1: return found[0] - return None + # Access points and phones often report their MAC address as port ID. + mac = normalize_mac(neighbor.get("remote_port")) + if mac: + found = [record for record in records.values() + if normalize_mac(getattr(record, "mac_address", None)) == mac] + if len(found) == 1: + return found[0] + # An end device with a single port (e.g. an AP from the Sophos import) can only be cabled there. + physical = [record for record in records.values() + if _physical_record(record) and not getattr(record, "mgmt_only", False)] + return physical[0] if len(physical) == 1 else None _NEW = "new" # placeholder ID of objects a dry run would create @@ -1623,7 +1633,7 @@ def _new_report(): return { "interfaces_created": 0, "interfaces_updated": 0, "interfaces_unchanged": 0, "ips_created": 0, "ips_updated": 0, "ips_unchanged": 0, - "cables_created": 0, "cables_skipped": 0, + "cables_created": 0, "cables_updated": 0, "cables_skipped": 0, "vrfs_created": 0, "prefixes_created": 0, "vlans_created": 0, "changes": [], "errors": [], "notes": [], } @@ -1736,8 +1746,55 @@ def _backup_config(nb, device, snapshot, dry_run, report): report["errors"].append(f"Konfigurations-Backup: {error}") +def _term(value, key): + return value.get(key) if isinstance(value, dict) else getattr(value, key, None) + + +def _termination_text(termination): + item = _term(termination, "object") or {} + owner = _term(_term(item, "device") or {}, "name") + return f"{owner} {_term(item, 'name')}" if owner else str(_term(item, "name") or _term(termination, "object_id")) + + +def _check_cable(nb, local, remote, label, update_cables, dry_run, report): + """Compare an existing cable of a switch port with its LLDP/CDP neighbor. + + NetBox is the source of truth: a different far end is only reported unless + ``update_cables`` is set. Cables to patch panels (front/rear ports) or with + several terminations are never touched. + """ + cable = nb.dcim.cables.get(related_id(local, "cable")) + if cable is None: + report["cables_skipped"] += 1 + return + sides = [list(_term(cable, "a_terminations") or []), list(_term(cable, "b_terminations") or [])] + local_side = next((side for side in sides if any(_term(item, "object_id") == local.id for item in side)), None) + far = sides[1] if local_side is sides[0] else sides[0] + if local_side is None or len(far) != 1 or _term(far[0], "object_type") != "dcim.interface": + report["cables_skipped"] += 1 + return + if _term(far[0], "object_id") == remote.id: + report["cables_skipped"] += 1 + return + old = _termination_text(far[0]) + remote_cable = related_id(remote, "cable") + if not update_cables or (remote_cable and remote_cable != cable.id): + reason = ("Gegenstelle hat bereits ein anderes Kabel" if update_cables + else "„Bestehende Kabel anpassen“ ist aus") + report["notes"].append(f"Kabel {label}: in NetBox mit {old} verbunden – nicht angepasst ({reason})") + return + report["cables_updated"] += 1 + report["changes"].append(f"⚠ Kabel {label}: ersetzt bisherige Gegenstelle {old}") + if not dry_run: + cable.update({ + "a_terminations": [{"object_type": "dcim.interface", "object_id": local.id}], + "b_terminations": [{"object_type": "dcim.interface", "object_id": remote.id}], + }) + remote.cable = cable + + def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=False, log=_noop, - backup_config=False): + backup_config=False, update_cables=False): """Write a discovery snapshot to NetBox. With ``dry_run`` nothing is written; the returned report lists what would @@ -1879,9 +1936,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa if key not in records: continue local = records[key] - if local is not None and getattr(local, "cable", None): - report["cables_skipped"] += 1 - continue + existing = getattr(local, "cable", None) if local is not None else None if neighbor["local_port"] in manual_devices: # 0 means "no device" was chosen in the review dialog. chosen = int(manual_devices[neighbor["local_port"]] or 0) @@ -1894,6 +1949,12 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa if remote_device.id in own_devices: continue remote = lookup.interface(remote_device, neighbor) + if existing: + if remote: + _check_cable(nb, local, remote, f"{device.name} {label}", update_cables, dry_run, report) + else: + report["cables_skipped"] += 1 + continue if not remote or getattr(remote, "cable", None): report["cables_skipped"] += 1 continue diff --git a/netbox_sync/ui/actions.py b/netbox_sync/ui/actions.py index b0dc158..835faf9 100644 --- a/netbox_sync/ui/actions.py +++ b/netbox_sync/ui/actions.py @@ -433,6 +433,7 @@ class Actions: return by_id = {switch["id"]: switch for switch in self.state.switches} backup = self.state.settings.get("backup_config") + update_cables = create_cables and bool(self.state.settings.get("update_cables")) # VLAN and network decisions are shared by all switches of the profile. vlan_map = self.state.profile.setdefault("vlan_map", {}) network_map = self.state.profile.setdefault("network_map", {}) @@ -500,7 +501,7 @@ class Actions: ctx.progress(index, len(items), switch["name"]) ctx.log(f"{switch['name']}: berechne Änderungen …") reports.append((switch, sync_snapshot_to_netbox(nb, switch, snapshot, create_cables, dry_run=True, - backup_config=backup))) + backup_config=backup, update_cables=update_cables))) return nb, reports def show_preview(result): @@ -511,13 +512,13 @@ class Actions: # follow-up task is not rejected as "still busy". dialog = SyncPreviewDialog(self.window, reports, create_cables) if dialog.exec(): - self._apply_switch_sync(nb, items, create_cables, log) + self._apply_switch_sync(nb, items, create_cables, log, update_cables) QTimer.singleShot(0, ask) self.tasks.run(plan, title="Zuordnung ermitteln", area="switch", on_success=review, on_error=self._netbox_failed) - def _apply_switch_sync(self, nb, items, create_cables, log): + def _apply_switch_sync(self, nb, items, create_cables, log, update_cables=False): def work(ctx): reports = [] for index, (switch, snapshot) in enumerate(items): @@ -525,7 +526,8 @@ class Actions: ctx.progress(index, len(items), switch["name"]) ctx.log(f"{switch['name']}: übertrage nach NetBox …") report = sync_snapshot_to_netbox(nb, switch, snapshot, create_cables, dry_run=False, - backup_config=self.state.settings.get("backup_config")) + backup_config=self.state.settings.get("backup_config"), + update_cables=update_cables) for error in report["errors"]: ctx.log(f"{switch['name']}: {error}", "error") reports.append((switch, report)) diff --git a/netbox_sync/ui/dialogs.py b/netbox_sync/ui/dialogs.py index a2271e7..a20b4ac 100644 --- a/netbox_sync/ui/dialogs.py +++ b/netbox_sync/ui/dialogs.py @@ -546,6 +546,8 @@ class SyncPreviewDialog(_Dialog): items.append((f"{totals[key]} {text}", "info")) if create_cables: items.append((f"{totals.get('cables_created', 0)} Kabel", "info")) + if totals.get("cables_updated"): + items.append((f"{totals['cables_updated']} Kabel angepasst", "error")) errors = sum(len(report["errors"]) for _switch, report in reports) if errors: items.append((f"{errors} Probleme", "error")) diff --git a/netbox_sync/ui/pages/switches.py b/netbox_sync/ui/pages/switches.py index 6217b54..a4c90a3 100644 --- a/netbox_sync/ui/pages/switches.py +++ b/netbox_sync/ui/pages/switches.py @@ -93,6 +93,11 @@ class SwitchesPage(Page): self.cables_option = checkbox("Kabel aus LLDP/CDP anlegen", tooltip="Legt Kabel zwischen Schnittstellen an, deren Gegenstelle in NetBox " "eindeutig gefunden wird. Bestehende Kabel werden nie verändert.") + self.update_cables_option = checkbox( + "Bestehende Kabel anpassen", + tooltip="Achtung: NetBox ist die Source of Truth. Weicht ein vorhandenes Kabel vom LLDP/CDP-Nachbarn ab, " + "wird es auf die vom Switch gemeldete Gegenstelle umgehängt. Kabel zu Patchpanels werden nie " + "verändert. Ohne diese Option werden Abweichungen nur gemeldet.") self.backup_option = checkbox("Konfiguration als Anhang sichern", tooltip="Hängt die laufende Konfiguration als Textdatei an das NetBox-Gerät " "(Plugin netbox-attachments). Passwörter, Schlüssel und Communities " @@ -103,6 +108,7 @@ class SwitchesPage(Page): filters.addWidget(self.only_neighbors) filters.addStretch(1) filters.addWidget(self.cables_option) + filters.addWidget(self.update_cables_option) filters.addWidget(self.backup_option) result_card.add(filters) result_columns = [ @@ -150,6 +156,8 @@ class SwitchesPage(Page): self.lldp_option.toggled.connect(lambda value: self.state.update_settings(enable_lldp=value)) self.cables_option.toggled.connect(lambda value: self.state.update_settings(create_cables=value)) self.backup_option.toggled.connect(lambda value: self.state.update_settings(backup_config=value)) + self.update_cables_option.toggled.connect(self._toggle_update_cables) + self.cables_option.toggled.connect(self.update_cables_option.setEnabled) self.state.switches_changed.connect(self.refresh) self.state.profile_switched.connect(self.refresh) self.state.profile_edited.connect(self.refresh_switches) @@ -162,10 +170,24 @@ class SwitchesPage(Page): def _load_settings(self): for widget, key in ((self.lldp_option, "enable_lldp"), (self.cables_option, "create_cables"), - (self.backup_option, "backup_config")): + (self.backup_option, "backup_config"), (self.update_cables_option, "update_cables")): widget.blockSignals(True) widget.setChecked(bool(self.state.settings.get(key))) widget.blockSignals(False) + self.update_cables_option.setEnabled(self.cables_option.isChecked()) + + def _toggle_update_cables(self, value): + if value and not widgets.confirm( + self.window, "Bestehende Kabel anpassen?", + "NetBox ist die Source of Truth. Mit dieser Option werden vorhandene Kabel, deren Gegenstelle nicht " + "zum LLDP/CDP-Nachbarn des Switches passt, umgehängt – die bisherige Verbindung geht in NetBox " + "verloren. Kabel zu Patchpanels bleiben unverändert. Jede Anpassung steht vorher in der Vorschau.", + ok_text="Einschalten", destructive=True): + self.update_cables_option.blockSignals(True) + self.update_cables_option.setChecked(False) + self.update_cables_option.blockSignals(False) + return + self.state.update_settings(update_cables=value) def _status_text(self, row): status = self.state.switch_status.get(row["id"]) diff --git a/tests/test_switch_sync.py b/tests/test_switch_sync.py index 09bf57f..8d97387 100644 --- a/tests/test_switch_sync.py +++ b/tests/test_switch_sync.py @@ -528,3 +528,71 @@ def test_config_backup_with_older_attachment_plugin(): payload = app.netbox_attachments.created[0] assert (payload["object_type"], payload["object_id"]) == ("dcim.device", 1) assert app.netbox_attachment_assignments.created == [] + + +def test_cable_to_access_point_that_reports_its_mac_as_port(): + nb, switch, snapshot = _numbered_setup() + nb.dcim.devices.records.append(Record(nb.dcim.devices, id=5, name="PC-AP-1", tenant=SimpleNamespace(id=7))) + nb.dcim.interfaces.records += [ + Record(nb.dcim.interfaces, id=50, name="LAN", device=SimpleNamespace(id=5), mac_address="C8:4F:86:88:96:8E", + type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None), + Record(nb.dcim.interfaces, id=51, name="LAN2", device=SimpleNamespace(id=5), mac_address=None, + type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None), + ] + snapshot["neighbors"][0].update(system_name="AP6420-PA3007MFJ3BDX1A", remote_port="c8:4f:86:88:96:8e") + switch["neighbor_devices"] = {"1/1/2": 5} + sync_snapshot_to_netbox(nb, switch, snapshot) + assert nb.dcim.cables.created[0]["b_terminations"] == [{"object_type": "dcim.interface", "object_id": 50}] + + # A device with a single port is cabled there even if neither name nor MAC match. + nb, switch, snapshot = _numbered_setup() + nb.dcim.devices.records.append(Record(nb.dcim.devices, id=5, name="PC-AP-1", tenant=SimpleNamespace(id=7))) + nb.dcim.interfaces.records.append(Record(nb.dcim.interfaces, id=50, name="eth0", device=SimpleNamespace(id=5), + type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None)) + snapshot["neighbors"][0].update(system_name="AP6420", remote_port="c8:4f:86:88:96:cc") + switch["neighbor_devices"] = {"1/1/2": 5} + sync_snapshot_to_netbox(nb, switch, snapshot) + assert nb.dcim.cables.created[0]["b_terminations"] == [{"object_type": "dcim.interface", "object_id": 50}] + + +def _cabled_setup(far_type="dcim.interface"): + """Port 1/1/2 (NetBox "2") has a cable to "old-device eth9"; LLDP reports server-01 eth0.""" + nb, switch, snapshot = _numbered_setup() + nb.dcim.interfaces.get(2).cable = SimpleNamespace(id=70) + far = {"object_type": far_type, "object_id": 99, + "object": {"name": "eth9", "device": {"name": "old-device"}}} + nb.dcim.cables.records.append(Record(nb.dcim.cables, id=70, a_terminations=[far], + b_terminations=[{"object_type": "dcim.interface", "object_id": 2}])) + switch["neighbor_devices"] = {"1/1/2": 2} + return nb, switch, snapshot + + +def test_differing_cable_is_only_reported_by_default(): + nb, switch, snapshot = _cabled_setup() + report = sync_snapshot_to_netbox(nb, switch, snapshot) + assert report["cables_updated"] == 0 and nb.dcim.cables.updates == [] + assert any("in NetBox mit old-device eth9 verbunden – nicht angepasst" in note for note in report["notes"]) + + +def test_differing_cable_is_moved_when_allowed(): + nb, switch, snapshot = _cabled_setup() + report = sync_snapshot_to_netbox(nb, switch, snapshot, dry_run=True, update_cables=True) + assert report["cables_updated"] == 1 and nb.dcim.cables.updates == [] + assert any(change.startswith("⚠ Kabel access-01") and "old-device eth9" in change for change in report["changes"]) + sync_snapshot_to_netbox(nb, switch, snapshot, update_cables=True) + assert nb.dcim.cables.updates == [(70, { + "a_terminations": [{"object_type": "dcim.interface", "object_id": 2}], + "b_terminations": [{"object_type": "dcim.interface", "object_id": 20}]})] + assert nb.dcim.cables.created == [] + + +def test_cables_to_patch_panels_and_busy_far_ends_are_kept(): + nb, switch, snapshot = _cabled_setup(far_type="dcim.frontport") + report = sync_snapshot_to_netbox(nb, switch, snapshot, update_cables=True) + assert report["cables_updated"] == 0 and nb.dcim.cables.updates == [] and not report["notes"] + + nb, switch, snapshot = _cabled_setup() + nb.dcim.interfaces.get(20).cable = SimpleNamespace(id=71) + 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"])