Cutsheet: port names in UniFi that no longer fit, document a cable from topology
Lint / JS (eslint) (push) Successful in 23s
Lint / Python (flake8) (push) Successful in 1m10s
Lint / Notify on failure (push) Skipped
Lint / Deploy (push) Skipped
Lint / Python (flake8) (pull_request) Successful in 53s
Lint / JS (eslint) (pull_request) Successful in 11s
Lint / Notify on failure (pull_request) Skipped
Lint / Deploy (pull_request) Skipped
Security / Python Security (bandit) (push) Successful in 1m26s
Test / Python Tests (pytest) (push) Successful in 1m49s
Security / Python Security (bandit) (pull_request) Successful in 2m17s
Test / Python Tests (pytest) (pull_request) Successful in 2m12s

- 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 <noreply@anthropic.com>
This commit is contained in:
2026-11-15 13:48:52 -05:00
co-authored by Claude Opus 5.5
parent d6fcddb6fc
commit 4dfabce2fb
9 changed files with 248 additions and 3 deletions
+10 -1
View File
@@ -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
+3
View File
@@ -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,
+51 -1
View File
@@ -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}`}</button>` : ''}`;
}
// ── 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 = `<div class="lt-table-wrap">
<table class="lt-table lt-table-sm">
<caption class="lt-sr-only">${esc(title)}</caption>
<thead><tr><th>Switch port</th><th>Name in UniFi</th><th>What Gandalf sees</th><th>Suggested name</th></tr></thead>
<tbody>${list.map(r => `
<tr>
<td>${deviceLink(r.switch)} <a class="cs-port" href="/device/${encodeURIComponent(r.switch)}#port-${esc(r.port_idx)}">port ${esc(r.port_idx)}</a></td>
<td>${esc(r.port_name)}</td>
<td>${esc(r.detail)}</td>
<td>${r.suggestion ? `<code>${esc(r.suggestion)}</code>` : '<span class="val-neutral">your call</span>'}</td>
</tr>`).join('')}
</tbody>
</table>
</div>`;
// The long, low-priority group starts folded
const open = kind !== 'unnamed' ? ' open' : '';
return `<details class="cs-portname-group"${open}>
<summary><span class="cs-chip ${cls}"><b>${list.length}</b> ${esc(title)}</span></summary>${table}</details>`;
}).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);
}
+3
View File
@@ -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; }
+18 -1
View File
@@ -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 ` · <a class="device-link" href="/cutsheet?${esc(q.toString())}">document it</a>`;
}
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) {
? `<br><span class="tp-dim-text">into ${esc(far.device)}${far.port ? ` port ${esc(far.port)}` : ''}</span>` : '';
row('Cutsheet', `<a class="device-link" href="/cutsheet#cable-${esc(link.cable.id)}">${esc(label)}</a>${link.cable.type ? ` · ${esc(link.cable.type)}` : ''}${link.cable.color ? ` · ${esc(link.cable.color)}` : ''}${to}`);
} else if (!link.wan) {
row('Cutsheet', '<span class="tp-dim-text">not documented</span>');
row('Cutsheet', `<span class="tp-dim-text">not documented</span>${documentLink(link, byId)}`);
}
const warn = link.name_mismatch
? `<p class="tp-panel-warn">⚠ The port is named after <strong>${esc(link.name_mismatch.named)}</strong>, but <strong>${esc(link.name_mismatch.actual)}</strong> is plugged into it. Rename the port in UniFi, or check the cable.</p>`
+9
View File
@@ -47,6 +47,15 @@
<div id="cs-suggestions"></div>
</section>
<section class="g-section no-print" id="cs-portnames-section">
<div class="g-section-header">
<h2 class="g-section-title">Port names in UniFi</h2>
<span class="g-section-badge" id="cs-portnames-count">0</span>
</div>
<p class="cs-hint">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.</p>
<div id="cs-portnames"></div>
</section>
<section class="g-section" id="cs-panels-section">
<div class="g-section-header">
<h2 class="g-section-title">Patch panels</h2>
+1
View File
@@ -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
+60
View File
@@ -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) == []
+93
View File
@@ -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)