From 4dfabce2fb0ed95f96b01ac16bbe035de355938e Mon Sep 17 00:00:00 2001 From: Jared Vititoe Date: Sun, 15 Nov 2026 01:34:08 -0500 Subject: [PATCH] Cutsheet: port names in UniFi that no longer fit, document a cable from topology - topology.port_name_report: switch port names that no longer fit what is plugged in, as a checklist with suggested names: named after the wrong device, named after a device that moved to another port, named with nothing plugged in (and who was last seen there), and still "Port N" with a known device on it. Ports named after a device that is only off are left alone. Gandalf only reports; it never renames anything in UniFi. - /api/cutsheet returns it as port_names; the cutsheet page shows it as "Port names in UniFi", grouped, with a summary chip. - The topology cable panel's "not documented" gets a "document it" link that opens the cutsheet's new-cable form with both ends, the NIC and DAC filled in; /cutsheet?... now takes b_device, b_port and cable_type. Co-Authored-By: Claude Opus 5.5 --- README.md | 11 ++++- app.py | 3 ++ static/cutsheet.js | 52 ++++++++++++++++++++++- static/style.css | 3 ++ static/topology.js | 19 ++++++++- templates/cutsheet.html | 9 ++++ tests/test_app.py | 1 + tests/test_topology.py | 60 ++++++++++++++++++++++++++ topology.py | 93 +++++++++++++++++++++++++++++++++++++++++ 9 files changed, 248 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 66fa7c7..ebec010 100644 --- a/README.md +++ b/README.md @@ -353,7 +353,16 @@ can view it; only the `admin` group can edit, and every change is logged with wh cables in one port). Runs that end at a jack are *unverified* while linked and *idle* when not. Planned, dark and retired cables aren't checked. - **Undocumented links**: live switch ports no cable mentions, with an Add button that pre-fills - what Gandalf knows. Each switch port panel also shows its planned cable, or links to add one. + what Gandalf knows. Each switch port panel also shows its planned cable, or links to add one. On + the topology page, a cable with no record has a **document it** link that opens this form with both + ends (and the NIC, and DAC when it is one) filled in. `/cutsheet?a_device=&a_port=&b_device=&b_port=&cable_type=` + opens it the same way. +- **Port names in UniFi**: a checklist of switch port names that no longer fit what is plugged in: + named after the wrong device, named after a device that has moved to another port, named but with + nothing plugged in (with who was last seen there), and still "Port N" with a known device on it + (folded). Each comes with a suggested name: the device, the device and NIC for a server with two + cables, "Uplink" or "Downlink to X" between switches. A port named after a device that is only + switched off is left alone. Rename them in UniFi yourself; Gandalf never changes UniFi. - **Labels to make**: cable IDs (one per cord end) and panel-port labels not yet stuck on, sized for typing on a handheld label maker. Tick each off once it's applied; **Print list** prints just this. - **CSV**: export, and import that adds or updates cables by ID. A file with any invalid row imports diff --git a/app.py b/app.py index ef0dd89..27ff38a 100644 --- a/app.py +++ b/app.py @@ -1032,6 +1032,9 @@ def _cutsheet_view() -> dict: snapshot = _state_json('network_snapshot') data['devices'] = sorted(set(switches) | set(snapshot.get('hosts') or {}) | {u['name'] for u in snapshot.get('unifi') or [] if u.get('name')}, key=str.lower) + # UniFi port names that no longer fit what is plugged in (Gandalf never renames them) + data['port_names'] = topology.port_name_report( + snapshot, link_stats, _state_json('modem_stats'), _state_json('known_uplinks')) data['verdicts'] = cutsheet.VERDICTS data['chassis'] = cutsheet.CHASSIS data['options'] = {'kinds': cutsheet.ITEM_KINDS, 'passive_kinds': cutsheet.PASSIVE_KINDS, diff --git a/static/cutsheet.js b/static/cutsheet.js index df9ee84..95f51b3 100644 --- a/static/cutsheet.js +++ b/static/cutsheet.js @@ -74,6 +74,7 @@ function renderSummary() { chip(matches, 'match what Gandalf sees', 'cs-chip-ok', 'cs-cables-section'), chip(problems, problems === 1 ? 'problem' : 'problems', problems ? 'cs-chip-bad' : '', 'cs-cables-section'), chip(_cs.suggestions.length, 'undocumented links', _cs.suggestions.length ? 'cs-chip-warn' : '', 'cs-suggest-section'), + chip(portFixes(), 'port names to fix', portFixes() ? 'cs-chip-warn' : '', 'cs-portnames-section'), chip(labels, 'labels to make', labels ? 'cs-chip-warn' : '', 'cs-labels-section'), ].join(''); } @@ -153,6 +154,51 @@ function renderSuggestions() { ${_showAllSuggestions ? 'Show fewer' : `Show all ${list.length}`}` : ''}`; } +// ── Port names in UniFi ───────────────────────────────────────────────── +const PORT_NAME_GROUPS = [ + ['wrong', 'Named after the wrong device', 'cs-chip-bad'], + ['moved', 'Named after a device that moved', 'cs-chip-warn'], + ['empty', 'Named, but nothing is plugged in', ''], + ['unnamed', 'Unnamed, with a known device plugged in', ''], +]; + +// Wrong and moved names are worth fixing; empty and unnamed ports are only worth a look +function portFixes() { + return (_cs.port_names || []).filter(r => r.kind === 'wrong' || r.kind === 'moved').length; +} + +function renderPortNames() { + const rows = _cs.port_names || []; + document.getElementById('cs-portnames-count').textContent = rows.length; + const wrap = document.getElementById('cs-portnames'); + if (!rows.length) { + wrap.innerHTML = emptyState('✅', 'Every port name fits what is plugged in', ''); + return; + } + wrap.innerHTML = PORT_NAME_GROUPS.map(([kind, title, cls]) => { + const list = rows.filter(r => r.kind === kind); + if (!list.length) return ''; + const table = `
+ + + + ${list.map(r => ` + + + + + + `).join('')} + +
${esc(title)}
Switch portName in UniFiWhat Gandalf seesSuggested name
${deviceLink(r.switch)} port ${esc(r.port_idx)}${esc(r.port_name)}${esc(r.detail)}${r.suggestion ? `${esc(r.suggestion)}` : 'your call'}
+
`; + // The long, low-priority group starts folded + const open = kind !== 'unnamed' ? ' open' : ''; + return `
+ ${list.length} ${esc(title)}${table}
`; + }).join(''); +} + function cableAt(name, port, side) { return _cs.cables.find(c => c.status !== 'retired' && ['a', 'b'].some(e => c[`${e}_device`] === name && c[`${e}_port`] === String(port) && c[`${e}_side`] === side)); @@ -331,6 +377,7 @@ function render() { renderSummary(); renderCables(); renderSuggestions(); + renderPortNames(); renderPanels(); renderLabels(); renderRack(); @@ -700,7 +747,10 @@ function printLabels() { function openFromQuery() { const q = new URLSearchParams(window.location.search); if (!CS_CAN_EDIT || !q.get('a_device')) return; - openCable(null, { a_device: q.get('a_device'), a_port: q.get('a_port') || '' }); + openCable(null, { + a_device: q.get('a_device'), a_port: q.get('a_port') || '', + b_device: q.get('b_device') || '', b_port: q.get('b_port') || '', cable_type: q.get('cable_type') || '', + }); history.replaceState(null, '', window.location.pathname); } diff --git a/static/style.css b/static/style.css index 9a723fc..99d9895 100644 --- a/static/style.css +++ b/static/style.css @@ -1102,6 +1102,9 @@ polygon.fp-led-off { fill: #6b6c71; } .cs-chip-bad { border-color: var(--status-critical, #e0312b); } .cs-chip-bad b { color: var(--status-critical, #e0312b); } .cs-chip-warn b { color: var(--accent-amber, #f0a020); } +.cs-portname-group { margin: 0 0 12px; } +.cs-portname-group > summary { cursor: pointer; list-style-position: inside; margin-bottom: 8px; } +.cs-portname-group code { white-space: nowrap; } .cs-filters { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; margin-bottom: 10px; } .cs-filters .lt-input { flex: 1 1 240px; min-width: 0; } .cs-filters .lt-select { flex: 0 1 180px; } diff --git a/static/topology.js b/static/topology.js index 185e7ca..6a752a5 100644 --- a/static/topology.js +++ b/static/topology.js @@ -974,6 +974,23 @@ function endHtml(end, byId) { return `${name}${where ? ` · ${where}` : ''}`; } +// A link to the cutsheet's new-cable form, filled in with both ends as Gandalf sees them +function documentLink(link, byId) { + if (!TOPO_CAN_EDIT || link.ghost || link.bundle) return ''; + const sw = [link.a, link.b].find(e => e.port_idx != null && (byId[e.node] || {}).kind !== 'stub'); + if (!sw) return ''; + const far = sw === link.a ? link.b : link.a; + const farNode = byId[far.node] || {}; + const q = new URLSearchParams({ a_device: sw.node, a_port: String(sw.port_idx) }); + if (farNode.kind && farNode.kind !== 'stub') { + q.set('b_device', far.node); + if (far.port_idx != null) q.set('b_port', String(far.port_idx)); + else if (far.iface) q.set('b_port', far.iface); + } + if (link.medium === 'dac') q.set('cable_type', 'DAC'); + return ` · document it`; +} + function showPanel(link) { const byId = Object.fromEntries(state.data.nodes.map(n => [n.id, n])); const panel = document.getElementById('tp-panel'); @@ -1001,7 +1018,7 @@ function showPanel(link) { ? `
into ${esc(far.device)}${far.port ? ` port ${esc(far.port)}` : ''}` : ''; row('Cutsheet', `${esc(label)}${link.cable.type ? ` · ${esc(link.cable.type)}` : ''}${link.cable.color ? ` · ${esc(link.cable.color)}` : ''}${to}`); } else if (!link.wan) { - row('Cutsheet', 'not documented'); + row('Cutsheet', `not documented${documentLink(link, byId)}`); } const warn = link.name_mismatch ? `

⚠ The port is named after ${esc(link.name_mismatch.named)}, but ${esc(link.name_mismatch.actual)} is plugged into it. Rename the port in UniFi, or check the cable.

` diff --git a/templates/cutsheet.html b/templates/cutsheet.html index 5894592..6bc5598 100644 --- a/templates/cutsheet.html +++ b/templates/cutsheet.html @@ -47,6 +47,15 @@
+
+
+

Port names in UniFi

+ 0 +
+

Switch port names that no longer fit what is plugged in, as a checklist. Rename them in UniFi: Gandalf only reports them and never changes UniFi.

+
+
+

Patch panels

diff --git a/tests/test_app.py b/tests/test_app.py index ca56e1a..e87b70e 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -217,6 +217,7 @@ class TestCutsheetApi: assert view['next_label'] == 'C01' assert view['labels']['cables'][0]['text'] == 'C07' assert any(d['name'] == 'PP1' for d in view['catalog']) + assert isinstance(view['port_names'], list) def test_create_cable(self, cs_client): client, db = cs_client diff --git a/tests/test_topology.py b/tests/test_topology.py index 69de108..ab12fb0 100644 --- a/tests/test_topology.py +++ b/tests/test_topology.py @@ -426,3 +426,63 @@ class TestPower: def test_every_power_device_is_listed(self): assert [s['node'] for s in self._graph()['power']] == ['RPDU', 'UPS 2U Pro', 'USP Strip'] + + +class TestPortNameReport: + def _report(self, poe_port_11='Port 11', pbs_up=True, extra=(), known=None): + snapshot, link_stats, modem = network(poe_port_11, pbs_up) + link_stats['unifi_switches']['24RJ45-POE']['ports'].update(dict(extra)) + return topology.port_name_report(snapshot, link_stats, modem, known) + + def _row(self, rows, sw, idx): + return next((r for r in rows if r['switch'] == sw and r['port_idx'] == idx), None) + + def test_named_after_the_wrong_device(self): + rows = self._report(poe_port_11='Host-A Management') + r = self._row(rows, '24RJ45-POE', 11) + assert r['kind'] == 'wrong' and r['suggestion'] == 'AP' + assert r['detail'] == ('Named after host-a, but AP is plugged in; ' + 'host-a is on 8SFP-AGG port 1, Dream Machine Pro port 1') + assert rows[0] is r # the most urgent kind comes first + + def test_named_after_a_device_that_moved(self): + rows = self._report(extra=[port(20, 'host-c', up=False)]) + r = self._row(rows, '24RJ45-POE', 20) + assert r['kind'] == 'moved' and r['suggestion'] == 'Port 20' + assert r['detail'] == 'Named after host-c, which is now on 8SFP-AGG port 8' + + def test_named_but_empty_says_who_was_last_seen(self): + known = {'pbs': {'uplinks': [{'switch': '24RJ45-POE', 'port_idx': 7}], 'seen': '2026-11-01 10:00:00 UTC'}} + rows = self._report(extra=[port(7, 'Guest Bedroom', up=False)], known=known) + r = self._row(rows, '24RJ45-POE', 7) + assert r['kind'] == 'empty' and r['suggestion'] == '' + assert r['detail'] == ('Nothing plugged in; last seen here: pbs (2026-11-01 10:00:00 UTC), ' + 'now on 24RJ45-POE port 15') + + def test_unnamed_ports_get_a_suggestion(self): + rows = self._report() + # A server with two cables gets its NIC in the name; a switch-to-switch port is a downlink + assert self._row(rows, '24RJ45-POE', 4)['suggestion'] == 'host-b enp2s0' + assert self._row(rows, '24RJ45-POE', 19)['suggestion'] == 'RPDU' + assert self._row(rows, '8SFP-AGG', 7)['suggestion'] == 'Uplink' + assert self._row(rows, '8SFP-AGG', 8)['suggestion'] == 'host-c' + assert {r['kind'] for r in rows} == {'unnamed'} + + def test_good_names_and_unknown_devices_are_left_alone(self): + rows = self._report() + for sw, idx in [('24RJ45-POE', 15), # "PBS" with pbs plugged in + ('24RJ45-POE', 3), # "Living Room Downlink" to the Flex + ('8SFP-AGG', 5), # "Downlink to 24RJ45-POE" + ('24RJ45-POE', 1), # a custom name over an unknown device + ('24RJ45-POE', 8), # an IP-only target + ('24RJ45-POE', 12), # "Port 12", nothing plugged in + ('RPDU', 1)]: # a PDU's management port + assert self._row(rows, sw, idx) is None, (sw, idx) + + def test_a_port_named_after_a_device_that_is_off_is_right(self): + rows = self._report(pbs_up=False) + for sw, idx in [('24RJ45-POE', 15)]: # "PBS" while pbs is down + assert self._row(rows, sw, idx) is None, (sw, idx) + + def test_no_data(self): + assert topology.port_name_report({}, {}, None) == [] diff --git a/topology.py b/topology.py index 5563d79..3b55364 100644 --- a/topology.py +++ b/topology.py @@ -135,6 +135,99 @@ def _named_device(text: str, known: Dict[str, str], skip=()) -> Optional[str]: return None +# What each port-name finding means, most urgent first +PORT_NAME_KINDS = ('wrong', 'moved', 'empty', 'unnamed') + + +def _port_name_suggestion(neighbour: str, kind: str, port: dict, links: int) -> str: + if kind in ('router', 'switch'): + return 'Uplink' if port.get('is_uplink') else f'Downlink to {neighbour}' + iface = str((port.get('lldp') or {}).get('port_id') or '') + # A server with two cables: say which NIC, so the two ports read differently + if kind == 'host' and links > 1 and iface and not _MAC_IN_TEXT.fullmatch(iface): + return f'{neighbour} {iface}' + return neighbour + + +def port_name_report(snapshot: dict, link_stats: dict, modem: Optional[dict], + known_uplinks: Optional[dict] = None) -> List[dict]: + """UniFi port names that no longer fit what is plugged in, as a checklist to fix in UniFi. + + Each row is {switch, port_idx, port_name, kind, neighbour, suggestion, detail}, kind one of: + wrong: named after one device, with a different known device plugged in + moved: named after a device that is now linked on another port, with nothing known here + empty: a custom name on a port with nothing plugged in (with who was last seen there) + unnamed: still "Port N" / "SFP+ N" with a known device plugged in + Gandalf only reports these; it never renames anything in UniFi. + """ + snapshot = snapshot or {} + link_stats = link_stats or {} + switches = link_stats.get('unifi_switches') or {} + configured = set(snapshot.get('hosts') or {}) + kinds = {e['name']: e['kind'] for e in devices.build_index(snapshot, link_stats, modem) + if e['kind'] != 'host' or e['name'] in configured} + known = {_norm(n): n for n in kinds} + + # Where each known device is linked right now, and who was last seen on each port + live_at: Dict[str, List[str]] = {} + for sw_name, sw in sorted(switches.items()): + for p in (sw.get('ports') or {}).values(): + nb = (p.get('lldp') or {}).get('system_name') or '' + if p.get('up') and nb in kinds and p.get('port_idx') is not None: + live_at.setdefault(nb, []).append(f'{sw_name} port {p["port_idx"]}') + last_seen: Dict[Tuple[str, int], Tuple[str, str]] = {} + for name, entry in (known_uplinks or {}).items(): + for up in (entry or {}).get('uplinks') or []: + if up.get('switch') and up.get('port_idx') is not None: + last_seen[(up['switch'], up['port_idx'])] = (name, (entry or {}).get('seen') or '') + + rows: List[dict] = [] + for sw_name in sorted(switches): + if kinds.get(sw_name) in POWER_KINDS or _POWER_MODELS.get((switches[sw_name] or {}).get('model', '')): + continue # a PDU's one management port + for pname, port in (switches[sw_name].get('ports') or {}).items(): + idx = port.get('port_idx') + if idx is None: + continue + nb = (port.get('lldp') or {}).get('system_name') or '' + nb = nb if nb in kinds and nb != sw_name else '' + generic = _is_generic_port_name(pname) + row = {'switch': sw_name, 'port_idx': idx, 'port_name': pname, 'neighbour': nb, + 'suggestion': '', 'detail': ''} + named = None if generic else _named_device(pname, known, {_norm(sw_name)}) + if nb and port.get('up'): + suggestion = _port_name_suggestion(nb, kinds[nb], port, len(live_at.get(nb, []))) + if named and named != nb and _norm(named) != _norm(nb): + elsewhere = [w for w in live_at.get(named, []) if w != f'{sw_name} port {idx}'] + row.update(kind='wrong', suggestion=suggestion, + detail=f'Named after {named}, but {nb} is plugged in' + + (f'; {named} is on {", ".join(elsewhere)}' if elsewhere else '')) + elif generic and not pname.lower().startswith(('uplink', 'downlink')): + row.update(kind='unnamed', suggestion=suggestion, + detail=f'{nb} is plugged in') + else: + continue + elif named and named in live_at: + row.update(kind='moved', suggestion=f'Port {idx}' if not port.get('up') else '', + detail=f'Named after {named}, which is now on {", ".join(live_at[named])}') + elif named: + continue # named after a known device that is just not linked now: the name is right + elif not generic and not port.get('up') and not port.get('lldp'): + seen = last_seen.get((sw_name, idx)) + detail = 'Nothing plugged in' + if seen: + detail += f'; last seen here: {seen[0]}' + (f' ({seen[1]})' if seen[1] else '') + if seen[0] in live_at: + detail += f', now on {", ".join(live_at[seen[0]])}' + row.update(kind='empty', detail=detail) + else: + continue + rows.append(row) + order = {k: i for i, k in enumerate(PORT_NAME_KINDS)} + rows.sort(key=lambda r: (order[r['kind']], r['switch'].lower(), r['port_idx'])) + return rows + + _MAC_IN_TEXT = re.compile(r'\b([0-9a-f]{2}(?:[:-][0-9a-f]{2}){5})\b', re.IGNORECASE)