feat: switch panel and PDF also use the VLANs assigned to cables

Ports without a label show the VLANs of their cable. A label with exactly
one number counts as that VLAN ID, so "Server 30", "VLAN 30", "30" and a
cable with VLAN 30 share one colour and legend entry. A numeric label that
differs from the cable VLANs is flagged with an orange corner and a
warning; tooltips and the PDF port list show label and cable VLANs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
MrBlakeandClaude Opus 5.5 committed 2026-10-30 10:17:54 +01:00
1 parent e9c00f2b11
commit 6906bf6ed6
9 files changed
+200 -39

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
from netbox.plugins import PluginConfig, get_plugin_config
__version__ = "0.19.1"
__version__ = "0.20.0"
class NetBoxUtilitiesConfig(PluginConfig):
@@ -545,3 +545,20 @@ a.nbu-disk-slot[draggable="true"] {
border: 1px solid var(--nbu-jack-border);
}
.nbu-jack-swatch.nbu-jack-disabled::after { top: .1rem; right: .1rem; width: .3rem; height: .3rem; }
/* Label and cable VLAN differ: orange corner, visible in both views */
.nbu-jack-mismatch::before,
.nbu-jack-sfp.nbu-jack-mismatch::before {
content: "";
position: absolute;
top: -1px;
left: -1px;
bottom: auto;
width: 0;
height: 0;
transform: none;
border-radius: .2rem 0 0 0;
border-style: solid;
border-width: .45rem .45rem 0 0;
border-color: #fd7e14 transparent transparent transparent;
background: none;
}
+42 -10
View File
@@ -27,13 +27,18 @@ TEXTS = {
"free": "Frei",
"disabled": "Deaktiviert",
"front": "Frontansicht",
"legend_state": "Kräftige Farbe mit dickem Rahmen = belegt · blasse Farbe = frei · gestrichelt mit ✕ = deaktiviert",
"legend_vlan": "VLANs (Label)",
"legend_state": (
"Kräftige Farbe mit dickem Rahmen = belegt · blasse Farbe = frei · gestrichelt mit ✕ = deaktiviert"
" · oranges Eck = Label und Kabel-VLAN weichen ab"
),
"legend_vlan": "VLANs (Label / Kabel)",
"no_label": "ohne Label",
"list": "Alle Schnittstellen",
"port": "Port",
"status": "Status",
"vlan": "VLAN (Label)",
"vlan_cable": "VLAN (Kabel)",
"mismatch": "weicht ab",
"peer": "Gegenstelle",
"description": "Beschreibung",
"type": "Typ",
@@ -57,13 +62,18 @@ TEXTS = {
"free": "Free",
"disabled": "Disabled",
"front": "Front panel",
"legend_state": "Strong colour with thick border = connected · pale colour = free · dashed with ✕ = disabled",
"legend_vlan": "VLANs (label)",
"legend_state": (
"Strong colour with thick border = connected · pale colour = free · dashed with ✕ = disabled"
" · orange corner = label and cable VLAN differ"
),
"legend_vlan": "VLANs (label / cable)",
"no_label": "no label",
"list": "All interfaces",
"port": "Port",
"status": "Status",
"vlan": "VLAN (label)",
"vlan_cable": "VLAN (cable)",
"mismatch": "differs",
"peer": "Peer",
"description": "Description",
"type": "Type",
@@ -90,6 +100,7 @@ FREE_FILL = colors.white
UNLABELLED_FILL = colors.HexColor("#e9ecef")
BORDER_DARK = colors.HexColor("#212529")
BORDER_LIGHT = colors.HexColor("#adb5bd")
MISMATCH = colors.HexColor("#fd7e14")
def language(code):
@@ -191,6 +202,16 @@ class PortPanel(Flowable):
vlan = vlan[:-1]
canvas.drawCentredString(x + self.tile_w / 2, y + 1.6 * mm, vlan)
if port.vlan_mismatch:
# Orange corner: label and cable VLAN differ.
canvas.setFillColor(MISMATCH)
path = canvas.beginPath()
path.moveTo(x, y + TILE_H)
path.lineTo(x + 2.4 * mm, y + TILE_H)
path.lineTo(x, y + TILE_H - 2.4 * mm)
path.close()
canvas.drawPath(path, stroke=0, fill=1)
if disabled:
# Small cross in the top right corner, away from the text.
size, inset = 1.4 * mm, 0.7 * mm
@@ -296,8 +317,17 @@ def _legend(ports, t, styles):
return [Paragraph(f"<b>{t['legend_vlan']}</b>", styles["small"]), Spacer(0, 1 * mm), table]
def _cable_cell(port, t):
if not port.cable_vlans:
return "–"
text = _escape(port.cable_vlan_text)
if port.vlan_mismatch:
text += f" <font color='#fd7e14'><b>⚠ {t['mismatch']}</b></font>"
return text
def _port_table(ports, t, styles):
header = [t["port"], t["status"], t["vlan"], t["peer"], t["description"], t["type"], t["lag"]]
header = [t["port"], t["status"], t["vlan"], t["vlan_cable"], t["peer"], t["description"], t["type"], t["lag"]]
data = [[Paragraph(f"<b>{text}</b>", styles["cell"]) for text in header]]
style = [
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#dee2e6")),
@@ -319,6 +349,7 @@ def _port_table(ports, t, styles):
Paragraph(name, styles["cell"]),
Paragraph(states[port.state], styles["cell"]),
Paragraph(_escape(port.label) or "–", styles["cell"]),
Paragraph(_cable_cell(port, t), styles["cell"]),
Paragraph(_escape(peer) or "–", styles["cell"]),
Paragraph(_escape(port.description) or "–", styles["cell"]),
Paragraph(_escape(port.type_display), styles["cell"]),
@@ -327,14 +358,15 @@ def _port_table(ports, t, styles):
)
if port.color:
fill = colors.HexColor(port.color)
style.append(("BACKGROUND", (2, index), (2, index), fill))
data[index][2] = Paragraph(
f"<font color='{hex_of(text_color(fill))}'>{_escape(port.label)}</font>", styles["cell"]
)
# Colour the column the VLAN comes from: the label, or the cable if there is no label.
column = 2 if port.label else 3
text = _escape(port.label) if port.label else _escape(port.cable_vlan_text)
style.append(("BACKGROUND", (column, index), (column, index), fill))
data[index][column] = Paragraph(f"<font color='{hex_of(text_color(fill))}'>{text}</font>", styles["cell"])
if port.state == switch_ports.STATE_DISABLED:
style.append(("TEXTCOLOR", (0, index), (1, index), colors.HexColor("#6c757d")))
width = PAGE[0] - 2 * MARGIN
widths = [w * width for w in (0.15, 0.07, 0.11, 0.25, 0.22, 0.13, 0.07)]
widths = [w * width for w in (0.14, 0.07, 0.10, 0.12, 0.21, 0.17, 0.13, 0.06)]
table = Table(data, colWidths=widths, repeatRows=1)
table.setStyle(TableStyle(style))
return table
+26 -13
View File
@@ -6,6 +6,7 @@ from django.views import View
from utilities.views import ContentTypePermissionRequiredMixin
from . import switch_port_pdf, switch_ports
from .runtime import connection_vlans_enabled
def _describe(endpoint):
@@ -26,6 +27,28 @@ def _peer(interface):
return ", ".join(_describe(endpoint) for endpoint in endpoints or [])
def _cable_vlans(interface):
"""[(vid, name)] of the VLANs assigned to the interface's cable, if connection VLANs are in use."""
if not interface.cable_id:
return []
assignment = getattr(interface.cable, "netbox_utilities_vlan_assignment", None)
if assignment is None:
return []
return [(vlan.vid, vlan.name) for vlan in assignment.vlans.all()]
def interface_queryset(request, device):
interfaces = (
Interface.objects.restrict(request.user, "view")
.filter(device=device)
.select_related("lag", "cable", "_path")
.order_by("_name")
)
if connection_vlans_enabled():
interfaces = interfaces.prefetch_related("cable__netbox_utilities_vlan_assignment__vlans")
return interfaces
def collect_ports(interfaces):
ports = []
for interface in interfaces:
@@ -46,6 +69,7 @@ def collect_ports(interfaces):
peer=peer,
lag=interface.lag.name if interface.lag_id else "",
url=interface.get_absolute_url(),
cable_vlans=_cable_vlans(interface) if connection_vlans_enabled() else [],
virtual=interface.type in switch_ports.VIRTUAL_TYPES,
)
)
@@ -54,13 +78,7 @@ def collect_ports(interfaces):
def switch_panel_context(request, device):
"""Front panel above the "Device" and "Management" cards, in the user's NetBox language."""
interfaces = (
Interface.objects.restrict(request.user, "view")
.filter(device=device)
.select_related("lag", "cable", "_path")
.order_by("_name")
)
ports = collect_ports(interfaces)
ports = collect_ports(interface_queryset(request, device))
switch_ports.assign_vlan_colors(ports)
texts = switch_ports.PANEL_TEXTS[switch_port_pdf.language(translation.get_language())]
for port in ports:
@@ -99,12 +117,7 @@ class SwitchPortsPDFView(ContentTypePermissionRequiredMixin, View):
device = get_object_or_404(
Device.objects.restrict(request.user, "view").select_related("site", "rack", "device_type"), pk=pk
)
interfaces = (
Interface.objects.restrict(request.user, "view")
.filter(device=device)
.select_related("lag", "cable", "_path")
.order_by("_name")
)
interfaces = interface_queryset(request, device)
lang = switch_port_pdf.language(translation.get_language())
pdf = switch_port_pdf.build_pdf(
device_info(device), collect_ports(interfaces), lang=lang, generated=timezone.localtime()
+59 -12
View File
@@ -57,6 +57,9 @@ PANEL_TEXTS = {
"peer": "Gegenstelle",
"marked": "als verbunden markiert",
"none": "Keine physischen Schnittstellen.",
"vlan_label": "VLAN (Label)",
"vlan_cable": "VLAN (Kabel)",
"mismatch": "Label und Kabel-VLAN weichen ab",
},
"en": {
"title": "Ports",
@@ -71,6 +74,9 @@ PANEL_TEXTS = {
"peer": "Peer",
"marked": "marked as connected",
"none": "No physical interfaces.",
"vlan_label": "VLAN (label)",
"vlan_cable": "VLAN (cable)",
"mismatch": "Label and cable VLAN differ",
},
}
@@ -162,6 +168,8 @@ class Port:
assigned_color: str = ""
# Translated status for tooltips, set by the view.
state_text: str = ""
# VLANs assigned to the cable of the port (connection VLANs): [(vid, name)].
cable_vlans: list = field(default_factory=list)
@property
def state(self):
@@ -193,7 +201,26 @@ class Port:
@property
def vlan(self):
return vlan_key(self.label)
"""The VLAN shown for the port: the label, or the VLANs of its cable if it has no label."""
return vlan_key(self.label) or self.cable_vlan_key
@property
def cable_vlan_key(self):
""" "10" or "10, 20" from the cable VLANs, matching the normalised labels."""
return ", ".join(str(vid) for vid in sorted({vid for vid, _ in self.cable_vlans}))
@property
def cable_vlan_text(self):
""" "10 Server, 20 VoIP" for tooltips and the port list."""
return ", ".join(f"{vid} {name}".strip() for vid, name in sorted(self.cable_vlans))
@property
def vlan_mismatch(self):
"""True if the numbers in the label differ from the cable VLANs; labels without numbers never mismatch."""
if not self.label or not self.cable_vlans:
return False
label_ids = {int(number) for number in _NATURAL.findall(self.label) if number.isdigit()}
return bool(label_ids) and label_ids != {vid for vid, _ in self.cable_vlans}
@property
def ink(self):
@@ -204,7 +231,19 @@ class Port:
def color(self):
if not self.vlan:
return None
return self.assigned_color or vlan_color(self.label)
return self.assigned_color or vlan_color(self.vlan_group)
@property
def vlan_group(self):
"""Identity of the VLAN for colours and the legend.
A label with exactly one number is that VLAN ID, so "Server 30", "VLAN 30", "30" and a cable
with VLAN 30 belong together; other labels ("Trunk", "10,20") stay as they are.
"""
if self.label:
numbers = [number for number in _NATURAL.findall(self.label) if number.isdigit()]
return str(int(numbers[0])) if len(numbers) == 1 else vlan_key(self.label)
return self.cable_vlan_key
@dataclass
@@ -279,26 +318,34 @@ def assign_vlan_colors(ports):
Only with more VLANs than palette colours do the remaining ones fall back to the hash colour.
"""
vlans = sorted({port.vlan for port in ports if port.vlan}, key=natural_key)
colors = {vlan: VLAN_PALETTE[index] for index, vlan in enumerate(vlans[: len(VLAN_PALETTE)])}
groups = sorted({port.vlan_group for port in ports if port.vlan_group}, key=natural_key)
colors = {group: VLAN_PALETTE[index] for index, group in enumerate(groups[: len(VLAN_PALETTE)])}
for port in ports:
if port.vlan:
port.assigned_color = colors.get(port.vlan, "")
if port.vlan_group:
port.assigned_color = colors.get(port.vlan_group, "")
return colors
def vlan_legend(ports):
"""[(vlan, colour, port count, connected count)] sorted naturally; unlabelled ports last."""
counts = {}
colors = {}
"""[(text, colour, port count, connected count)] per VLAN in natural order; ports without VLAN last.
Ports are grouped by vlan_group; the text is the first label of the group (e.g. "Server 30"),
or the cable VLANs if no port of the group has a label.
"""
counts, colors, names, labelled = {}, {}, {}, set()
for port in ports:
if port.virtual:
continue
colors.setdefault(port.vlan, port.color)
entry = counts.setdefault(port.vlan, [0, 0])
group = port.vlan_group
colors.setdefault(group, port.color)
if port.label and group not in labelled:
names[group] = port.vlan
labelled.add(group)
names.setdefault(group, port.vlan)
entry = counts.setdefault(group, [0, 0])
entry[0] += 1
entry[1] += port.state == STATE_CONNECTED
legend = [(vlan, colors[vlan], total, connected) for vlan, (total, connected) in counts.items() if vlan]
legend = [(names[group], colors[group], total, connected) for group, (total, connected) in counts.items() if group]
legend.sort(key=lambda item: natural_key(item[0]))
if "" in counts:
legend.append(("", None, counts[""][0], counts[""][1]))
@@ -29,10 +29,10 @@
<div class="nbu-faceplate-column">
{% for port in column %}
<a href="{{ port.url }}"
class="nbu-jack nbu-jack-{{ port.state }}{% if group.optical %} nbu-jack-sfp{% endif %}{% if port.color %} nbu-jack-labelled{% endif %}{% if port.is_management %} nbu-jack-mgmt{% endif %}"
class="nbu-jack nbu-jack-{{ port.state }}{% if group.optical %} nbu-jack-sfp{% endif %}{% if port.color %} nbu-jack-labelled{% endif %}{% if port.is_management %} nbu-jack-mgmt{% endif %}{% if port.vlan_mismatch %} nbu-jack-mismatch{% endif %}"
{% if port.color %}style="--nbu-vlan: {{ port.color }}; --nbu-ink: {{ port.ink }}"{% endif %}
data-bs-toggle="tooltip" data-bs-html="true"
title="<strong>{{ port.name|force_escape }}</strong><br>{{ port.state_text }}{% if port.label %}<br>{{ texts.vlan }}: {{ port.label|force_escape }}{% endif %}{% if port.peer %}<br>{{ texts.peer }}: {{ port.peer|force_escape }}{% endif %}{% if port.description %}<br><em>{{ port.description|force_escape }}</em>{% endif %}">
title="<strong>{{ port.name|force_escape }}</strong><br>{{ port.state_text }}{% if port.label %}<br>{{ texts.vlan_label }}: {{ port.label|force_escape }}{% endif %}{% if port.cable_vlans %}<br>{{ texts.vlan_cable }}: {{ port.cable_vlan_text|force_escape }}{% endif %}{% if port.vlan_mismatch %}<br><span class='text-warning'>⚠ {{ texts.mismatch }}</span>{% endif %}{% if port.peer %}<br>{{ texts.peer }}: {{ port.peer|force_escape }}{% endif %}{% if port.description %}<br><em>{{ port.description|force_escape }}</em>{% endif %}">
<span class="nbu-jack-number">{{ port.short }}</span>
<span class="nbu-jack-vlan">{{ port.vlan }}</span>
</a>
@@ -157,3 +157,40 @@ class ManagementTest(SimpleTestCase):
def test_other_ports_without_number_are_shortened(self):
self.assertEqual(port("console").short, "conso")
class CableVlanTest(SimpleTestCase):
def test_cable_vlans_are_used_without_label(self):
p = port("Gi1/0/1", cable_vlans=[(20, "VoIP"), (10, "Office")])
self.assertEqual(p.vlan, "10, 20")
self.assertEqual(p.cable_vlan_text, "10 Office, 20 VoIP")
self.assertFalse(p.vlan_mismatch)
def test_label_wins_and_cable_vlan_shares_its_colour(self):
labelled = port("Gi1/0/1", label="VLAN 10", cable_vlans=[(10, "Office")])
cable_only = port("Gi1/0/2", cable_vlans=[(10, "Office")])
switch_ports.assign_vlan_colors([labelled, cable_only])
self.assertEqual(labelled.vlan, "10")
self.assertEqual(labelled.color, cable_only.color)
self.assertFalse(labelled.vlan_mismatch)
def test_mismatch_only_for_numeric_labels(self):
self.assertTrue(port("1", label="20", cable_vlans=[(30, "")]).vlan_mismatch)
self.assertTrue(port("2", label="Server 30", cable_vlans=[(30, ""), (40, "")]).vlan_mismatch)
self.assertFalse(port("3", label="Trunk", cable_vlans=[(30, "")]).vlan_mismatch)
self.assertFalse(port("4", label="10,20", cable_vlans=[(20, ""), (10, "")]).vlan_mismatch)
class VlanIdentityTest(SimpleTestCase):
def test_label_number_and_cable_vlan_are_one_vlan(self):
ports = [
port("1", label="Server 30", connected=True),
port("2", label="VLAN 30"),
port("3", cable_vlans=[(30, "Server")], connected=True),
port("4", label="Trunk"),
port("5", label="10,20"),
]
switch_ports.assign_vlan_colors(ports)
self.assertEqual(len({p.color for p in ports[:3]}), 1)
legend = [(text, total, connected) for text, _, total, connected in switch_ports.vlan_legend(ports)]
self.assertEqual(legend, [("10,20", 1, 0), ("Server 30", 3, 2), ("Trunk", 1, 0)])