diff --git a/README.md b/README.md index e08e440..f7b9cfe 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ Plugin settings: - A **Prefix** column (first word of the site name) for device and rack lists, including sorting and filtering. - A **Disks** tab for servers, NAS, SAN and MSA devices: slot layout, disks, RAID groups, warranty and age warnings, replacement history, CSV import, HPE MSA disk export import, REST API and GraphQL. - **CPU & RAM** per server from a built-in catalogue of 700+ Intel and AMD server CPUs since 2012, with cluster capacity and overcommit for NetBox virtualization. -- A **Ports** tab for switches: front-panel view of all interfaces, coloured by usage or by VLAN (from the interface label), with peers, CSV export and print view. +- **Switch port usage as PDF** for switches: front panel coloured by VLAN (from the interface label) plus the full port list, in the user's NetBox language. Navigation settings are stored per user. The active tenant or tenant-group selection is stored in the browser session. @@ -223,8 +223,8 @@ sudo systemctl restart netbox netbox-rq | `hardware_enabled` | `True` | **CPU & RAM** tab, catalogue, columns and cluster capacity | | `hardware_device_roles` | `["Server"]` | Device roles (case-insensitive) that show the **CPU & RAM** tab; cluster hosts always show it | | `hardware_vcpu_ratio_warning` | `4` | Warn when a host or cluster has more vCPUs per physical core | -| `switch_ports_enabled` | `True` | **Ports** tab for switches | -| `switch_device_roles` | `["Switch"]` | Device roles (case-insensitive) that get the **Ports** tab | +| `switch_ports_enabled` | `True` | **Export switch port usage** button for switches | +| `switch_device_roles` | `["Switch"]` | Device roles (case-insensitive) that get the export button | ## Usage @@ -505,35 +505,35 @@ recording and editing use `netbox_utilities.add_devicehardware` and `netbox_utilities.change_devicehardware`. The catalogue uses the `netbox_utilities.*_cpumodel` permissions. -### Switch ports +### Switch port usage (PDF) -Devices with a role from `switch_device_roles` get a **Ports** tab; the badge -shows used/total physical ports. +Devices with a role from `switch_device_roles` get an **Export switch port +usage** button (*Switch-Belegung exportieren*) on the device page. It +downloads a PDF (A4 landscape) with: -- **Key figures:** physical ports, used (with percentage), free (enabled - without cable) and disabled. -- **Front panel:** every physical interface is a tile, arranged like the - device front with odd ports on top and even ports below. Ports are grouped - by name prefix, i.e. per stack member or line card (`Gi1/0/…`, `Gi2/0/…`), - and SFP/QSFP ports are shown separately. Each tile shows the port number and - the VLAN from the interface **label**. Hovering shows name, VLAN, status, - peer, description, LAG and type; clicking jumps to the port in the table. -- **Colour modes:** *Usage* (used, free, disabled) or *VLAN*: every label - value gets its own colour; `VLAN 10`, `vlan10` and `10` count as the same - VLAN. In VLAN mode the legend lists every VLAN with used/total ports, and a - click on a VLAN highlights only its ports. The chosen mode is remembered in - the browser. -- **Table:** all interfaces (including virtual ones such as LAGs and SVIs) with - status, VLAN label, peer, description, type and LAG, and a search field - that also highlights the matching tiles. -- **Peer:** the far end through patch panels when the cable path is complete, - otherwise the directly cabled object. Interfaces marked as connected count - as used. -- **Export:** *CSV* downloads the port list (semicolon separated, opens in - Excel); *Print* prints the front panel and table with colours. +- **Header:** device, site, rack/position, model and date, plus the key + figures: physical ports, connected (with percentage), free and disabled. +- **Front panel:** every physical interface as a tile, arranged like the + device front with odd ports on top and even ports below, grouped per stack + member or line card (`Gi1/0/…`, `Gi2/0/…`); SFP/QSFP ports are shown + separately. Each tile shows the port number and the VLAN from the interface + **label**. Every VLAN gets its own colour (`VLAN 10`, `vlan10` and `10` count + as the same VLAN); connected ports are filled with the full colour and a + thick border, free ports with a pale version, disabled ports have a dashed + border and a small ✕. The text colour is chosen per tile for the best + contrast (black or white). Tile widths adapt so that a 48-port switch fits + on one row. +- **Legend:** every VLAN with its colour and connected/total ports. +- **Port list:** all interfaces (including virtual ones such as LAGs and SVIs) + with status, VLAN label, peer, description, type and LAG. The peer is the + far end through patch panels when the cable path is complete, otherwise the + directly cabled object; interfaces marked as connected count as used. -The tab requires `dcim.view_interface`. Virtual interfaces (`virtual`, `lag`, -`bridge`) are not counted as ports. +The PDF follows the language set in the user's NetBox preferences (German or +English; other languages fall back to German). The button requires +`dcim.view_interface`. The PDF is generated with +[ReportLab](https://pypi.org/project/reportlab/), which is installed together +with the plugin; it needs no system libraries. ### Pre-filter for the B-side of a cable diff --git a/netbox_utilities/__init__.py b/netbox_utilities/__init__.py index 27b4f32..8c3feae 100644 --- a/netbox_utilities/__init__.py +++ b/netbox_utilities/__init__.py @@ -1,14 +1,12 @@ from netbox.plugins import PluginConfig, get_plugin_config -__version__ = "0.17.0" +__version__ = "0.18.0" class NetBoxUtilitiesConfig(PluginConfig): name = "netbox_utilities" verbose_name = "NetBox Utilities" - description = ( - "Navigation, tenant utilities, connection VLANs, partial-width racks, disks, CPU & RAM and bulk operations" - ) + description = "Navigation, tenant utilities, connection VLANs, partial-width racks, disks, CPU & RAM, switch port export and bulk operations" version = __version__ author = "LKE" base_url = "utilities" @@ -57,9 +55,6 @@ class NetBoxUtilitiesConfig(PluginConfig): from .hardware_integration import install_hardware_support install_hardware_support() - if get_plugin_config("netbox_utilities", "switch_ports_enabled"): - # Registers the "Ports" device tab before NetBox builds the dcim URLs. - from . import switch_port_views # noqa: F401 if get_plugin_config("netbox_utilities", "site_prefix_column_enabled"): from .site_prefix import install_site_prefix_column diff --git a/netbox_utilities/static/netbox_utilities/netbox_utilities.css b/netbox_utilities/static/netbox_utilities/netbox_utilities.css index 3262b95..f42c462 100644 --- a/netbox_utilities/static/netbox_utilities/netbox_utilities.css +++ b/netbox_utilities/static/netbox_utilities/netbox_utilities.css @@ -401,88 +401,3 @@ a.nbu-disk-slot[draggable="true"] { transform: rotate(90deg); } -/* ---------- Switch ports tab ---------- */ -.nbu-port-panel { - display: flex; - flex-wrap: wrap; - gap: .25rem; - padding: .5rem; - border-radius: .5rem; - background: var(--bs-tertiary-bg); - border: 1px solid var(--bs-border-color); -} -.nbu-port-column { - display: flex; - flex-direction: column; - gap: .25rem; -} -.nbu-port { - --nbu-vlan-color: var(--bs-secondary-bg); - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - width: 3.1rem; - height: 2.6rem; - border-radius: .3rem; - border: 2px solid transparent; - text-decoration: none; - line-height: 1.05; - transition: opacity .15s, transform .1s; -} -.nbu-port:hover { - transform: translateY(-1px); - text-decoration: none; -} -.nbu-port-number { - font-weight: 600; - font-size: .8rem; -} -.nbu-port-vlan { - font-size: .62rem; - max-width: 100%; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - padding: 0 .15rem; -} -.nbu-port-optical { - border-radius: .1rem; - width: 3.4rem; -} -/* Colour mode "Belegung" */ -.nbu-port-connected { background: var(--bs-success); color: #fff; } -.nbu-port-free { background: var(--bs-body-bg); color: var(--bs-body-color); border-color: var(--bs-border-color); } -.nbu-port-disabled { - background: repeating-linear-gradient(45deg, var(--bs-secondary-bg), var(--bs-secondary-bg) 4px, var(--bs-tertiary-bg) 4px, var(--bs-tertiary-bg) 8px); - color: var(--bs-secondary-color); - border-color: var(--bs-border-color); -} -/* Colour mode "VLAN": fill by VLAN, the border shows whether the port is in use */ -.nbu-ports-vlan .nbu-port { background: var(--nbu-vlan-color); color: #fff; } -.nbu-ports-vlan .nbu-port:not([style]) { color: var(--bs-body-color); } -.nbu-ports-vlan .nbu-port-free { opacity: .55; border-color: transparent; } -.nbu-ports-vlan .nbu-port-connected { border-color: var(--bs-body-color); } -.nbu-ports-vlan .nbu-port-disabled { opacity: .35; } -.nbu-port-dimmed { opacity: .15 !important; } - -.nbu-port-legend { - display: flex; - flex-wrap: wrap; - gap: .4rem 1rem; - align-items: center; -} -.nbu-port-swatch { - display: inline-block; - width: .9rem; - height: .9rem; - border-radius: .2rem; - margin-right: .3rem; - vertical-align: -.1rem; - border: 1px solid var(--bs-border-color); -} - -@media print { - .nbu-port, .nbu-port-swatch, .badge { -webkit-print-color-adjust: exact; print-color-adjust: exact; } - [data-nbu-port-search], .btn-group, .btn { display: none !important; } -} diff --git a/netbox_utilities/static/netbox_utilities/switch_ports.js b/netbox_utilities/static/netbox_utilities/switch_ports.js deleted file mode 100644 index 353d1e2..0000000 --- a/netbox_utilities/static/netbox_utilities/switch_ports.js +++ /dev/null @@ -1,93 +0,0 @@ -// "Ports" tab of switches: colour mode, VLAN filter, search and tile → table row highlighting. -(function () { - "use strict"; - - const STORAGE_KEY = "netbox_utilities.port_mode"; - - function init() { - const root = document.querySelector("[data-nbu-ports]"); - if (!root) return; - - const tiles = Array.from(root.querySelectorAll("[data-nbu-port]")); - const rows = Array.from(root.querySelectorAll("[data-nbu-port-row]")); - const search = root.querySelector("[data-nbu-port-search]"); - let vlanFilter = null; - - if (window.bootstrap && window.bootstrap.Tooltip) { - tiles.forEach((tile) => window.bootstrap.Tooltip.getOrCreateInstance(tile, { container: "body" })); - } - - function setMode(mode) { - root.classList.toggle("nbu-ports-vlan", mode === "vlan"); - root.querySelectorAll("[data-nbu-legend]").forEach((legend) => { - legend.classList.toggle("d-none", legend.dataset.nbuLegend !== mode); - }); - const radio = root.querySelector(`input[name="nbu-port-mode"][value="${mode}"]`); - if (radio) radio.checked = true; - try { - localStorage.setItem(STORAGE_KEY, mode); - } catch (error) { - /* private mode: the choice is just not remembered */ - } - if (mode !== "vlan") applyFilter(null); - } - - function applyFilter(vlan) { - vlanFilter = vlan; - tiles.forEach((tile) => tile.classList.toggle("nbu-port-dimmed", vlan !== null && tile.dataset.vlan !== vlan)); - root.querySelectorAll("[data-nbu-vlan-filter]").forEach((button) => { - button.classList.toggle("fw-bold", vlan !== null && button.dataset.nbuVlanFilter === vlan); - }); - filterRows(); - } - - function filterRows() { - const query = (search && search.value || "").trim().toLowerCase(); - rows.forEach((row) => { - const matchesText = !query || row.textContent.toLowerCase().includes(query); - const matchesVlan = vlanFilter === null || row.dataset.vlan === vlanFilter; - row.classList.toggle("d-none", !(matchesText && matchesVlan)); - }); - if (query) { - const visible = new Set(rows.filter((row) => !row.classList.contains("d-none")).map((row) => row.dataset.nbuPortRow)); - tiles.forEach((tile) => tile.classList.toggle("nbu-port-dimmed", !visible.has(tile.dataset.nbuPort))); - } else if (vlanFilter === null) { - tiles.forEach((tile) => tile.classList.remove("nbu-port-dimmed")); - } - } - - root.querySelectorAll('input[name="nbu-port-mode"]').forEach((radio) => { - radio.addEventListener("change", () => setMode(radio.value)); - }); - root.querySelectorAll("[data-nbu-vlan-filter]").forEach((button) => { - button.addEventListener("click", () => { - const vlan = button.dataset.nbuVlanFilter; - applyFilter(vlanFilter === vlan ? null : vlan); - }); - }); - if (search) search.addEventListener("input", filterRows); - - tiles.forEach((tile) => { - tile.addEventListener("click", () => { - const row = document.getElementById(`nbu-port-row-${tile.dataset.nbuPort}`); - if (!row) return; - row.classList.add("table-active"); - window.setTimeout(() => row.classList.remove("table-active"), 2000); - }); - }); - - let saved = "state"; - try { - saved = localStorage.getItem(STORAGE_KEY) || "state"; - } catch (error) { - /* ignore */ - } - setMode(saved === "vlan" ? "vlan" : "state"); - } - - if (document.readyState === "loading") { - document.addEventListener("DOMContentLoaded", init); - } else { - init(); - } -})(); diff --git a/netbox_utilities/switch_port_pdf.py b/netbox_utilities/switch_port_pdf.py new file mode 100644 index 0000000..97b1211 --- /dev/null +++ b/netbox_utilities/switch_port_pdf.py @@ -0,0 +1,406 @@ +"""PDF export of a switch's port usage: front panel coloured by VLAN label plus the full port list. + +Pure ReportLab code without NetBox imports, so it can be tested on its own. +""" + +import io +import math +from dataclasses import dataclass, field +from datetime import datetime + +from reportlab.lib import colors +from reportlab.lib.pagesizes import A4, landscape +from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet +from reportlab.lib.units import mm +from reportlab.platypus import Flowable, KeepTogether, Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle +from reportlab.platypus.flowables import CondPageBreak + +from . import switch_ports + +TEXTS = { + "de": { + "title": "Switch-Belegung", + "generated": "Stand", + "page": "Seite", + "ports": "Ports", + "connected": "Belegt", + "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)", + "no_label": "ohne Label", + "list": "Alle Schnittstellen", + "port": "Port", + "status": "Status", + "vlan": "VLAN (Label)", + "peer": "Gegenstelle", + "description": "Beschreibung", + "type": "Typ", + "lag": "LAG", + "marked": "als verbunden markiert", + "none": "Keine physischen Schnittstellen.", + "site": "Standort", + "rack": "Rack", + "model": "Modell", + "mgmt": "Mgmt", + "date_format": "%d.%m.%Y %H:%M", + "button": "Switch-Belegung exportieren", + "filename": "Switch-Belegung", + }, + "en": { + "title": "Switch port usage", + "generated": "As of", + "page": "Page", + "ports": "Ports", + "connected": "Connected", + "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)", + "no_label": "no label", + "list": "All interfaces", + "port": "Port", + "status": "Status", + "vlan": "VLAN (label)", + "peer": "Peer", + "description": "Description", + "type": "Type", + "lag": "LAG", + "marked": "marked as connected", + "none": "No physical interfaces.", + "site": "Site", + "rack": "Rack", + "model": "Model", + "mgmt": "Mgmt", + "date_format": "%Y-%m-%d %H:%M", + "button": "Export switch port usage", + "filename": "switch-port-usage", + }, +} + +PAGE = landscape(A4) +MARGIN = 12 * mm +TILE_W = 10.5 * mm +TILE_H = 9 * mm +TILE_GAP = 1.2 * mm +OPTICAL_W = 12 * mm +FREE_FILL = colors.white +UNLABELLED_FILL = colors.HexColor("#e9ecef") +BORDER_DARK = colors.HexColor("#212529") +BORDER_LIGHT = colors.HexColor("#adb5bd") + + +def language(code): + return "en" if (code or "").lower().startswith("en") else "de" + + +def luminance(color): + """WCAG relative luminance of a ReportLab colour.""" + + def channel(value): + return value / 12.92 if value <= 0.03928 else ((value + 0.055) / 1.055) ** 2.4 + + return 0.2126 * channel(color.red) + 0.7152 * channel(color.green) + 0.0722 * channel(color.blue) + + +def text_color(fill): + """Black or white text, whichever has the higher WCAG contrast ratio against the fill.""" + value = luminance(fill) + against_black = (value + 0.05) / 0.05 + against_white = 1.05 / (value + 0.05) + return colors.black if against_black >= against_white else colors.white + + +def tint(color, amount=0.6): + """Mix a colour with white; free ports use a pale version of their VLAN colour.""" + return colors.Color(*(channel + (1 - channel) * amount for channel in (color.red, color.green, color.blue))) + + +def hex_of(color): + return "#{:02x}{:02x}{:02x}".format(*(round(channel * 255) for channel in (color.red, color.green, color.blue))) + + +def tile_fill(port): + """Full VLAN colour for used ports, a pale one for free and disabled ports.""" + base = colors.HexColor(port.color) if port.color else UNLABELLED_FILL + if port.state == switch_ports.STATE_CONNECTED: + return base + return tint(base) if port.color else FREE_FILL + + +@dataclass +class DeviceInfo: + name: str + site: str = "" + rack: str = "" + model: str = "" + extra: list = field(default_factory=list) + + +class PortPanel(Flowable): + """One group of ports (stack member / line card) drawn like the device front.""" + + def __init__(self, columns, optical, width, tile_w): + super().__init__() + self.columns = columns + self.optical = optical + self.tile_w = tile_w + self.rows = max((len(column) for column in columns), default=1) + self.width = width + self.height = self.rows * TILE_H + (self.rows - 1) * TILE_GAP + 2 * TILE_GAP + + def wrap(self, available_width, available_height): + return self.width, self.height + + def draw(self): + canvas = self.canv + used = len(self.columns) * (self.tile_w + TILE_GAP) + TILE_GAP + canvas.setFillColor(colors.HexColor("#f1f3f5")) + canvas.setStrokeColor(BORDER_LIGHT) + canvas.roundRect(0, 0, used, self.height, 1.5 * mm, stroke=1, fill=1) + for index, column in enumerate(self.columns): + x = TILE_GAP + index * (self.tile_w + TILE_GAP) + for row, port in enumerate(column): + y = self.height - TILE_GAP - (row + 1) * TILE_H - row * TILE_GAP + self.draw_tile(port, x, y) + + def draw_tile(self, port, x, y): + canvas = self.canv + fill = tile_fill(port) + connected = port.state == switch_ports.STATE_CONNECTED + disabled = port.state == switch_ports.STATE_DISABLED + canvas.setFillColor(fill) + canvas.setStrokeColor(BORDER_DARK if connected else BORDER_LIGHT) + canvas.setLineWidth(1.6 if connected else 0.7) + if disabled: + canvas.setDash(1.2, 1.2) + radius = 0.4 * mm if self.optical else 1 * mm + canvas.roundRect(x, y, self.tile_w, TILE_H, radius, stroke=1, fill=1) + canvas.setDash() + + ink = text_color(fill) + canvas.setFillColor(ink) + canvas.setFont("Helvetica-Bold", 7.5) + canvas.drawCentredString(x + self.tile_w / 2, y + TILE_H - 3.4 * mm, port.short[:6]) + if port.vlan: + canvas.setFont("Helvetica", 5.5) + vlan = port.vlan + while vlan and canvas.stringWidth(vlan, "Helvetica", 5.5) > self.tile_w - 1 * mm: + vlan = vlan[:-1] + canvas.drawCentredString(x + self.tile_w / 2, y + 1.6 * mm, vlan) + + if disabled: + # Small cross in the top right corner, away from the text. + size, inset = 1.4 * mm, 0.7 * mm + right, top = x + self.tile_w - inset, y + TILE_H - inset + canvas.setStrokeColor(colors.HexColor("#dc3545")) + canvas.setLineWidth(0.8) + canvas.line(right - size, top - size, right, top) + canvas.line(right - size, top, right, top - size) + canvas.setLineWidth(0.5) + + +MIN_TILE_W = 8.5 * mm + + +def _layout(columns, optical, width): + """(tile width, column chunks): shrink tiles to fit one row, wrap evenly only if still too wide.""" + preferred = OPTICAL_W if optical else TILE_W + count = max(len(columns), 1) + fitting = (width - TILE_GAP) / count - TILE_GAP + if fitting >= MIN_TILE_W: + return min(preferred, fitting), [columns] + per_row = max(int((width - TILE_GAP) // (MIN_TILE_W + TILE_GAP)), 1) + chunks = math.ceil(count / per_row) + size = math.ceil(count / chunks) + tile_w = min(preferred, (width - TILE_GAP) / size - TILE_GAP) + return tile_w, [columns[index : index + size] for index in range(0, count, size)] + + +def _styles(): + sheet = getSampleStyleSheet() + return { + "title": ParagraphStyle("t", parent=sheet["Title"], alignment=0, fontSize=16, spaceAfter=1 * mm), + "meta": ParagraphStyle("m", parent=sheet["Normal"], fontSize=8.5, textColor=colors.HexColor("#495057")), + "h2": ParagraphStyle("h", parent=sheet["Heading2"], fontSize=11, spaceBefore=3 * mm, spaceAfter=1.5 * mm), + "group": ParagraphStyle("g", parent=sheet["Normal"], fontSize=7.5, textColor=colors.HexColor("#495057")), + "cell": ParagraphStyle("c", parent=sheet["Normal"], fontSize=7, leading=8.5), + "figure": ParagraphStyle("f", parent=sheet["Normal"], fontSize=14, leading=16), + "small": ParagraphStyle("s", parent=sheet["Normal"], fontSize=7, textColor=colors.HexColor("#495057")), + } + + +def _escape(text): + return (text or "").replace("&", "&").replace("<", "<").replace(">", ">") + + +def _key_figures(summary, t): + cells = [ + (t["ports"], str(summary["total"]), colors.HexColor("#212529")), + (t["connected"], f"{summary['connected']} ({summary['percent']} %)", colors.HexColor("#198754")), + (t["free"], str(summary["free"]), colors.HexColor("#212529")), + (t["disabled"], str(summary["disabled"]), colors.HexColor("#6c757d")), + ] + data = [ + [ + Paragraph(f'{label.upper()}', _styles()["cell"]) + for label, _, _ in cells + ], + [ + Paragraph(f'{value}', _styles()["figure"]) + for _, value, color in cells + ], + ] + table = Table(data, colWidths=[(PAGE[0] - 2 * MARGIN) / 4] * 4, rowHeights=[5 * mm, 9 * mm]) + table.setStyle( + TableStyle( + [ + ("BOX", (0, 0), (0, 1), 0.5, BORDER_LIGHT), + ("BOX", (1, 0), (1, 1), 0.5, BORDER_LIGHT), + ("BOX", (2, 0), (2, 1), 0.5, BORDER_LIGHT), + ("BOX", (3, 0), (3, 1), 0.5, BORDER_LIGHT), + ("LEFTPADDING", (0, 0), (-1, -1), 2.5 * mm), + ("TOPPADDING", (0, 0), (-1, -1), 1 * mm), + ("VALIGN", (0, 0), (-1, -1), "MIDDLE"), + ] + ) + ) + return table + + +def _legend(ports, t, styles): + legend = switch_ports.vlan_legend(ports) + items = [] + for vlan, color, total, connected in legend: + fill = colors.HexColor(color) if color else UNLABELLED_FILL + label = _escape(vlan) if vlan else t["no_label"] + items.append((fill, f"{label} ({connected}/{total})")) + if not items: + return [] + per_row = 6 + cells = [] + style = [("VALIGN", (0, 0), (-1, -1), "MIDDLE"), ("LEFTPADDING", (0, 0), (-1, -1), 1 * mm)] + for row_index in range(math.ceil(len(items) / per_row)): + row = [] + for column_index, (fill, text) in enumerate(items[row_index * per_row : (row_index + 1) * per_row]): + row.extend(["", Paragraph(text, styles["cell"])]) + style.append(("BACKGROUND", (column_index * 2, row_index), (column_index * 2, row_index), fill)) + style.append(("BOX", (column_index * 2, row_index), (column_index * 2, row_index), 0.4, BORDER_LIGHT)) + row.extend([""] * (per_row * 2 - len(row))) + cells.append(row) + widths = [4 * mm, (PAGE[0] - 2 * MARGIN) / per_row - 4 * mm] * per_row + table = Table(cells, colWidths=widths, rowHeights=5 * mm) + table.setStyle(TableStyle(style)) + return [Paragraph(f"{t['legend_vlan']}", styles["small"]), Spacer(0, 1 * mm), table] + + +def _port_table(ports, t, styles): + header = [t["port"], t["status"], t["vlan"], 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")), + ("LINEBELOW", (0, 0), (-1, -1), 0.25, colors.HexColor("#dee2e6")), + ("VALIGN", (0, 0), (-1, -1), "MIDDLE"), + ("TOPPADDING", (0, 0), (-1, -1), 0.8 * mm), + ("BOTTOMPADDING", (0, 0), (-1, -1), 0.8 * mm), + ] + states = { + switch_ports.STATE_CONNECTED: t["connected"], + switch_ports.STATE_FREE: t["free"], + switch_ports.STATE_DISABLED: t["disabled"], + } + for index, port in enumerate(ports, start=1): + name = _escape(port.name) + (f" [{t['mgmt']}]" if port.mgmt_only else "") + peer = port.peer if port.peer != switch_ports.MARKED_CONNECTED else t["marked"] + data.append( + [ + Paragraph(name, styles["cell"]), + Paragraph(states[port.state], styles["cell"]), + Paragraph(_escape(port.label) or "–", styles["cell"]), + Paragraph(_escape(peer) or "–", styles["cell"]), + Paragraph(_escape(port.description) or "–", styles["cell"]), + Paragraph(_escape(port.type_display), styles["cell"]), + Paragraph(_escape(port.lag) or "–", styles["cell"]), + ] + ) + 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"] + ) + 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.13, 0.08, 0.11, 0.25, 0.22, 0.13, 0.08)] + table = Table(data, colWidths=widths, repeatRows=1) + table.setStyle(TableStyle(style)) + return table + + +def build_pdf(device, ports, lang="de", generated=None): + """Return the PDF as bytes. ``device`` is a DeviceInfo, ``ports`` a list of switch_ports.Port.""" + t = TEXTS[language(lang)] + styles = _styles() + generated = generated or datetime.now() + buffer = io.BytesIO() + width = PAGE[0] - 2 * MARGIN + + def footer(canvas, document): + canvas.saveState() + canvas.setFont("Helvetica", 7) + canvas.setFillColor(colors.HexColor("#6c757d")) + canvas.drawString(MARGIN, 7 * mm, f"{t['title']} – {device.name}") + canvas.drawRightString(PAGE[0] - MARGIN, 7 * mm, f"{t['page']} {document.page}") + canvas.restoreState() + + document = SimpleDocTemplate( + buffer, + pagesize=PAGE, + leftMargin=MARGIN, + rightMargin=MARGIN, + topMargin=MARGIN, + bottomMargin=MARGIN, + title=f"{t['title']} – {device.name}", + author="NetBox Utilities", + ) + meta = [ + f"{t['site']}: {_escape(device.site)}" if device.site else "", + f"{t['rack']}: {_escape(device.rack)}" if device.rack else "", + f"{t['model']}: {_escape(device.model)}" if device.model else "", + *[_escape(item) for item in device.extra], + f"{t['generated']}: {generated.strftime(t['date_format'])}", + ] + story = [ + Paragraph(f"{t['title']} – {_escape(device.name)}", styles["title"]), + Paragraph(" · ".join(part for part in meta if part), styles["meta"]), + Spacer(0, 3 * mm), + _key_figures(switch_ports.summary(ports), t), + Paragraph(t["front"], styles["h2"]), + ] + + switch_ports.assign_vlan_colors(ports) + groups = switch_ports.build_groups(ports) + if not groups: + story.append(Paragraph(t["none"], styles["meta"])) + for group in groups: + tile_w, chunks = _layout(group.columns, group.optical, width) + panels = [PortPanel(chunk, group.optical, width, tile_w) for chunk in chunks] + title = Paragraph(f"{_escape(group.title)} · {len(group.ports)} {t['ports']}", styles["group"]) + block = [title, Spacer(0, 0.8 * mm)] + for panel in panels: + block.extend([panel, Spacer(0, 1.2 * mm)]) + story.append(KeepTogether(block)) + story.append(Spacer(0, 1.5 * mm)) + + story.append(Paragraph(t["legend_state"], styles["small"])) + story.append(Spacer(0, 2 * mm)) + story.extend(_legend(ports, t, styles)) + story.append(CondPageBreak(40 * mm)) + story.append(Paragraph(t["list"], styles["h2"])) + story.append(_port_table(ports, t, styles)) + + document.build(story, onFirstPage=footer, onLaterPages=footer) + return buffer.getvalue() diff --git a/netbox_utilities/switch_port_views.py b/netbox_utilities/switch_port_views.py index 640f7bc..23bf1b6 100644 --- a/netbox_utilities/switch_port_views.py +++ b/netbox_utilities/switch_port_views.py @@ -1,27 +1,11 @@ -import csv - from dcim.models import Device, Interface -from django.db.models import Q from django.http import HttpResponse -from netbox.views import generic -from utilities.views import ViewTab, register_model_view +from django.shortcuts import get_object_or_404 +from django.utils import timezone, translation +from django.views import View +from utilities.views import ContentTypePermissionRequiredMixin -from . import switch_ports -from .runtime import switch_ports_enabled - - -def _connected_query(): - return Q(cable__isnull=False) | Q(mark_connected=True) - - -def ports_tab_badge(device): - """ "belegt/gesamt" of the physical ports; None hides the tab for devices that are no switches.""" - if not switch_ports_enabled() or not switch_ports.is_switch(device): - return None - physical = Interface.objects.filter(device=device).exclude(type__in=switch_ports.VIRTUAL_TYPES) - total = physical.count() - connected = physical.filter(_connected_query(), enabled=True).count() - return f"{connected}/{total}" +from . import switch_port_pdf, switch_ports def _describe(endpoint): @@ -35,95 +19,73 @@ def _peer(interface): """Far end through patch panels if the path is complete, otherwise the directly cabled object.""" try: endpoints = interface.connected_endpoints if interface._path_id else [] - except Exception: # noqa: BLE001 - a broken path must not break the overview + except Exception: # noqa: BLE001 - a broken path must not break the export endpoints = [] if not endpoints and interface.cable_id: endpoints = interface.link_peers - if not endpoints: - return "", "" - first = endpoints[0] - text = ", ".join(_describe(endpoint) for endpoint in endpoints) - url = first.get_absolute_url() if hasattr(first, "get_absolute_url") else "" - return text, url + return ", ".join(_describe(endpoint) for endpoint in endpoints or []) -def collect_ports(device): - interfaces = ( - Interface.objects.filter(device=device).select_related("lag", "cable", "_path", "module").order_by("_name") - ) +def collect_ports(interfaces): ports = [] for interface in interfaces: - peer, peer_url = _peer(interface) - connected = bool(interface.cable_id or interface.mark_connected) + peer = _peer(interface) + if not peer and interface.mark_connected: + peer = switch_ports.MARKED_CONNECTED ports.append( switch_ports.Port( pk=interface.pk, name=interface.name, label=interface.label, type=interface.type, - type_display=interface.get_type_display(), + type_display=str(interface.get_type_display()), enabled=interface.enabled, - connected=connected, + connected=bool(interface.cable_id or interface.mark_connected), mgmt_only=interface.mgmt_only, description=interface.description, - peer=peer or ("als verbunden markiert" if interface.mark_connected else ""), - peer_url=peer_url, + peer=peer, lag=interface.lag.name if interface.lag_id else "", - speed=f"{interface.speed // 1000} Mbit/s" if interface.speed else "", - url=interface.get_absolute_url(), virtual=interface.type in switch_ports.VIRTUAL_TYPES, ) ) return ports -@register_model_view(Device, "ports", path="ports") -class DevicePortsView(generic.ObjectView): - queryset = Device.objects.all() - template_name = "netbox_utilities/device_ports.html" - tab = ViewTab( - label="Ports", - badge=ports_tab_badge, - permission="dcim.view_interface", - weight=2040, - hide_if_empty=True, +def device_info(device): + rack = "" + if device.rack_id: + rack = str(device.rack) + if device.position: + rack += f" / U{device.position:g}" + return switch_port_pdf.DeviceInfo( + name=device.name or str(device), + site=str(device.site) if device.site_id else "", + rack=rack, + model=str(device.device_type), ) - def get(self, request, **kwargs): - if request.GET.get("export") == "csv": - instance = self.get_object(**kwargs) - return self.export_csv(instance) - return super().get(request, **kwargs) - def get_extra_context(self, request, instance): - ports = collect_ports(instance) - return { - "ports": ports, - "groups": switch_ports.build_groups(ports), - "virtual_ports": [port for port in ports if port.virtual], - "summary": switch_ports.summary(ports), - "legend": switch_ports.vlan_legend(ports), - "states": switch_ports.STATE_LABELS, - } +class SwitchPortsPDFView(ContentTypePermissionRequiredMixin, View): + """PDF of the port usage of a switch, in the language of the user's NetBox preferences.""" - @staticmethod - def export_csv(device): - response = HttpResponse(content_type="text/csv; charset=utf-8") - response["Content-Disposition"] = f'attachment; filename="{device.name or device.pk}-ports.csv"' - response.write("") # Excel opens UTF-8 correctly with a BOM - writer = csv.writer(response, delimiter=";") - writer.writerow(["Port", "Status", "VLAN (Label)", "Gegenstelle", "Beschreibung", "Typ", "LAG", "Speed"]) - for port in collect_ports(device): - writer.writerow( - [ - port.name, - port.state_label, - port.label, - port.peer, - port.description, - port.type_display, - port.lag, - port.speed, - ] - ) + def get_required_permission(self): + return "dcim.view_interface" + + def get(self, request, pk): + 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") + ) + 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() + ) + filename = f"{switch_port_pdf.TEXTS[lang]['filename']}-{device.name or device.pk}.pdf".replace(" ", "_") + response = HttpResponse(pdf, content_type="application/pdf") + response["Content-Disposition"] = f'attachment; filename="{filename}"' return response diff --git a/netbox_utilities/switch_ports.py b/netbox_utilities/switch_ports.py index ebe3b77..573275a 100644 --- a/netbox_utilities/switch_ports.py +++ b/netbox_utilities/switch_ports.py @@ -6,6 +6,9 @@ from dataclasses import dataclass, field DEFAULT_SWITCH_DEVICE_ROLES = ("Switch",) +# Peer text of interfaces that are only marked as connected; translated in the export. +MARKED_CONNECTED = "__marked__" + STATE_CONNECTED = "connected" STATE_FREE = "free" STATE_DISABLED = "disabled" @@ -19,24 +22,24 @@ STATE_LABELS = { VIRTUAL_TYPES = ("virtual", "lag", "bridge") OPTICAL_MARKERS = ("sfp", "qsfp", "xfp", "x2", "cfp", "osfp", "gbic") -# Readable background colours for VLAN labels (white text works on all of them). +# Distinct background colours for VLAN labels; the text colour is chosen per colour for contrast. VLAN_PALETTE = ( - "#1f77b4", - "#d62728", - "#2ca02c", - "#9467bd", - "#e377c2", - "#8c564b", - "#17becf", - "#bcbd22", - "#ff7f0e", - "#393b79", - "#637939", - "#843c39", - "#7b4173", - "#3182bd", - "#e6550d", - "#31a354", + "#1f77b4", # blue + "#ff7f0e", # orange + "#2ca02c", # green + "#d62728", # red + "#9467bd", # purple + "#8c564b", # brown + "#e377c2", # pink + "#17becf", # cyan + "#bcbd22", # olive + "#7f7f7f", # grey + "#393b79", # navy + "#ffbb78", # light orange + "#98df8a", # light green + "#c5b0d5", # lavender + "#f7b6d2", # rose + "#9edae5", # light cyan ) _NAME_PATTERN = re.compile(r"^(?P.*?)(?P\d+)$") @@ -109,6 +112,8 @@ class Port: speed: str = "" url: str = "" virtual: bool = False + # Set by assign_vlan_colors(); otherwise the colour comes from a hash of the label. + assigned_color: str = "" @property def state(self): @@ -136,7 +141,9 @@ class Port: @property def color(self): - return vlan_color(self.label) + if not self.vlan: + return None + return self.assigned_color or vlan_color(self.label) @dataclass @@ -195,16 +202,31 @@ def summary(ports): } +def assign_vlan_colors(ports): + """Give every VLAN of one switch its own palette colour (in natural order), so no two collide. + + 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)])} + for port in ports: + if port.vlan: + port.assigned_color = colors.get(port.vlan, "") + return colors + + def vlan_legend(ports): """[(vlan, colour, port count, connected count)] sorted naturally; unlabelled ports last.""" counts = {} + colors = {} for port in ports: if port.virtual: continue + colors.setdefault(port.vlan, port.color) entry = counts.setdefault(port.vlan, [0, 0]) entry[0] += 1 entry[1] += port.state == STATE_CONNECTED - legend = [(vlan, vlan_color(vlan), total, connected) for vlan, (total, connected) in counts.items() if vlan] + legend = [(vlan, colors[vlan], total, connected) for vlan, (total, connected) in counts.items() if vlan] legend.sort(key=lambda item: natural_key(item[0])) if "" in counts: legend.append(("", None, counts[""][0], counts[""][1])) diff --git a/netbox_utilities/template_content.py b/netbox_utilities/template_content.py index b28ba97..a0b8675 100644 --- a/netbox_utilities/template_content.py +++ b/netbox_utilities/template_content.py @@ -1,6 +1,7 @@ from dcim.models import ModuleBay from django.middleware.csrf import get_token from django.urls import reverse +from django.utils import translation from netbox.plugins import PluginTemplateExtension from tenancy.models import Tenant, TenantGroup @@ -24,6 +25,7 @@ from .runtime import ( hardware_enabled, navigation_customization_enabled, offline_svg_export_enabled, + switch_ports_enabled, tenant_filter_enabled, ) @@ -94,6 +96,20 @@ class DeviceUtilitiesContent(PluginTemplateExtension): models = ["dcim.device"] def buttons(self): + return self._switch_ports_button() + self._bulk_module_button() + + def _switch_ports_button(self): + request, device = self.context["request"], self.context["object"] + if not switch_ports_enabled() or not request.user.has_perm("dcim.view_interface"): + return "" + from . import switch_port_pdf, switch_ports + + if not switch_ports.is_switch(device): + return "" + texts = switch_port_pdf.TEXTS[switch_port_pdf.language(translation.get_language())] + return self.render("netbox_utilities/device_switch_ports_button.html", {"label": texts["button"]}) + + def _bulk_module_button(self): request = self.context["request"] device = self.context["object"] if not request.user.has_perm("dcim.add_module"): diff --git a/netbox_utilities/templates/netbox_utilities/device_ports.html b/netbox_utilities/templates/netbox_utilities/device_ports.html deleted file mode 100644 index 8f05cae..0000000 --- a/netbox_utilities/templates/netbox_utilities/device_ports.html +++ /dev/null @@ -1,131 +0,0 @@ -{% extends 'dcim/device/base.html' %} -{% load static %} - -{% block content %} -
- {# ---------- Key figures and controls ---------- #} -
-
-
-
Ports
-
{{ summary.total }}
-
physische Schnittstellen
-
-
-
-
-
Belegt
-
{{ summary.connected }} ({{ summary.percent }} %)
-
-
-
-
-
-
Frei
-
{{ summary.free }}
-
aktiviert, ohne Kabel
-
-
-
-
-
Deaktiviert
-
{{ summary.disabled }}
-
Schnittstelle abgeschaltet
-
-
-
- - {# ---------- Front panel ---------- #} -
-

- Portbelegung -
- - - - -
- CSV - -

-
- {% if not groups %} -

Dieses Gerät hat keine physischen Schnittstellen.

- {% endif %} - {% for group in groups %} -
-
{{ group.title }} · {{ group.ports|length }} Ports
-
- {% for column in group.columns %} - - {% endfor %} -
-
- {% endfor %} - - {# Legends #} -
- {{ states.connected }} - {{ states.free }} - {{ states.disabled }} -
-
- {% for vlan, color, total, connected in legend %} - - {% empty %} - Keine Labels gepflegt. - {% endfor %} -
-
-
- - {# ---------- Table ---------- #} -
-

- Alle Schnittstellen - -

-
- - - - - - {% for port in ports %} - - - - - - - - - - {% endfor %} - -
PortStatusVLAN (Label)GegenstelleBeschreibungTypLAG
{{ port.name }}{% if port.mgmt_only %} Mgmt{% endif %} - {{ port.state_label }} - - {% if port.label %}{{ port.label }}{% else %}—{% endif %} - {% if port.peer_url %}{{ port.peer }}{% else %}{{ port.peer|default:"—" }}{% endif %}{{ port.description|default:"—" }}{{ port.type_display }}{{ port.lag|default:"—" }}
-
-
-
- -{% endblock content %} diff --git a/netbox_utilities/templates/netbox_utilities/device_switch_ports_button.html b/netbox_utilities/templates/netbox_utilities/device_switch_ports_button.html new file mode 100644 index 0000000..920a14d --- /dev/null +++ b/netbox_utilities/templates/netbox_utilities/device_switch_ports_button.html @@ -0,0 +1,4 @@ + + + {{ label }} + diff --git a/netbox_utilities/tests/test_switch_ports.py b/netbox_utilities/tests/test_switch_ports.py index 4bca8cf..bdb5113 100644 --- a/netbox_utilities/tests/test_switch_ports.py +++ b/netbox_utilities/tests/test_switch_ports.py @@ -82,3 +82,58 @@ class LayoutTest(SimpleTestCase): self.assertEqual( switch_ports.summary(ports), {"total": 3, "connected": 1, "free": 1, "disabled": 1, "percent": 33} ) + + +class ColorAssignmentTest(SimpleTestCase): + def test_every_vlan_gets_its_own_colour(self): + ports = [ + port(f"Gi1/0/{index}", label=label) for index, label in enumerate(["10", "VLAN 10", "20", "Trunk", ""]) + ] + colors = switch_ports.assign_vlan_colors(ports) + self.assertEqual(len(set(colors.values())), 3) + self.assertEqual(ports[0].color, ports[1].color) + self.assertIsNone(ports[4].color) + + +class PDFTest(SimpleTestCase): + def ports(self): + return [ + port("Gi1/0/1", label="10", connected=True, peer="srv1 – eth0"), + port("Gi1/0/2", label="20"), + port("Gi1/0/3", enabled=False), + port("Te1/1/1", type="10gbase-x-sfpp", label="Trunk", connected=True, peer=switch_ports.MARKED_CONNECTED), + port("Po1", type="lag", virtual=True), + ] + + def test_builds_pdf_in_both_languages(self): + from netbox_utilities import switch_port_pdf + + device = switch_port_pdf.DeviceInfo(name="sw1", site="HQ", rack="R1 / U10", model="C9300") + for lang in ("de", "en"): + with self.subTest(lang=lang): + data = switch_port_pdf.build_pdf(device, self.ports(), lang=lang) + self.assertTrue(data.startswith(b"%PDF")) + self.assertGreater(len(data), 2000) + + def test_language_follows_user_setting(self): + from netbox_utilities import switch_port_pdf + + self.assertEqual(switch_port_pdf.language("en-us"), "en") + self.assertEqual(switch_port_pdf.language("de"), "de") + self.assertEqual(switch_port_pdf.language(None), "de") + + def test_text_contrasts_with_fill(self): + from reportlab.lib import colors + + from netbox_utilities import switch_port_pdf + + self.assertEqual(switch_port_pdf.text_color(colors.HexColor("#ff7f0e")), colors.black) + self.assertEqual(switch_port_pdf.text_color(colors.HexColor("#2ca02c")), colors.black) + self.assertEqual(switch_port_pdf.text_color(colors.HexColor("#1f77b4")), colors.white) + self.assertEqual(switch_port_pdf.text_color(colors.HexColor("#393b79")), colors.white) + for color in switch_ports.VLAN_PALETTE: + with self.subTest(color=color): + fill = colors.HexColor(color) + ink = switch_port_pdf.text_color(fill) + light, dark = sorted((switch_port_pdf.luminance(fill), switch_port_pdf.luminance(ink)), reverse=True) + self.assertGreaterEqual((light + 0.05) / (dark + 0.05), 3) diff --git a/netbox_utilities/urls.py b/netbox_utilities/urls.py index d1e48ec..6602040 100644 --- a/netbox_utilities/urls.py +++ b/netbox_utilities/urls.py @@ -1,7 +1,7 @@ from django.urls import include, path from utilities.urls import get_model_urls -from . import disk_views, hardware_views, views # noqa: F401 - hardware_views registers its model views +from . import disk_views, hardware_views, switch_port_views, views # noqa: F401 - hardware_views registers its model views app_name = "netbox_utilities" @@ -32,6 +32,11 @@ urlpatterns = [ path("cpu-models//", include(get_model_urls("netbox_utilities", "cpumodel"))), path("hardware/", include(get_model_urls("netbox_utilities", "devicehardware", detail=False))), path("hardware//", include(get_model_urls("netbox_utilities", "devicehardware"))), + path( + "devices//switch-ports.pdf", + switch_port_views.SwitchPortsPDFView.as_view(), + name="device_switch_ports_pdf", + ), path("devices//disks/setup/", disk_views.DeviceDiskSetupView.as_view(), name="device_disk_setup"), path("devices//disks/fill/", disk_views.DeviceDiskBulkFillView.as_view(), name="device_disk_fill"), path("devices//disks/move/", disk_views.DeviceDiskMoveView.as_view(), name="device_disk_move"), diff --git a/pyproject.toml b/pyproject.toml index 17c9e7c..0b1611f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,10 +4,13 @@ build-backend = "hatchling.build" [project] name = "netbox-utilities" -version = "0.17.0" -description = "Navigation, tenant utilities, connection VLANs, partial-width racks, disks and bulk operations for NetBox 4.6/4.7" +version = "0.18.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" +dependencies = [ + "reportlab>=4.0", +] license = { text = "MIT" } authors = [ { name = "MrBlake" }