diff --git a/README.md b/README.md index 2570dd5..34cdd8e 100644 --- a/README.md +++ b/README.md @@ -106,7 +106,11 @@ vSphere and Proxmox VE, HPE/Aruba switches and Windows clients in NetBox. 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. 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 + matched by MAC, and a device with a single physical port is cabled there. + Wireless interfaces (Wi-Fi, LTE …) are never cable targets. In the review + dialog the far-end interface can be chosen per neighbor ("automatisch" shows + the interface that would be used); the choice is stored in the profile. + Every skipped cable is listed as a note with its reason - 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 diff --git a/netbox_sync/core/switches.py b/netbox_sync/core/switches.py index 4f26b77..060ca3e 100644 --- a/netbox_sync/core/switches.py +++ b/netbox_sync/core/switches.py @@ -1428,7 +1428,15 @@ def plan_switch_sync(nb, config, snapshot): if remote and remote.id not in known and remote.id != device.id: devices.append({"id": remote.id, "name": remote.name}) known.add(remote.id) - neighbors.append(dict(neighbor, device_id=device_id, method=method)) + interfaces, suggested, chosen = [], None, None + if remote: + interfaces = cable_targets(nb, remote.id, lookup) + found = lookup.interface(remote, neighbor) + suggested = found.name if found else None + stored = (config.get("neighbor_interfaces") or {}).get(local) + chosen = stored if any(item["id"] == stored for item in interfaces) else None + neighbors.append(dict(neighbor, device_id=device_id, method=method, interfaces=interfaces, + suggested_interface=suggested, interface_id=chosen)) # Stack members may be chosen from the same list (including the switch itself). for member_device in ([device, *filter(None, members.values())] if members else []): if member_device.id not in known: @@ -1531,10 +1539,13 @@ class _RemoteLookup: self.devices[cache_key] = found return found + def records(self, device_id): + if device_id not in self.interfaces: + self.interfaces[device_id] = _device_interfaces(self.nb, device_id) + return self.interfaces[device_id] + def interface(self, device, neighbor): - if device.id not in self.interfaces: - self.interfaces[device.id] = _device_interfaces(self.nb, device.id) - records = self.interfaces[device.id] + records = self.records(device.id) candidates = [neighbor.get("remote_port"), neighbor.get("port_description")] if neighbor.get("port_description"): candidates.append(neighbor["port_description"].split()[0]) @@ -1562,6 +1573,14 @@ class _RemoteLookup: return physical[0] if len(physical) == 1 else None +def cable_targets(nb, device_id, lookup=None): + """Interfaces of a device a cable can end on, as ``[{"id", "name", "cabled"}]`` in natural order.""" + records = (lookup or _RemoteLookup(nb)).records(device_id) + return [{"id": record.id, "name": record.name, "cabled": bool(getattr(record, "cable", None))} + for record in sorted(records.values(), key=lambda item: _natural_key(item.name)) + if _cableable_record(record)] + + _NEW = "new" # placeholder ID of objects a dry run would create @@ -2038,6 +2057,7 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa if create_cables: lookup = _RemoteLookup(nb) manual_devices = config.get("neighbor_devices") or {} + manual_interfaces = config.get("neighbor_interfaces") or {} for neighbor in snapshot["neighbors"]: name = neighbor.get("system_name") or neighbor.get("management_ip") or neighbor.get("chassis_id") or "?" label = f"{neighbor.get('local_port')} → {name} {neighbor.get('remote_port') or ''}".strip() @@ -2071,7 +2091,11 @@ def sync_snapshot_to_netbox(nb, config, snapshot, create_cables=True, dry_run=Fa continue if remote_device.id in own_devices: continue - remote = lookup.interface(remote_device, neighbor) + # A far-end interface chosen in the review dialog wins – as long as it belongs to the device. + chosen_interface = manual_interfaces.get(neighbor["local_port"]) + remote = next((record for record in lookup.records(remote_device.id).values() + if chosen_interface and record.id == chosen_interface), None) + remote = remote or lookup.interface(remote_device, neighbor) if existing: if remote: _check_cable(nb, local, remote, f"{device.name} {label}", update_cables, dry_run, report) diff --git a/netbox_sync/ui/actions.py b/netbox_sync/ui/actions.py index def2cc3..538786e 100644 --- a/netbox_sync/ui/actions.py +++ b/netbox_sync/ui/actions.py @@ -16,6 +16,7 @@ from netbox_sync.core.config import known_hosts_path from netbox_sync.core.netbox import NetBoxError, related_id, related_name from netbox_sync.core.switches import ( PLATFORMS, + cable_targets, describe_snapshot, discover_switch, plan_switch_sync, @@ -525,7 +526,8 @@ class Actions: # Started after the planning task has finished, so the next # task is not rejected as "still busy". if needs_review: - dialog = SwitchMappingDialog(self.window, reviewable, create_cables) + dialog = SwitchMappingDialog(self.window, reviewable, create_cables, + interface_loader=lambda device_id: cable_targets(nb, device_id)) if not dialog.exec(): return stored = {switch["id"]: switch for switch in self.state.switches} diff --git a/netbox_sync/ui/dialogs.py b/netbox_sync/ui/dialogs.py index 1eb90ed..55f7367 100644 --- a/netbox_sync/ui/dialogs.py +++ b/netbox_sync/ui/dialogs.py @@ -619,7 +619,10 @@ class SwitchMappingDialog(_Dialog): NEW = "\x00new" - def __init__(self, parent, plans, create_cables): + def __init__(self, parent, plans, create_cables, interface_loader=None): + # interface_loader(device_id) → cable targets of another chosen neighbor device. + self.interface_loader = interface_loader + self._far_end_cache = {} super().__init__(parent, "Zuordnung prüfen", "Schnittstellen, Nachbarn, Netze und VLANs prüfen und bei Bedarf korrigieren. Neue Objekte " "erhalten immer den Mandanten des Switches – die Auswahl wird im Profil gespeichert.", @@ -716,9 +719,9 @@ class SwitchMappingDialog(_Dialog): "Für jeden Nachbarn kann ein bestehendes NetBox-Gerät gewählt werden (Auswahl aus: " f"{', '.join(scopes)}). Die Gegenstelle wird über den Portnamen gesucht; „kein Kabel“ " "überspringt den Nachbarn.", muted=True, wrap=True)) - self.neighbor_table = QTableWidget(0, 5) + self.neighbor_table = QTableWidget(0, 6) self.neighbor_table.setHorizontalHeaderLabels(["Switch", "Lokaler Port", "Nachbar (LLDP/CDP)", - "Nachbar-Port", "NetBox-Gerät"]) + "Nachbar-Port", "NetBox-Gerät", "Nachbar-Schnittstelle"]) for switch, plan in plans: for neighbor in plan["neighbors"]: row = self.neighbor_table.rowCount() @@ -727,14 +730,22 @@ class SwitchMappingDialog(_Dialog): combo.set_items([("– kein Kabel –", 0)] + [(device["name"], device["id"]) for device in plan["devices"]], neighbor.get("device_id") or 0) texts = (switch["name"], neighbor["local_port"], neighbor.get("system_name") or - neighbor.get("management_ip") or "", neighbor.get("remote_port") or "") + neighbor.get("management_ip") or neighbor.get("chassis_id") or "", + neighbor.get("remote_port") or "") for column, text in enumerate(texts): self.neighbor_table.setItem(row, column, QTableWidgetItem(text)) self.neighbor_table.setCellWidget(row, 4, combo) - self.neighbor_rows.append((switch, neighbor, combo)) - self._prepare_table(self.neighbor_table, (140, 110, 220, 150, 260)) + port_combo = SearchableComboBox("Schnittstelle suchen …") + self._fill_far_ends(port_combo, neighbor.get("interfaces") or [], + neighbor.get("suggested_interface"), neighbor.get("interface_id")) + self.neighbor_table.setCellWidget(row, 5, port_combo) + combo.currentIndexChanged.connect( + lambda _index, device_combo=combo, target=port_combo, item=neighbor: + self._device_changed(device_combo, target, item)) + self.neighbor_rows.append((switch, neighbor, combo, port_combo)) + self._prepare_table(self.neighbor_table, (130, 95, 200, 140, 220, 220)) neighbor_layout.addWidget(self.neighbor_table, 1) - found = sum(1 for _switch, neighbor, _combo in self.neighbor_rows if neighbor.get("device_id")) + found = sum(1 for _switch, neighbor, *_combos in self.neighbor_rows if neighbor.get("device_id")) tabs.addTab(neighbor_page, f"Nachbarn ({found} von {len(self.neighbor_rows)} zugeordnet)") # Networks -------------------------------------------------------------- @@ -959,13 +970,43 @@ class SwitchMappingDialog(_Dialog): status.setCheckState(Qt.Checked if create is not False else Qt.Unchecked) status.setForeground(QColor(theme.color("warning"))) + @staticmethod + def _fill_far_ends(combo, interfaces, suggested=None, current=None, evaluated=True): + """"automatic" (with the interface it would pick) plus the cable targets of the device. + + ``evaluated`` is False for a device chosen in the dialog: its automatic match is only known at sync time. + """ + automatic = f"automatisch ({suggested})" if suggested else ( + "automatisch – keine passende gefunden" if interfaces and evaluated else "automatisch") + items = [(automatic, 0)] + [(item["name"] + (" (hat Kabel)" if item.get("cabled") else ""), item["id"]) + for item in interfaces] + combo.set_items(items, current or 0) + combo.setEnabled(bool(interfaces) or bool(suggested)) + + def _device_changed(self, device_combo, target, neighbor): + device_id = int(device_combo.valid_data() or 0) + if not device_id: + self._fill_far_ends(target, []) + return + if device_id == (neighbor.get("device_id") or 0): + self._fill_far_ends(target, neighbor.get("interfaces") or [], neighbor.get("suggested_interface"), + neighbor.get("interface_id")) + return + if device_id not in self._far_end_cache: + try: + self._far_end_cache[device_id] = self.interface_loader(device_id) if self.interface_loader else [] + except Exception: # noqa: BLE001 – the choice stays "automatic" + self._far_end_cache[device_id] = [] + self._fill_far_ends(target, self._far_end_cache[device_id], evaluated=False) + def _filter_interfaces(self, only_unclear): for row, _switch, item, _combo in self.interface_rows: self.interface_table.setRowHidden(row, only_unclear and item["method"] == "name") def accept(self): result = {switch["id"]: {"interface_map": dict(switch.get("interface_map") or {}), - "neighbor_devices": dict(switch.get("neighbor_devices") or {})} + "neighbor_devices": dict(switch.get("neighbor_devices") or {}), + "neighbor_interfaces": dict(switch.get("neighbor_interfaces") or {})} for switch, _plan in self.plans} # Members moved to another device: their port choices refer to the old # device and are dropped, so the ports are matched again automatically. @@ -996,7 +1037,7 @@ class SwitchMappingDialog(_Dialog): mapping.pop(item["name"], None) else: mapping[item["name"]] = target - for switch, neighbor, combo in self.neighbor_rows: + for switch, neighbor, combo, port_combo in self.neighbor_rows: chosen = combo.valid_data() chosen = int(chosen or 0) stored = result[switch["id"]]["neighbor_devices"] @@ -1004,6 +1045,13 @@ class SwitchMappingDialog(_Dialog): stored.pop(neighbor["local_port"], None) else: stored[neighbor["local_port"]] = chosen + # 0 = automatic (name, port number, MAC or single port); otherwise the chosen NetBox interface. + interface_id = int(port_combo.valid_data() or 0) if chosen else 0 + interfaces = result[switch["id"]]["neighbor_interfaces"] + if interface_id: + interfaces[neighbor["local_port"]] = interface_id + else: + interfaces.pop(neighbor["local_port"], None) network_map = dict(self.previous_network_map) for item, combo, status in self.network_rows: chosen = combo.currentData() diff --git a/tests/test_switch_sync.py b/tests/test_switch_sync.py index 9940ace..884e952 100644 --- a/tests/test_switch_sync.py +++ b/tests/test_switch_sync.py @@ -640,3 +640,42 @@ def test_wireless_interfaces_are_no_cable_targets(): report = sync_snapshot_to_netbox(nb, switch, snapshot) assert report["errors"] == [] assert nb.dcim.cables.created[0]["b_terminations"] == [{"object_type": "dcim.interface", "object_id": 50}] + + +def _ap_with_two_ports(): + nb, switch, snapshot = _numbered_setup() + nb.dcim.devices.records.append(Record(nb.dcim.devices, id=5, name="AP-005", tenant=SimpleNamespace(id=7))) + nb.dcim.interfaces.records += [ + Record(nb.dcim.interfaces, id=50, name="eth1", device=SimpleNamespace(id=5), mac_address=None, + type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None), + Record(nb.dcim.interfaces, id=51, name="eth2", device=SimpleNamespace(id=5), mac_address=None, + type=SimpleNamespace(value="1000base-t"), enabled=True, cable=None), + Record(nb.dcim.interfaces, id=52, name="wlan0", device=SimpleNamespace(id=5), mac_address=None, + type=SimpleNamespace(value="ieee802.11ax"), enabled=True, cable=None), + ] + snapshot["neighbors"][0].update(system_name="AP-005", remote_port="Uplink", port_description="") + return nb, switch, snapshot + + +def test_far_end_interface_can_be_chosen(): + nb, switch, snapshot = _ap_with_two_ports() + plan = plan_switch_sync(nb, switch, snapshot) + neighbor = plan["neighbors"][0] + assert [item["name"] for item in neighbor["interfaces"]] == ["eth1", "eth2"] # no Wi-Fi + assert neighbor["suggested_interface"] is None and neighbor["interface_id"] is None + + report = sync_snapshot_to_netbox(nb, switch, snapshot, dry_run=True) + assert report["cables_created"] == 0 and any("keine passende Schnittstelle" in n for n in report["notes"]) + + switch["neighbor_interfaces"] = {"1/1/2": 51} + assert plan_switch_sync(nb, switch, snapshot)["neighbors"][0]["interface_id"] == 51 + sync_snapshot_to_netbox(nb, switch, snapshot) + assert nb.dcim.cables.created[0]["b_terminations"] == [{"object_type": "dcim.interface", "object_id": 51}] + + +def test_chosen_interface_of_another_device_is_ignored(): + nb, switch, snapshot = _ap_with_two_ports() + switch["neighbor_interfaces"] = {"1/1/2": 20} # belongs to server-01, not AP-005 + assert plan_switch_sync(nb, switch, snapshot)["neighbors"][0]["interface_id"] is None + report = sync_snapshot_to_netbox(nb, switch, snapshot, dry_run=True) + assert report["cables_created"] == 0