feat: Ports tab for switches with front-panel view and VLAN colours
Devices with the role "Switch" get a Ports tab: key figures, a front-panel view of all physical interfaces grouped per stack member/line card and medium (odd ports on top, even below), coloured by usage or by the VLAN noted in the interface label, with a VLAN legend and filter, tooltips with peer and description, a searchable table of all interfaces, CSV export and a print view. Peers follow the cable path through patch panels. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
9fd3e01cdf
commit
9ecad07c96
9 files changed
+776
No files matched your search
@@ -48,6 +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.
|
||||
|
||||
Navigation settings are stored per user. The active tenant or tenant-group
|
||||
selection is stored in the browser session.
|
||||
@@ -222,6 +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 |
|
||||
|
||||
## Usage
|
||||
|
||||
@@ -502,6 +505,36 @@ recording and editing use `netbox_utilities.add_devicehardware` and
|
||||
`netbox_utilities.change_devicehardware`. The catalogue uses the
|
||||
`netbox_utilities.*_cpumodel` permissions.
|
||||
|
||||
### Switch ports
|
||||
|
||||
Devices with a role from `switch_device_roles` get a **Ports** tab; the badge
|
||||
shows used/total physical ports.
|
||||
|
||||
- **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.
|
||||
|
||||
The tab requires `dcim.view_interface`. Virtual interfaces (`virtual`, `lag`,
|
||||
`bridge`) are not counted as ports.
|
||||
|
||||
### Pre-filter for the B-side of a cable
|
||||
|
||||
When creating or editing a cable, the **B-side** section shows optional
|
||||
|
||||
@@ -31,6 +31,8 @@ class NetBoxUtilitiesConfig(PluginConfig):
|
||||
"hardware_enabled": True,
|
||||
"hardware_device_roles": ["Server"],
|
||||
"hardware_vcpu_ratio_warning": 4,
|
||||
"switch_ports_enabled": True,
|
||||
"switch_device_roles": ["Switch"],
|
||||
}
|
||||
middleware = [
|
||||
"netbox_utilities.middleware.GlobalTenantFilterMiddleware",
|
||||
@@ -55,6 +57,9 @@ 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
|
||||
|
||||
|
||||
@@ -19,6 +19,10 @@ def hardware_enabled():
|
||||
return bool(get_plugin_config("netbox_utilities", "hardware_enabled"))
|
||||
|
||||
|
||||
def switch_ports_enabled():
|
||||
return bool(get_plugin_config("netbox_utilities", "switch_ports_enabled"))
|
||||
|
||||
|
||||
def offline_svg_export_enabled():
|
||||
return bool(get_plugin_config("netbox_utilities", "offline_svg_export_enabled"))
|
||||
|
||||
|
||||
@@ -400,3 +400,89 @@ a.nbu-disk-slot[draggable="true"] {
|
||||
.nbu-disk-group-header[aria-expanded="true"] .nbu-disk-group-chevron {
|
||||
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; }
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// "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();
|
||||
}
|
||||
})();
|
||||
@@ -0,0 +1,129 @@
|
||||
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 . 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}"
|
||||
|
||||
|
||||
def _describe(endpoint):
|
||||
device = getattr(endpoint, "device", None) or getattr(endpoint, "parent_object", None)
|
||||
if device is not None and device != endpoint:
|
||||
return f"{device} – {endpoint}"
|
||||
return str(endpoint)
|
||||
|
||||
|
||||
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
|
||||
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
|
||||
|
||||
|
||||
def collect_ports(device):
|
||||
interfaces = (
|
||||
Interface.objects.filter(device=device).select_related("lag", "cable", "_path", "module").order_by("_name")
|
||||
)
|
||||
ports = []
|
||||
for interface in interfaces:
|
||||
peer, peer_url = _peer(interface)
|
||||
connected = bool(interface.cable_id or interface.mark_connected)
|
||||
ports.append(
|
||||
switch_ports.Port(
|
||||
pk=interface.pk,
|
||||
name=interface.name,
|
||||
label=interface.label,
|
||||
type=interface.type,
|
||||
type_display=interface.get_type_display(),
|
||||
enabled=interface.enabled,
|
||||
connected=connected,
|
||||
mgmt_only=interface.mgmt_only,
|
||||
description=interface.description,
|
||||
peer=peer or ("als verbunden markiert" if interface.mark_connected else ""),
|
||||
peer_url=peer_url,
|
||||
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 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,
|
||||
}
|
||||
|
||||
@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,
|
||||
]
|
||||
)
|
||||
return response
|
||||
@@ -0,0 +1,211 @@
|
||||
"""Pure helpers for the "Ports" tab of switches: grouping, front-panel layout and VLAN colours."""
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
DEFAULT_SWITCH_DEVICE_ROLES = ("Switch",)
|
||||
|
||||
STATE_CONNECTED = "connected"
|
||||
STATE_FREE = "free"
|
||||
STATE_DISABLED = "disabled"
|
||||
STATE_LABELS = {
|
||||
STATE_CONNECTED: "Belegt",
|
||||
STATE_FREE: "Frei",
|
||||
STATE_DISABLED: "Deaktiviert",
|
||||
}
|
||||
|
||||
# Interface types that are not physical front ports.
|
||||
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).
|
||||
VLAN_PALETTE = (
|
||||
"#1f77b4",
|
||||
"#d62728",
|
||||
"#2ca02c",
|
||||
"#9467bd",
|
||||
"#e377c2",
|
||||
"#8c564b",
|
||||
"#17becf",
|
||||
"#bcbd22",
|
||||
"#ff7f0e",
|
||||
"#393b79",
|
||||
"#637939",
|
||||
"#843c39",
|
||||
"#7b4173",
|
||||
"#3182bd",
|
||||
"#e6550d",
|
||||
"#31a354",
|
||||
)
|
||||
|
||||
_NAME_PATTERN = re.compile(r"^(?P<prefix>.*?)(?P<number>\d+)$")
|
||||
_NATURAL = re.compile(r"(\d+)")
|
||||
|
||||
|
||||
def configured_roles(roles=None):
|
||||
if roles is None:
|
||||
try:
|
||||
from netbox.plugins import get_plugin_config
|
||||
|
||||
roles = get_plugin_config("netbox_utilities", "switch_device_roles")
|
||||
except Exception: # noqa: BLE001 - outside NetBox (tests) fall back to defaults
|
||||
roles = None
|
||||
return {str(role).casefold() for role in (roles if roles is not None else DEFAULT_SWITCH_DEVICE_ROLES)}
|
||||
|
||||
|
||||
def is_switch(device, roles=None):
|
||||
role = getattr(device, "role", None)
|
||||
return bool(role and str(getattr(role, "name", "")).casefold() in configured_roles(roles))
|
||||
|
||||
|
||||
def natural_key(text):
|
||||
""" "Gi1/0/10" sorts after "Gi1/0/9"."""
|
||||
return [int(part) if part.isdigit() else part.casefold() for part in _NATURAL.split(text or "")]
|
||||
|
||||
|
||||
def split_name(name):
|
||||
"""("GigabitEthernet1/0/", 24) for "GigabitEthernet1/0/24"; (name, None) without a trailing number."""
|
||||
match = _NAME_PATTERN.match(name or "")
|
||||
if not match:
|
||||
return name or "", None
|
||||
return match.group("prefix"), int(match.group("number"))
|
||||
|
||||
|
||||
def is_optical(interface_type):
|
||||
text = (interface_type or "").casefold()
|
||||
return any(marker in text for marker in OPTICAL_MARKERS)
|
||||
|
||||
|
||||
def vlan_key(label):
|
||||
"""Normalised VLAN label so that "VLAN 10", "vlan10" and "10" get the same colour."""
|
||||
text = re.sub(r"\s+", " ", (label or "").strip())
|
||||
match = re.fullmatch(r"(?i)vlan\s*(\d+)", text)
|
||||
return match.group(1) if match else text
|
||||
|
||||
|
||||
def vlan_color(label):
|
||||
key = vlan_key(label)
|
||||
if not key:
|
||||
return None
|
||||
digest = hashlib.md5(key.casefold().encode("utf-8"), usedforsecurity=False).digest()
|
||||
return VLAN_PALETTE[digest[0] % len(VLAN_PALETTE)]
|
||||
|
||||
|
||||
@dataclass
|
||||
class Port:
|
||||
pk: int
|
||||
name: str
|
||||
label: str = ""
|
||||
type: str = ""
|
||||
type_display: str = ""
|
||||
enabled: bool = True
|
||||
connected: bool = False
|
||||
mgmt_only: bool = False
|
||||
description: str = ""
|
||||
peer: str = ""
|
||||
peer_url: str = ""
|
||||
lag: str = ""
|
||||
speed: str = ""
|
||||
url: str = ""
|
||||
virtual: bool = False
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
if not self.enabled:
|
||||
return STATE_DISABLED
|
||||
return STATE_CONNECTED if self.connected else STATE_FREE
|
||||
|
||||
@property
|
||||
def state_label(self):
|
||||
return STATE_LABELS[self.state]
|
||||
|
||||
@property
|
||||
def number(self):
|
||||
return split_name(self.name)[1]
|
||||
|
||||
@property
|
||||
def short(self):
|
||||
"""Text inside the tile: the port number, or the name if it has none."""
|
||||
number = self.number
|
||||
return str(number) if number is not None else self.name
|
||||
|
||||
@property
|
||||
def vlan(self):
|
||||
return vlan_key(self.label)
|
||||
|
||||
@property
|
||||
def color(self):
|
||||
return vlan_color(self.label)
|
||||
|
||||
|
||||
@dataclass
|
||||
class PortGroup:
|
||||
"""Ports with the same name prefix, e.g. one stack member or line card."""
|
||||
|
||||
title: str
|
||||
optical: bool
|
||||
ports: list = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def columns(self):
|
||||
"""Front-panel layout: odd numbers on top, even numbers below, like most switches."""
|
||||
ports = sorted(self.ports, key=lambda port: (port.number is None, port.number or 0, natural_key(port.name)))
|
||||
numbered = all(port.number is not None for port in ports)
|
||||
if numbered and len(ports) > 1:
|
||||
top = [port for port in ports if port.number % 2 == 1]
|
||||
bottom = [port for port in ports if port.number % 2 == 0]
|
||||
if top and bottom and abs(len(top) - len(bottom)) <= 1:
|
||||
return [[port for port in pair if port] for pair in _zip_longest(top, bottom)]
|
||||
return [[port] for port in ports]
|
||||
|
||||
|
||||
def _zip_longest(top, bottom):
|
||||
for index in range(max(len(top), len(bottom))):
|
||||
yield (top[index] if index < len(top) else None, bottom[index] if index < len(bottom) else None)
|
||||
|
||||
|
||||
def build_groups(ports):
|
||||
"""Physical ports grouped by name prefix and medium, in natural order."""
|
||||
groups = {}
|
||||
for port in ports:
|
||||
if port.virtual:
|
||||
continue
|
||||
prefix, _ = split_name(port.name)
|
||||
optical = is_optical(port.type)
|
||||
key = (prefix, optical)
|
||||
if key not in groups:
|
||||
title = prefix.rstrip("/:-. ") or "Ports"
|
||||
groups[key] = PortGroup(title=f"{title} (SFP)" if optical else title, optical=optical)
|
||||
groups[key].ports.append(port)
|
||||
return sorted(groups.values(), key=lambda group: (natural_key(group.title), group.optical))
|
||||
|
||||
|
||||
def summary(ports):
|
||||
physical = [port for port in ports if not port.virtual]
|
||||
total = len(physical)
|
||||
connected = sum(1 for port in physical if port.state == STATE_CONNECTED)
|
||||
disabled = sum(1 for port in physical if port.state == STATE_DISABLED)
|
||||
return {
|
||||
"total": total,
|
||||
"connected": connected,
|
||||
"free": total - connected - disabled,
|
||||
"disabled": disabled,
|
||||
"percent": round(connected / total * 100) if total else 0,
|
||||
}
|
||||
|
||||
|
||||
def vlan_legend(ports):
|
||||
"""[(vlan, colour, port count, connected count)] sorted naturally; unlabelled ports last."""
|
||||
counts = {}
|
||||
for port in ports:
|
||||
if port.virtual:
|
||||
continue
|
||||
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.sort(key=lambda item: natural_key(item[0]))
|
||||
if "" in counts:
|
||||
legend.append(("", None, counts[""][0], counts[""][1]))
|
||||
return legend
|
||||
@@ -0,0 +1,131 @@
|
||||
{% extends 'dcim/device/base.html' %}
|
||||
{% load static %}
|
||||
|
||||
{% block content %}
|
||||
<div id="nbu-ports" data-nbu-ports>
|
||||
{# ---------- Key figures and controls ---------- #}
|
||||
<div class="row g-3 mb-3">
|
||||
<div class="col-6 col-lg-3">
|
||||
<div class="card h-100 mb-0"><div class="card-body py-2">
|
||||
<div class="text-muted small text-uppercase">Ports</div>
|
||||
<div class="fs-3 fw-semibold lh-sm">{{ summary.total }}</div>
|
||||
<div class="small text-muted">physische Schnittstellen</div>
|
||||
</div></div>
|
||||
</div>
|
||||
<div class="col-6 col-lg-3">
|
||||
<div class="card h-100 mb-0"><div class="card-body py-2">
|
||||
<div class="text-muted small text-uppercase">Belegt</div>
|
||||
<div class="fs-3 fw-semibold lh-sm text-success">{{ summary.connected }} <span class="fs-6 text-muted">({{ summary.percent }} %)</span></div>
|
||||
<div class="progress mt-1" style="height: .4rem"><div class="progress-bar bg-success" style="width: {{ summary.percent }}%"></div></div>
|
||||
</div></div>
|
||||
</div>
|
||||
<div class="col-6 col-lg-3">
|
||||
<div class="card h-100 mb-0"><div class="card-body py-2">
|
||||
<div class="text-muted small text-uppercase">Frei</div>
|
||||
<div class="fs-3 fw-semibold lh-sm">{{ summary.free }}</div>
|
||||
<div class="small text-muted">aktiviert, ohne Kabel</div>
|
||||
</div></div>
|
||||
</div>
|
||||
<div class="col-6 col-lg-3">
|
||||
<div class="card h-100 mb-0"><div class="card-body py-2">
|
||||
<div class="text-muted small text-uppercase">Deaktiviert</div>
|
||||
<div class="fs-3 fw-semibold lh-sm text-secondary">{{ summary.disabled }}</div>
|
||||
<div class="small text-muted">Schnittstelle abgeschaltet</div>
|
||||
</div></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{# ---------- Front panel ---------- #}
|
||||
<div class="card">
|
||||
<h2 class="card-header d-flex flex-wrap align-items-center gap-2">
|
||||
<span class="me-auto"><i class="mdi mdi-ethernet me-1" aria-hidden="true"></i>Portbelegung</span>
|
||||
<div class="btn-group btn-group-sm" role="group" aria-label="Farbmodus">
|
||||
<input type="radio" class="btn-check" name="nbu-port-mode" id="nbu-port-mode-state" value="state" checked>
|
||||
<label class="btn btn-outline-primary" for="nbu-port-mode-state">Belegung</label>
|
||||
<input type="radio" class="btn-check" name="nbu-port-mode" id="nbu-port-mode-vlan" value="vlan">
|
||||
<label class="btn btn-outline-primary" for="nbu-port-mode-vlan">VLAN</label>
|
||||
</div>
|
||||
<a href="?export=csv" class="btn btn-sm btn-outline-secondary"><i class="mdi mdi-download" aria-hidden="true"></i> CSV</a>
|
||||
<button type="button" class="btn btn-sm btn-outline-secondary" onclick="window.print()"><i class="mdi mdi-printer" aria-hidden="true"></i> Drucken</button>
|
||||
</h2>
|
||||
<div class="card-body">
|
||||
{% if not groups %}
|
||||
<p class="text-muted mb-0">Dieses Gerät hat keine physischen Schnittstellen.</p>
|
||||
{% endif %}
|
||||
{% for group in groups %}
|
||||
<div class="nbu-port-group mb-3">
|
||||
<div class="small text-muted mb-1">{{ group.title }} <span class="text-body-secondary">· {{ group.ports|length }} Ports</span></div>
|
||||
<div class="nbu-port-panel">
|
||||
{% for column in group.columns %}
|
||||
<div class="nbu-port-column">
|
||||
{% for port in column %}
|
||||
<a href="#nbu-port-row-{{ port.pk }}"
|
||||
class="nbu-port nbu-port-{{ port.state }}{% if group.optical %} nbu-port-optical{% endif %}"
|
||||
data-nbu-port="{{ port.pk }}"
|
||||
data-vlan="{{ port.vlan }}"
|
||||
{% if port.color %}style="--nbu-vlan-color: {{ port.color }}"{% endif %}
|
||||
data-bs-toggle="tooltip" data-bs-html="true"
|
||||
title="<strong>{{ port.name|force_escape }}</strong>{% if port.label %}<br>VLAN: {{ port.label|force_escape }}{% endif %}<br>{{ port.state_label }}{% if port.peer %}<br>↔ {{ port.peer|force_escape }}{% endif %}{% if port.description %}<br><em>{{ port.description|force_escape }}</em>{% endif %}{% if port.lag %}<br>LAG: {{ port.lag|force_escape }}{% endif %}<br><span class='opacity-75'>{{ port.type_display|force_escape }}</span>">
|
||||
<span class="nbu-port-number">{{ port.short }}</span>
|
||||
<span class="nbu-port-vlan">{% if port.vlan %}{{ port.vlan }}{% else %} {% endif %}</span>
|
||||
</a>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
|
||||
{# Legends #}
|
||||
<div class="nbu-port-legend small" data-nbu-legend="state">
|
||||
<span><span class="nbu-port-swatch nbu-port-connected"></span>{{ states.connected }}</span>
|
||||
<span><span class="nbu-port-swatch nbu-port-free"></span>{{ states.free }}</span>
|
||||
<span><span class="nbu-port-swatch nbu-port-disabled"></span>{{ states.disabled }}</span>
|
||||
</div>
|
||||
<div class="nbu-port-legend small d-none" data-nbu-legend="vlan">
|
||||
{% for vlan, color, total, connected in legend %}
|
||||
<button type="button" class="btn btn-sm btn-link p-0 text-reset text-decoration-none" data-nbu-vlan-filter="{{ vlan }}">
|
||||
<span class="nbu-port-swatch" style="background: {{ color|default:'var(--bs-secondary-bg)' }}"></span>{{ vlan|default:"ohne Label" }}
|
||||
<span class="text-muted">({{ connected }}/{{ total }})</span>
|
||||
</button>
|
||||
{% empty %}
|
||||
<span class="text-muted">Keine Labels gepflegt.</span>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{# ---------- Table ---------- #}
|
||||
<div class="card">
|
||||
<h2 class="card-header d-flex flex-wrap align-items-center gap-2">
|
||||
<span class="me-auto">Alle Schnittstellen</span>
|
||||
<input type="search" class="form-control form-control-sm" style="max-width: 18rem" placeholder="Suchen: Port, VLAN, Gegenstelle …" data-nbu-port-search>
|
||||
</h2>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-hover table-sm align-middle mb-0">
|
||||
<thead>
|
||||
<tr><th>Port</th><th>Status</th><th>VLAN (Label)</th><th>Gegenstelle</th><th>Beschreibung</th><th>Typ</th><th>LAG</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for port in ports %}
|
||||
<tr id="nbu-port-row-{{ port.pk }}" data-nbu-port-row="{{ port.pk }}" data-vlan="{{ port.vlan }}">
|
||||
<td class="text-nowrap"><a href="{{ port.url }}">{{ port.name }}</a>{% if port.mgmt_only %} <span class="badge text-bg-info">Mgmt</span>{% endif %}</td>
|
||||
<td>
|
||||
<span class="badge {% if port.state == 'connected' %}text-bg-success{% elif port.state == 'disabled' %}text-bg-secondary{% else %}text-bg-light border{% endif %}">{{ port.state_label }}</span>
|
||||
</td>
|
||||
<td>
|
||||
{% if port.label %}<span class="badge" style="background: {{ port.color }}">{{ port.label }}</span>{% else %}<span class="text-muted">—</span>{% endif %}
|
||||
</td>
|
||||
<td>{% if port.peer_url %}<a href="{{ port.peer_url }}">{{ port.peer }}</a>{% else %}{{ port.peer|default:"—" }}{% endif %}</td>
|
||||
<td class="small">{{ port.description|default:"—" }}</td>
|
||||
<td class="small text-muted">{{ port.type_display }}</td>
|
||||
<td class="small">{{ port.lag|default:"—" }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="{% static 'netbox_utilities/switch_ports.js' %}" defer></script>
|
||||
{% endblock content %}
|
||||
@@ -0,0 +1,84 @@
|
||||
from types import SimpleNamespace
|
||||
|
||||
from django.test import SimpleTestCase
|
||||
|
||||
from netbox_utilities import switch_ports
|
||||
from netbox_utilities.switch_ports import Port
|
||||
|
||||
|
||||
def port(name, **kwargs):
|
||||
return Port(pk=hash(name) & 0xFFFF, name=name, **kwargs)
|
||||
|
||||
|
||||
class NameTest(SimpleTestCase):
|
||||
def test_split_name(self):
|
||||
self.assertEqual(switch_ports.split_name("GigabitEthernet1/0/24"), ("GigabitEthernet1/0/", 24))
|
||||
self.assertEqual(switch_ports.split_name("ethernet1/49"), ("ethernet1/", 49))
|
||||
self.assertEqual(switch_ports.split_name("Port 7"), ("Port ", 7))
|
||||
self.assertEqual(switch_ports.split_name("mgmt"), ("mgmt", None))
|
||||
|
||||
def test_natural_order(self):
|
||||
names = ["Gi1/0/10", "Gi1/0/2", "Gi1/0/1"]
|
||||
self.assertEqual(sorted(names, key=switch_ports.natural_key), ["Gi1/0/1", "Gi1/0/2", "Gi1/0/10"])
|
||||
|
||||
def test_optical_types(self):
|
||||
self.assertTrue(switch_ports.is_optical("10gbase-x-sfpp"))
|
||||
self.assertTrue(switch_ports.is_optical("100gbase-x-qsfp28"))
|
||||
self.assertFalse(switch_ports.is_optical("1000base-t"))
|
||||
|
||||
def test_roles(self):
|
||||
self.assertTrue(switch_ports.is_switch(SimpleNamespace(role=SimpleNamespace(name="switch")), ["Switch"]))
|
||||
self.assertFalse(switch_ports.is_switch(SimpleNamespace(role=SimpleNamespace(name="Server")), ["Switch"]))
|
||||
|
||||
|
||||
class VlanTest(SimpleTestCase):
|
||||
def test_same_vlan_same_colour(self):
|
||||
self.assertEqual(switch_ports.vlan_key("VLAN 10"), "10")
|
||||
self.assertEqual(switch_ports.vlan_key("vlan10"), "10")
|
||||
self.assertEqual(switch_ports.vlan_key(" Trunk 10,20 "), "Trunk 10,20")
|
||||
self.assertEqual(switch_ports.vlan_color("VLAN 10"), switch_ports.vlan_color("10"))
|
||||
self.assertIn(switch_ports.vlan_color("Server"), switch_ports.VLAN_PALETTE)
|
||||
self.assertIsNone(switch_ports.vlan_color(""))
|
||||
|
||||
def test_legend_counts(self):
|
||||
ports = [
|
||||
port("Gi1/0/1", label="10", connected=True),
|
||||
port("Gi1/0/2", label="VLAN 10"),
|
||||
port("Gi1/0/3", label="20", connected=True),
|
||||
port("Gi1/0/4"),
|
||||
port("Po1", type="lag", label="10", virtual=True),
|
||||
]
|
||||
legend = [(vlan, total, connected) for vlan, _, total, connected in switch_ports.vlan_legend(ports)]
|
||||
self.assertEqual(legend, [("10", 2, 1), ("20", 1, 1), ("", 1, 0)])
|
||||
|
||||
|
||||
class LayoutTest(SimpleTestCase):
|
||||
def test_odd_top_even_bottom(self):
|
||||
ports = [port(f"Gi1/0/{number}") for number in range(1, 7)]
|
||||
group = switch_ports.build_groups(ports)[0]
|
||||
self.assertEqual([[p.number for p in column] for column in group.columns], [[1, 2], [3, 4], [5, 6]])
|
||||
|
||||
def test_groups_by_member_and_medium(self):
|
||||
ports = [
|
||||
port("Gi2/0/1"),
|
||||
port("Gi1/0/1"),
|
||||
port("Te1/1/1", type="10gbase-x-sfpp"),
|
||||
port("Vlan10", type="virtual", virtual=True),
|
||||
]
|
||||
titles = [group.title for group in switch_ports.build_groups(ports)]
|
||||
self.assertEqual(titles, ["Gi1/0", "Gi2/0", "Te1/1 (SFP)"])
|
||||
|
||||
def test_single_row_without_numbers(self):
|
||||
group = switch_ports.build_groups([port("mgmt"), port("console")])
|
||||
self.assertEqual(sum(len(g.ports) for g in group), 2)
|
||||
|
||||
def test_summary(self):
|
||||
ports = [
|
||||
port("1", connected=True),
|
||||
port("2"),
|
||||
port("3", enabled=False, connected=True),
|
||||
port("Po1", virtual=True, connected=True),
|
||||
]
|
||||
self.assertEqual(
|
||||
switch_ports.summary(ports), {"total": 3, "connected": 1, "free": 1, "disabled": 1, "percent": 33}
|
||||
)
|
||||
Reference in new issue
Block a user