diff --git a/README.md b/README.md index d7a31db..0037c23 100644 --- a/README.md +++ b/README.md @@ -526,6 +526,21 @@ view in the web interface of Aruba switches: - The chosen view is remembered in the browser; texts follow the user's NetBox language (German or English). +**VLANs from labels and cables.** Besides the interface label, the VLANs +assigned to the port's cable (see *VLANs on connections*) are taken into +account, in the front panel and in the PDF: + +- A port with a label shows the label; a port without a label shows the VLANs + of its cable (e.g. `10` or `10, 20`). +- A label with exactly one number is that VLAN ID, so `Server 30`, `VLAN 30`, + `30` and a cable with VLAN 30 share one colour and one legend entry (named + after the label). Labels like `Trunk` or `10,20` stay as they are. +- If the numbers in the label differ from the cable VLANs (label `20`, cable + VLAN 30), the port gets an orange corner and the tooltip and the PDF port + list show a warning. Labels without a number never count as a mismatch. +- Tooltips and the PDF port list show both the label and the cable VLANs with + their names. + NetBox offers plugins no slot above these cards, so the panel is rendered into the left column and moved to the top by a small script; without JavaScript it stays in the left column. diff --git a/netbox_utilities/__init__.py b/netbox_utilities/__init__.py index f265da9..dfcf512 100644 --- a/netbox_utilities/__init__.py +++ b/netbox_utilities/__init__.py @@ -1,6 +1,6 @@ from netbox.plugins import PluginConfig, get_plugin_config -__version__ = "0.19.1" +__version__ = "0.20.0" class NetBoxUtilitiesConfig(PluginConfig): diff --git a/netbox_utilities/static/netbox_utilities/netbox_utilities.css b/netbox_utilities/static/netbox_utilities/netbox_utilities.css index a2fee94..56fd4f5 100644 --- a/netbox_utilities/static/netbox_utilities/netbox_utilities.css +++ b/netbox_utilities/static/netbox_utilities/netbox_utilities.css @@ -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; +} diff --git a/netbox_utilities/switch_port_pdf.py b/netbox_utilities/switch_port_pdf.py index ed1e4aa..650d87a 100644 --- a/netbox_utilities/switch_port_pdf.py +++ b/netbox_utilities/switch_port_pdf.py @@ -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"{t['legend_vlan']}", 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" ⚠ {t['mismatch']}" + 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"{text}", 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"{_escape(port.label)}", 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"{text}", 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 diff --git a/netbox_utilities/switch_port_views.py b/netbox_utilities/switch_port_views.py index 737aa67..4039629 100644 --- a/netbox_utilities/switch_port_views.py +++ b/netbox_utilities/switch_port_views.py @@ -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() diff --git a/netbox_utilities/switch_ports.py b/netbox_utilities/switch_ports.py index 9e2cee9..fd36648 100644 --- a/netbox_utilities/switch_ports.py +++ b/netbox_utilities/switch_ports.py @@ -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])) diff --git a/netbox_utilities/templates/netbox_utilities/device_switch_panel.html b/netbox_utilities/templates/netbox_utilities/device_switch_panel.html index 589f5f7..b080a60 100644 --- a/netbox_utilities/templates/netbox_utilities/device_switch_panel.html +++ b/netbox_utilities/templates/netbox_utilities/device_switch_panel.html @@ -29,10 +29,10 @@
{% for port in column %} + title="{{ port.name|force_escape }}
{{ port.state_text }}{% if port.label %}
{{ texts.vlan_label }}: {{ port.label|force_escape }}{% endif %}{% if port.cable_vlans %}
{{ texts.vlan_cable }}: {{ port.cable_vlan_text|force_escape }}{% endif %}{% if port.vlan_mismatch %}
⚠ {{ texts.mismatch }}{% endif %}{% if port.peer %}
{{ texts.peer }}: {{ port.peer|force_escape }}{% endif %}{% if port.description %}
{{ port.description|force_escape }}{% endif %}"> {{ port.short }} {{ port.vlan }}
diff --git a/netbox_utilities/tests/test_switch_ports.py b/netbox_utilities/tests/test_switch_ports.py index abe1a35..67debcf 100644 --- a/netbox_utilities/tests/test_switch_ports.py +++ b/netbox_utilities/tests/test_switch_ports.py @@ -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)]) diff --git a/pyproject.toml b/pyproject.toml index 82a1831..c40c349 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "netbox-utilities" -version = "0.19.1" +version = "0.20.0" description = "Navigation, tenant utilities, connection VLANs, partial-width racks, disks, CPU & RAM, switch port export and bulk operations for NetBox 4.6/4.7" readme = "README.md" requires-python = ">=3.12"