Compare commits

39 Commits
Author SHA1 Message Date
MrBlakeandClaude Opus 5.5 713556a33e fix: cleaner filter layout for the client software overview
The filter card gets a balanced layout: tenant group, tenant, a search field
with icon and the buttons in one row, below it the client roles as toggle
pills (applied immediately) and the filter hint. The broken checkbox styling
is gone. The empty state explains how software lists get into NetBox.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 14:28:29 +01:00
MrBlakeandClaude Opus 5.5 7d267ec05d fix: client software overview shows client roles only
The overview is always limited to devices whose role is listed in
software_device_roles, now "Client" and "Windows Client" by default and
matched by name or slug (windows-client from the Windows agent). The role
filter offers only these roles as checkboxes; none ticked means all client
roles, so servers can no longer appear by clearing the filter.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 14:25:12 +01:00
MrBlakeandClaude Opus 5.5 e24a12164c feat: transfer client software lists from inventory reports into netbox-slm
The NetBox Windows Agent and the NetBox Synchronizer write the installed
software as a report into the device comments. On every device save the
report is parsed (agent bullet list and synchronizer table) and the device's
netbox-slm installations are brought in line: missing products, versions and
installations are created, installations that left the report are removed.
Installations entered by hand are never touched. Deleting a device removes its
automatic installations first, since netbox-slm protects devices with
installations. The command netbox_utilities_sync_software transfers existing
reports once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 14:21:52 +01:00
MrBlakeandClaude Opus 5.5 63b3b31763 feat: client software overview based on netbox-slm
New page "Client Software Übersicht" in a "Software" group of the netbox-inventory
menu (fallback: own Hardware menu). It shows, per tenant or tenant group
including subgroups, the software products recorded with netbox-slm, their
versions and the clients they are installed on: key figures, charts of the most
widespread products and their version distribution, a sortable and searchable
product list, a drill-down per product/version with the list of clients, and a
CSV export. Without an own selection the global tenant filter applies; the
device role filter is pre-set to the configured client roles.

Devices with a client role (software_device_roles, default "Clients") get a
"Software" tab listing their installations with add, edit and delete actions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 14:18:59 +01:00
MrBlakeandClaude Opus 5.5 5d6c4c9cd8 fix: apply global tenant scope directly in the asset filterset
The asset list ignored the global tenant and tenant group filter. The asset
filterset now applies the active scope itself (including inherited tenants)
instead of relying on the injected URL parameter; the REST API stays
unfiltered. The replaced tenant filters use model choice filters like the
original plugin filters.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 13:03:10 +01:00
MrBlakeandClaude Opus 5.5 bfcfff60e4 fix: global tenant filter includes assets with inherited tenant
The tenant_id and tenant_group_id filters of netbox-inventory assets now also
match assets without their own tenant via the tenant of the assigned device,
module, inventory item or rack, like the tenant column. The global tenant and
tenant group filter uses these filters and no longer hides such assets.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 12:58:37 +01:00
MrBlakeandClaude Opus 5.5 204bb235a4 fix: asset tenant column falls back to the hardware's tenant
The tenant column of the netbox-inventory asset list stayed empty for assets
without their own tenant. It now shows the tenant of the assigned device,
module, inventory item or rack instead. reportlab is pinned below 5, which
pulled in pillow 13 and broke netbox-documentation's pillow<13 requirement.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 12:54:57 +01:00
MrBlakeandClaude Opus 5.5 f86306e686 feat: show tenant column in netbox-inventory asset list
The asset table of netbox-inventory gets a tenant column (registered if the
plugin does not provide one) that is part of the default columns, placed
right after the status.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 12:50:42 +01:00
MrBlakeandClaude Opus 5.5 cf1cafb632 feat: tenant-aware netbox-inventory assets
Assets without a tenant take the tenant of the device, module, inventory item or
rack they are assigned to, both in clean() and before save. The plugin's assign,
reassign and "create hardware from asset" views save assets without a tenant
field and failed with mandatory tenancy before. Asset forms are also pre-filled
from an assigned module or inventory item. Existing tenants are never changed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-18 12:43:08 +01:00
MrBlakeandClaude Opus 5.5 4dd01b82e3 fix: skip hidden stack fields when reordering device form fields
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 16:23:11 +01:00
MrBlakeandClaude Opus 5.5 2ea1dcaec3 fix: device edit form crashed when stack fields are hidden
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 16:22:58 +01:00
MrBlakeandClaude Opus 5.5 cc2546b332 fix: show switch stack options only for devices with a switch role
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 16:20:51 +01:00
MrBlakeandClaude Opus 5.5 102b161356 feat: continue cable trace across wireless links
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-05 10:04:04 +01:00
MrBlakeandClaude Opus 5.5 d49c4c6ee7 feat: ignore LAG note in port labels for VLAN colours and checks
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 10:05:59 +01:00
MrBlakeandClaude Opus 5.5 5fcd7799e3 feat: REST API endpoint for switch stacks
/api/plugins/utilities/switch-stacks/ reads and writes stacks, filterable by
device_id and member_id.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 09:25:52 +01:00
MrBlakeandClaude Opus 5.5 a87d3b1cdf fix: spacing between stack member name and its front panel
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 09:19:50 +01:00
MrBlakeandClaude Opus 5.5 356034fe98 fix: stack members show the whole switch stack in the port panel and PDF
The current device is marked in the panel.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 09:17:34 +01:00
MrBlakeandClaude Opus 5.5 ce174c6541 feat: switch port PDF covers the whole switch stack
Front panels and port lists are drawn per stack member with shared VLAN colours.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 09:12:22 +01:00
MrBlakeandClaude Opus 5.5 567daf7963 feat: switch stacks – stack members shown one below the other in the port panel
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-04 09:02:04 +01:00
MrBlakeandClaude Opus 5.5 6906bf6ed6 feat: switch panel and PDF also use the VLANs assigned to cables
Ports without a label show the VLANs of their cable. A label with exactly
one number counts as that VLAN ID, so "Server 30", "VLAN 30", "30" and a
cable with VLAN 30 share one colour and legend entry. A numeric label that
differs from the cable VLANs is flagged with an orange corner and a
warning; tooltips and the PDF port list show label and cable VLANs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 10:17:54 +01:00
MrBlakeandClaude Opus 5.5 e9c00f2b11 fix: MGMT label for management ports and light/dark theme for the switch panel
Management ports (management only, or named mgmt/management/oobm/me0 ...)
show "MGMT" instead of the overflowing full name and form their own group
at the end; other ports without a number are shortened. The faceplate,
jacks, notches and frames use theme variables for NetBox's light and dark
mode instead of a fixed dark design.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 10:12:13 +01:00
MrBlakeandClaude Opus 5.5 b1ecbbbb75 feat: Aruba-style switch front panel on the device page
Switches show a Ports panel above the Device and Management cards: a dark
faceplate with every physical port as RJ45/SFP jack (odd on top, even
below, per stack member), a status view (link, free, disabled) and a VLAN
view with the label colours of the PDF, contrast-aware text, legend,
tooltips with peer and description, key figures and a link to the PDF
export. Texts follow the user's NetBox language. The panel is rendered
into the left column and moved to the top by a small script.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 10:03:07 +01:00
MrBlakeandClaude Opus 5.5 7289c21684 feat: switch port PDF back in A4 landscape
A 48-port switch fits on one row again; the port list keeps the wider
columns without line breaks and the VLAN legend is kept on one page.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 09:34:06 +01:00
MrBlakeandClaude Opus 5.5 f144f23b31 feat: switch port PDF in A4 portrait
The export uses A4 portrait: wide port groups are split evenly (a 48-port
switch into 1-24 and 25-48) with larger tiles, the legend has four
columns and the port list has wider columns and a smaller font so that
names, status and type no longer wrap.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 09:28:56 +01:00
MrBlakeandClaude Opus 5.5 8eb075db9f feat: export switch port usage as PDF instead of a Ports tab
Switches get an "Export switch port usage" button that downloads an A4
landscape PDF: key figures, a front panel with one colour per VLAN label
(full colour = connected, pale = free, dashed with a cross = disabled,
text colour chosen for contrast), a VLAN legend and the full port list
with peers. The PDF follows the language of the user's NetBox
preferences (German or English). The Ports tab with its script and
styles is removed. ReportLab becomes a dependency.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 09:25:29 +01:00
MrBlakeandClaude Opus 5.5 8f2cc22f88 chore: bump version to 0.17.0
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-30 09:15:38 +01:00
MrBlakeandClaude Opus 5.5 9ecad07c96 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]>
2026-10-30 08:54:37 +01:00
MrBlakeandClaude Opus 5.5 9fd3e01cdf feat: clearer cluster capacity panel
Key figures (hosts, vCPU:core, RAM allocation, N+1) as tiles with
colours, warnings in one compact box and the host table across the full
width with RAM bars, coloured ratios and one-line VM figures.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 12:50:05 +01:00
MrBlakeandClaude Opus 5.5 8aa8d3fe1e fix: do not spread unplaced VMs once a VM of the cluster is pinned
As soon as any VM of a cluster (in any status) is assigned to one of its
hosts, the placement is treated as managed by hand: VMs without a host
are no longer spread over the hosts and only count towards the cluster
totals. Cluster panel and host tab say which case applies.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 11:12:15 +01:00
MrBlakeandClaude Opus 5.5 afa15eb46a feat: spread cluster VMs without a fixed host over the cluster hosts
VMs assigned only to a cluster now count towards every host of that
cluster in proportion to its size: vCPUs by threads, memory by host RAM,
evenly if no host has CPU & RAM recorded. The cluster host table and the
CPU & RAM tab of a host include this share; the cluster totals still
count each VM once. Hosts are matched by device ID instead of name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 11:02:35 +01:00
MrBlakeandClaude Opus 5.5 675574ee00 feat: CPU & RAM as a device tab next to Disks
The CPU & RAM panel on the device page becomes its own tab with the
total core count as badge. Besides CPU and RAM it shows the capacity of
a virtualization host and the list of VMs running on it. Saving the
form returns to the tab.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 11:00:30 +01:00
MrBlakeandClaude Opus 5.5 8624ddb62f docs: use the new Hardware menu name for the disk CSV import
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 10:53:45 +01:00
MrBlakeandClaude Opus 5.5 c8b581089c feat: CPU & RAM per server with a catalogue of Intel and AMD server CPUs
Devices get a CPU & RAM panel: CPU model from a built-in catalogue of
over 700 Intel Xeon and AMD Opteron/EPYC server CPUs since 2012 (cores,
threads, base/turbo clock, TDP, socket, year, max sockets; checked against
Intel ARK, AMD and server vendor data), CPU count and RAM with modules,
type and speed. The catalogue is loaded by migration 0011, can be edited
and extended in the UI and refreshed with netbox_utilities_cpu_catalog.

Virtualization: clusters show their capacity (cores, threads and RAM of
the hosts against the vCPUs and memory of the VMs, vCPU:core ratio, RAM
allocation, N+1 reserve) with a per-host table, hosts list their VMs and
VMs show the CPU of their host. Optional columns for the device and
cluster lists, CSV import, REST API, GraphQL and search are included.
The plugin menu is now called "Hardware".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 10:53:36 +01:00
MrBlakeandClaude Opus 5.5 8396b7c64a docs: add screenshots and generalise README
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 20:58:18 +01:00
MrBlakeandClaude Opus 5.5 95fd28f2a4 feat: MSA import reads disk group exports and loosely named columns
The disk group export of an HPE MSA sets RAID level and pool on the RAID
groups of the selected devices. Column names are matched case- and
punctuation-insensitively with common aliases, positions are accepted as
1.4, 1:4, 1/4 or "Enclosure 1, Slot 4" or as separate enclosure and slot
columns, and both export kinds are detected in the regular disk import.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 15:02:46 +02:00
MrBlakeandClaude Opus 5.5 2b40fbfae0 fix: MSA import wizard posted back to the disk CSV import
When the CSV import handed an MSA export to the wizard, its forms had no
action and submitted to /disks/import/, which failed with KeyError 'format'.
All wizard forms now post to the MSA import URL.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 14:16:26 +02:00
MrBlakeandClaude Opus 5.5 2a6abc396d feat: hand HPE MSA exports from the disk CSV import to the MSA wizard
An MSA disk export pasted or uploaded in Disks > Import failed with
"Unknown header: Location". The import now recognises the MSA columns and
opens the shelf assignment step of the MSA import instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 14:13:10 +02:00
MrBlakeandClaude Opus 5.5 7754e823cb fix: disk CSV import crashed with "Disk.bay must be a DiskBayLayout instance"
The bay and raid_group cleaners returned the plain name, which reached the
model instance as a string whenever clean() stopped early on another error.
They now keep the name aside and leave None behind.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 14:10:24 +02:00
MrBlakeandClaude Opus 5.5 a7801ec297 feat: import the disk CSV export of an HPE MSA
A three-step wizard reads the MSA disk export, maps each enclosure (shelf)
to a device and previews new, updated, replaced, skipped and conflicting
disks. Devices without slot areas get one created during the import,
pre-filled from the device type template or the export. Disk groups can
become RAID groups and the install date can be estimated from the power
on hours.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-21 14:06:22 +02:00
74 changed files with 8578 additions and 32 deletions

No files matched your search

+299 -6
View File
@@ -12,6 +12,24 @@ uploads and more.
| **Python** | `>=3.12` |
| **Repository** | <https://git.mrblake.cc/MrBlake/Netbox-Utilities> |
## Screenshots
Disks grouped by device, with failed-disk warnings:
![Disks grouped by device, with failed-disk warnings](docs/screenshots/disks-by-device.png)
Disk list:
![Disk list](docs/screenshots/disks.png)
Personalised navigation:
![Personalised navigation](docs/screenshots/navigation.png)
Plugin settings:
![Plugin settings](docs/screenshots/settings.png)
## Features
- Every user can reorder or hide the menus of the left navigation.
@@ -28,7 +46,10 @@ uploads and more.
- Cables and wireless links can be assigned to one or more VLANs.
- The B-side device selection of a cable can be pre-filtered by tenant group, tenant and site.
- 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, REST API and GraphQL.
- 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.
- **Switch front panel** on the device page (Aruba-style, status or VLAN colours) and **switch port usage as PDF**, in the user's NetBox language.
- **Client Software Übersicht** (with the optional [netbox-slm](https://github.com/ICTU/netbox_slm) plugin): software products, versions and the clients they are installed on per tenant or tenant group, with charts and CSV export, plus a **Software** tab for clients.
Navigation settings are stored per user. The active tenant or tenant-group
selection is stored in the browser session.
@@ -200,6 +221,14 @@ sudo systemctl restart netbox netbox-rq
| `disk_device_roles` | `["Server", "NAS", "SAN", "MSA"]` | Device role names (case-insensitive) that get the **Disks** tab |
| `disk_age_warning_years` | `5` | Warn about disks older than this (manufacture date, otherwise install date) |
| `disk_warranty_warning_days` | `90` | Warn this many days before the warranty ends |
| `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` | Front panel and **Export switch port usage** button for switches |
| `switch_device_roles` | `["Switch"]` | Device roles (case-insensitive) that get the front panel and export button |
| `software_enabled` | `True` | Client software overview and **Software** device tab (requires netbox-slm) |
| `software_device_roles` | `["Client", "Windows Client"]` | Device roles (name or slug, case-insensitive) shown in the client software overview and given the **Software** tab |
| `wireless_trace_enabled` | `True` | Cable trace continues across wireless links (radio bridges) to the cabled port of the peer radio |
## Usage
@@ -251,7 +280,7 @@ can start at slot 0 again.
for the device type. The next device of the same type offers **Apply
template**, which creates all stored areas with one click; on a device that
already has areas, the button adds the missing ones. Templates are managed under
**Disks > Disk templates** in the main menu.
**Hardware > Disk templates** in the main menu.
**Slot grid.** Each area is drawn as its own grid and coloured by
status (active, hot spare, failed, planned). A warning icon marks disks with
@@ -294,10 +323,11 @@ capacity, the usable RAID capacity, spares and failed disks. The warnings panel
lists failed disks, expired warranties, warranties ending within
`disk_warranty_warning_days` and disks older than `disk_age_warning_years`.
**Main menu.** The plugin adds its own **Disks** menu with the entries
**Disks**, **RAID groups** and **Disk templates**.
**Main menu.** The plugin adds its own **Hardware** menu with the entries
**Disks**, **RAID groups** and **Disk templates**, plus **CPU & RAM** and
**CPU models** (see below).
**Disks grouped by device.** **Disks > Disks** shows all disks grouped by device.
**Disks grouped by device.** **Hardware > Disks** shows all disks grouped by device.
Each device is a collapsible section whose header shows the device, role, site,
tenant, number of disks, raw capacity, failed disks and warnings, plus a link to
the device's **Disks** tab. The page offers a search (serial number, model,
@@ -315,7 +345,7 @@ device and slot. The device list offers an optional **Disks** column
(used/total, linked to the tab) under **Configure Table**; it runs two queries
per row, so enable it only where needed.
**CSV import.** **Disks > Disks > Import** accepts CSV, JSON or YAML
**CSV import.** **Hardware > Disks > Import** accepts CSV, JSON or YAML
with these columns: `device` (device name), `bay` (area name, may be empty when
the device has only one area), `slot`, `status`, `disk_type`,
`interface`, `form_factor`, `manufacturer`, `model`, `capacity` (e.g. `4 TB`),
@@ -333,6 +363,35 @@ srv-01,Front,1,spare,ssd,sas,Samsung,PM1643a,1.92 TB,S4XXNA0R123457,2029-05-31
srv-01,PCIe,0,active,nvme,nvme,Samsung,PM9A3,3.84 TB,S64XNA0T654321,2030-01-31
```
**HPE MSA import.** The *HPE MSA export* button next to **Hardware > Disks** (also
*MSA import* in a device's **Disks** tab) reads the CSV disk export of an HPE MSA
(*Pools → Disks*, export to CSV). The `Location` column (`1.4` = enclosure 1,
slot 4) defines the enclosures; in the next step each enclosure (shelf) is
assigned to a NetBox device. The preview shows per disk whether it is new,
updated (same serial in the same slot), replacing another disk, skipped or in
conflict (slot outside the area, serial already installed elsewhere). If a
device has no slot area yet, the area is created during the import, pre-filled
from the device type template or from the export (12 or 24 bays). `Type`,
`Size` (GiB are converted), `Disk Group`, `Revision` and `Health` are mapped;
`GLOBAL SP`/`DEDICATED SP` become hot spares, `Fault` becomes failed. Optionally
missing RAID groups are created from `Disk Group` (level *Other*) and the install
date is estimated from `Power On Hours`.
The import also accepts the **disk group export** (*Pools → Disk Groups*,
export to CSV). It sets the RAID level (`RAID10`, `RAID-5`, `R6`, `NRAID` → JBOD;
unknown levels such as ADAPT become *Other*) and a description with pool, size
and disk count on the RAID groups of the same name on the selected devices;
devices that already have such groups are pre-selected. Import the disk export
first, then the disk group export. Missing groups are only created on request.
Column names are matched loosely: case, spaces and punctuation are ignored and
common alternatives are accepted (e.g. `Serial`/`SN`, `Capacity`, `Vendor`,
`Firmware`, separate `Enclosure` and `Slot` columns). Positions may be written
as `1.4`, `1:4`, `1/4` or `Enclosure 1, Slot 4`. Comma, semicolon and tab
separated files in UTF-8 or Windows-1252 work. Both MSA exports are also
recognised when uploaded in the regular disk CSV import and handed over to the
MSA import automatically.
**REST API and GraphQL.**
| Endpoint | Content |
@@ -352,6 +411,229 @@ and `netbox_utilities_disk_bay_template(_list)`.
layout and filling slots requires `netbox_utilities.add_disk`, replacing
requires `netbox_utilities.change_disk`, and RAID groups use the
`netbox_utilities.*_raidgroup` permissions.
The HPE MSA import requires `netbox_utilities.add_disk`; updating or replacing
existing disks additionally requires `netbox_utilities.change_disk`, and creating
RAID groups `netbox_utilities.add_raidgroup` (otherwise they are skipped).
### CPU & RAM
Servers and virtualization hosts get a **CPU & RAM** tab next to **Disks**.
It is shown for devices whose role is listed in `hardware_device_roles`, for
every device assigned to a cluster, and for every device that already has CPU &
RAM recorded; the badge shows the total number of cores. **Add** opens a form
with:
- **CPU model**: a searchable select over the catalogue. Typing `6338`,
`Gold 6338` or `epyc 7543` is enough; each entry shows cores, threads and
base/turbo clock.
- **Number of CPUs** (populated sockets). It is checked against the maximum
socket count of the model, e.g. EPYC "P" models are single-socket only.
- **RAM**: number and size of the modules, total RAM (calculated from modules ×
size when left empty), type (DDR3/DDR4/DDR5) and speed in MT/s.
The tab then shows e.g. *2 × Intel Xeon Gold 6338 · 64 cores / 128 threads ·
1 TB (16 × 64 GB DDR4-3200)*. The device list offers the optional columns
**CPU**, **Cores / Threads** and **RAM** under **Configure Table**.
**CPU catalogue.** **Hardware > CPU models** lists about 700 server CPUs:
| Vendor | Families |
|---|---|
| Intel | Xeon E5-2600/2400/4600/1600 v1–v4, E7 v2–v4, E3-1200 v2–v6, Xeon E-2100 to E-2400, Xeon 6300P, Xeon Scalable 1st–5th Gen (Skylake to Emerald Rapids), Xeon 6 (Sierra Forest, Granite Rapids), Xeon 6+ (Clearwater Forest) |
| AMD | Opteron 4300/6300, EPYC 7001/7002/7003 (incl. F and X models), 9004 (Genoa, Genoa-X, Bergamo), 8004, 4004, 4005, 9005 (Turin) |
Each entry has cores, threads, base and turbo clock, TDP, socket, launch year
and maximum socket count. The values were checked against Intel ARK, AMD and
server vendor specifications. Missing models can be added in the UI or by CSV
import; catalogue entries can be edited, too. The catalogue is loaded by the
migration and refreshed after a plugin update with:
```bash
cd /opt/netbox/netbox
../venv/bin/python manage.py netbox_utilities_cpu_catalog # add new models, keep edited ones
../venv/bin/python manage.py netbox_utilities_cpu_catalog --force # also reset edited catalogue entries
```
Models you created yourself are never changed by the command.
**Virtualization.** CPU & RAM work together with NetBox clusters and virtual
machines (vCPUs and memory of the VM):
- **Cluster page:** a **Capacity (CPU & RAM)** panel sums the hosts (devices
of the cluster) and compares them with the VMs: physical cores/threads and
RAM, allocated vCPUs and RAM, the vCPU-to-core ratio, RAM allocation in
percent and the RAM that remains if the largest host fails (N+1). A table
lists every host with its CPU, VMs, ratio and RAM usage; hosts without CPU &
RAM are flagged with a link to record them.
- **Host (device):** the CPU & RAM tab adds the capacity of that host and a
list of the VMs running on it (VMs whose *Device* is set).
- **VM page:** a **Host hardware** panel shows the CPU of the host, or of the
cluster hosts if the VM has no fixed host, and warns if the VM has more
vCPUs than the host has threads.
- **Cluster list:** the optional column **vCPU : core · RAM** shows the ratio
and RAM allocation per cluster.
Warnings appear when VMs are allocated more RAM than the hosts have, when the
RAM no longer fits after the failure of the largest host, and when the vCPU
ratio exceeds `hardware_vcpu_ratio_warning`. VMs with the status *Offline* or
*Decommissioning* are not counted.
VMs that are assigned only to a cluster, without a fixed host (*Device*), are
spread over the cluster hosts in proportion to their size: vCPUs by the number
of threads, memory by the host RAM. A host with twice the threads carries twice
the vCPUs of these VMs. If no host of the cluster has CPU & RAM recorded, the
load is split evenly. As soon as a single VM of the cluster (in any status) is
assigned to one of its hosts, the placement counts as managed by hand: nothing
is spread, and the VMs without a host only count towards the cluster totals. The cluster table and the CPU & RAM tab of each host
include this share and mark it as such; the cluster totals count every VM once. VM memory is read in MB as NetBox stores it.
**CSV import.** **Hardware > CPU & RAM > Import** accepts `device` (name),
`cpu` (catalogue model name, e.g. `Xeon Gold 6338`), `cpu_count`, `memory_gb`,
`memory_type` (`ddr3`, `ddr4`, `ddr5`), `memory_modules`, `memory_module_gb`,
`memory_speed_mts`, `description`, `comments` and `tags`.
```csv
device,cpu,cpu_count,memory_modules,memory_module_gb,memory_type,memory_speed_mts
esx01,Xeon Gold 6338,2,16,64,ddr4,3200
esx02,EPYC 9354,2,24,32,ddr5,4800
```
**REST API and GraphQL.** `/api/plugins/utilities/cpu-models/` and
`/api/plugins/utilities/device-hardware/` (with read-only `total_cores` and
`total_threads`); filters include `?q=6338`, `?manufacturer=amd`,
`?cores__gte=32`, `?cluster_id=4` and `?cpu_id=17`. GraphQL offers
`netbox_utilities_cpu_model(_list)` and `netbox_utilities_device_hardware(_list)`.
**Permissions.** The tab and panels require `netbox_utilities.view_devicehardware`;
recording and editing use `netbox_utilities.add_devicehardware` and
`netbox_utilities.change_devicehardware`. The catalogue uses the
`netbox_utilities.*_cpumodel` permissions.
### Client software overview
Requires the [netbox-slm](https://github.com/ICTU/netbox_slm) plugin, which stores
software products, versions and installations. *Inventory → Software → Client
Software Übersicht* (in the menu of netbox-inventory, otherwise in the
*Hardware* menu of this plugin) shows for the selected tenants and tenant groups
(including subgroups):
- key figures: clients, share with recorded software, products, versions and
clients running a version past its end of support,
- charts of the most widespread products and their version distribution
(newest version strongest, expired versions hatched red),
- a sortable, searchable list of all products.
Clicking a product shows how many clients run each version and the list of
clients; clicking a version filters that list. The current selection can be
exported as CSV. Without an own selection the global tenant filter applies.
Only devices with a role from `software_device_roles` (name or slug, e.g.
`Windows Client` / `windows-client`) are included; servers and other devices
never appear. The role checkboxes narrow the selection to single client roles.
Software lists of the **NetBox Windows Agent** (mode `netbox`) and the
**NetBox Synchronizer** desktop app (agent scan) arrive as an inventory report
in the device comments. Every time such a device is saved, its software list is
transferred into netbox-slm: missing products, versions and installations are
created, and installations that disappeared from the report are removed. Only
installations created this way (comment *Automatisch aus dem
Inventarbericht übernommen*) are removed; entries made by hand stay. A product
gets the dcim manufacturer of the same name as the publisher, if one exists,
otherwise the publisher goes into its description. Agent lines without a
recognisable version (at least one dot) get the version `unbekannt`. Deleting a
device removes its automatic installations first, so netbox-slm does not block
the deletion.
Devices that already have a report are transferred once with:
```bash
/opt/netbox/venv/bin/python /opt/netbox/netbox/manage.py netbox_utilities_sync_software
```
Devices with one of these roles get a **Software** tab listing their
installations with add, edit and delete buttons. Other devices show the tab
only if software is recorded for them. Permissions are those of netbox-slm
(`netbox_slm.view_softwareproductinstallation` and friends).
### Switch front panel
On the **Device** tab of a switch (role from `switch_device_roles`) a **Ports**
panel appears above the *Device* and *Management* cards, similar to the port
view in the web interface of Aruba switches:
- A dark faceplate with every physical port as an RJ45 or SFP jack, odd ports
on top and even ports below, grouped per stack member or line card.
- **Status** view: green = link/connected, empty jack = free, red dot = disabled.
- Management ports (marked *management only* or named `mgmt`, `management`,
`oobm`, `me0` …) are shown as **MGMT** in a group of their own at the end.
- The faceplate follows NetBox's light and dark theme.
- **VLAN** view: every VLAN from the interface label gets its own colour (the
same colours as in the PDF), the VLAN is printed in the jack and the text
colour is chosen for contrast; free ports are dimmed, connected ports framed.
A legend lists every VLAN with connected/total ports.
- Hovering shows name, status, VLAN, peer and description; clicking opens the
interface. The header shows the key figures and links to the PDF export.
- 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.
- A LAG note in the label such as `10,20 (LAG 1)` (written by NetBox
Synchronizer for LAG members) is shown, but ignored for VLAN colours, the
legend and the mismatch check.
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.
**Switch stacks via REST API.** The stack set in the device form (*Switch-Stack*
and *Stack-Mitglieder*) can also be read and written through
`/api/plugins/utilities/switch-stacks/`: `device` is the stack switch, `members`
the IDs of the further member devices. Filter with `?device_id=` or
`?member_id=`. The model has no change log and no tags; permissions are
`netbox_utilities.*_switchstack`. NetBox Synchronizer uses this endpoint to fill
in detected stacks.
### Switch port usage (PDF)
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:
- **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). A 48-port switch fits on one row; wider groups
are split evenly.
- **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 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
@@ -549,6 +831,17 @@ cable ends are evaluated; the tenant is only set if it is unambiguous. If an
automatically set tenant is saved unchanged, the browser asks for an explicit
confirmation.
Assets of the optional [netbox-inventory](https://github.com/ArnesSI/netbox-inventory)
plugin are tenant-aware as well: the asset forms are pre-filled like core
objects (also from an assigned module or inventory item), and an asset without
a tenant takes the tenant of the device, module, inventory item or rack it is
assigned to when it is saved. This keeps the plugin's *assign*, *reassign* and
*create hardware from asset* views working with mandatory tenancy, which save
the asset without a tenant field. An asset that is in stock and has no
assigned hardware still needs a tenant. The asset list shows a **Tenant**
column next to the status by default; users with a saved table configuration
can add it via *Configure Table*.
`tenant_required = False` disables the feature permanently and takes precedence
over the UI setting.
Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 151 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

+26 -2
View File
@@ -1,12 +1,12 @@
from netbox.plugins import PluginConfig, get_plugin_config
__version__ = "0.16.0"
__version__ = "0.29.2"
class NetBoxUtilitiesConfig(PluginConfig):
name = "netbox_utilities"
verbose_name = "NetBox Utilities"
description = "Navigation, tenant utilities, connection VLANs, partial-width racks, disks and bulk operations"
description = "Navigation, tenant utilities, connection VLANs, partial-width racks, disks, CPU & RAM, switch port export, client software overview and bulk operations"
version = __version__
author = "LKE"
base_url = "utilities"
@@ -26,6 +26,14 @@ class NetBoxUtilitiesConfig(PluginConfig):
"disk_device_roles": ["Server", "NAS", "SAN", "MSA"],
"disk_age_warning_years": 5,
"disk_warranty_warning_days": 90,
"hardware_enabled": True,
"hardware_device_roles": ["Server"],
"hardware_vcpu_ratio_warning": 4,
"switch_ports_enabled": True,
"switch_device_roles": ["Switch"],
"wireless_trace_enabled": True,
"software_enabled": True,
"software_device_roles": ["Client", "Windows Client"],
}
middleware = [
"netbox_utilities.middleware.GlobalTenantFilterMiddleware",
@@ -46,6 +54,10 @@ class NetBoxUtilitiesConfig(PluginConfig):
from .disk_integration import install_disk_support
install_disk_support()
if get_plugin_config("netbox_utilities", "hardware_enabled"):
from .hardware_integration import install_hardware_support
install_hardware_support()
if get_plugin_config("netbox_utilities", "site_prefix_column_enabled"):
from .site_prefix import install_site_prefix_column
@@ -58,10 +70,22 @@ class NetBoxUtilitiesConfig(PluginConfig):
from .connection_scope import install_connection_scope_filter
install_connection_scope_filter()
if get_plugin_config("netbox_utilities", "wireless_trace_enabled"):
from .wireless_trace import install_wireless_trace
install_wireless_trace()
if self.apps.is_installed("netbox_export"):
from .netbox_export import install_netbox_export_rack_width_support
install_netbox_export_rack_width_support()
if self.apps.is_installed("netbox_inventory"):
from .inventory_assets import install_asset_tenant_column
install_asset_tenant_column()
if get_plugin_config("netbox_utilities", "software_enabled") and self.apps.is_installed("netbox_slm"):
from .software_integration import install_software_support
install_software_support()
if get_plugin_config("netbox_utilities", "reorder_rack_bulk_save_enabled"):
from .reorder_rack import install_reorder_rack_bulk_save
+91 -1
View File
@@ -3,7 +3,9 @@ from netbox.api.serializers import NetBoxModelSerializer
from rest_framework import serializers
from tenancy.api.serializers import TenantSerializer
from ..models import Disk, DiskBayLayout, DiskBayTemplate, RAIDGroup
from dcim.models import Device
from ..models import CPUModel, DeviceHardware, Disk, DiskBayLayout, DiskBayTemplate, RAIDGroup, SwitchStack
LAYOUT_FIELDS = ("name", "weight", "slot_count", "rows", "first_slot", "numbering", "form_factor")
@@ -125,3 +127,91 @@ class DiskBayTemplateSerializer(NetBoxModelSerializer):
"last_updated",
)
brief_fields = ("id", "url", "display", "device_type", "name", "slot_count")
class CPUModelSerializer(NetBoxModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="plugins-api:netbox_utilities-api:cpumodel-detail")
display = serializers.SerializerMethodField(read_only=True)
class Meta:
model = CPUModel
fields = (
"id",
"url",
"display_url",
"display",
"manufacturer",
"family",
"name",
"cores",
"threads",
"base_clock_ghz",
"boost_clock_ghz",
"tdp_watts",
"socket",
"launch_year",
"max_sockets",
"builtin",
"customized",
"description",
"tags",
"custom_fields",
"created",
"last_updated",
)
brief_fields = ("id", "url", "display", "manufacturer", "name", "cores", "threads")
def get_display(self, obj):
# Shown in the CPU select: "Intel Xeon Gold 6338 – 32 Kerne / 64 Threads, 2 / 3,2 GHz".
return f"{obj} – {obj.summary}"
class DeviceHardwareSerializer(NetBoxModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="plugins-api:netbox_utilities-api:devicehardware-detail")
device = DeviceSerializer(nested=True)
cpu = CPUModelSerializer(nested=True, required=False, allow_null=True)
total_cores = serializers.IntegerField(read_only=True, allow_null=True)
total_threads = serializers.IntegerField(read_only=True, allow_null=True)
class Meta:
model = DeviceHardware
fields = (
"id",
"url",
"display_url",
"display",
"device",
"cpu",
"cpu_count",
"total_cores",
"total_threads",
"memory_gb",
"memory_type",
"memory_modules",
"memory_module_gb",
"memory_speed_mts",
"description",
"comments",
"tags",
"custom_fields",
"created",
"last_updated",
)
brief_fields = ("id", "url", "display", "device", "cpu", "cpu_count", "memory_gb")
class SwitchStackSerializer(serializers.ModelSerializer):
"""Stack switch and its further members as device IDs (the switch itself is always the first member)."""
device = serializers.PrimaryKeyRelatedField(queryset=Device.objects.all())
members = serializers.PrimaryKeyRelatedField(queryset=Device.objects.all(), many=True, required=False)
class Meta:
model = SwitchStack
fields = ("id", "device", "members", "updated")
def validate(self, data):
device = data.get("device") or getattr(self.instance, "device", None)
if device is not None and any(member.pk == device.pk for member in data.get("members") or []):
raise serializers.ValidationError({"members": "Der Switch kann nicht sein eigenes Mitglied sein."})
return data
+3
View File
@@ -9,5 +9,8 @@ router.register("disks", views.DiskViewSet)
router.register("raid-groups", views.RAIDGroupViewSet)
router.register("disk-bay-layouts", views.DiskBayLayoutViewSet)
router.register("disk-bay-templates", views.DiskBayTemplateViewSet)
router.register("cpu-models", views.CPUModelViewSet)
router.register("device-hardware", views.DeviceHardwareViewSet)
router.register("switch-stacks", views.SwitchStackViewSet)
urlpatterns = router.urls
+33 -2
View File
@@ -1,7 +1,9 @@
from netbox.api.authentication import TokenPermissions
from netbox.api.viewsets import NetBoxModelViewSet
from rest_framework.viewsets import ModelViewSet
from .. import disk_filtersets
from ..models import Disk, DiskBayLayout, DiskBayTemplate, RAIDGroup
from .. import disk_filtersets, hardware_filtersets
from ..models import CPUModel, DeviceHardware, Disk, DiskBayLayout, DiskBayTemplate, RAIDGroup, SwitchStack
from . import serializers
@@ -27,3 +29,32 @@ class DiskBayTemplateViewSet(NetBoxModelViewSet):
queryset = DiskBayTemplate.objects.select_related("device_type")
serializer_class = serializers.DiskBayTemplateSerializer
filterset_class = disk_filtersets.DiskBayTemplateFilterSet
class CPUModelViewSet(NetBoxModelViewSet):
queryset = CPUModel.objects.all()
serializer_class = serializers.CPUModelSerializer
filterset_class = hardware_filtersets.CPUModelFilterSet
class DeviceHardwareViewSet(NetBoxModelViewSet):
queryset = DeviceHardware.objects.select_related("device", "cpu")
serializer_class = serializers.DeviceHardwareSerializer
filterset_class = hardware_filtersets.DeviceHardwareFilterSet
class SwitchStackViewSet(ModelViewSet):
"""Plain model without change log or tags; filter with ``?device_id=`` or ``?member_id=``."""
queryset = SwitchStack.objects.prefetch_related("members").order_by("pk")
serializer_class = serializers.SwitchStackSerializer
permission_classes = [TokenPermissions]
def get_queryset(self):
queryset = super().get_queryset()
params = self.request.query_params
if params.get("device_id"):
queryset = queryset.filter(device_id__in=params.getlist("device_id"))
if params.get("member_id"):
queryset = queryset.filter(members__in=params.getlist("member_id")).distinct()
return queryset
+900
View File
@@ -0,0 +1,900 @@
"""Built-in catalogue of Intel and AMD server CPUs since 2012.
Values follow the vendor specifications (cores, threads, base/boost clock in GHz,
TDP in watts). The catalogue is loaded by a migration and can be refreshed with
``manage.py netbox_utilities_cpu_catalog``; entries can also be edited or added in
the UI. Edited entries are not overwritten unless the command runs with --force.
Each family: (manufacturer, family, socket, launch year, max sockets, models)
Each model: (name, cores, threads, base GHz, boost GHz or None, TDP W)
A trailing "P" on EPYC models means single-socket only.
"""
INTEL = "intel"
AMD = "amd"
FAMILIES = (
#
# Intel Xeon E5 / E7
#
(INTEL, "Xeon E5-2600 (Sandy Bridge-EP)", "LGA2011", 2012, 2, (
("Xeon E5-2603", 4, 4, 1.8, None, 80),
("Xeon E5-2609", 4, 4, 2.4, None, 80),
("Xeon E5-2620", 6, 12, 2.0, 2.5, 95),
("Xeon E5-2630", 6, 12, 2.3, 2.8, 95),
("Xeon E5-2630L", 6, 12, 2.0, 2.5, 60),
("Xeon E5-2637", 2, 4, 3.0, 3.5, 80),
("Xeon E5-2640", 6, 12, 2.5, 3.0, 95),
("Xeon E5-2643", 4, 8, 3.3, 3.5, 130),
("Xeon E5-2650", 8, 16, 2.0, 2.8, 95),
("Xeon E5-2650L", 8, 16, 1.8, 2.3, 70),
("Xeon E5-2660", 8, 16, 2.2, 3.0, 95),
("Xeon E5-2665", 8, 16, 2.4, 3.1, 115),
("Xeon E5-2667", 6, 12, 2.9, 3.5, 130),
("Xeon E5-2670", 8, 16, 2.6, 3.3, 115),
("Xeon E5-2680", 8, 16, 2.7, 3.5, 130),
("Xeon E5-2690", 8, 16, 2.9, 3.8, 135),
("Xeon E5-2687W", 8, 16, 3.1, 3.8, 150),
)),
(INTEL, "Xeon E5-2400 (Sandy Bridge-EN)", "LGA1356", 2012, 2, (
("Xeon E5-2407", 4, 4, 2.2, None, 80),
("Xeon E5-2420", 6, 12, 1.9, 2.4, 95),
("Xeon E5-2430", 6, 12, 2.2, 2.7, 95),
("Xeon E5-2440", 6, 12, 2.4, 2.9, 95),
("Xeon E5-2450", 8, 16, 2.1, 2.9, 95),
("Xeon E5-2470", 8, 16, 2.3, 3.1, 95),
)),
(INTEL, "Xeon E5-4600 (Sandy Bridge-EP)", "LGA2011", 2012, 4, (
("Xeon E5-4610", 6, 12, 2.4, 2.9, 95),
("Xeon E5-4620", 8, 16, 2.2, 2.6, 95),
("Xeon E5-4640", 8, 16, 2.4, 2.8, 95),
("Xeon E5-4650", 8, 16, 2.7, 3.3, 130),
)),
(INTEL, "Xeon E5-2600 v2 (Ivy Bridge-EP)", "LGA2011", 2013, 2, (
("Xeon E5-2603 v2", 4, 4, 1.8, None, 80),
("Xeon E5-2609 v2", 4, 4, 2.5, None, 80),
("Xeon E5-2620 v2", 6, 12, 2.1, 2.6, 80),
("Xeon E5-2630 v2", 6, 12, 2.6, 3.1, 80),
("Xeon E5-2630L v2", 6, 12, 2.4, 2.8, 60),
("Xeon E5-2637 v2", 4, 8, 3.5, 3.8, 130),
("Xeon E5-2640 v2", 8, 16, 2.0, 2.5, 95),
("Xeon E5-2643 v2", 6, 12, 3.5, 3.8, 130),
("Xeon E5-2650 v2", 8, 16, 2.6, 3.4, 95),
("Xeon E5-2650L v2", 10, 20, 1.7, 2.1, 70),
("Xeon E5-2660 v2", 10, 20, 2.2, 3.0, 95),
("Xeon E5-2667 v2", 8, 16, 3.3, 4.0, 130),
("Xeon E5-2670 v2", 10, 20, 2.5, 3.3, 115),
("Xeon E5-2680 v2", 10, 20, 2.8, 3.6, 115),
("Xeon E5-2690 v2", 10, 20, 3.0, 3.6, 130),
("Xeon E5-2695 v2", 12, 24, 2.4, 3.2, 115),
("Xeon E5-2697 v2", 12, 24, 2.7, 3.5, 130),
("Xeon E5-2687W v2", 8, 16, 3.4, 4.0, 150),
)),
(INTEL, "Xeon E5-2400 v2 (Ivy Bridge-EN)", "LGA1356", 2014, 2, (
("Xeon E5-2407 v2", 4, 4, 2.4, None, 80),
("Xeon E5-2420 v2", 6, 12, 2.2, 2.7, 80),
("Xeon E5-2430 v2", 6, 12, 2.5, 3.0, 80),
("Xeon E5-2440 v2", 8, 16, 1.9, 2.4, 95),
("Xeon E5-2450 v2", 8, 16, 2.5, 3.3, 95),
("Xeon E5-2470 v2", 10, 20, 2.4, 3.2, 95),
)),
(INTEL, "Xeon E5-4600 v2 (Ivy Bridge-EP)", "LGA2011", 2014, 4, (
("Xeon E5-4610 v2", 8, 16, 2.3, 2.7, 95),
("Xeon E5-4620 v2", 8, 16, 2.6, 3.0, 95),
("Xeon E5-4640 v2", 10, 20, 2.2, 2.7, 95),
("Xeon E5-4650 v2", 10, 20, 2.4, 2.9, 95),
("Xeon E5-4657L v2", 12, 24, 2.4, 2.9, 115),
("Xeon E5-4603 v2", 4, 8, 2.2, None, 95),
("Xeon E5-4607 v2", 6, 12, 2.6, None, 95),
)),
(INTEL, "Xeon E7 v2 (Ivy Bridge-EX)", "LGA2011-1", 2014, 8, (
("Xeon E7-4850 v2", 12, 24, 2.3, 2.8, 105),
("Xeon E7-4870 v2", 15, 30, 2.3, 2.9, 130),
("Xeon E7-8870 v2", 15, 30, 2.3, 2.9, 130),
("Xeon E7-8890 v2", 15, 30, 2.8, 3.4, 155),
("Xeon E7-4809 v2", 6, 12, 1.9, None, 105),
("Xeon E7-4820 v2", 8, 16, 2.0, 2.5, 105),
("Xeon E7-4830 v2", 10, 20, 2.2, 2.7, 105),
("Xeon E7-4860 v2", 12, 24, 2.6, 3.2, 130),
("Xeon E7-4880 v2", 15, 30, 2.5, 3.1, 130),
("Xeon E7-4890 v2", 15, 30, 2.8, 3.4, 155),
("Xeon E7-8850 v2", 12, 24, 2.3, 2.8, 105),
("Xeon E7-8880 v2", 15, 30, 2.5, 3.1, 130),
("Xeon E7-8891 v2", 10, 20, 3.2, 3.7, 155),
("Xeon E7-8893 v2", 6, 12, 3.4, 3.7, 155),
)),
(INTEL, "Xeon E5-2600 v3 (Haswell-EP)", "LGA2011-3", 2014, 2, (
("Xeon E5-2603 v3", 6, 6, 1.6, None, 85),
("Xeon E5-2609 v3", 6, 6, 1.9, None, 85),
("Xeon E5-2620 v3", 6, 12, 2.4, 3.2, 85),
("Xeon E5-2623 v3", 4, 8, 3.0, 3.5, 105),
("Xeon E5-2630 v3", 8, 16, 2.4, 3.2, 85),
("Xeon E5-2630L v3", 8, 16, 1.8, 2.9, 55),
("Xeon E5-2637 v3", 4, 8, 3.5, 3.7, 135),
("Xeon E5-2640 v3", 8, 16, 2.6, 3.4, 90),
("Xeon E5-2643 v3", 6, 12, 3.4, 3.7, 135),
("Xeon E5-2650 v3", 10, 20, 2.3, 3.0, 105),
("Xeon E5-2650L v3", 12, 24, 1.8, 2.5, 65),
("Xeon E5-2660 v3", 10, 20, 2.6, 3.3, 105),
("Xeon E5-2667 v3", 8, 16, 3.2, 3.6, 135),
("Xeon E5-2670 v3", 12, 24, 2.3, 3.1, 120),
("Xeon E5-2680 v3", 12, 24, 2.5, 3.3, 120),
("Xeon E5-2683 v3", 14, 28, 2.0, 3.0, 120),
("Xeon E5-2687W v3", 10, 20, 3.1, 3.5, 160),
("Xeon E5-2690 v3", 12, 24, 2.6, 3.5, 135),
("Xeon E5-2695 v3", 14, 28, 2.3, 3.3, 120),
("Xeon E5-2697 v3", 14, 28, 2.6, 3.6, 145),
("Xeon E5-2698 v3", 16, 32, 2.3, 3.6, 135),
("Xeon E5-2699 v3", 18, 36, 2.3, 3.6, 145),
)),
(INTEL, "Xeon E5-1600 v3 (Haswell-EP)", "LGA2011-3", 2014, 1, (
("Xeon E5-1620 v3", 4, 8, 3.5, 3.6, 140),
("Xeon E5-1650 v3", 6, 12, 3.5, 3.8, 140),
("Xeon E5-1630 v3", 4, 8, 3.7, 3.8, 140),
("Xeon E5-1660 v3", 8, 16, 3.0, 3.5, 140),
("Xeon E5-1680 v3", 8, 16, 3.2, 3.8, 140),
)),
(INTEL, "Xeon E5-4600 v3 (Haswell-EP)", "LGA2011-3", 2015, 4, (
("Xeon E5-4620 v3", 10, 20, 2.0, 2.6, 105),
("Xeon E5-4640 v3", 12, 24, 1.9, 2.6, 105),
("Xeon E5-4650 v3", 12, 24, 2.1, 2.8, 105),
("Xeon E5-4669 v3", 18, 36, 2.1, 2.9, 135),
("Xeon E5-4610 v3", 10, 20, 1.7, None, 105),
("Xeon E5-4627 v3", 10, 10, 2.6, 3.2, 135),
("Xeon E5-4660 v3", 14, 28, 2.1, 2.9, 120),
("Xeon E5-4667 v3", 16, 32, 2.0, 2.9, 135),
)),
(INTEL, "Xeon E7 v3 (Haswell-EX)", "LGA2011-1", 2015, 8, (
("Xeon E7-4850 v3", 14, 28, 2.2, 2.8, 115),
("Xeon E7-8870 v3", 18, 36, 2.1, 2.9, 140),
("Xeon E7-8890 v3", 18, 36, 2.5, 3.3, 165),
("Xeon E7-4809 v3", 8, 16, 2.0, None, 115),
("Xeon E7-4820 v3", 10, 20, 1.9, None, 115),
("Xeon E7-4830 v3", 12, 24, 2.1, 2.7, 115),
("Xeon E7-8860 v3", 16, 32, 2.2, 3.2, 140),
("Xeon E7-8867 v3", 16, 32, 2.5, 3.3, 165),
("Xeon E7-8880 v3", 18, 36, 2.3, 3.1, 140),
("Xeon E7-8891 v3", 10, 20, 2.8, 3.5, 165),
("Xeon E7-8893 v3", 4, 8, 3.2, 3.5, 140),
)),
(INTEL, "Xeon E5-2600 v4 (Broadwell-EP)", "LGA2011-3", 2016, 2, (
("Xeon E5-2603 v4", 6, 6, 1.7, None, 85),
("Xeon E5-2609 v4", 8, 8, 1.7, None, 85),
("Xeon E5-2620 v4", 8, 16, 2.1, 3.0, 85),
("Xeon E5-2623 v4", 4, 8, 2.6, 3.2, 85),
("Xeon E5-2630 v4", 10, 20, 2.2, 3.1, 85),
("Xeon E5-2630L v4", 10, 20, 1.8, 2.9, 55),
("Xeon E5-2637 v4", 4, 8, 3.5, 3.7, 135),
("Xeon E5-2640 v4", 10, 20, 2.4, 3.4, 90),
("Xeon E5-2643 v4", 6, 12, 3.4, 3.7, 135),
("Xeon E5-2650 v4", 12, 24, 2.2, 2.9, 105),
("Xeon E5-2650L v4", 14, 28, 1.7, 2.5, 65),
("Xeon E5-2660 v4", 14, 28, 2.0, 3.2, 105),
("Xeon E5-2667 v4", 8, 16, 3.2, 3.6, 135),
("Xeon E5-2680 v4", 14, 28, 2.4, 3.3, 120),
("Xeon E5-2683 v4", 16, 32, 2.1, 3.0, 120),
("Xeon E5-2690 v4", 14, 28, 2.6, 3.5, 135),
("Xeon E5-2695 v4", 18, 36, 2.1, 3.3, 120),
("Xeon E5-2697 v4", 18, 36, 2.3, 3.6, 145),
("Xeon E5-2697A v4", 16, 32, 2.6, 3.6, 145),
("Xeon E5-2698 v4", 20, 40, 2.2, 3.6, 135),
("Xeon E5-2699 v4", 22, 44, 2.2, 3.6, 145),
("Xeon E5-2687W v4", 12, 24, 3.0, 3.5, 160),
("Xeon E5-2699A v4", 22, 44, 2.4, 3.6, 145),
)),
(INTEL, "Xeon E5-1600 v4 (Broadwell-EP)", "LGA2011-3", 2016, 1, (
("Xeon E5-1620 v4", 4, 8, 3.5, 3.8, 140),
("Xeon E5-1650 v4", 6, 12, 3.6, 4.0, 140),
("Xeon E5-1660 v4", 8, 16, 3.2, 3.8, 140),
("Xeon E5-1630 v4", 4, 8, 3.7, 4.0, 140),
("Xeon E5-1680 v4", 8, 16, 3.4, 4.0, 140),
)),
(INTEL, "Xeon E5-4600 v4 (Broadwell-EP)", "LGA2011-3", 2016, 4, (
("Xeon E5-4620 v4", 10, 20, 2.1, 2.6, 105),
("Xeon E5-4640 v4", 12, 24, 2.1, 2.6, 105),
("Xeon E5-4650 v4", 14, 28, 2.2, 2.8, 105),
("Xeon E5-4669 v4", 22, 44, 2.2, 3.0, 135),
("Xeon E5-4610 v4", 10, 20, 1.8, None, 105),
("Xeon E5-4627 v4", 10, 10, 2.6, 3.2, 135),
("Xeon E5-4660 v4", 16, 32, 2.2, 3.0, 120),
("Xeon E5-4667 v4", 18, 36, 2.2, 3.0, 135),
)),
(INTEL, "Xeon E7 v4 (Broadwell-EX)", "LGA2011-1", 2016, 8, (
("Xeon E7-4850 v4", 16, 32, 2.1, 2.8, 115),
("Xeon E7-8880 v4", 22, 44, 2.2, 3.3, 150),
("Xeon E7-8890 v4", 24, 48, 2.2, 3.4, 165),
("Xeon E7-4809 v4", 8, 16, 2.1, None, 115),
("Xeon E7-4820 v4", 10, 20, 2.0, None, 115),
("Xeon E7-4830 v4", 14, 28, 2.0, 2.8, 115),
("Xeon E7-8860 v4", 18, 36, 2.2, 3.2, 140),
("Xeon E7-8867 v4", 18, 36, 2.4, 3.3, 165),
("Xeon E7-8870 v4", 20, 40, 2.1, 3.0, 140),
("Xeon E7-8891 v4", 10, 20, 2.8, 3.5, 165),
("Xeon E7-8893 v4", 4, 8, 3.2, 3.5, 140),
("Xeon E7-8894 v4", 24, 48, 2.4, 3.4, 165),
)),
#
# Intel Xeon E3 / E (single socket)
#
(INTEL, "Xeon E3-1200 v2 (Ivy Bridge)", "LGA1155", 2012, 1, (
("Xeon E3-1220 v2", 4, 4, 3.1, 3.5, 69),
("Xeon E3-1230 v2", 4, 8, 3.3, 3.7, 69),
("Xeon E3-1240 v2", 4, 8, 3.4, 3.8, 69),
("Xeon E3-1270 v2", 4, 8, 3.5, 3.9, 69),
("Xeon E3-1225 v2", 4, 4, 3.2, 3.6, 77),
("Xeon E3-1245 v2", 4, 8, 3.4, 3.8, 77),
("Xeon E3-1275 v2", 4, 8, 3.5, 3.9, 77),
("Xeon E3-1280 v2", 4, 8, 3.6, 4.0, 69),
("Xeon E3-1290 v2", 4, 8, 3.7, 4.1, 87),
)),
(INTEL, "Xeon E3-1200 v3 (Haswell)", "LGA1150", 2013, 1, (
("Xeon E3-1220 v3", 4, 4, 3.1, 3.5, 80),
("Xeon E3-1230 v3", 4, 8, 3.3, 3.7, 80),
("Xeon E3-1231 v3", 4, 8, 3.4, 3.8, 80),
("Xeon E3-1240 v3", 4, 8, 3.4, 3.8, 80),
("Xeon E3-1270 v3", 4, 8, 3.5, 3.9, 80),
("Xeon E3-1225 v3", 4, 4, 3.2, 3.6, 84),
("Xeon E3-1241 v3", 4, 8, 3.5, 3.9, 80),
("Xeon E3-1245 v3", 4, 8, 3.4, 3.8, 84),
("Xeon E3-1246 v3", 4, 8, 3.5, 3.9, 84),
("Xeon E3-1271 v3", 4, 8, 3.6, 4.0, 80),
("Xeon E3-1275 v3", 4, 8, 3.5, 3.9, 84),
("Xeon E3-1280 v3", 4, 8, 3.6, 4.0, 82),
("Xeon E3-1281 v3", 4, 8, 3.7, 4.1, 82),
)),
(INTEL, "Xeon E3-1200 v5 (Skylake)", "LGA1151", 2015, 1, (
("Xeon E3-1220 v5", 4, 4, 3.0, 3.5, 80),
("Xeon E3-1230 v5", 4, 8, 3.4, 3.8, 80),
("Xeon E3-1240 v5", 4, 8, 3.5, 3.9, 80),
("Xeon E3-1270 v5", 4, 8, 3.6, 4.0, 80),
("Xeon E3-1245 v5", 4, 8, 3.5, 3.9, 80),
("Xeon E3-1280 v5", 4, 8, 3.7, 4.0, 80),
)),
(INTEL, "Xeon E3-1200 v6 (Kaby Lake)", "LGA1151", 2017, 1, (
("Xeon E3-1220 v6", 4, 4, 3.0, 3.5, 72),
("Xeon E3-1230 v6", 4, 8, 3.5, 3.9, 72),
("Xeon E3-1240 v6", 4, 8, 3.7, 4.1, 72),
("Xeon E3-1270 v6", 4, 8, 3.8, 4.2, 72),
("Xeon E3-1280 v6", 4, 8, 3.9, 4.2, 72),
("Xeon E3-1225 v6", 4, 4, 3.3, 3.7, 73),
("Xeon E3-1245 v6", 4, 8, 3.7, 4.1, 73),
("Xeon E3-1275 v6", 4, 8, 3.8, 4.2, 73),
("Xeon E3-1285 v6", 4, 8, 4.1, 4.5, 79),
)),
(INTEL, "Xeon E-2100 (Coffee Lake)", "LGA1151", 2018, 1, (
("Xeon E-2124", 4, 4, 3.3, 4.3, 71),
("Xeon E-2134", 4, 8, 3.5, 4.5, 71),
("Xeon E-2136", 6, 12, 3.3, 4.5, 80),
("Xeon E-2144G", 4, 8, 3.6, 4.5, 71),
("Xeon E-2146G", 6, 12, 3.5, 4.5, 80),
("Xeon E-2176G", 6, 12, 3.7, 4.7, 80),
("Xeon E-2186G", 6, 12, 3.8, 4.7, 95),
("Xeon E-2124G", 4, 4, 3.4, 4.5, 71),
("Xeon E-2126G", 6, 6, 3.3, 4.5, 80),
("Xeon E-2174G", 4, 8, 3.8, 4.7, 71),
)),
(INTEL, "Xeon E-2200 (Coffee Lake Refresh)", "LGA1151", 2019, 1, (
("Xeon E-2224", 4, 4, 3.4, 4.6, 71),
("Xeon E-2234", 4, 8, 3.6, 4.8, 71),
("Xeon E-2236", 6, 12, 3.4, 4.8, 80),
("Xeon E-2244G", 4, 8, 3.8, 4.8, 71),
("Xeon E-2246G", 6, 12, 3.6, 4.8, 80),
("Xeon E-2274G", 4, 8, 4.0, 4.9, 83),
("Xeon E-2276G", 6, 12, 3.8, 4.9, 80),
("Xeon E-2278G", 8, 16, 3.4, 5.0, 80),
("Xeon E-2288G", 8, 16, 3.7, 5.0, 95),
("Xeon E-2224G", 4, 4, 3.5, 4.7, 71),
("Xeon E-2226G", 6, 6, 3.4, 4.7, 80),
("Xeon E-2286G", 6, 12, 4.0, 4.9, 95),
)),
(INTEL, "Xeon E-2300 (Rocket Lake)", "LGA1200", 2021, 1, (
("Xeon E-2314", 4, 4, 2.8, 4.5, 65),
("Xeon E-2324G", 4, 4, 3.1, 4.6, 65),
("Xeon E-2334", 4, 8, 3.4, 4.8, 65),
("Xeon E-2336", 6, 12, 2.9, 4.8, 65),
("Xeon E-2356G", 6, 12, 3.2, 5.0, 80),
("Xeon E-2378", 8, 16, 2.6, 4.8, 65),
("Xeon E-2378G", 8, 16, 2.8, 5.1, 80),
("Xeon E-2386G", 6, 12, 3.5, 5.1, 95),
("Xeon E-2388G", 8, 16, 3.2, 5.1, 95),
("Xeon E-2374G", 4, 8, 3.7, 5.0, 80),
)),
(INTEL, "Xeon E-2400 (Raptor Lake)", "LGA1700", 2023, 1, (
("Xeon E-2414", 4, 4, 2.6, 4.5, 55),
("Xeon E-2434", 4, 8, 3.4, 5.0, 55),
("Xeon E-2436", 6, 12, 2.9, 4.8, 65),
("Xeon E-2456", 6, 12, 3.3, 5.1, 80),
("Xeon E-2468", 8, 16, 2.6, 5.2, 65),
("Xeon E-2478", 8, 16, 2.8, 5.2, 80),
("Xeon E-2488", 8, 16, 3.2, 5.6, 95),
("Xeon E-2486", 6, 12, 3.5, 5.6, 95),
)),
#
# Intel Xeon Scalable
#
(INTEL, "Xeon Scalable 1. Gen (Skylake-SP)", "LGA3647", 2017, 8, (
("Xeon Bronze 3104", 6, 6, 1.7, None, 85),
("Xeon Bronze 3106", 8, 8, 1.7, None, 85),
("Xeon Silver 4108", 8, 16, 1.8, 3.0, 85),
("Xeon Silver 4109T", 8, 16, 2.0, 3.0, 70),
("Xeon Silver 4110", 8, 16, 2.1, 3.0, 85),
("Xeon Silver 4112", 4, 8, 2.6, 3.0, 85),
("Xeon Silver 4114", 10, 20, 2.2, 3.0, 85),
("Xeon Silver 4116", 12, 24, 2.1, 3.0, 85),
("Xeon Gold 5115", 10, 20, 2.4, 3.2, 85),
("Xeon Gold 5118", 12, 24, 2.3, 3.2, 105),
("Xeon Gold 5120", 14, 28, 2.2, 3.2, 105),
("Xeon Gold 5122", 4, 8, 3.6, 3.7, 105),
("Xeon Gold 6126", 12, 24, 2.6, 3.7, 125),
("Xeon Gold 6128", 6, 12, 3.4, 3.7, 115),
("Xeon Gold 6130", 16, 32, 2.1, 3.7, 125),
("Xeon Gold 6132", 14, 28, 2.6, 3.7, 140),
("Xeon Gold 6134", 8, 16, 3.2, 3.7, 130),
("Xeon Gold 6136", 12, 24, 3.0, 3.7, 150),
("Xeon Gold 6138", 20, 40, 2.0, 3.7, 125),
("Xeon Gold 6140", 18, 36, 2.3, 3.7, 140),
("Xeon Gold 6142", 16, 32, 2.6, 3.7, 150),
("Xeon Gold 6144", 8, 16, 3.5, 4.2, 150),
("Xeon Gold 6146", 12, 24, 3.2, 4.2, 165),
("Xeon Gold 6148", 20, 40, 2.4, 3.7, 150),
("Xeon Gold 6150", 18, 36, 2.7, 3.7, 165),
("Xeon Gold 6152", 22, 44, 2.1, 3.7, 140),
("Xeon Gold 6154", 18, 36, 3.0, 3.7, 200),
("Xeon Platinum 8153", 16, 32, 2.0, 2.8, 125),
("Xeon Platinum 8160", 24, 48, 2.1, 3.7, 150),
("Xeon Platinum 8164", 26, 52, 2.0, 3.7, 150),
("Xeon Platinum 8168", 24, 48, 2.7, 3.7, 205),
("Xeon Platinum 8170", 26, 52, 2.1, 3.7, 165),
("Xeon Platinum 8176", 28, 56, 2.1, 3.8, 165),
("Xeon Platinum 8180", 28, 56, 2.5, 3.8, 205),
("Xeon Silver 4114T", 10, 20, 2.2, 3.0, 85),
("Xeon Silver 4116T", 12, 24, 2.1, 3.0, 85),
("Xeon Gold 5117", 14, 28, 2.0, 2.8, 105),
("Xeon Gold 5119T", 14, 28, 1.9, 3.2, 85),
("Xeon Gold 5120T", 14, 28, 2.2, 3.2, 105),
("Xeon Gold 6126T", 12, 24, 2.6, 3.7, 125),
("Xeon Gold 6130T", 16, 32, 2.1, 3.7, 125),
("Xeon Gold 6134M", 8, 16, 3.2, 3.7, 130),
("Xeon Gold 6138T", 20, 40, 2.0, 3.7, 125),
("Xeon Gold 6140M", 18, 36, 2.3, 3.7, 140),
("Xeon Gold 6142M", 16, 32, 2.6, 3.7, 150),
("Xeon Platinum 8156", 4, 8, 3.6, 3.7, 105),
("Xeon Platinum 8158", 12, 24, 3.0, 3.7, 150),
("Xeon Platinum 8160M", 24, 48, 2.1, 3.7, 150),
("Xeon Platinum 8160T", 24, 48, 2.1, 3.7, 150),
("Xeon Platinum 8170M", 26, 52, 2.1, 3.7, 165),
("Xeon Platinum 8176M", 28, 56, 2.1, 3.8, 165),
("Xeon Platinum 8180M", 28, 56, 2.5, 3.8, 205),
)),
(INTEL, "Xeon Scalable 2. Gen (Cascade Lake)", "LGA3647", 2019, 8, (
("Xeon Bronze 3204", 6, 6, 1.9, None, 85),
("Xeon Silver 4208", 8, 16, 2.1, 3.2, 85),
("Xeon Silver 4210", 10, 20, 2.2, 3.2, 85),
("Xeon Silver 4214", 12, 24, 2.2, 3.2, 85),
("Xeon Silver 4215", 8, 16, 2.5, 3.5, 85),
("Xeon Silver 4216", 16, 32, 2.1, 3.2, 100),
("Xeon Gold 5215", 10, 20, 2.5, 3.4, 85),
("Xeon Gold 5217", 8, 16, 3.0, 3.7, 115),
("Xeon Gold 5218", 16, 32, 2.3, 3.9, 125),
("Xeon Gold 5220", 18, 36, 2.2, 3.9, 125),
("Xeon Gold 5222", 4, 8, 3.8, 3.9, 105),
("Xeon Gold 6226", 12, 24, 2.7, 3.7, 125),
("Xeon Gold 6230", 20, 40, 2.1, 3.9, 125),
("Xeon Gold 6234", 8, 16, 3.3, 4.0, 130),
("Xeon Gold 6238", 22, 44, 2.1, 3.7, 140),
("Xeon Gold 6240", 18, 36, 2.6, 3.9, 150),
("Xeon Gold 6242", 16, 32, 2.8, 3.9, 150),
("Xeon Gold 6244", 8, 16, 3.6, 4.4, 150),
("Xeon Gold 6246", 12, 24, 3.3, 4.2, 165),
("Xeon Gold 6248", 20, 40, 2.5, 3.9, 150),
("Xeon Gold 6252", 24, 48, 2.1, 3.7, 150),
("Xeon Gold 6254", 18, 36, 3.1, 4.0, 200),
("Xeon Platinum 8253", 16, 32, 2.2, 3.0, 125),
("Xeon Platinum 8260", 24, 48, 2.4, 3.9, 165),
("Xeon Platinum 8268", 24, 48, 2.9, 3.9, 205),
("Xeon Platinum 8270", 26, 52, 2.7, 4.0, 205),
("Xeon Platinum 8276", 28, 56, 2.2, 4.0, 165),
("Xeon Platinum 8280", 28, 56, 2.7, 4.0, 205),
("Xeon Gold 6208U", 16, 32, 2.9, 3.9, 150),
("Xeon Gold 6209U", 20, 40, 2.1, 3.9, 125),
("Xeon Gold 6210U", 20, 40, 2.5, 3.9, 150),
("Xeon Gold 6212U", 24, 48, 2.4, 3.9, 165),
("Xeon Silver 4209T", 8, 16, 2.2, 3.2, 70),
("Xeon Silver 4210T", 10, 20, 2.3, 3.2, 95),
("Xeon Silver 4214Y", 12, 24, 2.2, 3.2, 85),
("Xeon Gold 5215L", 10, 20, 2.5, 3.4, 85),
("Xeon Gold 5215M", 10, 20, 2.5, 3.4, 85),
("Xeon Gold 5218B", 16, 32, 2.3, 3.9, 125),
("Xeon Gold 5218N", 16, 32, 2.3, 3.7, 125),
("Xeon Gold 5218T", 16, 32, 2.1, 3.8, 105),
("Xeon Gold 5220S", 18, 36, 2.7, 3.9, 125),
("Xeon Gold 5220T", 18, 36, 1.9, 3.9, 105),
("Xeon Gold 6222V", 20, 40, 1.8, 3.6, 115),
("Xeon Gold 6230N", 20, 40, 2.3, 3.5, 125),
("Xeon Gold 6230T", 20, 40, 2.1, 3.9, 125),
("Xeon Gold 6238L", 22, 44, 2.1, 3.7, 140),
("Xeon Gold 6238M", 22, 44, 2.1, 3.7, 140),
("Xeon Gold 6238T", 22, 44, 1.9, 3.7, 125),
("Xeon Gold 6240L", 18, 36, 2.6, 3.9, 150),
("Xeon Gold 6240M", 18, 36, 2.6, 3.9, 150),
("Xeon Gold 6240Y", 18, 36, 2.6, 3.9, 150),
("Xeon Gold 6250", 8, 16, 3.9, 4.5, 185),
("Xeon Gold 6250L", 8, 16, 3.9, 4.5, 185),
("Xeon Gold 6252N", 24, 48, 2.3, 3.6, 150),
("Xeon Gold 6256", 12, 24, 3.6, 4.5, 205),
("Xeon Gold 6262V", 24, 48, 1.9, 3.6, 135),
("Xeon Platinum 8256", 4, 8, 3.8, 3.9, 105),
("Xeon Platinum 8260L", 24, 48, 2.4, 3.9, 165),
("Xeon Platinum 8260M", 24, 48, 2.4, 3.9, 165),
("Xeon Platinum 8260Y", 24, 48, 2.4, 3.9, 165),
("Xeon Platinum 8276L", 28, 56, 2.2, 4.0, 165),
("Xeon Platinum 8276M", 28, 56, 2.2, 4.0, 165),
("Xeon Platinum 8280L", 28, 56, 2.7, 4.0, 205),
("Xeon Platinum 8280M", 28, 56, 2.7, 4.0, 205),
)),
(INTEL, "Xeon Scalable 2. Gen Refresh (Cascade Lake R)", "LGA3647", 2020, 2, (
("Xeon Bronze 3206R", 8, 8, 1.9, None, 85),
("Xeon Silver 4210R", 10, 20, 2.4, 3.2, 100),
("Xeon Silver 4214R", 12, 24, 2.4, 3.5, 100),
("Xeon Silver 4215R", 8, 16, 3.2, 4.0, 130),
("Xeon Gold 5218R", 20, 40, 2.1, 4.0, 125),
("Xeon Gold 5220R", 24, 48, 2.2, 4.0, 150),
("Xeon Gold 6226R", 16, 32, 2.9, 3.9, 150),
("Xeon Gold 6230R", 26, 52, 2.1, 4.0, 150),
("Xeon Gold 6238R", 28, 56, 2.2, 4.0, 165),
("Xeon Gold 6240R", 24, 48, 2.4, 4.0, 165),
("Xeon Gold 6242R", 20, 40, 3.1, 4.1, 205),
("Xeon Gold 6246R", 16, 32, 3.4, 4.1, 205),
("Xeon Gold 6248R", 24, 48, 3.0, 4.0, 205),
("Xeon Gold 6258R", 28, 56, 2.7, 4.0, 205),
("Xeon Silver 4216R", 16, 32, 2.2, 3.7, 125),
)),
(INTEL, "Xeon Scalable 3. Gen (Ice Lake-SP)", "LGA4189", 2021, 2, (
("Xeon Silver 4309Y", 8, 16, 2.8, 3.6, 105),
("Xeon Silver 4310", 12, 24, 2.1, 3.3, 120),
("Xeon Silver 4314", 16, 32, 2.4, 3.4, 135),
("Xeon Silver 4316", 20, 40, 2.3, 3.4, 150),
("Xeon Gold 5315Y", 8, 16, 3.2, 3.6, 140),
("Xeon Gold 5317", 12, 24, 3.0, 3.6, 150),
("Xeon Gold 5318Y", 24, 48, 2.1, 3.4, 165),
("Xeon Gold 5320", 26, 52, 2.2, 3.4, 185),
("Xeon Gold 6326", 16, 32, 2.9, 3.5, 185),
("Xeon Gold 6330", 28, 56, 2.0, 3.1, 205),
("Xeon Gold 6334", 8, 16, 3.6, 3.7, 165),
("Xeon Gold 6336Y", 24, 48, 2.4, 3.6, 185),
("Xeon Gold 6338", 32, 64, 2.0, 3.2, 205),
("Xeon Gold 6342", 24, 48, 2.8, 3.5, 230),
("Xeon Gold 6346", 16, 32, 3.1, 3.6, 205),
("Xeon Gold 6348", 28, 56, 2.6, 3.5, 235),
("Xeon Gold 6354", 18, 36, 3.0, 3.6, 205),
("Xeon Platinum 8352Y", 32, 64, 2.2, 3.4, 205),
("Xeon Platinum 8358", 32, 64, 2.6, 3.4, 250),
("Xeon Platinum 8360Y", 36, 72, 2.4, 3.5, 250),
("Xeon Platinum 8362", 32, 64, 2.8, 3.6, 265),
("Xeon Platinum 8368", 38, 76, 2.4, 3.4, 270),
("Xeon Platinum 8380", 40, 80, 2.3, 3.4, 270),
("Xeon Gold 6312U", 24, 48, 2.4, 3.6, 185),
("Xeon Gold 6314U", 32, 64, 2.3, 3.4, 205),
("Xeon Silver 4310T", 10, 20, 2.3, 3.4, 105),
("Xeon Gold 5318N", 24, 48, 2.1, 3.4, 150),
("Xeon Gold 5318S", 24, 48, 2.1, 3.4, 165),
("Xeon Gold 5320T", 20, 40, 2.3, 3.5, 150),
("Xeon Gold 6330N", 28, 56, 2.2, 3.4, 165),
("Xeon Gold 6338N", 32, 64, 2.2, 3.5, 185),
("Xeon Gold 6338T", 24, 48, 2.1, 3.4, 165),
("Xeon Platinum 8351N", 36, 72, 2.4, 3.5, 225),
("Xeon Platinum 8352M", 32, 64, 2.3, 3.5, 185),
("Xeon Platinum 8352S", 32, 64, 2.2, 3.4, 205),
("Xeon Platinum 8352V", 36, 72, 2.1, 3.5, 195),
("Xeon Platinum 8358P", 32, 64, 2.6, 3.4, 240),
("Xeon Platinum 8368Q", 38, 76, 2.6, 3.7, 270),
)),
(INTEL, "Xeon Scalable 4. Gen (Sapphire Rapids)", "LGA4677", 2023, 8, (
("Xeon Bronze 3408U", 8, 8, 1.8, 1.9, 125),
("Xeon Silver 4410Y", 12, 24, 2.0, 3.9, 150),
("Xeon Silver 4416+", 20, 40, 2.0, 3.9, 165),
("Xeon Gold 5415+", 8, 16, 2.9, 4.1, 150),
("Xeon Gold 5416S", 16, 32, 2.0, 4.0, 150),
("Xeon Gold 5418Y", 24, 48, 2.0, 3.8, 185),
("Xeon Gold 5420+", 28, 56, 2.0, 4.1, 205),
("Xeon Gold 6416H", 18, 36, 2.2, 4.2, 165),
("Xeon Gold 6426Y", 16, 32, 2.5, 4.1, 185),
("Xeon Gold 6430", 32, 64, 2.1, 3.4, 270),
("Xeon Gold 6434", 8, 16, 3.7, 4.1, 195),
("Xeon Gold 6438Y+", 32, 64, 2.0, 4.0, 205),
("Xeon Gold 6442Y", 24, 48, 2.6, 4.0, 225),
("Xeon Gold 6444Y", 16, 32, 3.6, 4.0, 270),
("Xeon Gold 6448Y", 32, 64, 2.1, 4.1, 225),
("Xeon Gold 6454S", 32, 64, 2.2, 3.4, 270),
("Xeon Gold 6458Q", 32, 64, 3.1, 4.0, 350),
("Xeon Platinum 8452Y", 36, 72, 2.0, 3.2, 300),
("Xeon Platinum 8460Y+", 40, 80, 2.0, 3.7, 300),
("Xeon Platinum 8462Y+", 32, 64, 2.8, 4.1, 300),
("Xeon Platinum 8468", 48, 96, 2.1, 3.8, 350),
("Xeon Platinum 8470", 52, 104, 2.0, 3.8, 350),
("Xeon Platinum 8480+", 56, 112, 2.0, 3.8, 350),
("Xeon Platinum 8490H", 60, 120, 1.9, 3.5, 350),
("Xeon Silver 4410T", 10, 20, 2.7, 4.0, 150),
("Xeon Gold 5411N", 24, 48, 1.9, 3.9, 165),
("Xeon Gold 5412U", 24, 48, 2.1, 3.9, 185),
("Xeon Gold 5418N", 24, 48, 1.8, 3.8, 165),
("Xeon Gold 6414U", 32, 64, 2.0, 3.4, 250),
("Xeon Gold 6418H", 24, 48, 2.1, 4.0, 185),
("Xeon Gold 6421N", 32, 64, 1.8, 3.6, 185),
("Xeon Gold 6428N", 32, 64, 1.8, 3.8, 185),
("Xeon Gold 6434H", 8, 16, 3.7, 4.1, 195),
("Xeon Gold 6438M", 32, 64, 2.2, 3.9, 205),
("Xeon Gold 6438N", 32, 64, 2.0, 3.6, 205),
("Xeon Gold 6448H", 32, 64, 2.4, 4.1, 250),
("Xeon Platinum 8444H", 16, 32, 2.9, 4.0, 270),
("Xeon Platinum 8450H", 28, 56, 2.0, 3.5, 250),
("Xeon Platinum 8454H", 32, 64, 2.1, 3.4, 270),
("Xeon Platinum 8458P", 44, 88, 2.7, 3.8, 350),
("Xeon Platinum 8460H", 40, 80, 2.2, 3.8, 330),
("Xeon Platinum 8461V", 48, 96, 2.2, 3.7, 300),
("Xeon Platinum 8468H", 48, 96, 2.1, 3.8, 330),
("Xeon Platinum 8468V", 48, 96, 2.4, 3.8, 330),
("Xeon Platinum 8470N", 52, 104, 1.7, 3.6, 300),
("Xeon Platinum 8470Q", 52, 104, 2.1, 3.8, 350),
("Xeon Platinum 8471N", 52, 104, 1.8, 3.6, 300),
)),
(INTEL, "Xeon Scalable 5. Gen (Emerald Rapids)", "LGA4677", 2023, 2, (
("Xeon Bronze 3508U", 8, 8, 2.1, 2.2, 125),
("Xeon Silver 4509Y", 8, 16, 2.6, 4.1, 125),
("Xeon Silver 4510", 12, 24, 2.4, 4.1, 150),
("Xeon Silver 4514Y", 16, 32, 2.0, 3.4, 150),
("Xeon Silver 4516Y+", 24, 48, 2.2, 3.7, 185),
("Xeon Gold 5512U", 28, 56, 2.1, 3.7, 185),
("Xeon Gold 5515+", 8, 16, 3.2, 4.1, 165),
("Xeon Gold 5520+", 28, 56, 2.2, 4.0, 205),
("Xeon Gold 6526Y", 16, 32, 2.8, 3.9, 195),
("Xeon Gold 6534", 8, 16, 3.9, 4.2, 195),
("Xeon Gold 6538Y+", 32, 64, 2.2, 4.0, 225),
("Xeon Gold 6542Y", 24, 48, 2.9, 4.1, 250),
("Xeon Gold 6544Y", 16, 32, 3.6, 4.1, 270),
("Xeon Gold 6548Y+", 32, 64, 2.5, 4.1, 250),
("Xeon Gold 6554S", 36, 72, 2.2, 4.0, 270),
("Xeon Gold 6558Q", 32, 64, 3.2, 4.1, 350),
("Xeon Platinum 8558", 48, 96, 2.1, 4.0, 330),
("Xeon Platinum 8562Y+", 32, 64, 2.8, 4.1, 300),
("Xeon Platinum 8568Y+", 48, 96, 2.3, 4.0, 350),
("Xeon Platinum 8580", 60, 120, 2.0, 4.0, 350),
("Xeon Platinum 8592+", 64, 128, 1.9, 3.9, 350),
("Xeon Silver 4510T", 12, 24, 2.0, 3.7, 115),
("Xeon Gold 6530", 32, 64, 2.1, 4.0, 270),
("Xeon Gold 6538N", 32, 64, 2.1, 4.1, 205),
("Xeon Gold 6548N", 32, 64, 2.8, 4.1, 250),
("Xeon Platinum 8558P", 48, 96, 2.7, 4.0, 350),
("Xeon Platinum 8558U", 48, 96, 2.0, 4.0, 300),
("Xeon Platinum 8570", 56, 112, 2.1, 4.0, 350),
("Xeon Platinum 8571N", 52, 104, 2.4, 4.0, 300),
("Xeon Platinum 8581V", 60, 120, 2.0, 3.9, 270),
("Xeon Platinum 8592V", 64, 128, 2.0, 3.9, 330),
("Xeon Platinum 8593Q", 64, 128, 2.2, 3.9, 385),
)),
(INTEL, "Xeon 6 E-Core (Sierra Forest)", "LGA4710", 2024, 2, (
("Xeon 6710E", 64, 64, 2.4, 3.2, 205),
("Xeon 6731E", 96, 96, 2.2, 3.1, 250),
("Xeon 6740E", 96, 96, 2.4, 3.2, 250),
("Xeon 6746E", 112, 112, 2.0, 2.7, 250),
("Xeon 6756E", 128, 128, 1.8, 2.6, 225),
("Xeon 6766E", 144, 144, 1.9, 2.7, 250),
("Xeon 6780E", 144, 144, 2.2, 3.0, 330),
)),
(INTEL, "Xeon 6900P (Granite Rapids-AP)", "LGA7529", 2024, 2, (
("Xeon 6960P", 72, 144, 2.7, 3.9, 500),
("Xeon 6972P", 96, 192, 2.4, 3.9, 500),
("Xeon 6979P", 120, 240, 2.1, 3.9, 500),
("Xeon 6980P", 128, 256, 2.0, 3.9, 500),
("Xeon 6944P", 72, 144, 1.8, 3.9, 350),
("Xeon 6952P", 96, 192, 2.1, 3.9, 400),
("Xeon 6962P", 72, 144, 2.7, 3.9, 500),
)),
(INTEL, "Xeon 6700P/6500P (Granite Rapids-SP)", "LGA4710", 2025, 8, (
("Xeon 6505P", 12, 24, 2.2, 4.1, 150),
("Xeon 6507P", 8, 16, 3.5, 4.3, 150),
("Xeon 6511P", 16, 32, 2.5, 4.3, 150),
("Xeon 6515P", 16, 32, 2.4, 3.8, 150),
("Xeon 6517P", 16, 32, 3.2, 4.2, 190),
("Xeon 6520P", 24, 48, 2.4, 4.0, 210),
("Xeon 6521P", 24, 48, 2.6, 4.1, 225),
("Xeon 6527P", 24, 48, 3.0, 4.2, 255),
("Xeon 6530P", 32, 64, 2.3, 4.1, 225),
("Xeon 6714P", 8, 16, 4.0, 4.3, 165),
("Xeon 6724P", 16, 32, 3.6, 4.3, 210),
("Xeon 6730P", 32, 64, 2.5, 3.8, 250),
("Xeon 6736P", 36, 72, 2.0, 4.1, 205),
("Xeon 6737P", 32, 64, 2.9, 4.0, 270),
("Xeon 6740P", 48, 96, 2.1, 3.8, 270),
("Xeon 6745P", 32, 64, 3.1, 4.3, 300),
("Xeon 6747P", 48, 96, 2.7, 3.9, 330),
("Xeon 6748P", 48, 96, 2.5, 4.1, 300),
("Xeon 6760P", 64, 128, 2.2, 3.8, 330),
("Xeon 6761P", 64, 128, 2.5, 3.9, 350),
("Xeon 6767P", 64, 128, 2.4, 3.9, 350),
("Xeon 6768P", 64, 128, 2.4, 3.9, 330),
("Xeon 6776P", 64, 128, 2.3, 3.6, 350),
("Xeon 6787P", 86, 172, 2.0, 3.8, 350),
("Xeon 6728P", 24, 48, 2.7, 4.1, 210),
("Xeon 6731P", 32, 64, 2.5, 4.1, 245),
("Xeon 6732P", 32, 64, 3.8, 4.3, 350),
("Xeon 6738P", 32, 64, 2.9, 4.2, 270),
("Xeon 6741P", 48, 96, 2.5, 3.8, 300),
("Xeon 6774P", 64, 128, 2.5, 3.9, 350),
("Xeon 6781P", 80, 160, 2.0, 3.8, 350),
("Xeon 6788P", 86, 172, 2.0, 3.8, 350),
)),
(INTEL, "Xeon 6300P (Raptor Lake-E)", "LGA1700", 2025, 1, (
("Xeon 6315P", 4, 4, 2.8, 4.7, 55),
("Xeon 6325P", 4, 8, 3.5, 5.2, 55),
("Xeon 6333P", 6, 12, 3.1, 5.2, 65),
("Xeon 6337P", 6, 12, 3.5, 5.3, 80),
("Xeon 6349P", 6, 12, 3.6, 5.7, 95),
("Xeon 6353P", 8, 16, 2.7, 5.4, 65),
("Xeon 6357P", 8, 16, 3.0, 5.4, 80),
("Xeon 6369P", 8, 16, 3.3, 5.7, 95),
)),
(INTEL, "Xeon 6+ (Clearwater Forest)", "LGA7529", 2026, 2, (
("Xeon 6960E+", 144, 144, 2.4, 3.2, 330),
("Xeon 6970E+", 192, 192, 2.3, 3.2, 400),
("Xeon 6980E+", 264, 264, 2.1, 3.2, 400),
("Xeon 6990E+", 288, 288, 2.2, 3.2, 450),
)),
#
# AMD Opteron
#
(AMD, "Opteron 6300 (Abu Dhabi)", "G34", 2012, 4, (
("Opteron 6308", 4, 4, 3.5, None, 115),
("Opteron 6320", 8, 8, 2.8, 3.3, 115),
("Opteron 6328", 8, 8, 3.2, 3.8, 115),
("Opteron 6344", 12, 12, 2.6, 3.2, 115),
("Opteron 6348", 12, 12, 2.8, 3.4, 115),
("Opteron 6366 HE", 16, 16, 1.8, 3.1, 85),
("Opteron 6376", 16, 16, 2.3, 3.2, 115),
("Opteron 6378", 16, 16, 2.4, 3.3, 115),
("Opteron 6380", 16, 16, 2.5, 3.4, 115),
("Opteron 6386 SE", 16, 16, 2.8, 3.5, 140),
("Opteron 6338P", 12, 12, 2.3, 2.8, 99),
("Opteron 6370P", 16, 16, 2.0, 2.5, 99),
)),
(AMD, "Opteron 4300 (Seoul)", "C32", 2012, 2, (
("Opteron 4310 EE", 4, 4, 2.2, 3.0, 35),
("Opteron 4332 HE", 6, 6, 3.0, 3.7, 65),
("Opteron 4334", 6, 6, 3.1, 3.5, 95),
("Opteron 4340", 6, 6, 3.5, 3.8, 95),
("Opteron 4376 HE", 8, 8, 2.6, 3.6, 65),
("Opteron 4386", 8, 8, 3.1, 3.8, 95),
("Opteron 4365 EE", 8, 8, 2.0, 2.8, 40),
)),
#
# AMD EPYC
#
(AMD, "EPYC 7001 (Naples)", "SP3", 2017, 2, (
("EPYC 7251", 8, 16, 2.1, 2.9, 120),
("EPYC 7261", 8, 16, 2.5, 2.9, 170),
("EPYC 7281", 16, 32, 2.1, 2.7, 170),
("EPYC 7301", 16, 32, 2.2, 2.7, 170),
("EPYC 7351", 16, 32, 2.4, 2.9, 170),
("EPYC 7351P", 16, 32, 2.4, 2.9, 170),
("EPYC 7371", 16, 32, 3.1, 3.8, 200),
("EPYC 7401", 24, 48, 2.0, 3.0, 170),
("EPYC 7401P", 24, 48, 2.0, 3.0, 170),
("EPYC 7451", 24, 48, 2.3, 3.2, 180),
("EPYC 7501", 32, 64, 2.0, 3.0, 170),
("EPYC 7551", 32, 64, 2.0, 3.0, 180),
("EPYC 7551P", 32, 64, 2.0, 3.0, 180),
("EPYC 7601", 32, 64, 2.2, 3.2, 180),
)),
(AMD, "EPYC 7002 (Rome)", "SP3", 2019, 2, (
("EPYC 7232P", 8, 16, 3.1, 3.2, 120),
("EPYC 7252", 8, 16, 3.1, 3.2, 120),
("EPYC 7262", 8, 16, 3.2, 3.4, 155),
("EPYC 7272", 12, 24, 2.9, 3.2, 120),
("EPYC 7282", 16, 32, 2.8, 3.2, 120),
("EPYC 7302", 16, 32, 3.0, 3.3, 155),
("EPYC 7302P", 16, 32, 3.0, 3.3, 155),
("EPYC 7352", 24, 48, 2.3, 3.2, 155),
("EPYC 7402", 24, 48, 2.8, 3.35, 180),
("EPYC 7402P", 24, 48, 2.8, 3.35, 180),
("EPYC 7452", 32, 64, 2.35, 3.35, 155),
("EPYC 7502", 32, 64, 2.5, 3.35, 180),
("EPYC 7502P", 32, 64, 2.5, 3.35, 180),
("EPYC 7542", 32, 64, 2.9, 3.4, 225),
("EPYC 7552", 48, 96, 2.2, 3.3, 200),
("EPYC 7642", 48, 96, 2.3, 3.3, 225),
("EPYC 7662", 64, 128, 2.0, 3.3, 225),
("EPYC 7702", 64, 128, 2.0, 3.35, 200),
("EPYC 7702P", 64, 128, 2.0, 3.35, 200),
("EPYC 7742", 64, 128, 2.25, 3.4, 225),
("EPYC 7H12", 64, 128, 2.6, 3.3, 280),
("EPYC 7532", 32, 64, 2.4, 3.3, 200),
)),
(AMD, "EPYC 7002 F (Rome, High Frequency)", "SP3", 2020, 2, (
("EPYC 7F32", 8, 16, 3.7, 3.9, 180),
("EPYC 7F52", 16, 32, 3.5, 3.9, 240),
("EPYC 7F72", 24, 48, 3.2, 3.7, 240),
)),
(AMD, "EPYC 7003 (Milan)", "SP3", 2021, 2, (
("EPYC 72F3", 8, 16, 3.7, 4.1, 180),
("EPYC 7313", 16, 32, 3.0, 3.7, 155),
("EPYC 7313P", 16, 32, 3.0, 3.7, 155),
("EPYC 7343", 16, 32, 3.2, 3.9, 190),
("EPYC 73F3", 16, 32, 3.5, 4.0, 240),
("EPYC 7413", 24, 48, 2.65, 3.6, 180),
("EPYC 7443", 24, 48, 2.85, 4.0, 200),
("EPYC 7443P", 24, 48, 2.85, 4.0, 200),
("EPYC 74F3", 24, 48, 3.2, 4.0, 240),
("EPYC 7453", 28, 56, 2.75, 3.45, 225),
("EPYC 7513", 32, 64, 2.6, 3.65, 200),
("EPYC 7543", 32, 64, 2.8, 3.7, 225),
("EPYC 7543P", 32, 64, 2.8, 3.7, 225),
("EPYC 75F3", 32, 64, 2.95, 4.0, 280),
("EPYC 7643", 48, 96, 2.3, 3.6, 225),
("EPYC 7663", 56, 112, 2.0, 3.5, 240),
("EPYC 7713", 64, 128, 2.0, 3.675, 225),
("EPYC 7713P", 64, 128, 2.0, 3.675, 225),
("EPYC 7763", 64, 128, 2.45, 3.5, 280),
("EPYC 7643P", 48, 96, 2.3, 3.6, 225),
("EPYC 7663P", 56, 112, 2.0, 3.5, 240),
)),
(AMD, "EPYC 7003X (Milan-X)", "SP3", 2022, 2, (
("EPYC 7373X", 16, 32, 3.05, 3.8, 240),
("EPYC 7473X", 24, 48, 2.8, 3.7, 240),
("EPYC 7573X", 32, 64, 2.8, 3.6, 280),
("EPYC 7773X", 64, 128, 2.2, 3.5, 280),
)),
(AMD, "EPYC 7003 (Milan, 2023)", "SP3", 2023, 2, (
("EPYC 7203", 8, 16, 2.8, 3.4, 120),
("EPYC 7303", 16, 32, 2.4, 3.4, 130),
("EPYC 7203P", 8, 16, 2.8, 3.4, 120),
("EPYC 7303P", 16, 32, 2.4, 3.4, 130),
)),
(AMD, "EPYC 9004 (Genoa)", "SP5", 2022, 2, (
("EPYC 9124", 16, 32, 3.0, 3.7, 200),
("EPYC 9174F", 16, 32, 4.1, 4.4, 320),
("EPYC 9224", 24, 48, 2.5, 3.7, 200),
("EPYC 9254", 24, 48, 2.9, 4.15, 200),
("EPYC 9274F", 24, 48, 4.05, 4.3, 320),
("EPYC 9334", 32, 64, 2.7, 3.9, 210),
("EPYC 9354", 32, 64, 3.25, 3.75, 280),
("EPYC 9354P", 32, 64, 3.25, 3.75, 280),
("EPYC 9374F", 32, 64, 3.85, 4.3, 320),
("EPYC 9454", 48, 96, 2.75, 3.8, 290),
("EPYC 9454P", 48, 96, 2.75, 3.8, 290),
("EPYC 9474F", 48, 96, 3.6, 4.1, 360),
("EPYC 9534", 64, 128, 2.45, 3.7, 280),
("EPYC 9554", 64, 128, 3.1, 3.75, 360),
("EPYC 9554P", 64, 128, 3.1, 3.75, 360),
("EPYC 9634", 84, 168, 2.25, 3.7, 290),
("EPYC 9654", 96, 192, 2.4, 3.7, 360),
("EPYC 9654P", 96, 192, 2.4, 3.7, 360),
)),
(AMD, "EPYC 9004X (Genoa-X)", "SP5", 2023, 2, (
("EPYC 9184X", 16, 32, 3.55, 4.2, 320),
("EPYC 9384X", 32, 64, 3.1, 3.9, 320),
("EPYC 9684X", 96, 192, 2.55, 3.7, 400),
)),
(AMD, "EPYC 97x4 (Bergamo)", "SP5", 2023, 2, (
("EPYC 9734", 112, 224, 2.2, 3.0, 340),
("EPYC 9754", 128, 256, 2.25, 3.1, 360),
("EPYC 9754S", 128, 128, 2.25, 3.1, 360),
)),
(AMD, "EPYC 8004 (Siena)", "SP6", 2023, 1, (
("EPYC 8024P", 8, 16, 2.4, 3.0, 90),
("EPYC 8124P", 16, 32, 2.45, 3.0, 125),
("EPYC 8224P", 24, 48, 2.55, 3.0, 160),
("EPYC 8324P", 32, 64, 2.65, 3.0, 180),
("EPYC 8434P", 48, 96, 2.5, 3.1, 200),
("EPYC 8534P", 64, 128, 2.3, 3.1, 200),
("EPYC 8024PN", 8, 16, 2.05, None, 80),
("EPYC 8124PN", 16, 32, 2.0, None, 100),
("EPYC 8224PN", 24, 48, 2.0, None, 120),
("EPYC 8324PN", 32, 64, 2.05, None, 130),
("EPYC 8434PN", 48, 96, 2.0, 3.0, 155),
("EPYC 8534PN", 64, 128, 2.0, None, 175),
)),
(AMD, "EPYC 4004 (Raphael)", "AM5", 2024, 1, (
("EPYC 4124P", 4, 8, 3.8, 5.1, 65),
("EPYC 4244P", 6, 12, 3.8, 5.1, 65),
("EPYC 4344P", 8, 16, 3.8, 5.3, 65),
("EPYC 4364P", 8, 16, 4.5, 5.4, 105),
("EPYC 4464P", 12, 24, 3.7, 5.4, 65),
("EPYC 4484PX", 12, 24, 4.4, 5.6, 120),
("EPYC 4564P", 16, 32, 4.5, 5.7, 170),
("EPYC 4584PX", 16, 32, 4.2, 5.7, 120),
)),
(AMD, "EPYC 4005 (Grado)", "AM5", 2025, 1, (
("EPYC 4245P", 6, 12, 3.9, 5.4, 65),
("EPYC 4345P", 8, 16, 3.8, 5.5, 65),
("EPYC 4465P", 12, 24, 3.4, 5.4, 65),
("EPYC 4545P", 16, 32, 3.0, 5.4, 65),
("EPYC 4565P", 16, 32, 4.3, 5.7, 170),
("EPYC 4585PX", 16, 32, 4.3, 5.7, 170),
)),
(AMD, "EPYC 9005 (Turin)", "SP5", 2024, 2, (
("EPYC 9015", 8, 16, 3.6, 4.1, 125),
("EPYC 9115", 16, 32, 2.6, 4.1, 125),
("EPYC 9135", 16, 32, 3.65, 4.3, 200),
("EPYC 9175F", 16, 32, 4.2, 5.0, 320),
("EPYC 9255", 24, 48, 3.25, 4.3, 200),
("EPYC 9275F", 24, 48, 4.1, 4.8, 320),
("EPYC 9335", 32, 64, 3.0, 4.4, 210),
("EPYC 9355", 32, 64, 3.55, 4.4, 280),
("EPYC 9355P", 32, 64, 3.55, 4.4, 280),
("EPYC 9365", 36, 72, 3.4, 4.3, 300),
("EPYC 9375F", 32, 64, 3.8, 4.8, 320),
("EPYC 9455", 48, 96, 3.15, 4.4, 300),
("EPYC 9455P", 48, 96, 3.15, 4.4, 300),
("EPYC 9475F", 48, 96, 3.65, 4.8, 400),
("EPYC 9535", 64, 128, 2.4, 4.3, 300),
("EPYC 9555", 64, 128, 3.2, 4.4, 360),
("EPYC 9555P", 64, 128, 3.2, 4.4, 360),
("EPYC 9565", 72, 144, 3.15, 4.3, 400),
("EPYC 9575F", 64, 128, 3.3, 5.0, 400),
("EPYC 9645", 96, 192, 2.3, 3.7, 320),
("EPYC 9655", 96, 192, 2.5, 4.5, 400),
("EPYC 9655P", 96, 192, 2.5, 4.5, 400),
("EPYC 9745", 128, 256, 2.4, 3.7, 400),
("EPYC 9755", 128, 256, 2.7, 4.1, 500),
("EPYC 9825", 144, 288, 2.2, 3.7, 390),
("EPYC 9845", 160, 320, 2.1, 3.7, 390),
("EPYC 9965", 192, 384, 2.25, 3.7, 500),
)),
) # fmt: skip
def max_sockets(name, family_max):
"""EPYC "P" models (e.g. 7402P, 9354P, 4484PX) are single-socket only."""
if name.startswith("EPYC") and name.endswith(("P", "PX")):
return 1
return family_max
def entries():
"""Yield one dict per CPU, ready for CPUModel(**entry)."""
for manufacturer, family, socket, year, family_max, models in FAMILIES:
for name, cores, threads, base, boost, tdp in models:
yield {
"manufacturer": manufacturer,
"family": family,
"name": name,
"cores": cores,
"threads": threads,
"base_clock_ghz": base,
"boost_clock_ghz": boost,
"tdp_watts": tdp,
"socket": socket,
"launch_year": year,
"max_sockets": max_sockets(name, family_max),
}
def sync(model, force=False):
"""Create missing catalogue CPUs; update untouched built-in ones. Returns (created, updated).
``model`` is the CPUModel class (also the historical one inside migrations).
Entries with ``builtin=False`` were added by users and are never touched; built-in
entries edited in the UI keep their values unless ``force`` is set.
"""
from decimal import Decimal
created = updated = 0
existing = {(cpu.manufacturer, cpu.name.casefold()): cpu for cpu in model.objects.all()}
for entry in entries():
values = {
**entry,
"base_clock_ghz": Decimal(str(entry["base_clock_ghz"])),
"boost_clock_ghz": Decimal(str(entry["boost_clock_ghz"])) if entry["boost_clock_ghz"] else None,
}
cpu = existing.get((entry["manufacturer"], entry["name"].casefold()))
if cpu is None:
model.objects.create(builtin=True, **values)
created += 1
elif cpu.builtin and (force or not cpu.customized):
changed = [name for name, value in values.items() if getattr(cpu, name) != value]
if changed:
for name in changed:
setattr(cpu, name, values[name])
cpu.save(update_fields=changed)
updated += 1
return created, updated
+111 -7
View File
@@ -15,7 +15,7 @@ from utilities.forms.fields import (
from utilities.forms.rendering import FieldSet
from utilities.forms.widgets import DatePicker
from . import disks
from . import disks, msa_import
from .models import (
BAY_LAYOUT_FIELDS,
Disk,
@@ -415,11 +415,13 @@ class DiskImportForm(NetBoxModelImportForm):
"tags",
)
# bay and raid_group arrive as names. The field cleaners keep the name aside and leave None behind,
# so the model instance never receives a string, even if clean() stops early on another error.
def clean_raid_group(self):
return self.cleaned_data.get("raid_group") or ""
self._raid_group_name = (self.cleaned_data.get("raid_group") or "").strip()
def clean_bay(self):
return self.cleaned_data.get("bay") or ""
self._bay_name = (self.cleaned_data.get("bay") or "").strip()
def clean(self):
super().clean()
@@ -430,7 +432,7 @@ class DiskImportForm(NetBoxModelImportForm):
if (capacity := cleaned_data.get("capacity")) is not None:
self.instance.capacity_gb = capacity
device = cleaned_data.get("device")
bay_name = cleaned_data.get("bay")
bay_name = getattr(self, "_bay_name", "")
cleaned_data["bay"] = None
if device:
bays = list(DiskBayLayout.objects.filter(device=device))
@@ -442,15 +444,14 @@ class DiskImportForm(NetBoxModelImportForm):
self.add_error("bay", f"Das Gerät {device} hat keinen Bereich „{bay_name}“.")
elif len(bays) == 1:
cleaned_data["bay"] = bays[0]
group_name = cleaned_data.get("raid_group")
group_name = getattr(self, "_raid_group_name", "")
cleaned_data["raid_group"] = None
if group_name and device:
group = RAIDGroup.objects.filter(device=device, name=group_name).first()
if group is None:
self.add_error("raid_group", f"Das Gerät {device} hat keine RAID-Gruppe „{group_name}“.")
else:
cleaned_data["raid_group"] = group
else:
cleaned_data["raid_group"] = None
return cleaned_data
@@ -487,3 +488,106 @@ class DiskBulkEditForm(NetBoxModelBulkEditForm):
"description",
"comments",
)
class MSAUploadForm(forms.Form):
"""Step 1 of the HPE MSA import: the CSV export from Pools → Disks."""
export_file = forms.FileField(
label="CSV-Datei",
required=False,
widget=forms.ClearableFileInput(attrs={"class": "form-control", "accept": ".csv,text/csv"}),
)
export_text = forms.CharField(
label="… oder Inhalt einfügen",
required=False,
widget=forms.Textarea(attrs={"class": "form-control font-monospace", "rows": 8}),
)
def clean(self):
cleaned_data = super().clean()
upload = cleaned_data.get("export_file")
data = upload.read() if upload else cleaned_data.get("export_text", "")
if not data or not str(data).strip():
raise ValidationError("Bitte eine CSV-Datei hochladen oder den Inhalt einfügen.")
export = msa_import.parse_export(data)
if export.is_empty:
raise ValidationError(export.errors)
cleaned_data["export"] = export
cleaned_data["raw"] = data if isinstance(data, str) else msa_import.decode(data)
return cleaned_data
class MSAAssignForm(forms.Form):
"""Step 2: which NetBox device is which MSA enclosure (shelf)."""
create_raid_groups = forms.BooleanField(
label="RAID-Gruppen aus „Disk Group“ anlegen",
required=False,
initial=True,
widget=forms.CheckboxInput(attrs={"class": "form-check-input"}),
help_text="Fehlende Gruppen werden mit RAID-Level „Sonstiges“ angelegt; das Level bitte danach prüfen.",
)
replace_existing = forms.BooleanField(
label="Belegte Steckplätze ersetzen",
required=False,
widget=forms.CheckboxInput(attrs={"class": "form-check-input"}),
help_text="Steckt in NetBox ein anderer Datenträger im Steckplatz, wird er als ausgebaut markiert.",
)
estimate_install_date = forms.BooleanField(
label="Einbaudatum aus Betriebsstunden schätzen",
required=False,
initial=True,
widget=forms.CheckboxInput(attrs={"class": "form-check-input"}),
help_text="Nur für neue Datenträger; damit greift die Alterswarnung.",
)
def __init__(self, *args, enclosures=(), **kwargs):
super().__init__(*args, **kwargs)
self.enclosures = list(enclosures)
for enclosure in self.enclosures:
self.fields[f"device_{enclosure}"] = DynamicModelChoiceField(
label=f"Shelf {enclosure}",
queryset=Device.objects.all(),
required=False,
selector=True,
)
def device_fields(self):
return [(enclosure, self[f"device_{enclosure}"]) for enclosure in self.enclosures]
def option_fields(self):
return [self[name] for name in ("create_raid_groups", "replace_existing", "estimate_install_date")]
def clean(self):
cleaned_data = super().clean()
assigned = {
enclosure: cleaned_data.get(f"device_{enclosure}")
for enclosure in self.enclosures
if cleaned_data.get(f"device_{enclosure}")
}
if not assigned:
raise ValidationError("Bitte mindestens einem Shelf ein Gerät zuweisen.")
seen = {}
for enclosure, device in assigned.items():
if device.pk in seen:
self.add_error(f"device_{enclosure}", f"{device} ist bereits Shelf {seen[device.pk]} zugewiesen.")
seen[device.pk] = enclosure
cleaned_data["assigned"] = assigned
return cleaned_data
class MSAGroupAssignForm(forms.Form):
"""Disk group export: which devices get the RAID levels of the listed disk groups."""
devices = DynamicModelMultipleChoiceField(
label="Geräte",
queryset=Device.objects.all(),
help_text="Alle Shelfs der MSA, deren Datenträger zu diesen Disk Groups gehören.",
)
create_missing = forms.BooleanField(
label="Fehlende RAID-Gruppen anlegen",
required=False,
widget=forms.CheckboxInput(attrs={"class": "form-check-input"}),
help_text="Sonst werden nur vorhandene Gruppen mit gleichem Namen aktualisiert.",
)
+409 -1
View File
@@ -1,3 +1,5 @@
import base64
from datetime import timedelta
from itertools import groupby
from urllib.parse import urlencode
@@ -9,12 +11,13 @@ from django.db import transaction
from django.http import JsonResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.utils import timezone
from django.views import View
from netbox.plugins import get_plugin_config
from netbox.views import generic
from utilities.views import ContentTypePermissionRequiredMixin, ViewTab, register_model_view
from . import disk_filtersets, disk_forms, disk_tables, disks
from . import disk_filtersets, disk_forms, disk_tables, disks, msa_import
from .models import DEFAULT_BAY_NAME, Disk, DiskBayLayout, DiskBayTemplate, RAIDGroup
BAY_NAME_SUGGESTIONS = ("Front", "Rückseite", "Intern", "BOSS-Karte (M.2)", "PCIe", "M.2")
@@ -471,6 +474,21 @@ class DiskBulkImportView(generic.BulkImportView):
queryset = Disk.objects.all()
model_form = disk_forms.DiskImportForm
def post(self, request):
# An HPE MSA export pasted or uploaded here goes straight to the MSA wizard.
upload = request.FILES.get("upload_file")
if upload is not None:
raw = msa_import.decode(upload.read())
upload.seek(0)
else:
raw = request.POST.get("data", "")
if msa_import.looks_like_export(raw):
export = msa_import.parse_export(raw)
if not export.is_empty:
messages.info(request, "Die Datei ist ein HPE-MSA-Export und wird mit dem MSA-Import eingelesen.")
return MSADiskImportView().start(request, raw, export)
return super().post(request)
@register_model_view(Disk, "bulk_edit", path="edit", detail=False)
class DiskBulkEditView(generic.BulkEditView):
@@ -572,3 +590,393 @@ class DiskBayTemplateBulkDeleteView(generic.BulkDeleteView):
queryset = DiskBayTemplate.objects.all()
filterset = disk_filtersets.DiskBayTemplateFilterSet
table = disk_tables.DiskBayTemplateTable
#
# HPE MSA import
#
MSA_GROUP_DESCRIPTION = "Aus HPE MSA importiert"
IMPORTING_ACTIONS = (msa_import.ACTION_NEW, msa_import.ACTION_UPDATE, msa_import.ACTION_REPLACE)
class MSADiskImportView(ContentTypePermissionRequiredMixin, View):
"""Import the disk CSV export of an HPE MSA: map each enclosure (shelf) to a device, preview, create.
The wizard keeps no server-side state; the export travels base64-encoded in a hidden field.
"""
template_name = "netbox_utilities/disk_msa_import.html"
def get_required_permission(self):
return "netbox_utilities.add_disk"
def get(self, request):
return self._render(request, "upload", upload_form=disk_forms.MSAUploadForm())
def post(self, request):
step = request.POST.get("step", "upload")
if step == "upload" or not request.POST.get("export_data"):
upload_form = disk_forms.MSAUploadForm(request.POST, request.FILES)
if not upload_form.is_valid():
return self._render(request, "upload", upload_form=upload_form)
return self.start(request, upload_form.cleaned_data["raw"], upload_form.cleaned_data["export"])
try:
raw = base64.b64decode(request.POST["export_data"]).decode("utf-8")
except (ValueError, UnicodeDecodeError):
messages.error(request, "Die Importdaten waren beschädigt. Bitte die Datei erneut hochladen.")
return redirect("plugins:netbox_utilities:disk_msa_import")
export = msa_import.parse_export(raw)
if export.kind == msa_import.KIND_GROUPS:
return self._post_groups(request, raw, export)
assign_form = self._assign_form(request, export, data=request.POST)
if step == "back" or not assign_form.is_valid():
return self._render_assign(request, raw, export, assign_form)
bound = step == "plan"
plans = [
self._plan_enclosure(request, enclosure, device, export.enclosures[enclosure], assign_form, bound)
for enclosure, device in assign_form.cleaned_data["assigned"].items()
]
if bound and "do_import" in request.POST:
error = self._import_blocker(request, plans)
if error:
messages.error(request, error)
else:
try:
summary = self._execute(request, plans, assign_form.cleaned_data)
except ValidationError as exc:
for message in exc.messages:
messages.error(request, message)
else:
messages.success(request, summary)
devices = [plan["device"] for plan in plans]
if len(devices) == 1:
return redirect("dcim:device_disks", pk=devices[0].pk)
return redirect(
f"{reverse('plugins:netbox_utilities:disk_by_device')}?"
+ urlencode([("device_id", device.pk) for device in devices])
)
return self._render(
request,
"plan",
export_data=self._encode(raw),
assign_form=assign_form,
plans=plans,
parse_errors=export.errors,
)
def start(self, request, raw, export):
"""First page after reading a file: shelf assignment for disks, device choice for disk groups."""
if export.kind == msa_import.KIND_GROUPS:
return self._render_groups(request, raw, export, self._group_form(request, export))
return self._render_assign(request, raw, export, self._assign_form(request, export))
@staticmethod
def _encode(raw):
return base64.b64encode(raw.encode("utf-8")).decode("ascii")
@staticmethod
def _assign_form(request, export, data=None):
form = disk_forms.MSAAssignForm(data, enclosures=list(export.enclosures))
devices = Device.objects.restrict(request.user, "view")
for enclosure in form.enclosures:
form.fields[f"device_{enclosure}"].queryset = devices
return form
def _render_assign(self, request, raw, export, assign_form):
enclosures = [
{
"id": enclosure,
"field": assign_form[f"device_{enclosure}"],
"count": len(items),
"first": items[0].slot,
"last": items[-1].slot,
"models": sorted({item.model for item in items if item.model}),
}
for enclosure, items in export.enclosures.items()
]
return self._render(
request,
"assign",
export_data=self._encode(raw),
assign_form=assign_form,
enclosures=enclosures,
parse_errors=export.errors,
)
@staticmethod
def _bay_defaults(device, items):
"""Initial values for a new slot area: the device type template, else a guess from the export."""
templates = DiskBayTemplate.objects.filter(device_type_id=device.device_type_id).order_by("weight", "name")
template = templates.first()
if template is not None:
values = template.layout_values()
else:
first = 0 if min(item.slot for item in items) == 0 else 1
count = msa_import.suggest_slot_count(max(item.slot for item in items) - first + 1)
values = {
"name": DEFAULT_BAY_NAME,
"weight": 100,
"slot_count": count,
"rows": 1,
"first_slot": first,
"numbering": disks.NUMBERING_HORIZONTAL,
"form_factor": msa_import.suggest_form_factor(count),
}
values["save_as_template"] = template is None
return values
def _plan_enclosure(self, request, enclosure, device, items, assign_form, bound):
bays = list(DiskBayLayout.objects.filter(device=device).order_by("weight", "name", "pk"))
bay = bay_form = None
if bays:
requested = request.POST.get(f"bay_{enclosure}") if bound else None
bay = next((item for item in bays if str(item.pk) == requested), None)
if bay is None:
highest = max(item.slot for item in items)
bay = next((item for item in bays if item.first_slot <= highest <= item.last_slot), bays[0])
first_slot, last_slot = bay.first_slot, bay.last_slot
else:
# The device has no slots yet: ask for the area right here, pre-filled from the export.
defaults = self._bay_defaults(device, items)
bay_form = disk_forms.DiskBayLayoutForm(
request.POST if bound else None,
prefix=f"bay{enclosure}",
instance=DiskBayLayout(device=device),
initial=defaults,
)
bay_form.fields["slot_count"].widget.attrs.pop("autofocus", None)
if bound and bay_form.is_valid():
first_slot = bay_form.cleaned_data["first_slot"]
slot_count = bay_form.cleaned_data["slot_count"]
else:
first_slot, slot_count = defaults["first_slot"], defaults["slot_count"]
last_slot = first_slot + slot_count - 1
# Disks in the chosen area, or without area while the device has none yet.
installed = Disk.objects.filter(device=device, status__in=disks.SLOT_OCCUPYING_STATUSES)
installed = installed.filter(bay=bay) if bay is not None else installed.filter(bay__isnull=True)
occupants = {disk.slot: disk for disk in installed}
holders = {}
serials = [item.serial for item in items if item.serial]
for disk in Disk.objects.filter(serial__in=serials, status__in=disks.SLOT_OCCUPYING_STATUSES).select_related(
"device", "bay"
):
holders.setdefault(disk.serial.casefold(), []).append(disk)
replace = assign_form.cleaned_data["replace_existing"]
rows = []
for item in items:
occupant = occupants.get(item.slot)
elsewhere = next(
(
f"{disk.device} – {disk.slot_label}"
for disk in holders.get(item.serial.casefold(), [])
if occupant is None or disk.pk != occupant.pk
),
None,
)
action, reason = msa_import.classify(
item,
first_slot,
last_slot,
occupant_serial=None if occupant is None else occupant.serial,
serial_elsewhere=elsewhere,
replace=replace,
)
label, color = msa_import.ACTION_LABELS[action]
rows.append(
{
"item": item,
"occupant": occupant,
"action": action,
"label": label,
"color": color,
"reason": reason,
"capacity": disks.format_capacity(item.capacity_gb),
}
)
return {
"enclosure": enclosure,
"device": device,
"bays": bays,
"bay": bay,
"bay_form": bay_form,
"rows": rows,
"importing": sum(1 for row in rows if row["action"] in IMPORTING_ACTIONS),
"groups": sorted({item.disk_group for item in items if item.disk_group}),
}
@staticmethod
def _import_blocker(request, plans):
if any(plan["bay_form"] is not None and not plan["bay_form"].is_valid() for plan in plans):
return "Bitte die Angaben zu den neuen Steckplatz-Bereichen korrigieren."
actions = [row["action"] for plan in plans for row in plan["rows"]]
if not any(action in IMPORTING_ACTIONS for action in actions):
return "Es gibt nichts zu importieren."
changes = any(action in (msa_import.ACTION_UPDATE, msa_import.ACTION_REPLACE) for action in actions)
if changes and not request.user.has_perm("netbox_utilities.change_disk"):
return "Zum Aktualisieren oder Ersetzen vorhandener Datenträger fehlt die Berechtigung."
return None
@staticmethod
def _execute(request, plans, options):
today = timezone.localdate()
may_add_groups = request.user.has_perm("netbox_utilities.add_raidgroup")
totals = dict.fromkeys((*IMPORTING_ACTIONS, "bays", "groups"), 0)
with transaction.atomic():
for plan in plans:
device, bay, bay_form = plan["device"], plan["bay"], plan["bay_form"]
if bay_form is not None:
bay = bay_form.save()
totals["bays"] += 1
# Disks recorded before the device had any area belong to its first one.
for disk in Disk.objects.filter(device=device, bay__isnull=True):
disk.snapshot()
disk.bay = bay
disk.save()
if bay_form.cleaned_data.get("save_as_template"):
values = bay.layout_values()
DiskBayTemplate.objects.update_or_create(
device_type_id=device.device_type_id, name=values.pop("name"), defaults=values
)
groups = {group.name.casefold(): group for group in RAIDGroup.objects.filter(device=device)}
if options["create_raid_groups"] and may_add_groups:
for name in plan["groups"]:
if name.casefold() not in groups:
group = RAIDGroup(
device=device, name=name, level="other", description=MSA_GROUP_DESCRIPTION
)
group.full_clean()
group.save()
groups[name.casefold()] = group
totals["groups"] += 1
for row in plan["rows"]:
item, action = row["item"], row["action"]
if action not in IMPORTING_ACTIONS:
continue
values = {
"status": item.status,
"disk_type": item.disk_type,
"interface": item.interface,
"manufacturer": item.manufacturer,
"model": item.model,
"capacity_gb": item.capacity_gb,
"firmware": item.firmware,
"raid_group": groups.get(item.disk_group.casefold()) if item.disk_group else None,
}
if action == msa_import.ACTION_UPDATE:
disk = Disk.objects.get(pk=row["occupant"].pk)
disk.snapshot()
disk.bay = bay
for name, value in values.items():
if value not in (None, "") or name == "raid_group":
setattr(disk, name, value)
else:
if action == msa_import.ACTION_REPLACE:
old = Disk.objects.get(pk=row["occupant"].pk)
old.snapshot()
old.status = disks.STATUS_REPLACED
old.save()
disk = Disk(device=device, bay=bay, slot=item.slot, serial=item.serial, **values)
disk.form_factor = bay.form_factor
if options["estimate_install_date"] and item.power_on_hours:
disk.install_date = today - timedelta(hours=item.power_on_hours)
else:
disk.install_date = today
disk.full_clean()
disk.save()
totals[action] += 1
parts = [f"{totals[msa_import.ACTION_NEW]} neu", f"{totals[msa_import.ACTION_UPDATE]} aktualisiert"]
if totals[msa_import.ACTION_REPLACE]:
parts.append(f"{totals[msa_import.ACTION_REPLACE]} ersetzt")
text = "MSA-Import abgeschlossen: " + ", ".join(parts) + "."
if totals["bays"]:
text += f" {totals['bays']} Steckplatz-Bereich(e) angelegt."
if totals["groups"]:
text += f" {totals['groups']} RAID-Gruppe(n) angelegt – bitte das RAID-Level prüfen."
return text
#
# Disk group export
#
def _group_form(self, request, export, data=None):
form = disk_forms.MSAGroupAssignForm(data)
devices = Device.objects.restrict(request.user, "view")
form.fields["devices"].queryset = devices
if data is None:
# Pre-select the devices which already have groups of these names, e.g. from the disk import.
names = [group.name for group in export.groups]
form.initial["devices"] = list(
devices.filter(netbox_utilities_raid_groups__name__in=names).distinct().values_list("pk", flat=True)
)
return form
def _render_groups(self, request, raw, export, group_form):
names = [group.name for group in export.groups]
existing = {}
for group in RAIDGroup.objects.filter(name__in=names).select_related("device"):
existing.setdefault(group.name.casefold(), []).append(group)
rows = [
{
"group": group,
"level_label": disks.RAID_LEVELS[group.level],
"existing": existing.get(group.name.casefold(), []),
}
for group in export.groups
]
return self._render(
request,
"groups",
export_data=self._encode(raw),
group_form=group_form,
rows=rows,
parse_errors=export.errors,
)
def _post_groups(self, request, raw, export):
group_form = self._group_form(request, export, data=request.POST)
if not group_form.is_valid():
return self._render_groups(request, raw, export, group_form)
create = group_form.cleaned_data["create_missing"] and request.user.has_perm("netbox_utilities.add_raidgroup")
if not request.user.has_perm("netbox_utilities.change_raidgroup"):
messages.error(request, "Zum Aktualisieren von RAID-Gruppen fehlt die Berechtigung.")
return self._render_groups(request, raw, export, group_form)
updated = created = 0
devices = list(group_form.cleaned_data["devices"])
with transaction.atomic():
for device in devices:
for item in export.groups:
group = RAIDGroup.objects.filter(device=device, name__iexact=item.name).first()
if group is None:
if not create:
continue
group = RAIDGroup(device=device, name=item.name)
created += 1
else:
group.snapshot()
updated += 1
group.level = item.level
if not group.description or group.description == MSA_GROUP_DESCRIPTION:
group.description = item.description or MSA_GROUP_DESCRIPTION
group.full_clean()
group.save()
messages.success(request, f"Disk Groups übernommen: {updated} RAID-Gruppe(n) aktualisiert, {created} angelegt.")
if len(devices) == 1:
return redirect("dcim:device_disks", pk=devices[0].pk)
return redirect(
f"{reverse('plugins:netbox_utilities:raidgroup_list')}?"
+ urlencode([("device_id", device.pk) for device in devices])
)
def _render(self, request, step, **context):
return render(request, self.template_name, {"step": step, **context})
+54 -1
View File
@@ -4,7 +4,7 @@ import strawberry
import strawberry_django
from netbox.graphql.types import NetBoxObjectType
from .models import Disk, DiskBayLayout, DiskBayTemplate, RAIDGroup
from .models import CPUModel, DeviceHardware, Disk, DiskBayLayout, DiskBayTemplate, RAIDGroup
if TYPE_CHECKING:
from dcim.graphql.types import DeviceType, DeviceTypeType
@@ -70,6 +70,55 @@ class NetBoxUtilitiesDiskBayTemplateType(NetBoxObjectType):
device_type: Annotated["DeviceTypeType", strawberry.lazy("dcim.graphql.types")]
@strawberry_django.type(
CPUModel,
fields=[
"id",
"manufacturer",
"family",
"name",
"cores",
"threads",
"base_clock_ghz",
"boost_clock_ghz",
"tdp_watts",
"socket",
"launch_year",
"max_sockets",
"builtin",
"description",
],
)
class NetBoxUtilitiesCPUModelType(NetBoxObjectType):
pass
@strawberry_django.type(
DeviceHardware,
fields=[
"id",
"cpu_count",
"memory_gb",
"memory_type",
"memory_modules",
"memory_module_gb",
"memory_speed_mts",
"description",
],
)
class NetBoxUtilitiesDeviceHardwareType(NetBoxObjectType):
device: Annotated["DeviceType", strawberry.lazy("dcim.graphql.types")]
cpu: Annotated["NetBoxUtilitiesCPUModelType", strawberry.lazy("netbox_utilities.graphql")] | None
@strawberry_django.field
def total_cores(self) -> int | None:
return self.total_cores
@strawberry_django.field
def total_threads(self) -> int | None:
return self.total_threads
@strawberry.type(name="Query")
class NetBoxUtilitiesDiskQuery:
netbox_utilities_disk: NetBoxUtilitiesDiskType = strawberry_django.field()
@@ -80,6 +129,10 @@ class NetBoxUtilitiesDiskQuery:
netbox_utilities_disk_bay_layout_list: list[NetBoxUtilitiesDiskBayLayoutType] = strawberry_django.field()
netbox_utilities_disk_bay_template: NetBoxUtilitiesDiskBayTemplateType = strawberry_django.field()
netbox_utilities_disk_bay_template_list: list[NetBoxUtilitiesDiskBayTemplateType] = strawberry_django.field()
netbox_utilities_cpu_model: NetBoxUtilitiesCPUModelType = strawberry_django.field()
netbox_utilities_cpu_model_list: list[NetBoxUtilitiesCPUModelType] = strawberry_django.field()
netbox_utilities_device_hardware: NetBoxUtilitiesDeviceHardwareType = strawberry_django.field()
netbox_utilities_device_hardware_list: list[NetBoxUtilitiesDeviceHardwareType] = strawberry_django.field()
schema = [NetBoxUtilitiesDiskQuery]
+254
View File
@@ -0,0 +1,254 @@
"""Pure helpers for "CPU & RAM": capacity of hosts and clusters versus the virtual machines on them."""
from dataclasses import dataclass, field
from decimal import Decimal
DEFAULT_HARDWARE_DEVICE_ROLES = ("Server",)
# vCPUs per physical core above which the cluster is shown as overcommitted.
DEFAULT_VCPU_RATIO_WARNING = 4
# VM states that do not use host resources.
INACTIVE_VM_STATUSES = ("offline", "decommissioning")
MEMORY_TYPES = {
"ddr3": "DDR3",
"ddr4": "DDR4",
"ddr5": "DDR5",
"other": "Sonstiges",
}
def configured_roles(roles=None):
if roles is None:
try:
from netbox.plugins import get_plugin_config
roles = get_plugin_config("netbox_utilities", "hardware_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_HARDWARE_DEVICE_ROLES)}
def supports_hardware(device, roles=None):
"""Servers by role, and every device that is a host of a virtualization cluster."""
if getattr(device, "cluster_id", None):
return True
role = getattr(device, "role", None)
return bool(role and str(getattr(role, "name", "")).casefold() in configured_roles(roles))
def vcpu_ratio_warning():
try:
from netbox.plugins import get_plugin_config
return get_plugin_config("netbox_utilities", "hardware_vcpu_ratio_warning")
except Exception: # noqa: BLE001
return DEFAULT_VCPU_RATIO_WARNING
def format_memory(gigabytes):
"""RAM as vendors label it: 768 GB, 1,5 TB."""
if gigabytes in (None, ""):
return "—"
gigabytes = Decimal(str(gigabytes))
if gigabytes >= 1024:
text = f"{gigabytes / 1024:.2f}".rstrip("0").rstrip(".")
return f"{text} TB".replace(".", ",")
text = f"{gigabytes:.1f}".rstrip("0").rstrip(".")
return f"{text} GB".replace(".", ",")
def format_clock(ghz):
if ghz in (None, ""):
return "—"
text = f"{Decimal(str(ghz)):.2f}".rstrip("0").rstrip(".")
return f"{text} GHz".replace(".", ",")
def format_ratio(value):
if value is None:
return "—"
return f"{value:.1f}".replace(".", ",") + " : 1"
def percent(part, whole):
if not whole:
return None
return round(float(part) / float(whole) * 100)
@dataclass
class Host:
"""One physical host; cores/threads/memory are None when no hardware is recorded.
vcpus/vm_memory_gb come from VMs placed on this host, shared_* is its share of the
cluster VMs without a fixed host (see build_capacity).
"""
name: str
cores: int | None = None
threads: int | None = None
memory_gb: float | None = None
key: object = None
vcpus: float = 0
vm_memory_gb: float = 0
vm_count: int = 0
shared_vcpus: float = 0
shared_memory_gb: float = 0
def __post_init__(self):
if self.key is None:
self.key = self.name
@property
def complete(self):
return bool(self.cores and self.memory_gb)
@property
def total_vcpus(self):
return self.vcpus + self.shared_vcpus
@property
def total_vm_memory_gb(self):
return self.vm_memory_gb + self.shared_memory_gb
@dataclass
class Capacity:
hosts: list = field(default_factory=list)
vm_count: int = 0
vcpus: float = 0
vm_memory_gb: float = 0
unplaced_vm_count: int = 0
# True for one host of a cluster: vcpus/vm_memory_gb include its share of the unplaced VMs.
host_share: bool = False
# Some VM is pinned to a host, so VMs without a host are not spread automatically.
manual_placement: bool = False
# VMs without a host were spread over the hosts.
distributed: bool = False
@property
def known_hosts(self):
return [host for host in self.hosts if host.complete]
@property
def missing_hosts(self):
return [host for host in self.hosts if not host.complete]
@property
def cores(self):
return sum(host.cores or 0 for host in self.hosts)
@property
def threads(self):
return sum(host.threads or 0 for host in self.hosts)
@property
def memory_gb(self):
return sum(host.memory_gb or 0 for host in self.hosts)
@property
def vcpu_per_core(self):
return self.vcpus / self.cores if self.cores else None
@property
def vcpu_per_thread(self):
return self.vcpus / self.threads if self.threads else None
@property
def memory_percent(self):
return percent(self.vm_memory_gb, self.memory_gb)
@property
def failover_memory_gb(self):
"""RAM left if the largest host fails (N+1); None with fewer than two known hosts."""
known = self.known_hosts
if len(known) < 2:
return None
return self.memory_gb - max(host.memory_gb for host in known)
@property
def failover_ok(self):
reserve = self.failover_memory_gb
return None if reserve is None else self.vm_memory_gb <= reserve
def warnings(self, ratio_warning=DEFAULT_VCPU_RATIO_WARNING):
"""(level, text) tuples for the capacity panel."""
result = []
if self.missing_hosts:
names = ", ".join(host.name for host in self.missing_hosts)
result.append(("warning", f"CPU/RAM fehlt bei: {names}"))
if self.memory_gb and self.vm_memory_gb > self.memory_gb:
result.append(("danger", "Die VMs haben mehr RAM zugewiesen, als die Hosts haben."))
elif self.failover_ok is False:
result.append(("warning", "Fällt der größte Host aus, reicht der RAM nicht für alle VMs (N+1)."))
ratio = self.vcpu_per_core
if ratio_warning and ratio is not None and ratio > ratio_warning:
result.append(("warning", f"Mehr als {ratio_warning} vCPUs pro physischem Kern."))
return result
def _weights(hosts, attribute):
"""Share per host proportional to its size; equal shares if no host has the value recorded."""
sizes = [getattr(host, attribute) or 0 for host in hosts]
total = sum(sizes)
if not total:
return [1 / len(hosts)] * len(hosts)
return [size / total for size in sizes]
def build_capacity(hosts, vms):
"""Aggregate hosts and VMs.
hosts: iterable of Host (memory in GB).
vms: iterable of (host key or None, vcpus, memory in MB, status).
VMs without a fixed host (only a cluster) are spread over the hosts in proportion to
their size: vCPUs by threads, memory by RAM. As soon as any VM of the cluster (in any
status) is pinned to one of its hosts, the placement is managed by hand and nothing is
spread; the unplaced VMs then only count towards the cluster totals.
"""
capacity = Capacity(hosts=list(hosts))
by_key = {host.key: host for host in capacity.hosts}
unplaced_vcpus = unplaced_memory_gb = 0
for host_key, vcpus, memory_mb, status in vms:
if host_key in by_key:
capacity.manual_placement = True
if status in INACTIVE_VM_STATUSES:
continue
vcpus = float(vcpus or 0)
memory_gb = (memory_mb or 0) / 1024
capacity.vm_count += 1
capacity.vcpus += vcpus
capacity.vm_memory_gb += memory_gb
host = by_key.get(host_key)
if host is None:
capacity.unplaced_vm_count += 1
unplaced_vcpus += vcpus
unplaced_memory_gb += memory_gb
else:
host.vm_count += 1
host.vcpus += vcpus
host.vm_memory_gb += memory_gb
if capacity.hosts and capacity.unplaced_vm_count and not capacity.manual_placement:
capacity.distributed = True
for host, weight in zip(capacity.hosts, _weights(capacity.hosts, "threads"), strict=True):
host.shared_vcpus = unplaced_vcpus * weight
for host, weight in zip(capacity.hosts, _weights(capacity.hosts, "memory_gb"), strict=True):
host.shared_memory_gb = unplaced_memory_gb * weight
return capacity
def host_capacity(cluster_capacity, host):
"""A Capacity for one host of a cluster, including its share of the VMs without a fixed host."""
return Capacity(
hosts=[host],
vm_count=host.vm_count,
vcpus=host.total_vcpus,
vm_memory_gb=host.total_vm_memory_gb,
unplaced_vm_count=cluster_capacity.unplaced_vm_count,
host_share=True,
manual_placement=cluster_capacity.manual_placement,
distributed=cluster_capacity.distributed,
)
+76
View File
@@ -0,0 +1,76 @@
import django_filters
from dcim.models import Device
from django.db.models import Q
from netbox.filtersets import NetBoxModelFilterSet
from tenancy.models import Tenant
from virtualization.models import Cluster
from .models import CPUManufacturerChoices, CPUModel, DeviceHardware, MemoryTypeChoices
class CPUModelFilterSet(NetBoxModelFilterSet):
manufacturer = django_filters.MultipleChoiceFilter(choices=CPUManufacturerChoices)
family = django_filters.CharFilter(lookup_expr="icontains")
socket = django_filters.CharFilter(lookup_expr="iexact")
cores = django_filters.NumberFilter()
cores__gte = django_filters.NumberFilter(field_name="cores", lookup_expr="gte", label="Kerne ab")
cores__lte = django_filters.NumberFilter(field_name="cores", lookup_expr="lte", label="Kerne bis")
launch_year = django_filters.NumberFilter()
launch_year__gte = django_filters.NumberFilter(field_name="launch_year", lookup_expr="gte", label="Ab Jahr")
in_use = django_filters.BooleanFilter(method="filter_in_use", label="In Verwendung")
class Meta:
model = CPUModel
fields = ("id", "name", "max_sockets", "builtin")
def search(self, queryset, name, value):
value = value.strip()
if not value:
return queryset
query = Q()
# "Gold 6338", "epyc 7543" or "intel 6338": every word must match somewhere.
for word in value.split():
query &= (
Q(name__icontains=word)
| Q(family__icontains=word)
| Q(manufacturer__iexact=word)
| Q(socket__iexact=word)
)
return queryset.filter(query)
def filter_in_use(self, queryset, name, value):
if value is None:
return queryset
return queryset.filter(devices__isnull=not value).distinct()
class DeviceHardwareFilterSet(NetBoxModelFilterSet):
device_id = django_filters.ModelMultipleChoiceFilter(queryset=Device.objects.all(), label="Gerät (ID)")
device = django_filters.ModelMultipleChoiceFilter(
field_name="device__name", queryset=Device.objects.all(), to_field_name="name", label="Gerät (Name)"
)
cpu_id = django_filters.ModelMultipleChoiceFilter(queryset=CPUModel.objects.all(), label="CPU-Modell (ID)")
cluster_id = django_filters.ModelMultipleChoiceFilter(
field_name="device__cluster", queryset=Cluster.objects.all(), label="Cluster (ID)"
)
manufacturer = django_filters.MultipleChoiceFilter(field_name="cpu__manufacturer", choices=CPUManufacturerChoices)
memory_type = django_filters.MultipleChoiceFilter(choices=MemoryTypeChoices)
memory_gb__gte = django_filters.NumberFilter(field_name="memory_gb", lookup_expr="gte", label="RAM ab (GB)")
# Read by the global tenant filter middleware, which may pass several tenants of a group.
tenant_id = django_filters.ModelMultipleChoiceFilter(
field_name="device__tenant", queryset=Tenant.objects.all(), label="Mandant (ID)"
)
class Meta:
model = DeviceHardware
fields = ("id", "cpu_count", "memory_gb")
def search(self, queryset, name, value):
if not value.strip():
return queryset
return queryset.filter(
Q(device__name__icontains=value)
| Q(cpu__name__icontains=value)
| Q(cpu__family__icontains=value)
| Q(description__icontains=value)
)
+172
View File
@@ -0,0 +1,172 @@
from dcim.models import Device
from django import forms
from netbox.forms import NetBoxModelFilterSetForm, NetBoxModelForm, NetBoxModelImportForm
from utilities.forms.fields import (
CommentField,
CSVChoiceField,
CSVModelChoiceField,
DynamicModelChoiceField,
DynamicModelMultipleChoiceField,
TagFilterField,
)
from utilities.forms.rendering import FieldSet
from virtualization.models import Cluster
from .models import CPUManufacturerChoices, CPUModel, DeviceHardware, MemoryTypeChoices
class CPUModelForm(NetBoxModelForm):
fieldsets = (
FieldSet("manufacturer", "family", "name", "socket", "launch_year", name="CPU"),
FieldSet("cores", "threads", "base_clock_ghz", "boost_clock_ghz", "tdp_watts", "max_sockets", name="Leistung"),
FieldSet("description", "tags", name="Sonstiges"),
)
class Meta:
model = CPUModel
fields = (
"manufacturer",
"family",
"name",
"socket",
"launch_year",
"cores",
"threads",
"base_clock_ghz",
"boost_clock_ghz",
"tdp_watts",
"max_sockets",
"description",
"tags",
)
def save(self, *args, **kwargs):
# Edited catalogue entries keep their values when the catalogue is refreshed.
if self.instance.pk and self.instance.builtin and self.has_changed():
self.instance.customized = True
return super().save(*args, **kwargs)
class CPUModelImportForm(NetBoxModelImportForm):
manufacturer = CSVChoiceField(label="Hersteller", choices=CPUManufacturerChoices)
class Meta:
model = CPUModel
fields = (
"manufacturer",
"family",
"name",
"socket",
"launch_year",
"cores",
"threads",
"base_clock_ghz",
"boost_clock_ghz",
"tdp_watts",
"max_sockets",
"description",
"tags",
)
class CPUModelFilterForm(NetBoxModelFilterSetForm):
model = CPUModel
fieldsets = (
FieldSet("q", "filter_id", "tag"),
FieldSet("manufacturer", "family", "socket", "cores__gte", "launch_year__gte", "in_use", name="CPU"),
)
manufacturer = forms.MultipleChoiceField(label="Hersteller", choices=CPUManufacturerChoices, required=False)
family = forms.CharField(label="Familie", required=False)
socket = forms.CharField(label="Sockel", required=False)
cores__gte = forms.IntegerField(label="Kerne ab", required=False)
launch_year__gte = forms.IntegerField(label="Ab Jahr", required=False)
in_use = forms.NullBooleanField(
label="In Verwendung",
required=False,
widget=forms.Select(choices=(("", "—"), ("true", "Ja"), ("false", "Nein"))),
)
tag = TagFilterField(model)
class DeviceHardwareForm(NetBoxModelForm):
device = DynamicModelChoiceField(label="Gerät", queryset=Device.objects.all(), selector=True)
cpu = DynamicModelChoiceField(
label="CPU-Modell",
queryset=CPUModel.objects.all(),
required=False,
help_text="Suche nach Modell oder Familie, z. B. „6338“, „Gold 6338“ oder „EPYC 7543“.",
)
comments = CommentField()
fieldsets = (
FieldSet("device", name="Gerät"),
FieldSet("cpu", "cpu_count", name="CPU"),
FieldSet(
"memory_modules", "memory_module_gb", "memory_gb", "memory_type", "memory_speed_mts", name="Arbeitsspeicher"
),
FieldSet("description", "tags", name="Sonstiges"),
)
class Meta:
model = DeviceHardware
fields = (
"device",
"cpu",
"cpu_count",
"memory_modules",
"memory_module_gb",
"memory_gb",
"memory_type",
"memory_speed_mts",
"description",
"comments",
"tags",
)
help_texts = {
"memory_gb": "Leer lassen, um ihn aus Anzahl × Größe der Module zu berechnen.",
}
class DeviceHardwareImportForm(NetBoxModelImportForm):
device = CSVModelChoiceField(
label="Gerät", queryset=Device.objects.all(), to_field_name="name", help_text="Name des Geräts"
)
cpu = CSVModelChoiceField(
label="CPU-Modell",
queryset=CPUModel.objects.all(),
to_field_name="name",
required=False,
help_text="Modellname aus dem Katalog, z. B. Xeon Gold 6338",
)
memory_type = CSVChoiceField(label="RAM-Typ", choices=MemoryTypeChoices, required=False)
class Meta:
model = DeviceHardware
fields = (
"device",
"cpu",
"cpu_count",
"memory_gb",
"memory_type",
"memory_modules",
"memory_module_gb",
"memory_speed_mts",
"description",
"comments",
"tags",
)
class DeviceHardwareFilterForm(NetBoxModelFilterSetForm):
model = DeviceHardware
fieldsets = (
FieldSet("q", "filter_id", "tag"),
FieldSet("device_id", "cluster_id", "cpu_id", "manufacturer", "memory_type", "memory_gb__gte", name="Hardware"),
)
device_id = DynamicModelMultipleChoiceField(queryset=Device.objects.all(), required=False, label="Gerät")
cluster_id = DynamicModelMultipleChoiceField(queryset=Cluster.objects.all(), required=False, label="Cluster")
cpu_id = DynamicModelMultipleChoiceField(queryset=CPUModel.objects.all(), required=False, label="CPU-Modell")
manufacturer = forms.MultipleChoiceField(label="Hersteller", choices=CPUManufacturerChoices, required=False)
memory_type = forms.MultipleChoiceField(label="RAM-Typ", choices=MemoryTypeChoices, required=False)
memory_gb__gte = forms.IntegerField(label="RAM ab (GB)", required=False)
tag = TagFilterField(model)
+85
View File
@@ -0,0 +1,85 @@
import django_tables2 as tables
def _record(device):
return getattr(device, "netbox_utilities_hardware", None)
class DeviceCPUColumn(tables.Column):
def render(self, record):
hardware = _record(record)
return hardware.cpu_display if hardware and hardware.cpu_id else "—"
def value(self, record):
hardware = _record(record)
return hardware.cpu_display if hardware and hardware.cpu_id else ""
class DeviceCoresColumn(tables.Column):
def render(self, record):
hardware = _record(record)
if not hardware or not hardware.cpu_id:
return "—"
return f"{hardware.total_cores} / {hardware.total_threads}"
def value(self, record):
hardware = _record(record)
return hardware.total_cores if hardware and hardware.cpu_id else ""
class DeviceMemoryColumn(tables.Column):
def render(self, record):
hardware = _record(record)
return hardware.memory_display if hardware and hardware.memory_gb else "—"
def value(self, record):
hardware = _record(record)
return hardware.memory_gb if hardware and hardware.memory_gb else ""
class ClusterCapacityColumn(tables.Column):
"""vCPU:core ratio and RAM allocation of a cluster, e.g. "3,2 : 1 · 74 %"."""
@staticmethod
def capacity(record):
from dcim.models import Device
from virtualization.models import VirtualMachine
from .hardware import build_capacity
from .hardware_views import host_entry, vm_rows
hosts = Device.objects.filter(cluster=record).select_related("netbox_utilities_hardware__cpu")
vms = VirtualMachine.objects.filter(cluster=record)
return build_capacity([host_entry(device) for device in hosts], vm_rows(vms))
def render(self, record):
from .hardware import format_ratio
capacity = self.capacity(record)
if not capacity.cores:
return "—"
memory = f" · {capacity.memory_percent} % RAM" if capacity.memory_percent is not None else ""
return f"{format_ratio(capacity.vcpu_per_core)}{memory}"
def value(self, record):
return self.render(record)
def install_hardware_support():
from dcim.tables import DeviceTable
from utilities.tables import register_table_column
from virtualization.tables import ClusterTable
# Registers the "CPU & RAM" device tab before NetBox builds the dcim URLs.
from . import hardware_views # noqa: F401
common = {"accessor": tables.A("pk"), "orderable": False, "empty_values": ()}
register_table_column(DeviceCPUColumn(verbose_name="CPU", **common), "netbox_utilities_cpu", DeviceTable)
register_table_column(
DeviceCoresColumn(verbose_name="Kerne / Threads", **common), "netbox_utilities_cores", DeviceTable
)
register_table_column(DeviceMemoryColumn(verbose_name="RAM", **common), "netbox_utilities_memory", DeviceTable)
# Runs a few queries per row, so it is only shown when added under "Configure Table".
register_table_column(
ClusterCapacityColumn(verbose_name="vCPU : Kern · RAM", **common), "netbox_utilities_capacity", ClusterTable
)
+119
View File
@@ -0,0 +1,119 @@
import django_tables2 as tables
from netbox.tables import NetBoxTable, columns
from . import hardware
from .models import CPUModel, DeviceHardware
class ClockColumn(tables.Column):
def render(self, value):
return hardware.format_clock(value)
class MemoryColumn(tables.Column):
def render(self, value):
return hardware.format_memory(value)
class CPUModelTable(NetBoxTable):
name = tables.Column(linkify=True, verbose_name="Modell")
manufacturer = columns.ChoiceFieldColumn(verbose_name="Hersteller")
family = tables.Column(verbose_name="Familie")
cores = tables.Column(verbose_name="Kerne")
threads = tables.Column(verbose_name="Threads")
base_clock_ghz = ClockColumn(verbose_name="Basistakt")
boost_clock_ghz = ClockColumn(verbose_name="Turbo")
tdp_watts = tables.Column(verbose_name="TDP (W)")
socket = tables.Column(verbose_name="Sockel")
launch_year = tables.Column(verbose_name="Jahr")
max_sockets = tables.Column(verbose_name="Max. Sockel")
builtin = columns.BooleanColumn(verbose_name="Katalog")
device_count = columns.LinkedCountColumn(
viewname="plugins:netbox_utilities:devicehardware_list",
url_params={"cpu_id": "pk"},
verbose_name="Geräte",
)
tags = columns.TagColumn(url_name="plugins:netbox_utilities:cpumodel_list")
class Meta(NetBoxTable.Meta):
model = CPUModel
fields = (
"pk",
"id",
"name",
"manufacturer",
"family",
"cores",
"threads",
"base_clock_ghz",
"boost_clock_ghz",
"tdp_watts",
"socket",
"launch_year",
"max_sockets",
"builtin",
"device_count",
"description",
"tags",
"created",
"last_updated",
)
default_columns = (
"name",
"family",
"cores",
"threads",
"base_clock_ghz",
"boost_clock_ghz",
"socket",
"launch_year",
"device_count",
)
class DeviceHardwareTable(NetBoxTable):
device = tables.Column(linkify=True, verbose_name="Gerät")
cluster = tables.Column(accessor=tables.A("device__cluster"), linkify=True, verbose_name="Cluster")
cpu = tables.Column(linkify=True, verbose_name="CPU-Modell")
cpu_count = tables.Column(verbose_name="CPUs")
total_cores = tables.Column(verbose_name="Kerne", orderable=False)
total_threads = tables.Column(verbose_name="Threads", orderable=False)
memory_gb = MemoryColumn(verbose_name="RAM")
memory_type = columns.ChoiceFieldColumn(verbose_name="RAM-Typ")
memory_detail = tables.Column(verbose_name="Bestückung", orderable=False)
comments = columns.MarkdownColumn()
tags = columns.TagColumn(url_name="plugins:netbox_utilities:devicehardware_list")
class Meta(NetBoxTable.Meta):
model = DeviceHardware
fields = (
"pk",
"id",
"device",
"cluster",
"cpu",
"cpu_count",
"total_cores",
"total_threads",
"memory_gb",
"memory_type",
"memory_modules",
"memory_module_gb",
"memory_speed_mts",
"memory_detail",
"description",
"comments",
"tags",
"created",
"last_updated",
)
default_columns = (
"device",
"cluster",
"cpu",
"cpu_count",
"total_cores",
"total_threads",
"memory_gb",
"memory_detail",
)
+291
View File
@@ -0,0 +1,291 @@
from dcim.models import Device
from django.db.models import Count
from django.urls import reverse
from netbox.views import generic
from utilities.views import ViewTab, register_model_view
from virtualization.models import VirtualMachine
from . import hardware, hardware_filtersets, hardware_forms, hardware_tables
from .models import CPUModel, DeviceHardware
from .runtime import hardware_enabled
def host_entry(device):
"""hardware.Host for a device, with or without recorded CPU/RAM."""
record = getattr(device, "netbox_utilities_hardware", None)
if record is None:
return hardware.Host(name=device.name, key=device.pk)
return hardware.Host(
name=device.name,
key=device.pk,
cores=record.total_cores,
threads=record.total_threads,
memory_gb=record.memory_gb,
)
def vm_rows(vms):
return [(vm.device_id, vm.vcpus, vm.memory, vm.status) for vm in vms]
def capacity_context(capacity):
return {
"capacity": capacity,
"vcpu_per_core": hardware.format_ratio(capacity.vcpu_per_core),
"vcpu_per_thread": hardware.format_ratio(capacity.vcpu_per_thread),
"memory": hardware.format_memory(capacity.memory_gb),
"vm_memory": hardware.format_memory(round(capacity.vm_memory_gb, 1)),
"failover_memory": hardware.format_memory(capacity.failover_memory_gb),
"capacity_warnings": capacity.warnings(hardware.vcpu_ratio_warning()),
}
def hardware_tab_url(device):
return reverse("dcim:device_hardware", kwargs={"pk": device.pk})
def hardware_tab_badge(device):
"""Total cores of the device; "—" without CPU; None hides the tab for other devices."""
if not hardware_enabled():
return None
record = DeviceHardware.objects.filter(device=device).select_related("cpu").first()
if record is None:
return "—" if hardware.supports_hardware(device) else None
return str(record.total_cores) if record.cpu_id else "—"
@register_model_view(Device, "hardware", path="hardware")
class DeviceHardwareTabView(generic.ObjectView):
queryset = Device.objects.all()
template_name = "netbox_utilities/device_hardware.html"
tab = ViewTab(
label="CPU & RAM",
badge=hardware_tab_badge,
permission="netbox_utilities.view_devicehardware",
weight=2060,
hide_if_empty=True,
)
def get_extra_context(self, request, instance):
return device_hardware_context(request, instance)
def device_hardware_context(request, device):
"""The "CPU & RAM" tab: CPU/RAM and, for virtualization hosts, the VMs running on it."""
record = DeviceHardware.objects.filter(device=device).select_related("cpu").first()
context = {
"record": record,
"supported": hardware.supports_hardware(device),
"can_add": request.user.has_perm("netbox_utilities.add_devicehardware"),
"can_change": request.user.has_perm("netbox_utilities.change_devicehardware"),
"add_url": f"{reverse('plugins:netbox_utilities:devicehardware_add')}?device={device.pk}"
f"&return_url={hardware_tab_url(device)}",
}
vms = list(
VirtualMachine.objects.restrict(request.user, "view")
.filter(device=device)
.select_related("tenant")
.order_by("name")
)
if device.cluster_id:
# Includes this host's share of the cluster VMs that have no fixed host.
cluster_capacity, _ = build_cluster_capacity(request, device.cluster_id, extra_host=device)
host = next(host for host in cluster_capacity.hosts if host.key == device.pk)
capacity = hardware.host_capacity(cluster_capacity, host)
elif vms:
capacity = hardware.build_capacity([host_entry(device)], vm_rows(vms))
host = capacity.hosts[0]
if device.cluster_id or vms:
context.update(capacity_context(capacity))
context["host"] = host
context["vms"] = vms
context["vm_list_url"] = f"{reverse('virtualization:virtualmachine_list')}?device_id={device.pk}"
return context
def build_cluster_capacity(request, cluster_id, extra_host=None):
"""Capacity of a cluster's hosts and VMs; returns (capacity, host devices in the same order)."""
hosts = list(
Device.objects.restrict(request.user, "view")
.filter(cluster_id=cluster_id)
.select_related("netbox_utilities_hardware__cpu")
.order_by("name")
)
if extra_host is not None and all(host.pk != extra_host.pk for host in hosts):
hosts.append(extra_host)
vms = VirtualMachine.objects.restrict(request.user, "view").filter(cluster_id=cluster_id)
return hardware.build_capacity([host_entry(device) for device in hosts], vm_rows(vms)), hosts
def ratio_level(ratio, limit):
"""Bootstrap colour for a vCPU:core ratio."""
if ratio is None:
return "secondary"
if limit and ratio > limit:
return "danger" if ratio > limit * 1.5 else "warning"
return "success"
def memory_level(value):
if value is None:
return "secondary"
return "danger" if value > 100 else "warning" if value > 85 else "success"
def cluster_capacity_context(request, cluster):
capacity, hosts = build_cluster_capacity(request, cluster.pk)
limit = hardware.vcpu_ratio_warning()
rows = []
for device, host in zip(hosts, capacity.hosts, strict=True):
record = getattr(device, "netbox_utilities_hardware", None)
ratio = host.total_vcpus / host.cores if host.cores else None
memory_percent = hardware.percent(host.total_vm_memory_gb, host.memory_gb)
rows.append(
{
"device": device,
"record": record,
"host": host,
"memory": hardware.format_memory(host.memory_gb),
"vm_memory": hardware.format_memory(round(host.total_vm_memory_gb, 1)),
"memory_percent": memory_percent,
"memory_bar": min(memory_percent or 0, 100),
"memory_level": memory_level(memory_percent),
"vcpu_per_core": hardware.format_ratio(ratio),
"ratio_level": ratio_level(ratio, limit),
}
)
memory_percent = capacity.memory_percent
return {
**capacity_context(capacity),
"ratio_limit": limit,
"cluster_ratio_level": ratio_level(capacity.vcpu_per_core, limit),
"cluster_memory_bar": min(memory_percent or 0, 100),
"cluster_memory_level": memory_level(memory_percent),
"rows": rows,
"hardware_list_url": f"{reverse('plugins:netbox_utilities:devicehardware_list')}?cluster_id={cluster.pk}",
"can_add": request.user.has_perm("netbox_utilities.add_devicehardware"),
}
def vm_host_context(request, vm):
"""Panel on the VM page: the host's CPU and what share of it the VM gets."""
device = vm.device
if device is None and vm.cluster_id:
hosts = Device.objects.filter(cluster_id=vm.cluster_id)
records = list(DeviceHardware.objects.filter(device__in=hosts).select_related("cpu", "device"))
else:
records = list(DeviceHardware.objects.filter(device=device).select_related("cpu", "device")) if device else []
cpus = sorted({str(record.cpu) for record in records if record.cpu_id})
smallest = min((record.total_threads for record in records if record.total_threads), default=None)
return {
"device": device,
"records": records,
"cpus": cpus,
"vcpus": vm.vcpus,
"smallest_threads": smallest,
"vcpu_share": hardware.percent(vm.vcpus or 0, smallest),
"oversized": bool(smallest and vm.vcpus and vm.vcpus > smallest),
}
#
# CPU models
#
@register_model_view(CPUModel, "list", path="", detail=False)
class CPUModelListView(generic.ObjectListView):
queryset = CPUModel.objects.annotate(device_count=Count("devices"))
table = hardware_tables.CPUModelTable
filterset = hardware_filtersets.CPUModelFilterSet
filterset_form = hardware_forms.CPUModelFilterForm
@register_model_view(CPUModel)
class CPUModelView(generic.ObjectView):
queryset = CPUModel.objects.all()
def get_extra_context(self, request, instance):
records = DeviceHardware.objects.restrict(request.user, "view").filter(cpu=instance)
return {
"devices_table": hardware_tables.DeviceHardwareTable(
records.select_related("device", "device__cluster", "cpu"), orderable=False
),
"device_count": records.count(),
}
@register_model_view(CPUModel, "add", detail=False)
@register_model_view(CPUModel, "edit")
class CPUModelEditView(generic.ObjectEditView):
queryset = CPUModel.objects.all()
form = hardware_forms.CPUModelForm
@register_model_view(CPUModel, "delete")
class CPUModelDeleteView(generic.ObjectDeleteView):
queryset = CPUModel.objects.all()
@register_model_view(CPUModel, "bulk_import", path="import", detail=False)
class CPUModelBulkImportView(generic.BulkImportView):
queryset = CPUModel.objects.all()
model_form = hardware_forms.CPUModelImportForm
@register_model_view(CPUModel, "bulk_delete", path="delete", detail=False)
class CPUModelBulkDeleteView(generic.BulkDeleteView):
queryset = CPUModel.objects.annotate(device_count=Count("devices"))
filterset = hardware_filtersets.CPUModelFilterSet
table = hardware_tables.CPUModelTable
#
# CPU & RAM per device
#
@register_model_view(DeviceHardware, "list", path="", detail=False)
class DeviceHardwareListView(generic.ObjectListView):
queryset = DeviceHardware.objects.select_related("device", "device__cluster", "cpu")
table = hardware_tables.DeviceHardwareTable
filterset = hardware_filtersets.DeviceHardwareFilterSet
filterset_form = hardware_forms.DeviceHardwareFilterForm
@register_model_view(DeviceHardware)
class DeviceHardwareView(generic.ObjectView):
queryset = DeviceHardware.objects.select_related("device", "cpu")
def get_extra_context(self, request, instance):
return device_hardware_context(request, instance.device)
@register_model_view(DeviceHardware, "add", detail=False)
@register_model_view(DeviceHardware, "edit")
class DeviceHardwareEditView(generic.ObjectEditView):
queryset = DeviceHardware.objects.all()
form = hardware_forms.DeviceHardwareForm
def get_return_url(self, request, obj=None):
if obj is not None and obj.pk and obj.device_id and "return_url" not in request.GET:
return hardware_tab_url(obj.device)
return super().get_return_url(request, obj)
@register_model_view(DeviceHardware, "delete")
class DeviceHardwareDeleteView(generic.ObjectDeleteView):
queryset = DeviceHardware.objects.all()
@register_model_view(DeviceHardware, "bulk_import", path="import", detail=False)
class DeviceHardwareBulkImportView(generic.BulkImportView):
queryset = DeviceHardware.objects.all()
model_form = hardware_forms.DeviceHardwareImportForm
@register_model_view(DeviceHardware, "bulk_delete", path="delete", detail=False)
class DeviceHardwareBulkDeleteView(generic.BulkDeleteView):
queryset = DeviceHardware.objects.select_related("device", "cpu")
filterset = hardware_filtersets.DeviceHardwareFilterSet
table = hardware_tables.DeviceHardwareTable
+133
View File
@@ -0,0 +1,133 @@
import django_tables2 as tables
from django.db.models import Q
from django.utils.html import format_html
from django.utils.translation import gettext_lazy as _
from .tenant_autofill import ASSET_HARDWARE_RELATIONS
COLUMN_NAME = "tenant"
def asset_tenant(asset):
"""Tenant of the asset itself, otherwise the tenant of its assigned hardware (or that hardware's device)."""
if tenant := getattr(asset, "tenant", None):
return tenant
for relation in ASSET_HARDWARE_RELATIONS:
hardware = getattr(asset, relation, None)
if hardware is None:
continue
if tenant := getattr(hardware, "tenant", None):
return tenant
if tenant := getattr(getattr(hardware, "device", None), "tenant", None):
return tenant
return None
class AssetTenantColumn(tables.Column):
"""Asset tenant, falling back to the tenant of the assigned device, module, inventory item or rack."""
def render(self, record):
tenant = asset_tenant(record)
if tenant is None:
return "—"
url = tenant.get_absolute_url() if hasattr(tenant, "get_absolute_url") else None
return format_html('<a href="{}">{}</a>', url, tenant) if url else str(tenant)
def asset_tenant_query(tenant_ids):
"""Assets whose own tenant, or (without own tenant) whose hardware's tenant, is one of tenant_ids."""
inherited = Q()
for path in ("device", "module__device", "inventoryitem__device", "rack"):
inherited |= Q(**{f"{path}__tenant_id__in": tenant_ids})
return Q(tenant_id__in=tenant_ids) | (Q(tenant__isnull=True) & inherited)
def _ids(values):
return [int(getattr(value, "pk", value)) for value in values or () if value not in (None, "")]
def filter_asset_tenant(queryset, name, value):
tenant_ids = _ids(value)
return queryset.filter(asset_tenant_query(tenant_ids)) if tenant_ids else queryset
def filter_asset_tenant_group(queryset, name, value):
from tenancy.models import Tenant, TenantGroup
group_ids = set()
for group in TenantGroup.objects.filter(pk__in=_ids(value)):
group_ids.update(group.get_descendants(include_self=True).values_list("pk", flat=True))
if not group_ids:
return queryset
tenant_ids = list(Tenant.objects.filter(group_id__in=group_ids).values_list("pk", flat=True))
return queryset.filter(asset_tenant_query(tenant_ids))
def install_asset_tenant_filters():
"""
Tenant filters include inherited tenants, and the global tenant scope is applied directly.
The global filter does not rely on the URL parameter injected by the middleware here: any
invalid or ignored parameter would otherwise silently show all assets.
"""
from django_filters import ModelMultipleChoiceFilter
from netbox_inventory.filtersets import AssetFilterSet
from tenancy.models import Tenant, TenantGroup
from .tenant_scope import active_tenant_scope
AssetFilterSet.base_filters["tenant_id"] = ModelMultipleChoiceFilter(
queryset=Tenant.objects.all(),
field_name="tenant",
method=filter_asset_tenant,
label="Tenant (ID), including the tenant of the assigned hardware",
)
AssetFilterSet.base_filters["tenant_group_id"] = ModelMultipleChoiceFilter(
queryset=TenantGroup.objects.all(),
field_name="tenant__group",
method=filter_asset_tenant_group,
label="Tenant group (ID), including the tenant of the assigned hardware",
)
if getattr(AssetFilterSet, "_netbox_utilities_scoped", False):
return
original_filter_queryset = AssetFilterSet.filter_queryset
def scoped_filter_queryset(self, queryset):
queryset = original_filter_queryset(self, queryset)
scope = active_tenant_scope.get()
request = getattr(self, "request", None)
# Like the middleware: the REST API is never filtered implicitly.
if scope is None or request is None or request.path_info.startswith("/api/"):
return queryset
return queryset.filter(asset_tenant_query(list(scope.tenant_ids)))
AssetFilterSet.filter_queryset = scoped_filter_queryset
AssetFilterSet._netbox_utilities_scoped = True
def add_to_default_columns(table, column=COLUMN_NAME, after=("status", "asset_tag", "hardware_type")):
"""Show the column by default (users without saved table preferences), next to the status."""
defaults = [name for name in table.Meta.default_columns if name != column]
for anchor in after:
if anchor in defaults:
defaults.insert(defaults.index(anchor) + 1, column)
break
else:
defaults.append(column)
table.Meta.default_columns = tuple(defaults)
def install_asset_tenant_column():
"""Show the tenant of every netbox-inventory asset in the asset list."""
from netbox_inventory.tables import AssetTable
from utilities.tables import register_table_column
column = AssetTenantColumn(
accessor=tables.A("pk"), verbose_name=_("Tenant"), empty_values=(), order_by=("tenant__name",)
)
# Replaces the plugin's own column, which stays empty for assets that only inherit a tenant.
AssetTable.base_columns.pop(COLUMN_NAME, None)
register_table_column(column, COLUMN_NAME, AssetTable)
add_to_default_columns(AssetTable)
install_asset_tenant_filters()
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,22 @@
from django.core.management.base import BaseCommand
from netbox_utilities import cpu_catalog
from netbox_utilities.models import CPUModel
class Command(BaseCommand):
help = "Load or refresh the built-in Intel/AMD server CPU catalogue."
def add_arguments(self, parser):
parser.add_argument(
"--force",
action="store_true",
help="Also reset catalogue entries that were edited in the UI.",
)
def handle(self, *args, **options):
created, updated = cpu_catalog.sync(CPUModel, force=options["force"])
total = len(list(cpu_catalog.entries()))
self.stdout.write(
self.style.SUCCESS(f"CPU-Katalog: {created} neu, {updated} aktualisiert ({total} Modelle im Katalog).")
)
@@ -0,0 +1,41 @@
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = (
"Transfer the software lists of inventory reports (NetBox Windows Agent, NetBox Synchronizer) "
"in device comments into netbox-slm installations."
)
def add_arguments(self, parser):
parser.add_argument("--device", type=int, action="append", help="Only this device ID (repeatable)")
def handle(self, *args, **options):
from dcim.models import Device
from django.db.models import Q
from netbox_utilities.software_sync import sync_device_software
devices = Device.objects.filter(
Q(comments__icontains="installed software") | Q(comments__icontains="installierte software")
)
if options.get("device"):
devices = devices.filter(pk__in=options["device"])
total_created = total_removed = synced = 0
for device in devices.iterator():
try:
created, removed = sync_device_software(device)
except Exception as error: # noqa: BLE001 - report the device and continue with the next one
self.stderr.write(f"{device} (#{device.pk}): {error}")
continue
synced += 1
total_created += created
total_removed += removed
if created or removed:
self.stdout.write(f"{device}: +{created} / -{removed}")
self.stdout.write(
self.style.SUCCESS(
f"{synced} Geräte abgeglichen, {total_created} Installationen angelegt, {total_removed} entfernt."
)
)
+196
View File
@@ -0,0 +1,196 @@
import django.core.validators
import django.db.models.deletion
import taggit.managers
import utilities.json
from django.db import migrations, models
MANUFACTURER_CHOICES = [("intel", "Intel"), ("amd", "AMD"), ("other", "Sonstiges")]
MEMORY_TYPE_CHOICES = [("ddr3", "DDR3"), ("ddr4", "DDR4"), ("ddr5", "DDR5"), ("other", "Sonstiges")]
def netbox_model_fields():
return [
("id", models.BigAutoField(auto_created=True, primary_key=True, serialize=False)),
("created", models.DateTimeField(auto_now_add=True, null=True)),
("last_updated", models.DateTimeField(auto_now=True, null=True)),
(
"custom_field_data",
models.JSONField(blank=True, default=dict, encoder=utilities.json.CustomFieldJSONEncoder),
),
]
def tags_field():
return ("tags", taggit.managers.TaggableManager(through="extras.TaggedItem", to="extras.Tag"))
def load_cpu_catalog(apps, schema_editor):
from netbox_utilities import cpu_catalog
cpu_catalog.sync(apps.get_model("netbox_utilities", "CPUModel"))
class Migration(migrations.Migration):
dependencies = [
("dcim", "__latest__"),
("extras", "__latest__"),
("netbox_utilities", "0010_disk_bays"),
]
operations = [
migrations.CreateModel(
name="CPUModel",
fields=[
*netbox_model_fields(),
(
"manufacturer",
models.CharField(choices=MANUFACTURER_CHOICES, max_length=20, verbose_name="Hersteller"),
),
(
"family",
models.CharField(
blank=True,
help_text="z. B. Xeon Scalable 3. Gen (Ice Lake-SP)",
max_length=100,
verbose_name="Familie",
),
),
(
"name",
models.CharField(
help_text="z. B. Xeon Gold 6338 oder EPYC 7543", max_length=100, verbose_name="Modell"
),
),
(
"cores",
models.PositiveSmallIntegerField(
validators=[
django.core.validators.MinValueValidator(1),
django.core.validators.MaxValueValidator(1024),
],
verbose_name="Kerne",
),
),
(
"threads",
models.PositiveSmallIntegerField(
validators=[
django.core.validators.MinValueValidator(1),
django.core.validators.MaxValueValidator(2048),
],
verbose_name="Threads",
),
),
("base_clock_ghz", models.DecimalField(decimal_places=2, max_digits=4, verbose_name="Basistakt (GHz)")),
(
"boost_clock_ghz",
models.DecimalField(
blank=True, decimal_places=2, max_digits=4, null=True, verbose_name="Turbo (GHz)"
),
),
("tdp_watts", models.PositiveSmallIntegerField(blank=True, null=True, verbose_name="TDP (W)")),
("socket", models.CharField(blank=True, max_length=30, verbose_name="Sockel")),
(
"launch_year",
models.PositiveSmallIntegerField(blank=True, null=True, verbose_name="Erscheinungsjahr"),
),
(
"max_sockets",
models.PositiveSmallIntegerField(
default=2,
help_text="Wie viele CPUs dieses Modells ein System höchstens haben kann.",
validators=[
django.core.validators.MinValueValidator(1),
django.core.validators.MaxValueValidator(8),
],
verbose_name="Max. Sockel",
),
),
("builtin", models.BooleanField(default=False, editable=False, verbose_name="Aus dem Katalog")),
("customized", models.BooleanField(default=False, editable=False, verbose_name="Angepasst")),
("description", models.CharField(blank=True, max_length=200, verbose_name="Beschreibung")),
tags_field(),
],
options={
"ordering": ("manufacturer", "-launch_year", "name"),
"verbose_name": "CPU-Modell",
"verbose_name_plural": "CPU-Modelle",
"constraints": [
models.UniqueConstraint(
fields=("manufacturer", "name"), name="netbox_utilities_cpumodel_unique_name"
)
],
},
),
migrations.CreateModel(
name="DeviceHardware",
fields=[
*netbox_model_fields(),
(
"device",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
related_name="netbox_utilities_hardware",
to="dcim.device",
verbose_name="Gerät",
),
),
(
"cpu",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.PROTECT,
related_name="devices",
to="netbox_utilities.cpumodel",
verbose_name="CPU-Modell",
),
),
(
"cpu_count",
models.PositiveSmallIntegerField(
default=1,
help_text="Bestückte Sockel",
validators=[
django.core.validators.MinValueValidator(1),
django.core.validators.MaxValueValidator(8),
],
verbose_name="Anzahl CPUs",
),
),
("memory_gb", models.PositiveIntegerField(blank=True, null=True, verbose_name="RAM gesamt (GB)")),
(
"memory_type",
models.CharField(blank=True, choices=MEMORY_TYPE_CHOICES, max_length=20, verbose_name="RAM-Typ"),
),
(
"memory_modules",
models.PositiveSmallIntegerField(
blank=True,
null=True,
validators=[django.core.validators.MaxValueValidator(256)],
verbose_name="Anzahl Module",
),
),
(
"memory_module_gb",
models.PositiveIntegerField(blank=True, null=True, verbose_name="Modulgröße (GB)"),
),
(
"memory_speed_mts",
models.PositiveIntegerField(
blank=True, help_text="z. B. 3200 oder 4800", null=True, verbose_name="Takt (MT/s)"
),
),
("description", models.CharField(blank=True, max_length=200, verbose_name="Beschreibung")),
("comments", models.TextField(blank=True, verbose_name="Kommentare")),
tags_field(),
],
options={
"ordering": ("device",),
"verbose_name": "CPU & RAM",
"verbose_name_plural": "CPU & RAM",
},
),
migrations.RunPython(load_cpu_catalog, migrations.RunPython.noop),
]
@@ -0,0 +1,42 @@
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("dcim", "0237_module_remove_local_context_data"),
("netbox_utilities", "0011_cpu_ram"),
]
operations = [
migrations.CreateModel(
name="SwitchStack",
fields=[
(
"id",
models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID"),
),
("updated", models.DateTimeField(auto_now=True)),
(
"device",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
related_name="netbox_utilities_switch_stack",
to="dcim.device",
),
),
(
"members",
models.ManyToManyField(
blank=True,
related_name="netbox_utilities_stack_memberships",
to="dcim.device",
),
),
],
options={
"verbose_name": "Switch-Stack",
"verbose_name_plural": "Switch-Stacks",
},
),
]
+185 -1
View File
@@ -7,7 +7,7 @@ from django.utils import timezone
from netbox.models import NetBoxModel
from utilities.choices import ChoiceSet
from . import disks
from . import disks, hardware
class NavigationPreference(models.Model):
@@ -88,6 +88,29 @@ class DeviceRackPlacement(models.Model):
return f"{self.device}: 1/{self.width}, Position {self.horizontal_position}"
class SwitchStack(models.Model):
"""A switch that represents a stack; its members are shown one below the other in the port panel."""
device = models.OneToOneField(
"dcim.Device",
on_delete=models.CASCADE,
related_name="netbox_utilities_switch_stack",
)
members = models.ManyToManyField(
"dcim.Device",
blank=True,
related_name="netbox_utilities_stack_memberships",
)
updated = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = "Switch-Stack"
verbose_name_plural = "Switch-Stacks"
def __str__(self):
return f"Stack {self.device}"
class CableVLANAssignment(models.Model):
cable = models.OneToOneField(
"dcim.Cable",
@@ -497,3 +520,164 @@ class Disk(NetBoxModel):
if self.status == disks.STATUS_REPLACED and not self.removal_date:
self.removal_date = timezone.localdate()
return super().save(*args, **kwargs)
#
# CPU & RAM
#
class CPUManufacturerChoices(ChoiceSet):
CHOICES = [
("intel", "Intel"),
("amd", "AMD"),
("other", "Sonstiges"),
]
class MemoryTypeChoices(ChoiceSet):
CHOICES = list(hardware.MEMORY_TYPES.items())
class CPUModel(NetBoxModel):
"""One entry of the CPU catalogue; the built-in entries come from cpu_catalog.py."""
manufacturer = models.CharField("Hersteller", max_length=20, choices=CPUManufacturerChoices)
family = models.CharField(
"Familie", max_length=100, blank=True, help_text="z. B. Xeon Scalable 3. Gen (Ice Lake-SP)"
)
name = models.CharField("Modell", max_length=100, help_text="z. B. Xeon Gold 6338 oder EPYC 7543")
cores = models.PositiveSmallIntegerField("Kerne", validators=[MinValueValidator(1), MaxValueValidator(1024)])
threads = models.PositiveSmallIntegerField("Threads", validators=[MinValueValidator(1), MaxValueValidator(2048)])
base_clock_ghz = models.DecimalField("Basistakt (GHz)", max_digits=4, decimal_places=2)
boost_clock_ghz = models.DecimalField("Turbo (GHz)", max_digits=4, decimal_places=2, blank=True, null=True)
tdp_watts = models.PositiveSmallIntegerField("TDP (W)", blank=True, null=True)
socket = models.CharField("Sockel", max_length=30, blank=True)
launch_year = models.PositiveSmallIntegerField("Erscheinungsjahr", blank=True, null=True)
max_sockets = models.PositiveSmallIntegerField(
"Max. Sockel",
default=2,
validators=[MinValueValidator(1), MaxValueValidator(8)],
help_text="Wie viele CPUs dieses Modells ein System höchstens haben kann.",
)
builtin = models.BooleanField("Aus dem Katalog", default=False, editable=False)
customized = models.BooleanField("Angepasst", default=False, editable=False)
description = models.CharField("Beschreibung", max_length=200, blank=True)
class Meta:
ordering = ("manufacturer", "-launch_year", "name")
constraints = (
models.UniqueConstraint(fields=("manufacturer", "name"), name="netbox_utilities_cpumodel_unique_name"),
)
verbose_name = "CPU-Modell"
verbose_name_plural = "CPU-Modelle"
def __str__(self):
return f"{self.get_manufacturer_display()} {self.name}" if self.manufacturer != "other" else self.name
def get_absolute_url(self):
return reverse("plugins:netbox_utilities:cpumodel", args=[self.pk])
@property
def clock_display(self):
base = hardware.format_clock(self.base_clock_ghz)
return f"{base} / {hardware.format_clock(self.boost_clock_ghz)}" if self.boost_clock_ghz else base
@property
def summary(self):
""" "32 Kerne / 64 Threads, 2,0 / 3,2 GHz" for selects and panels."""
return f"{self.cores} Kerne / {self.threads} Threads, {self.clock_display}"
def clean(self):
super().clean()
if self.cores and self.threads and self.threads < self.cores:
raise ValidationError({"threads": "Es kann nicht weniger Threads als Kerne geben."})
if self.base_clock_ghz and self.boost_clock_ghz and self.boost_clock_ghz < self.base_clock_ghz:
raise ValidationError({"boost_clock_ghz": "Der Turbo-Takt liegt unter dem Basistakt."})
class DeviceHardware(NetBoxModel):
"""CPU and RAM of one device (server or virtualization host)."""
device = models.OneToOneField(
"dcim.Device",
on_delete=models.CASCADE,
related_name="netbox_utilities_hardware",
verbose_name="Gerät",
)
cpu = models.ForeignKey(
CPUModel,
on_delete=models.PROTECT,
related_name="devices",
blank=True,
null=True,
verbose_name="CPU-Modell",
)
cpu_count = models.PositiveSmallIntegerField(
"Anzahl CPUs",
default=1,
validators=[MinValueValidator(1), MaxValueValidator(8)],
help_text="Bestückte Sockel",
)
memory_gb = models.PositiveIntegerField("RAM gesamt (GB)", blank=True, null=True)
memory_type = models.CharField("RAM-Typ", max_length=20, choices=MemoryTypeChoices, blank=True)
memory_modules = models.PositiveSmallIntegerField(
"Anzahl Module", blank=True, null=True, validators=[MaxValueValidator(256)]
)
memory_module_gb = models.PositiveIntegerField("Modulgröße (GB)", blank=True, null=True)
memory_speed_mts = models.PositiveIntegerField(
"Takt (MT/s)", blank=True, null=True, help_text="z. B. 3200 oder 4800"
)
description = models.CharField("Beschreibung", max_length=200, blank=True)
comments = models.TextField("Kommentare", blank=True)
class Meta:
ordering = ("device",)
verbose_name = "CPU & RAM"
verbose_name_plural = "CPU & RAM"
def __str__(self):
return f"{self.device} – CPU & RAM"
def get_absolute_url(self):
return reverse("plugins:netbox_utilities:devicehardware", args=[self.pk])
@property
def total_cores(self):
return self.cpu.cores * self.cpu_count if self.cpu_id else None
@property
def total_threads(self):
return self.cpu.threads * self.cpu_count if self.cpu_id else None
@property
def cpu_display(self):
if not self.cpu_id:
return "—"
return f"{self.cpu_count} × {self.cpu}" if self.cpu_count > 1 else str(self.cpu)
@property
def memory_display(self):
return hardware.format_memory(self.memory_gb)
@property
def memory_detail(self):
""" "12 × 32 GB DDR4-3200"."""
parts = []
if self.memory_modules and self.memory_module_gb:
parts.append(f"{self.memory_modules} × {self.memory_module_gb} GB")
kind = self.get_memory_type_display() if self.memory_type else ""
if kind and self.memory_speed_mts:
kind = f"{kind}-{self.memory_speed_mts}"
elif self.memory_speed_mts:
kind = f"{self.memory_speed_mts} MT/s"
if kind:
parts.append(kind)
return " ".join(parts)
def clean(self):
super().clean()
if not self.memory_gb and self.memory_modules and self.memory_module_gb:
self.memory_gb = self.memory_modules * self.memory_module_gb
if self.cpu_id and self.cpu_count and self.cpu_count > self.cpu.max_sockets:
raise ValidationError({"cpu_count": f"{self.cpu} unterstützt höchstens {self.cpu.max_sockets} Sockel."})
+370
View File
@@ -0,0 +1,370 @@
"""Pure helpers for importing CSV exports of an HPE MSA: the disk list and the disk group list.
Column names are matched loosely: case, spaces and punctuation are ignored and common
alternative names are accepted, so slightly different firmware versions or re-saved
files (Excel with semicolons, other encodings) still work.
"""
import csv
import io
import re
from dataclasses import dataclass, field
from . import disks
KIND_DISKS = "disks"
KIND_GROUPS = "groups"
# Normalised header names (see _key) accepted for each value.
DISK_COLUMNS = {
"location": ("location", "position", "pos", "disklocation", "drivelocation", "encslot", "enclosureslot"),
"enclosure": ("enclosure", "enclosureid", "encl", "shelf", "shelfid", "enclosurenumber"),
"slot": ("slot", "slotnumber", "slotid", "bay", "baynumber", "drivebay"),
"serial": ("serialnumber", "serial", "sn", "serialno", "diskserialnumber"),
"size": ("size", "capacity", "totalsize", "disksize"),
"type": ("type", "disktype", "drivetype", "interface", "mediatype"),
"usage": ("usage", "role", "diskusage"),
"disk_group": ("diskgroup", "diskgroupname", "group", "vdisk", "vdiskname"),
"health": ("health", "healthstatus"),
"manufacturer": ("manufacturer", "vendor", "make"),
"model": ("model", "modelnumber", "productid", "partnumber"),
"firmware": ("revision", "firmware", "firmwarerevision", "fwrevision", "fw", "firmwareversion"),
"rpm": ("rmin", "rpm", "speed", "rotationalspeed", "speedrpm"),
"power_on_hours": ("poweronhours", "poh", "poweronhrs", "hourspoweredon"),
}
GROUP_COLUMNS = {
"name": ("name", "diskgroup", "diskgroupname", "vdisk", "vdiskname", "groupname"),
"level": ("raidlevel", "raid", "level", "raidtype"),
"pool": ("pool", "poolname"),
"size": ("totalsize", "size", "capacity"),
"disks": ("disks", "diskcount", "numberofdisks", "numdisks", "drives"),
"health": ("health", "healthstatus"),
"disk_type": ("disktype", "type"),
}
# Usage values of hot spares; "dedicated" spares belong to one disk group.
SPARE_USAGES = ("globalsp", "dedicatedsp", "spare", "globalspare", "dedicatedspare", "hotspare")
# Health values which mean the disk has failed.
FAILED_HEALTH = ("fault", "failed", "error")
# Disk group values without a real group.
NO_GROUP = ("", "-", "n/a", "none")
_LOCATION_PATTERN = re.compile(r"(\d+)\D+(\d+)")
@dataclass
class MSADisk:
enclosure: str
slot: int
status: str
disk_type: str = ""
interface: str = ""
capacity_gb: int | None = None
disk_group: str = ""
serial: str = ""
manufacturer: str = ""
model: str = ""
firmware: str = ""
power_on_hours: int | None = None
usage: str = ""
health: str = ""
@dataclass
class MSAGroup:
name: str
level: str
level_text: str = ""
pool: str = ""
size: str = ""
disk_count: int | None = None
health: str = ""
@property
def description(self):
parts = [
f"Pool {self.pool}" if self.pool else "",
self.size,
f"{self.disk_count} Datenträger" if self.disk_count else "",
]
return ", ".join(part for part in parts if part)
@dataclass
class MSAExport:
kind: str = KIND_DISKS
disks: list = field(default_factory=list)
groups: list = field(default_factory=list)
errors: list = field(default_factory=list)
@property
def enclosures(self):
"""Enclosure IDs in natural order with their disks."""
result = {}
for disk in sorted(self.disks, key=lambda item: (_natural(item.enclosure), item.slot)):
result.setdefault(disk.enclosure, []).append(disk)
return result
@property
def is_empty(self):
return not self.disks and not self.groups
def _natural(value):
return (0, int(value), "") if str(value).isdigit() else (1, 0, str(value))
def _key(text):
return re.sub(r"[^a-z0-9]", "", (text or "").casefold())
def decode(data):
if isinstance(data, bytes):
for encoding in ("utf-8-sig", "cp1252"):
try:
return data.decode(encoding)
except UnicodeDecodeError:
continue
return str(data or "").lstrip("")
def _int(value):
try:
return int(str(value).strip().replace(".", "").replace(",", ""))
except ValueError:
return None
def _read(text):
"""Return (rows, header lookup) for CSV text with ',', ';' or tab as delimiter."""
try:
dialect = csv.Sniffer().sniff(text.splitlines()[0], delimiters=",;\t")
except csv.Error:
dialect = csv.excel
reader = csv.DictReader(io.StringIO(text), dialect=dialect)
return reader, {_key(name): name for name in (reader.fieldnames or []) if name}
def _resolve(headers, columns):
"""Map each value name to the header present in the file, or None."""
return {
name: next((headers[alias] for alias in aliases if alias in headers), None) for name, aliases in columns.items()
}
def detect_kind(text):
"""KIND_DISKS, KIND_GROUPS or None, judged from the header line only."""
text = decode(text).strip()
if not text:
return None
_, headers = _read(text.splitlines()[0])
disk_columns = _resolve(headers, DISK_COLUMNS)
if disk_columns["location"] or (disk_columns["enclosure"] and disk_columns["slot"]):
return KIND_DISKS
group_columns = _resolve(headers, GROUP_COLUMNS)
if group_columns["name"] and group_columns["level"]:
return KIND_GROUPS
return None
def looks_like_export(text):
return detect_kind(text) is not None
def parse_location(text):
"""'1.4', '1:4', '1/4', '1-4' or 'Enclosure 1 Slot 4' → ('1', 4); None if unreadable."""
match = _LOCATION_PATTERN.search(text or "")
if not match:
return None
return str(int(match.group(1))), int(match.group(2))
def map_type(value, rpm=""):
"""Translate the MSA "Type" column, e.g. "SSD SAS", "SAS", "SAS MDL" or "SATA", into (type, interface)."""
text = (value or "").upper()
interface = "sata" if "SATA" in text else "sas" if "SAS" in text else "nvme" if "NVME" in text else ""
if "SSD" in text or "NVME" in text or text.startswith("SSAS"):
disk_type = "ssd" if interface != "nvme" else "nvme"
elif text or (rpm and rpm.strip().lower() not in ("0k", "0")):
disk_type = "hdd"
else:
disk_type = ""
return disk_type, interface
def map_status(usage, health):
if _key(health) in FAILED_HEALTH:
return disks.STATUS_FAILED
if _key(usage) in SPARE_USAGES:
return disks.STATUS_SPARE
return disks.STATUS_ACTIVE
def map_raid_level(text):
"""'RAID10', 'RAID-5', 'raid 6', 'R5', 'NRAID' or 'ADAPT' → a RAID_LEVELS key ("other" if unknown)."""
key = _key(text)
if re.fullmatch(r"r\d+", key):
key = "raid" + key[1:]
if key in ("nraid", "jbod", "none", "single"):
return "jbod"
if key == "raid1e":
return "raid1"
return key if key in disks.RAID_LEVELS else "other"
def parse_export(data):
"""Parse a disk or disk group export; rows that cannot be read end up in errors."""
text = decode(data).strip()
export = MSAExport()
if not text:
export.errors.append("Die Datei ist leer.")
return export
kind = detect_kind(text)
if kind == KIND_GROUPS:
export.kind = KIND_GROUPS
_parse_groups(text, export)
elif kind == KIND_DISKS:
_parse_disks(text, export)
else:
export.errors.append(
"Unbekanntes Format. Erwartet wird der Datenträger-Export (Spalte „Location“ bzw. „Enclosure“ und "
"„Slot“) oder der Disk-Group-Export (Spalten „Name“ und „RAID Level“) einer HPE MSA."
)
if export.is_empty and not export.errors:
export.errors.append("Die Datei enthält keine Einträge.")
return export
def _parse_disks(text, export):
reader, headers = _read(text)
columns = _resolve(headers, DISK_COLUMNS)
def column(row, name):
key = columns[name]
return (row.get(key) or "").strip() if key else ""
seen = set()
for line, row in enumerate(reader, start=2):
if columns["location"]:
location = column(row, "location")
else:
location = f"{column(row, 'enclosure')}.{column(row, 'slot')}".strip(".")
if not location:
continue
position = parse_location(location)
if position is None:
export.errors.append(f"Zeile {line}: ungültige Position {location!r} (erwartet z. B. 1.4).")
continue
if position in seen:
export.errors.append(f"Zeile {line}: Position {location} kommt mehrfach vor.")
continue
seen.add(position)
try:
capacity = disks.parse_capacity(column(row, "size")) if column(row, "size") else None
except ValueError:
capacity = None
disk_type, interface = map_type(column(row, "type"), column(row, "rpm"))
group = column(row, "disk_group")
usage, health = column(row, "usage"), column(row, "health")
hours = column(row, "power_on_hours")
export.disks.append(
MSADisk(
enclosure=position[0],
slot=position[1],
status=map_status(usage, health),
disk_type=disk_type,
interface=interface,
capacity_gb=capacity,
disk_group="" if group.casefold() in NO_GROUP else group,
serial=column(row, "serial"),
manufacturer=column(row, "manufacturer"),
model=column(row, "model"),
firmware=column(row, "firmware"),
power_on_hours=_int(hours) if hours else None,
usage=usage,
health=health,
)
)
def _parse_groups(text, export):
reader, headers = _read(text)
columns = _resolve(headers, GROUP_COLUMNS)
def column(row, name):
key = columns[name]
return (row.get(key) or "").strip() if key else ""
seen = set()
for line, row in enumerate(reader, start=2):
name = column(row, "name")
if not name:
continue
if name.casefold() in seen:
export.errors.append(f"Zeile {line}: Disk Group {name} kommt mehrfach vor.")
continue
seen.add(name.casefold())
level_text = column(row, "level")
count = column(row, "disks")
export.groups.append(
MSAGroup(
name=name,
level=map_raid_level(level_text),
level_text=level_text,
pool=column(row, "pool"),
size=column(row, "size"),
disk_count=_int(count) if count else None,
health=column(row, "health"),
)
)
def suggest_slot_count(highest_slot):
"""Common MSA enclosure sizes: 12 LFF or 24 SFF bays; anything bigger is taken as is."""
for size in (12, 24):
if highest_slot <= size:
return size
return highest_slot
def suggest_form_factor(slot_count):
return "3.5" if slot_count == 12 else "2.5" if slot_count == 24 else ""
ACTION_NEW = "new"
ACTION_UPDATE = "update"
ACTION_REPLACE = "replace"
ACTION_SKIP = "skip"
ACTION_CONFLICT = "conflict"
ACTION_LABELS = {
ACTION_NEW: ("Neu", "success"),
ACTION_UPDATE: ("Aktualisieren", "info"),
ACTION_REPLACE: ("Ersetzt vorhandenen", "warning"),
ACTION_SKIP: ("Übersprungen", "secondary"),
ACTION_CONFLICT: ("Konflikt", "danger"),
}
def classify(disk, first_slot, last_slot, occupant_serial=None, serial_elsewhere=None, replace=False):
"""Decide what happens to one exported disk; returns (action, reason).
occupant_serial: serial of the disk currently in the target slot ("" if it has none,
None if the slot is free). serial_elsewhere: label of another slot that already
holds this serial, if any.
"""
if not first_slot <= disk.slot <= last_slot:
return ACTION_CONFLICT, f"Steckplatz {disk.slot} liegt außerhalb des Bereichs ({first_slot}–{last_slot})."
if disk.serial and serial_elsewhere:
return ACTION_CONFLICT, f"Seriennummer steckt laut NetBox bereits in {serial_elsewhere}."
if occupant_serial is None:
return ACTION_NEW, ""
if disk.serial and occupant_serial.casefold() == disk.serial.casefold():
return ACTION_UPDATE, ""
if replace:
return (
ACTION_REPLACE,
f"Bisheriger Datenträger {occupant_serial or '(ohne Seriennummer)'} wird als ausgebaut markiert.",
)
return ACTION_SKIP, f"Steckplatz ist mit {occupant_serial or 'einem Datenträger ohne Seriennummer'} belegt."
+46 -3
View File
@@ -19,10 +19,10 @@ menu_items = (
),
)
# Own top-level menu for disks; the disk entry opens the list grouped by device.
# Own top-level menu for server hardware; the disk entry opens the list grouped by device.
menu = PluginMenu(
label="Datenträger",
icon_class="mdi mdi-harddisk",
label="Hardware",
icon_class="mdi mdi-server",
groups=(
(
"Datenträger",
@@ -38,6 +38,12 @@ menu = PluginMenu(
icon_class="mdi mdi-upload",
permissions=("netbox_utilities.add_disk",),
),
PluginMenuButton(
link="plugins:netbox_utilities:disk_msa_import",
title="HPE-MSA-Export importieren",
icon_class="mdi mdi-database-import",
permissions=("netbox_utilities.add_disk",),
),
),
),
PluginMenuItem(
@@ -52,5 +58,42 @@ menu = PluginMenu(
),
),
),
(
"CPU & RAM",
(
PluginMenuItem(
link="plugins:netbox_utilities:devicehardware_list",
link_text="CPU & RAM",
permissions=("netbox_utilities.view_devicehardware",),
buttons=(
PluginMenuButton(
link="plugins:netbox_utilities:devicehardware_add",
title="Hinzufügen",
icon_class="mdi mdi-plus-thick",
permissions=("netbox_utilities.add_devicehardware",),
),
PluginMenuButton(
link="plugins:netbox_utilities:devicehardware_bulk_import",
title="Importieren",
icon_class="mdi mdi-upload",
permissions=("netbox_utilities.add_devicehardware",),
),
),
),
PluginMenuItem(
link="plugins:netbox_utilities:cpumodel_list",
link_text="CPU-Modelle",
permissions=("netbox_utilities.view_cpumodel",),
buttons=(
PluginMenuButton(
link="plugins:netbox_utilities:cpumodel_add",
title="Hinzufügen",
icon_class="mdi mdi-plus-thick",
permissions=("netbox_utilities.add_cpumodel",),
),
),
),
),
),
),
)
+8 -2
View File
@@ -12,6 +12,7 @@ from django.db.models import Count, Q
from django.db.models.signals import post_save, pre_save
from .models import DeviceRackPlacement
from .switch_stack import STACK_FORM_FIELDS
logger = logging.getLogger(__name__)
@@ -391,9 +392,11 @@ def _install_device_form():
if getattr(DeviceEditView, "_netbox_utilities_rack_width_installed", False):
return
from .switch_stack import build_stack_form_mixin
base_device_form = DeviceEditView.form
class RackWidthDeviceForm(base_device_form):
class RackWidthDeviceForm(build_stack_form_mixin(), base_device_form):
utilities_rack_width = forms.ChoiceField(
label="Rackbreite",
choices=WIDTH_CHOICES,
@@ -422,12 +425,15 @@ def _install_device_form():
reordered = {}
for name, field in self.fields.items():
if name in {"utilities_rack_width", "utilities_horizontal_position"}:
if name in {"utilities_rack_width", "utilities_horizontal_position", *STACK_FORM_FIELDS}:
continue
reordered[name] = field
if name == "position":
reordered["utilities_rack_width"] = self.fields["utilities_rack_width"]
reordered["utilities_horizontal_position"] = self.fields["utilities_horizontal_position"]
for name in STACK_FORM_FIELDS:
if name in self.fields:
reordered[name] = self.fields[name]
self.fields = reordered
def clean(self):
+14
View File
@@ -15,6 +15,20 @@ def connection_vlans_enabled():
return bool(get_plugin_config("netbox_utilities", "connection_vlans_enabled"))
def hardware_enabled():
return bool(get_plugin_config("netbox_utilities", "hardware_enabled"))
def software_enabled():
from django.apps import apps
return bool(get_plugin_config("netbox_utilities", "software_enabled")) and apps.is_installed("netbox_slm")
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"))
+13 -2
View File
@@ -1,6 +1,6 @@
from netbox.search import SearchIndex
from .models import Disk, RAIDGroup
from .models import CPUModel, Disk, RAIDGroup
class DiskIndex(SearchIndex):
@@ -25,4 +25,15 @@ class RAIDGroupIndex(SearchIndex):
display_attrs = ("device", "level")
indexes = [DiskIndex, RAIDGroupIndex]
class CPUModelIndex(SearchIndex):
model = CPUModel
fields = (
("name", 100),
("family", 300),
("socket", 500),
("description", 500),
)
display_attrs = ("manufacturer", "cores", "threads", "base_clock_ghz")
indexes = [DiskIndex, RAIDGroupIndex, CPUModelIndex]
+181
View File
@@ -0,0 +1,181 @@
"""Pure helpers for the client software overview (data from the netbox-slm plugin)."""
import re
from dataclasses import dataclass, field
from datetime import date
DEFAULT_SOFTWARE_DEVICE_ROLES = ("Client", "Windows Client")
# Number of products in the "top products" chart.
TOP_PRODUCTS = 10
def configured_roles(roles=None):
if roles is None:
try:
from netbox.plugins import get_plugin_config
roles = get_plugin_config("netbox_utilities", "software_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_SOFTWARE_DEVICE_ROLES)}
def is_client_role(role, roles=None):
"""A role counts as client role if its name or slug is configured ("Windows Client" or "windows-client")."""
if role is None:
return False
configured = configured_roles(roles)
slugs = {name.replace(" ", "-") for name in configured}
return (
str(getattr(role, "name", "")).casefold() in configured
or str(getattr(role, "slug", "")).casefold() in configured | slugs
)
def supports_software(device, roles=None):
"""Devices with a configured client role get the "Software" tab."""
return is_client_role(getattr(device, "role", None), roles)
def version_key(name):
"""Natural sort key: "10.2" after "9.11", numbers before text, case-insensitive."""
parts = re.split(r"(\d+)", str(name or "").casefold())
return tuple((0, int(part), "") if part.isdigit() else (1, 0, part) for part in parts if part)
def percent(part, total):
return round(part * 100 / total) if total else 0
@dataclass
class VersionStats:
id: int
name: str
end_of_support: date | None = None
release_type: str = ""
devices: set = field(default_factory=set)
installations: int = 0
# Share of the product's devices, and intensity in the version chart (newest = strongest)
share: int = 0
shade: int = 100
@property
def device_count(self):
return len(self.devices)
def support_expired(self, today=None):
return bool(self.end_of_support and self.end_of_support < (today or date.today()))
@dataclass
class ProductStats:
id: int
name: str
manufacturer: str = ""
versions: dict = field(default_factory=dict)
devices: set = field(default_factory=set)
installations: int = 0
share: int = 0
bar: int = 0
@property
def device_count(self):
return len(self.devices)
@property
def version_count(self):
return len(self.versions)
@property
def versions_by_name(self):
"""Newest version first."""
return sorted(self.versions.values(), key=lambda version: version_key(version.name), reverse=True)
@property
def latest_version(self):
versions = self.versions_by_name
return versions[0] if versions else None
@property
def expired_devices(self):
return {device for version in self.versions.values() if version.support_expired() for device in version.devices}
@dataclass
class SoftwareSummary:
products: list
device_total: int
devices_with_software: int
installations: int
version_count: int
expired_device_count: int
@property
def devices_without_software(self):
return max(self.device_total - self.devices_with_software, 0)
@property
def coverage(self):
return percent(self.devices_with_software, self.device_total)
@property
def product_count(self):
return len(self.products)
@property
def top_products(self):
return self.products[:TOP_PRODUCTS]
def summarize(rows, device_total=None):
"""
Aggregate installation rows into products and versions.
Each row is a mapping with product_id, product_name, manufacturer, version_id, version_name,
end_of_support, release_type and device_id. Devices are counted once per product/version, even
if the same software was recorded twice on a device.
"""
products = {}
all_devices = set()
installations = 0
for row in rows:
installations += 1
product = products.get(row["product_id"])
if product is None:
product = products[row["product_id"]] = ProductStats(
id=row["product_id"], name=row["product_name"], manufacturer=row.get("manufacturer") or ""
)
version = product.versions.get(row["version_id"])
if version is None:
version = product.versions[row["version_id"]] = VersionStats(
id=row["version_id"],
name=row["version_name"],
end_of_support=row.get("end_of_support"),
release_type=row.get("release_type") or "",
)
product.installations += 1
version.installations += 1
product.devices.add(row["device_id"])
version.devices.add(row["device_id"])
all_devices.add(row["device_id"])
total = device_total if device_total is not None else len(all_devices)
ordered = sorted(products.values(), key=lambda product: (-product.device_count, product.name.casefold()))
most = ordered[0].device_count if ordered else 0
for product in ordered:
product.share = percent(product.device_count, total)
product.bar = percent(product.device_count, most)
versions = product.versions_by_name
for index, version in enumerate(versions):
version.share = percent(version.device_count, product.device_count)
# Newest version at 100 %, older ones fade out to 35 %.
version.shade = 100 - round(index * 65 / max(len(versions) - 1, 1))
expired = {device for product in ordered for device in product.expired_devices}
return SoftwareSummary(
products=ordered,
device_total=total,
devices_with_software=len(all_devices),
installations=installations,
version_count=sum(product.version_count for product in ordered),
expired_device_count=len(expired),
)
+68
View File
@@ -0,0 +1,68 @@
"""Hooks the client software overview into NetBox: device tab and "Software" group in the Inventory menu."""
from django.core.signals import request_started
SOFTWARE_GROUP_LABEL = "Software"
INVENTORY_MENU_LABEL = "Inventory"
FALLBACK_MENU_LABEL = "Hardware"
def software_menu_items():
from netbox.plugins import PluginMenuButton, PluginMenuItem
return (
PluginMenuItem(
link="plugins:netbox_utilities:software_overview",
link_text="Client Software Übersicht",
permissions=["netbox_slm.view_softwareproductinstallation"],
buttons=(
PluginMenuButton(
link="plugins:netbox_slm:softwareproductinstallation_add",
title="Installation erfassen",
icon_class="mdi mdi-plus-thick",
permissions=["netbox_slm.add_softwareproductinstallation"],
),
),
),
)
def add_software_group(menus):
"""
Append the "Software" group to the Inventory menu of netbox-inventory.
Falls back to the plugin's own "Hardware" menu if netbox-inventory has no top-level menu.
Returns the menu that received the group, or None.
"""
from netbox.navigation import MenuGroup
menus = list(menus)
target = next((menu for menu in menus if str(menu.label) == INVENTORY_MENU_LABEL), None)
target = target or next((menu for menu in menus if str(menu.label) == FALLBACK_MENU_LABEL), None)
if target is None:
return None
groups = list(target.groups)
if any(str(group.label) == SOFTWARE_GROUP_LABEL for group in groups):
return target
groups.append(MenuGroup(SOFTWARE_GROUP_LABEL, software_menu_items()))
target.groups = groups
return target
def _install_menu_on_first_request(**kwargs):
# All plugins have registered their menus once the first request arrives.
request_started.disconnect(dispatch_uid=__name__)
from netbox.registry import registry
add_software_group(registry["plugins"]["menus"])
def install_software_support():
# Registers the device "Software" tab before NetBox builds the dcim URLs.
from . import software_views # noqa: F401
from .software_sync import install_software_sync
# Software lists of the Windows agent and the NetBox Synchronizer arrive in the device comments.
install_software_sync()
request_started.connect(_install_menu_on_first_request, dispatch_uid=__name__)
+243
View File
@@ -0,0 +1,243 @@
"""
Transfer the software list of inventory reports in device comments into netbox-slm.
Two writers put a software list into the comments of a client device:
* the NetBox Windows Agent (mode ``netbox``)::
## Installed software (2)
- 7-Zip 23.01 (x64) 23.01 — Igor Pavlov
- Mozilla Firefox (x64 de) 120.0 — Mozilla
* the NetBox Synchronizer desktop app (agent scan in mode ``listen``)::
### Installierte Software (2)
| Programm | Version | Hersteller |
|---|---|---|
| 7-Zip 23.01 (x64) | 23.01 | Igor Pavlov |
On every device save the installations recorded this way are brought in line with the report.
Installations entered by hand are never changed or removed.
"""
import logging
import re
from dataclasses import dataclass
logger = logging.getLogger(__name__)
# Marks installations created from a report; only these are removed again when a report drops them.
SYNC_MARKER = "Automatisch aus dem Inventarbericht übernommen (netbox-utilities)."
UNKNOWN_VERSION = "unbekannt"
_HEADING = re.compile(r"^\s*#{1,6}\s*(installed software|installierte software)\b", re.IGNORECASE)
_ANY_HEADING = re.compile(r"^\s*#{1,6}\s")
# At least one dot, so a year in a product name ("Office 2024") is not taken for a version.
_VERSION = re.compile(r"^v?\d+(?:\.\w+)+(?:[\-_+]\w+)*$", re.IGNORECASE)
_TABLE_SEPARATOR = re.compile(r"^\|?\s*:?-{2,}")
@dataclass(frozen=True)
class SoftwareEntry:
name: str
version: str
publisher: str = ""
@property
def key(self):
return self.name.casefold(), self.version.casefold()
def has_software_report(comments):
return any(_HEADING.match(line) for line in str(comments or "").splitlines())
def _software_lines(comments):
"""Lines of the first software section, up to the next heading."""
inside = False
for line in str(comments or "").splitlines():
if _HEADING.match(line):
if inside:
return
inside = True
continue
if inside:
if _ANY_HEADING.match(line) or line.strip().startswith("<!--"):
return
yield line.strip()
def _parse_table_row(line):
cells = [cell.strip() for cell in line.strip().strip("|").split("|")]
if len(cells) < 2 or _TABLE_SEPARATOR.match(line) or cells[0].casefold() in {"programm", "name", "software"}:
return None
return cells[0], cells[1], cells[2] if len(cells) > 2 else ""
def _parse_bullet(line):
"""``- Name Version — Publisher``: the version is the last word if it looks like one."""
text = line[1:].strip()
publisher = ""
if " — " in text:
text, publisher = (part.strip() for part in text.rsplit(" — ", 1))
words = text.rsplit(" ", 1)
if len(words) == 2 and _VERSION.match(words[1]):
return words[0], words[1], publisher
return text, "", publisher
def clean_name(name, version):
"""Remove a version the vendor appended to the product name ("Foo 1.2", "Foo - 1.2.3")."""
name = " ".join(str(name or "").split())
version = str(version or "").strip()
if not version:
return name
match = re.match(r"^(?P<base>.+?)\s*(?:-\s*)?v?(?P<tail>\d[\w.\-+]*)$", name)
if match:
tail = match.group("tail")
if version.startswith(tail) or tail.startswith(version):
return match.group("base").rstrip(" -")
return name
def parse_software_report(comments):
"""Software entries of a report in device comments; an empty list without a report."""
entries = {}
for line in _software_lines(comments):
if line.startswith("|"):
parsed = _parse_table_row(line)
elif line.startswith(("- ", "* ")):
parsed = _parse_bullet(line)
else:
parsed = None
if not parsed or not parsed[0].strip():
continue
raw_name, version, publisher = (" ".join(str(part or "").split()) for part in parsed)
version = version or UNKNOWN_VERSION
entry = SoftwareEntry(clean_name(raw_name, version)[:128], version[:64], publisher[:255])
entries.setdefault(entry.key, entry)
return list(entries.values())
def _product_for(entry, products, manufacturers):
from netbox_slm.models import SoftwareProduct
key = entry.name.casefold()
product = products.get(key)
if product is None:
product = SoftwareProduct.objects.filter(name__iexact=entry.name).order_by("pk").first()
if product is None:
product = SoftwareProduct(name=entry.name, manufacturer=manufacturers.get(entry.publisher.casefold()))
if product.manufacturer is None and entry.publisher:
product.description = entry.publisher
product.full_clean()
product.save()
products[key] = product
return product
def _version_for(product, entry, versions):
from netbox_slm.models import SoftwareProductVersion
key = (product.pk, entry.version.casefold())
version = versions.get(key)
if version is None:
version = (
SoftwareProductVersion.objects.filter(software_product=product, name__iexact=entry.version)
.order_by("pk")
.first()
)
if version is None:
version = SoftwareProductVersion(software_product=product, name=entry.version)
version.full_clean()
version.save()
versions[key] = version
return version
def sync_device_software(device):
"""
Bring the netbox-slm installations of a device in line with the report in its comments.
Returns (created, removed). Devices without a report are left untouched, so removing the
report by hand does not delete anything.
"""
from dcim.models import Manufacturer
from django.db import transaction
from netbox_slm.models import SoftwareProductInstallation
comments = getattr(device, "comments", "")
if not has_software_report(comments):
return 0, 0
entries = parse_software_report(comments)
manufacturers = {
manufacturer.name.casefold(): manufacturer
for manufacturer in Manufacturer.objects.filter(
name__in={entry.publisher for entry in entries if entry.publisher}
)
}
with transaction.atomic():
existing = SoftwareProductInstallation.objects.filter(device=device).select_related(
"software_product", "version"
)
present = {}
for installation in existing:
key = (installation.software_product.name.casefold(), installation.version.name.casefold())
present.setdefault(key, installation)
wanted = {entry.key: entry for entry in entries}
products, versions, created = {}, {}, 0
for key, entry in wanted.items():
if key in present:
continue
product = _product_for(entry, products, manufacturers)
version = _version_for(product, entry, versions)
SoftwareProductInstallation.objects.create(
device=device, software_product=product, version=version, comments=SYNC_MARKER
)
created += 1
stale = [
installation.pk
for key, installation in present.items()
if key not in wanted and installation.comments == SYNC_MARKER
]
removed = SoftwareProductInstallation.objects.filter(pk__in=stale).delete()[0] if stale else 0
return created, removed
def _sync_after_save(sender, instance, raw=False, **kwargs):
if raw or not has_software_report(getattr(instance, "comments", "")):
return
try:
sync_device_software(instance)
except Exception: # noqa: BLE001 - a broken report must never block saving the device
logger.exception("Software of device %s could not be transferred to netbox-slm", instance.pk)
def remove_synced_installations(device):
"""netbox-slm protects devices with installations; the automatic ones go with the device."""
from netbox_slm.models import SoftwareProductInstallation
return SoftwareProductInstallation.objects.filter(device=device, comments=SYNC_MARKER).delete()[0]
def install_software_sync():
from dcim.models import Device
from django.db.models.signals import post_save
post_save.connect(_sync_after_save, sender=Device, dispatch_uid=f"{__name__}.device")
if getattr(Device.delete, "_netbox_utilities_software", False):
return
original_delete = Device.delete
def delete(self, *args, **kwargs):
if self.pk:
remove_synced_installations(self)
return original_delete(self, *args, **kwargs)
delete._netbox_utilities_software = True
Device.delete = delete
+279
View File
@@ -0,0 +1,279 @@
"""Client software overview and the device "Software" tab, based on netbox-slm installations."""
import csv
from dcim.models import Device, DeviceRole
from django import forms
from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import render
from django.urls import reverse
from django.utils import timezone
from django.views.generic import View
from netbox.views import generic
from tenancy.models import Tenant, TenantGroup
from utilities.forms.fields import DynamicModelMultipleChoiceField
from utilities.views import ContentTypePermissionRequiredMixin, ViewTab, register_model_view
from . import software
from .tenant_scope import active_tenant_scope
INSTALLATION_PERMISSION = "netbox_slm.view_softwareproductinstallation"
ROW_FIELDS = {
"product_id": "software_product_id",
"product_name": "software_product__name",
"manufacturer": "software_product__manufacturer__name",
"version_id": "version_id",
"version_name": "version__name",
"end_of_support": "version__end_of_support",
"release_type": "version__release_type",
"device_id": "device_id",
}
def installation_model():
from netbox_slm.models import SoftwareProductInstallation
return SoftwareProductInstallation
def client_role_ids():
return [role.pk for role in DeviceRole.objects.all() if software.is_client_role(role)]
def client_roles():
return DeviceRole.objects.filter(pk__in=client_role_ids()).order_by("name")
class SoftwareOverviewFilterForm(forms.Form):
tenant_group_id = DynamicModelMultipleChoiceField(
queryset=TenantGroup.objects.all(), required=False, label="Mandantengruppe"
)
tenant_id = DynamicModelMultipleChoiceField(
queryset=Tenant.objects.all(),
required=False,
label="Mandant",
query_params={"group_id": "$tenant_group_id"},
)
# Only client roles: servers and other devices never appear in the overview.
role_id = forms.ModelMultipleChoiceField(
queryset=DeviceRole.objects.none(),
required=False,
label="Gerätrolle",
widget=forms.CheckboxSelectMultiple(attrs={"class": "form-check-input"}),
)
q = forms.CharField(required=False, label="Software suchen")
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields["role_id"].queryset = client_roles()
def group_tenant_ids(groups):
group_ids = set()
for group in groups:
group_ids.update(group.get_descendants(include_self=True).values_list("pk", flat=True))
return set(Tenant.objects.filter(group_id__in=group_ids).values_list("pk", flat=True))
class SoftwareOverviewView(ContentTypePermissionRequiredMixin, View):
"""Software products, versions and the clients they are installed on, per tenant or tenant group."""
template_name = "netbox_utilities/software_overview.html"
def get_required_permission(self):
return INSTALLATION_PERMISSION
def get(self, request):
params = request.GET.copy()
params.pop("submitted", None)
form = SoftwareOverviewFilterForm(params)
form.is_valid()
data = getattr(form, "cleaned_data", {})
devices = Device.objects.restrict(request.user, "view")
tenant_ids, scope_label = self.selected_tenant_ids(request, data)
if tenant_ids is not None:
devices = devices.filter(tenant_id__in=tenant_ids)
# Always clients only; no role ticked means all client roles.
devices = devices.filter(role__in=data.get("role_id") or client_role_ids())
installations = (
installation_model()
.objects.restrict(request.user, "view")
.filter(device__isnull=False, device__in=devices)
)
if q := (data.get("q") or "").strip():
installations = installations.filter(
Q(software_product__name__icontains=q)
| Q(software_product__manufacturer__name__icontains=q)
| Q(version__name__icontains=q)
)
product_id = _int(params.get("product"))
version_id = _int(params.get("version"))
if params.get("export") == "csv":
if product_id:
installations = installations.filter(software_product_id=product_id)
if version_id:
installations = installations.filter(version_id=version_id)
return csv_response(installations)
rows = [
{key: row[path] for key, path in ROW_FIELDS.items()}
for row in installations.values(*ROW_FIELDS.values())
]
summary = software.summarize(rows, device_total=devices.count())
filter_query = _query(params, drop=("product", "version", "export"))
context = {
"form": form,
"summary": summary,
"scope_label": scope_label,
"filter_query": filter_query,
"today": timezone.localdate(),
"can_add": request.user.has_perm("netbox_slm.add_softwareproductinstallation"),
}
if product_id:
product = next((item for item in summary.products if item.id == product_id), None)
context.update(product_context(request, installations, product, version_id))
return render(request, self.template_name, context)
@staticmethod
def selected_tenant_ids(request, data):
"""Tenant ids to filter by (None = all) and a label if the global tenant filter applies."""
tenants, groups = data.get("tenant_id"), data.get("tenant_group_id")
if tenants or groups:
ids = {tenant.pk for tenant in tenants or ()}
if groups:
ids |= group_tenant_ids(groups)
return ids, None
scope = active_tenant_scope.get()
if scope is None:
return None, None
selected = getattr(request, "netbox_utilities_tenant_group", None) or getattr(
request, "netbox_utilities_tenant", None
)
return set(scope.tenant_ids), str(selected) if selected else "aktiv"
def product_context(request, installations, product, version_id):
"""Drill-down of one product: its versions and the devices it is installed on."""
if product is None:
return {"product_missing": True}
selected = product.versions.get(version_id) if version_id else None
queryset = installations.filter(software_product_id=product.id)
if selected:
queryset = queryset.filter(version_id=selected.id)
entries = sorted(
queryset.select_related("device", "device__tenant", "device__site", "device__role", "version"),
key=lambda entry: (entry.device.name or "").casefold(),
)
return {
"product": product,
"product_obj": product_object(request, product.id),
"selected_version": selected,
"entries": entries,
}
def product_object(request, product_id):
from netbox_slm.models import SoftwareProduct
return SoftwareProduct.objects.restrict(request.user, "view").filter(pk=product_id).first()
def csv_response(installations):
response = HttpResponse(content_type="text/csv; charset=utf-8")
response["Content-Disposition"] = 'attachment; filename="client-software.csv"'
response.write("") # Excel recognises UTF-8 with BOM
writer = csv.writer(response, delimiter=";")
writer.writerow(["Mandant", "Rechner", "Rolle", "Standort", "Hersteller", "Software", "Version", "Support-Ende"])
queryset = installations.select_related(
"device__tenant", "device__role", "device__site", "software_product__manufacturer", "version"
).order_by("device__tenant__name", "device__name", "software_product__name")
for entry in queryset:
device = entry.device
writer.writerow(
[
device.tenant or "",
device.name or "",
device.role or "",
device.site or "",
entry.software_product.manufacturer or "",
entry.software_product,
entry.version,
entry.version.end_of_support or "",
]
)
return response
def _int(value):
try:
return int(value)
except (TypeError, ValueError):
return None
def _query(params, drop=()):
params = params.copy()
for key in drop:
params.pop(key, None)
params["submitted"] = "1"
return params.urlencode()
#
# Device tab
#
def software_tab_badge(device):
"""Number of installations; hidden for devices without client role and without software."""
from .runtime import software_enabled
if not software_enabled():
return None
count = installation_model().objects.filter(device=device).count()
if count:
return str(count)
return "0" if software.supports_software(device) else None
@register_model_view(Device, "software", path="software")
class DeviceSoftwareTabView(generic.ObjectView):
queryset = Device.objects.all()
template_name = "netbox_utilities/device_software.html"
tab = ViewTab(
label="Software",
badge=software_tab_badge,
permission=INSTALLATION_PERMISSION,
weight=2070,
hide_if_empty=True,
)
def get_extra_context(self, request, instance):
entries = sorted(
installation_model()
.objects.restrict(request.user, "view")
.filter(device=instance)
.select_related("software_product", "software_product__manufacturer", "version"),
key=lambda entry: (entry.software_product.name.casefold(), software.version_key(entry.version.name)),
)
tab_url = reverse("dcim:device_software", kwargs={"pk": instance.pk})
overview_url = reverse("plugins:netbox_utilities:software_overview")
if instance.tenant_id:
overview_url += f"?submitted=1&tenant_id={instance.tenant_id}"
return {
"entries": entries,
"today": timezone.localdate(),
"supported": software.supports_software(instance),
"tab_url": tab_url,
"overview_url": overview_url,
"add_url": f"{reverse('plugins:netbox_slm:softwareproductinstallation_add')}?device={instance.pk}"
f"&return_url={tab_url}",
"can_add": request.user.has_perm("netbox_slm.add_softwareproductinstallation"),
"can_change": request.user.has_perm("netbox_slm.change_softwareproductinstallation"),
"can_delete": request.user.has_perm("netbox_slm.delete_softwareproductinstallation"),
}
@@ -400,3 +400,365 @@ a.nbu-disk-slot[draggable="true"] {
.nbu-disk-group-header[aria-expanded="true"] .nbu-disk-group-chevron {
transform: rotate(90deg);
}
/* ---------- Switch front panel on the device page (Aruba-like) ---------- */
/* Light theme by default; NetBox sets data-bs-theme="dark" on the html element for the dark theme. */
.nbu-switch-card {
--nbu-plate-from: #eef0f2;
--nbu-plate-to: #d9dde1;
--nbu-plate-edge: #c4c9ce;
--nbu-plate-label: #495057;
--nbu-jack-border: rgba(0, 0, 0, .35);
--nbu-jack-free: #ffffff;
--nbu-jack-free-ink: #6c757d;
--nbu-link: #2fb344;
--nbu-frame: #212529;
}
[data-bs-theme="dark"] .nbu-switch-card {
--nbu-plate-from: #3a3f45;
--nbu-plate-to: #2a2e33;
--nbu-plate-edge: #1d2024;
--nbu-plate-label: #ced4da;
--nbu-jack-border: rgba(0, 0, 0, .6);
--nbu-jack-free: #15181b;
--nbu-jack-free-ink: #8a9199;
--nbu-frame: #ffffff;
}
.nbu-faceplate {
display: flex;
flex-wrap: wrap;
align-items: flex-end;
gap: .75rem 1.25rem;
padding: .75rem 1rem;
border-radius: .6rem;
border: 1px solid var(--nbu-plate-edge);
background: linear-gradient(180deg, var(--nbu-plate-from) 0%, var(--nbu-plate-to) 100%);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, .15), 0 1px 3px rgba(0, 0, 0, .15);
overflow-x: auto;
}
.nbu-faceplate-label {
color: var(--nbu-plate-label);
font-size: .7rem;
margin-bottom: .3rem;
letter-spacing: .02em;
}
.nbu-faceplate-ports {
display: flex;
gap: .25rem;
}
.nbu-faceplate-column {
display: flex;
flex-direction: column;
gap: .25rem;
}
.nbu-jack {
--nbu-vlan: #6c757d;
--nbu-ink: #fff;
position: relative;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 2.15rem;
height: 1.9rem;
border-radius: .2rem .2rem .35rem .35rem;
border: 1px solid var(--nbu-jack-border);
text-decoration: none !important;
line-height: 1;
transition: transform .1s, filter .1s;
}
/* RJ45 latch notch in the colour of the faceplate */
.nbu-jack:not(.nbu-jack-sfp)::before {
content: "";
position: absolute;
bottom: -1px;
left: 50%;
width: 40%;
height: .22rem;
transform: translateX(-50%);
background: var(--nbu-plate-to);
border-radius: .15rem .15rem 0 0;
}
.nbu-jack-sfp {
width: 2.5rem;
border-radius: .12rem;
}
.nbu-jack:hover {
transform: translateY(-1px);
filter: brightness(1.1);
}
.nbu-jack-number {
font-size: .68rem;
font-weight: 700;
}
.nbu-jack-mgmt .nbu-jack-number {
font-size: .55rem;
letter-spacing: .02em;
}
.nbu-jack-vlan {
font-size: .5rem;
max-width: 100%;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
padding: 0 .1rem;
display: none;
}
/* Status view: green link, free port in the jack colour of the theme, disabled with a red dot */
.nbu-jack-connected { background: var(--nbu-link); color: #fff; }
.nbu-jack-free,
.nbu-jack-disabled { background: var(--nbu-jack-free); color: var(--nbu-jack-free-ink); }
.nbu-jack-disabled::after {
content: "";
position: absolute;
top: .15rem;
right: .15rem;
width: .4rem;
height: .4rem;
border-radius: 50%;
background: #d63939;
}
/* VLAN view: fill by VLAN label; free ports dimmed, connected ports framed */
.nbu-switch-vlan .nbu-jack-vlan { display: block; }
.nbu-switch-vlan .nbu-jack-labelled { background: var(--nbu-vlan); color: var(--nbu-ink); }
.nbu-switch-vlan .nbu-jack:not(.nbu-jack-labelled) { background: var(--nbu-jack-free); color: var(--nbu-jack-free-ink); }
.nbu-switch-vlan .nbu-jack-connected { box-shadow: 0 0 0 2px var(--nbu-frame); }
.nbu-switch-vlan .nbu-jack-free.nbu-jack-labelled,
.nbu-switch-vlan .nbu-jack-disabled.nbu-jack-labelled { opacity: .45; }
.nbu-switch-legend {
display: flex;
flex-wrap: wrap;
gap: .3rem 1rem;
}
.nbu-jack-swatch {
position: relative;
display: inline-block;
width: .85rem;
height: .85rem;
border-radius: .15rem;
margin-right: .3rem;
vertical-align: -.1rem;
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;
}
/* Client Software Übersicht */
.nbu-sw-filter-footer {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 0.75rem 1.5rem;
margin-top: 1rem;
padding-top: 0.875rem;
border-top: 1px solid var(--tblr-border-color);
}
.nbu-sw-roles {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem;
}
.nbu-sw-roles-label {
color: var(--tblr-secondary);
font-size: 0.75rem;
font-weight: 600;
letter-spacing: 0.04em;
text-transform: uppercase;
margin-right: 0.25rem;
}
.nbu-sw-role {
border: 1px solid var(--tblr-border-color);
background: var(--tblr-bg-surface);
color: var(--tblr-body-color);
white-space: nowrap;
}
.nbu-sw-role:hover {
border-color: var(--tblr-primary);
color: var(--tblr-primary);
}
.btn-check:checked + .nbu-sw-role {
background: var(--tblr-primary);
border-color: var(--tblr-primary);
color: var(--tblr-primary-fg, #fff);
}
.btn-check:focus-visible + .nbu-sw-role {
box-shadow: 0 0 0 0.2rem rgba(var(--tblr-primary-rgb), 0.25);
}
.nbu-sw-filter-hint {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 0.5rem;
font-size: 0.8125rem;
}
.nbu-sw-kpi-label {
color: var(--tblr-secondary);
font-size: 0.75rem;
font-weight: 600;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.nbu-sw-kpi-value {
font-size: 1.75rem;
font-weight: 700;
line-height: 1.2;
font-variant-numeric: tabular-nums;
}
.nbu-sw-kpi-hint {
color: var(--tblr-secondary);
font-size: 0.8125rem;
margin-top: 0.25rem;
}
.nbu-sw-kpi-warning {
border-left: 4px solid var(--tblr-danger);
}
.nbu-sw-kpi-warning .nbu-sw-kpi-value {
color: var(--tblr-danger);
}
.nbu-sw-bars li + li {
margin-top: 0.25rem;
}
.nbu-sw-bar-row {
display: grid;
grid-template-columns: minmax(6rem, 13rem) 1fr minmax(5.5rem, auto);
gap: 0.75rem;
align-items: center;
padding: 0.3rem 0.5rem;
border-radius: var(--tblr-border-radius);
color: inherit;
text-decoration: none;
}
.nbu-sw-bar-row:hover,
.nbu-sw-bar-row:focus-visible,
.nbu-sw-bar-row.active {
background: var(--tblr-bg-surface-secondary, rgba(var(--tblr-primary-rgb), 0.06));
color: inherit;
text-decoration: none;
}
.nbu-sw-bar-row.active {
outline: 2px solid rgba(var(--tblr-primary-rgb), 0.5);
}
.nbu-sw-bar-label {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.nbu-sw-bar-track {
height: 0.75rem;
border-radius: 999px;
background: rgba(var(--tblr-secondary-rgb, 108, 122, 145), 0.15);
overflow: hidden;
}
.nbu-sw-bar-fill {
display: block;
height: 100%;
min-width: 2px;
border-radius: 999px;
background: color-mix(in srgb, var(--tblr-primary) var(--nbu-sw-shade, 100%), transparent);
}
.nbu-sw-bar-value {
text-align: right;
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
/* Versionsverteilung als gestapelter Balken, neueste Version links und am kräftigsten */
.nbu-sw-stack {
display: flex;
gap: 2px;
height: 0.75rem;
min-width: 6rem;
border-radius: 999px;
overflow: hidden;
}
.nbu-sw-stack-part {
min-width: 3px;
background: color-mix(in srgb, var(--tblr-primary) var(--nbu-sw-shade, 100%), transparent);
}
.nbu-sw-stack-part.nbu-sw-expired,
.nbu-sw-bar-fill.nbu-sw-expired {
background: repeating-linear-gradient(
135deg,
var(--tblr-danger) 0 4px,
color-mix(in srgb, var(--tblr-danger) 45%, transparent) 4px 8px
);
}
.nbu-sw-sortable {
cursor: pointer;
user-select: none;
white-space: nowrap;
}
.nbu-sw-sortable::after {
content: "\F04BF"; /* mdi-unfold-more-horizontal */
font-family: "Material Design Icons";
margin-left: 0.25rem;
opacity: 0.35;
}
.nbu-sw-sortable[aria-sort="ascending"]::after {
content: "\F0143"; /* mdi-chevron-up */
opacity: 1;
}
.nbu-sw-sortable[aria-sort="descending"]::after {
content: "\F0140"; /* mdi-chevron-down */
opacity: 1;
}
@media (max-width: 575.98px) {
.nbu-sw-bar-row {
grid-template-columns: 1fr minmax(4.5rem, auto);
}
.nbu-sw-bar-row .nbu-sw-bar-track,
.nbu-sw-bar-row .nbu-sw-stack {
grid-column: 1 / -1;
grid-row: 2;
}
}
@@ -0,0 +1,66 @@
// Switch front panel on the device page: moves it above the "Device" and "Management" cards and
// switches between the status and VLAN colours.
(function () {
"use strict";
const STORAGE_KEY = "netbox_utilities.switch_panel_mode";
function relocate(panel) {
// The plugin can only render into a column; place the panel above the row with both columns.
const row = panel.closest(".row");
if (!row || row.dataset.nbuSwitchPanelMoved) return;
row.dataset.nbuSwitchPanelMoved = "true";
const wrapper = document.createElement("div");
wrapper.className = "row mb-3";
const column = document.createElement("div");
column.className = "col col-12";
column.appendChild(panel);
wrapper.appendChild(column);
row.parentNode.insertBefore(wrapper, row);
}
function init() {
const panel = document.querySelector("[data-nbu-switch-panel]");
if (!panel) return;
relocate(panel);
if (window.bootstrap && window.bootstrap.Tooltip) {
panel.querySelectorAll('[data-bs-toggle="tooltip"]').forEach((element) => {
window.bootstrap.Tooltip.getOrCreateInstance(element, { container: "body" });
});
}
function setMode(mode) {
panel.classList.toggle("nbu-switch-vlan", mode === "vlan");
panel.querySelectorAll("[data-nbu-switch-mode]").forEach((button) => {
button.classList.toggle("active", button.dataset.nbuSwitchMode === mode);
});
panel.querySelectorAll("[data-nbu-switch-legend]").forEach((legend) => {
legend.classList.toggle("d-none", legend.dataset.nbuSwitchLegend !== mode);
});
try {
localStorage.setItem(STORAGE_KEY, mode);
} catch (error) {
/* private mode: the choice is just not remembered */
}
}
panel.querySelectorAll("[data-nbu-switch-mode]").forEach((button) => {
button.addEventListener("click", () => setMode(button.dataset.nbuSwitchMode));
});
let saved = "status";
try {
saved = localStorage.getItem(STORAGE_KEY) || "status";
} catch (error) {
/* ignore */
}
setMode(saved === "vlan" ? "vlan" : "status");
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", init);
} else {
init();
}
})();
+453
View File
@@ -0,0 +1,453 @@
"""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"
" · 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",
"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"
" · 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",
"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 = 12.5 * mm
TILE_H = 9.5 * mm
TILE_GAP = 1.2 * mm
OPTICAL_W = 13.5 * mm
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):
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 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
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=6.5, leading=7.8),
"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("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
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'<font size="7" color="#6c757d">{label.upper()}</font>', _styles()["cell"])
for label, _, _ in cells
],
[
Paragraph(f'<font size="14" color="{hex_of(color)}"><b>{value}</b></font>', _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} <font color='#6c757d'>({connected}/{total})</font>"))
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"<b>{t['legend_vlan']}</b>", styles["small"]), Spacer(0, 1 * mm), table]
def _cable_cell(port, t):
if not port.cable_vlans:
return "–"
text = _escape(port.cable_vlan_text)
if port.vlan_mismatch:
text += f" <font color='#fd7e14'><b>⚠ {t['mismatch']}</b></font>"
return text
def _port_table(ports, t, styles):
header = [t["port"], t["status"], t["vlan"], t["vlan_cable"], t["peer"], t["description"], t["type"], t["lag"]]
data = [[Paragraph(f"<b>{text}</b>", styles["cell"]) for text in header]]
style = [
("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#dee2e6")),
("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" <font color='#0d6efd'>[{t['mgmt']}]</font>" 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(_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"]),
Paragraph(_escape(port.lag) or "–", styles["cell"]),
]
)
if port.color:
fill = colors.HexColor(port.color)
# Colour the column the VLAN comes from: the label, or the cable if there is no label.
column = 2 if port.label else 3
text = _escape(port.label) if port.label else _escape(port.cable_vlan_text)
style.append(("BACKGROUND", (column, index), (column, index), fill))
data[index][column] = Paragraph(f"<font color='{hex_of(text_color(fill))}'>{text}</font>", styles["cell"])
if port.state == switch_ports.STATE_DISABLED:
style.append(("TEXTCOLOR", (0, index), (1, index), colors.HexColor("#6c757d")))
width = PAGE[0] - 2 * MARGIN
widths = [w * width for w in (0.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
def build_pdf(device, ports, lang="de", generated=None, members=None):
"""Return the PDF as bytes. ``device`` is a DeviceInfo, ``ports`` a list of switch_ports.Port.
For a switch stack, ``members`` is [(DeviceInfo, ports)] for every stack member including the
switch itself; front panels and port lists are then drawn per member, ``ports`` covers all of them.
"""
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)
units = members or [(device, ports)]
if not any(switch_ports.build_groups(unit_ports) for _, unit_ports in units):
story.append(Paragraph(t["none"], styles["meta"]))
for unit, unit_ports in units:
groups = switch_ports.build_groups(unit_ports)
if members:
story.append(Paragraph(_escape(unit.name), styles["group"]))
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))
# Keep the explanation and the VLAN legend on one page.
story.append(
KeepTogether([Paragraph(t["legend_state"], styles["small"]), Spacer(0, 2 * mm), *_legend(ports, t, styles)])
)
story.append(CondPageBreak(40 * mm))
story.append(Paragraph(t["list"], styles["h2"]))
if members:
for unit, unit_ports in members:
story.append(Paragraph(_escape(unit.name), styles["group"]))
story.append(_port_table(unit_ports, t, styles))
story.append(Spacer(0, 2 * mm))
else:
story.append(_port_table(ports, t, styles))
document.build(story, onFirstPage=footer, onLaterPages=footer)
return buffer.getvalue()
+150
View File
@@ -0,0 +1,150 @@
from dcim.models import Device, Interface
from django.http import HttpResponse
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_port_pdf, switch_ports
from .runtime import connection_vlans_enabled
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 export
endpoints = []
if not endpoints and interface.cable_id:
endpoints = interface.link_peers
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:
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=str(interface.get_type_display()),
enabled=interface.enabled,
connected=bool(interface.cable_id or interface.mark_connected),
mgmt_only=interface.mgmt_only,
description=interface.description,
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,
)
)
return ports
def switch_panel_context(request, device):
"""Front panel above the "Device" and "Management" cards, in the user's NetBox language.
A switch stack shows one front panel per member, one below the other, with shared VLAN colours.
"""
from .switch_stack import stack_units
units = [
{"device": unit, "current": unit.pk == device.pk, "ports": collect_ports(interface_queryset(request, unit))}
for unit in stack_units(device)
]
ports = [port for unit in units for port in unit["ports"]]
switch_ports.assign_vlan_colors(ports)
texts = switch_ports.PANEL_TEXTS[switch_port_pdf.language(translation.get_language())]
for port in ports:
if port.peer == switch_ports.MARKED_CONNECTED:
port.peer = texts["marked"]
port.state_text = texts[port.state]
for unit in units:
unit["groups"] = switch_ports.build_groups(unit["ports"])
return {
"stack": len(units) > 1,
"units": units,
"has_ports": any(unit["groups"] for unit in units),
"groups": units[0]["groups"],
"summary": switch_ports.summary(ports),
"legend": switch_ports.vlan_legend(ports),
"texts": texts,
}
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),
)
class SwitchPortsPDFView(ContentTypePermissionRequiredMixin, View):
"""PDF of the port usage of a switch, in the language of the user's NetBox preferences."""
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
)
from .switch_stack import stack_units
lang = switch_port_pdf.language(translation.get_language())
stack = stack_units(device)
units = [(device_info(unit), collect_ports(interface_queryset(request, unit))) for unit in stack]
ports = [port for _, unit_ports in units for port in unit_ports]
pdf = switch_port_pdf.build_pdf(
device_info(stack[0]),
ports,
lang=lang,
generated=timezone.localtime(),
members=units if len(stack) > 1 else None,
)
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
+363
View File
@@ -0,0 +1,363 @@
"""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",)
# 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"
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")
# Distinct background colours for VLAN labels; the text colour is chosen per colour for contrast.
VLAN_PALETTE = (
"#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
)
# Texts of the front panel on the device page, by NetBox user language.
PANEL_TEXTS = {
"de": {
"title": "Ports",
"this_device": "dieses Gerät",
"status": "Status",
"vlan": "VLAN",
"connected": "Belegt",
"free": "Frei",
"disabled": "Deaktiviert",
"no_label": "ohne Label",
"ports": "Ports",
"export": "PDF exportieren",
"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",
"this_device": "this device",
"status": "Status",
"vlan": "VLAN",
"connected": "Connected",
"free": "Free",
"disabled": "Disabled",
"no_label": "no label",
"ports": "ports",
"export": "Export PDF",
"peer": "Peer",
"marked": "marked as connected",
"none": "No physical interfaces.",
"vlan_label": "VLAN (label)",
"vlan_cable": "VLAN (cable)",
"mismatch": "Label and cable VLAN differ",
},
}
# Out-of-band management ports by name, e.g. "mgmt", "Management", "mgmt0", "oobm", "me0", "MgmtEth0/RP0/CPU0/0".
_MGMT_NAME = re.compile(r"(?i)^(mgmt|management|oobm|me0|fxp0|em0|ma1|mgmteth)")
_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"))
# "(LAG 1)" in a port label names the LAG of the port (written by NetBox Synchronizer), not a VLAN.
_LAG_NOTE = re.compile(r"(?i)\s*\(\s*LAG\s*\d+\s*\)")
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 ink_for(hex_color):
""" "#000000" or "#ffffff", whichever has the higher WCAG contrast against the colour."""
value = hex_color.lstrip("#")
red, green, blue = (int(value[index : index + 2], 16) / 255 for index in (0, 2, 4))
def channel(component):
return component / 12.92 if component <= 0.03928 else ((component + 0.055) / 1.055) ** 2.4
luminance = 0.2126 * channel(red) + 0.7152 * channel(green) + 0.0722 * channel(blue)
return "#000000" if (luminance + 0.05) / 0.05 >= 1.05 / (luminance + 0.05) else "#ffffff"
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
# Set by assign_vlan_colors(); otherwise the colour comes from a hash of the label.
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):
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 is_management(self):
return self.mgmt_only or bool(_MGMT_NAME.match(self.name or ""))
@property
def short(self):
"""Text inside the tile: the port number, "MGMT" for management ports, else a shortened name."""
if self.is_management:
return "MGMT"
number = self.number
if number is not None:
return str(number)
return (self.name or "")[:5]
@property
def vlan(self):
"""The VLAN shown for the port: the label, or the VLANs of its cable if it has no label."""
return vlan_key(self.vlan_text) or self.cable_vlan_key
@property
def vlan_text(self):
"""The label without a LAG note: "10,20 (LAG 1)" → "10,20"."""
return _LAG_NOTE.sub("", self.label or "").strip()
@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.vlan_text or not self.cable_vlans:
return False
label_ids = {int(number) for number in _NATURAL.findall(self.vlan_text) if number.isdigit()}
return bool(label_ids) and label_ids != {vid for vid, _ in self.cable_vlans}
@property
def ink(self):
"""Text colour (black or white) that contrasts best with the VLAN colour."""
return ink_for(self.color) if self.color else ""
@property
def color(self):
if not self.vlan:
return None
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.vlan_text:
numbers = [number for number in _NATURAL.findall(self.vlan_text) if number.isdigit()]
return str(int(numbers[0])) if len(numbers) == 1 else vlan_key(self.vlan_text)
return self.cable_vlan_key
@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)
MGMT_GROUP = ("__mgmt__", False)
def build_groups(ports):
"""Physical ports grouped by name prefix and medium, in natural order."""
groups = {}
for port in ports:
if port.virtual:
continue
if port.is_management:
# All management ports in one small group at the end.
groups.setdefault(MGMT_GROUP, PortGroup(title="Management", optical=False)).ports.append(port)
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)
management = groups.get(MGMT_GROUP)
return sorted(
groups.values(),
key=lambda group: (group is management, 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 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.
"""
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_group:
port.assigned_color = colors.get(port.vlan_group, "")
return colors
def vlan_legend(ports):
"""[(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
group = port.vlan_group
colors.setdefault(group, port.color)
if port.vlan_text 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 = [(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]))
return legend
+102
View File
@@ -0,0 +1,102 @@
from types import SimpleNamespace
from django import forms
from django.core.exceptions import ValidationError
from .models import SwitchStack
STACK_FORM_FIELDS = ("utilities_switch_stack", "utilities_stack_members")
def stack_members(device):
"""Member devices of the stack represented by the device, in natural name order; [] if it is no stack."""
from .switch_ports import natural_key
if device is None or not device.pk:
return []
stack = SwitchStack.objects.filter(device=device).first()
if stack is None:
return []
members = stack.members.exclude(pk=device.pk).select_related("role", "site", "rack", "device_type")
return sorted(members, key=lambda member: natural_key(member.name or str(member)))
def stack_units(device):
"""[stack switch, *members] for a stack switch or one of its members; [device] outside a stack."""
if device is None or not device.pk:
return [device]
stack = (
SwitchStack.objects.filter(device=device).select_related("device").first()
or SwitchStack.objects.filter(members=device).select_related("device").first()
)
if stack is None:
return [device]
return [stack.device, *stack_members(stack.device)]
def build_stack_form_mixin():
from dcim.models import Device
from utilities.forms.fields import DynamicModelMultipleChoiceField
class SwitchStackFormMixin(forms.Form):
utilities_switch_stack = forms.BooleanField(
label="Switch-Stack",
required=False,
help_text="Dieser Switch steht für einen Stack; die Mitglieder werden in der Ports-Übersicht "
"untereinander abgebildet.",
)
utilities_stack_members = DynamicModelMultipleChoiceField(
label="Stack-Mitglieder",
queryset=Device.objects.all(),
required=False,
query_params={"role_id": "$role"},
help_text="Weitere Switches des Stacks (dieser Switch ist immer das erste Mitglied).",
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if not self._is_switch_form():
for name in STACK_FORM_FIELDS:
self.fields.pop(name, None)
return
if not self.is_bound and self.instance.pk:
members = stack_members(self.instance)
self.initial["utilities_switch_stack"] = SwitchStack.objects.filter(device=self.instance).exists()
self.initial["utilities_stack_members"] = [member.pk for member in members]
def _is_switch_form(self):
"""Stack options only belong to switches (role chosen in the form, else the saved role)."""
from dcim.models import DeviceRole
from .switch_ports import is_switch
role = None
role_id = (self.data.get("role") if self.is_bound else None) or self.initial.get("role")
if role_id:
role = DeviceRole.objects.filter(pk=getattr(role_id, "pk", role_id)).first()
if role is None and self.instance.pk:
role = getattr(self.instance, "role", None)
return is_switch(SimpleNamespace(role=role))
def clean(self):
super().clean()
members = list(self.cleaned_data.get("utilities_stack_members") or [])
if self.instance.pk and any(member.pk == self.instance.pk for member in members):
self.add_error("utilities_stack_members", ValidationError("Der Switch kann nicht sein eigenes Mitglied sein."))
return self.cleaned_data
def save(self, commit=True):
device = super().save(commit=commit)
if commit and "utilities_switch_stack" in self.fields:
save_stack(device, self.cleaned_data.get("utilities_switch_stack"), self.cleaned_data.get("utilities_stack_members"))
return device
return SwitchStackFormMixin
def save_stack(device, is_stack, members):
if not is_stack:
SwitchStack.objects.filter(device=device).delete()
return
stack, _ = SwitchStack.objects.get_or_create(device=device)
stack.members.set([member for member in members or [] if member.pk != device.pk])
+63
View File
@@ -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
@@ -21,8 +22,10 @@ from .navigation_helpers import (
)
from .runtime import (
connection_vlans_enabled,
hardware_enabled,
navigation_customization_enabled,
offline_svg_export_enabled,
switch_ports_enabled,
tenant_filter_enabled,
)
@@ -93,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"):
@@ -109,6 +126,21 @@ class DeviceUtilitiesContent(PluginTemplateExtension):
return ""
return self.render("netbox_utilities/device_bulk_module_button.html")
def left_page(self):
# Rendered into the left column; switch_panel.js moves it above the "Device" and "Management" cards.
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_ports
from .switch_port_views import switch_panel_context
if not switch_ports.is_switch(device):
return ""
return self.render(
"netbox_utilities/device_switch_panel.html",
{**switch_panel_context(request, device), "asset_version": __version__},
)
def right_page(self):
placement = DeviceRackPlacement.objects.filter(device=self.context["object"]).first()
if placement is None:
@@ -122,6 +154,35 @@ class DeviceUtilitiesContent(PluginTemplateExtension):
)
class ClusterHardwareContent(PluginTemplateExtension):
models = ["virtualization.cluster"]
def full_width_page(self):
request = self.context["request"]
if not hardware_enabled() or not request.user.has_perm("netbox_utilities.view_devicehardware"):
return ""
from .hardware_views import cluster_capacity_context
return self.render(
"netbox_utilities/cluster_capacity_panel.html", cluster_capacity_context(request, self.context["object"])
)
class VirtualMachineHardwareContent(PluginTemplateExtension):
models = ["virtualization.virtualmachine"]
def right_page(self):
request = self.context["request"]
if not hardware_enabled() or not request.user.has_perm("netbox_utilities.view_devicehardware"):
return ""
from .hardware_views import vm_host_context
vm = self.context["object"]
if vm.device_id is None and vm.cluster_id is None:
return ""
return self.render("netbox_utilities/vm_host_panel.html", vm_host_context(request, vm))
class ConnectionVLANContent(PluginTemplateExtension):
models = ["dcim.cable", "wireless.wirelesslink"]
@@ -174,4 +235,6 @@ template_extensions = [
DeviceUtilitiesContent,
ConnectionVLANContent,
RackUtilitiesContent,
ClusterHardwareContent,
VirtualMachineHardwareContent,
]
@@ -0,0 +1,134 @@
<div class="card">
<h2 class="card-header d-flex align-items-center">
<span class="me-auto"><i class="mdi mdi-chip me-1" aria-hidden="true"></i>Kapazität (CPU &amp; RAM)</span>
<a href="{{ hardware_list_url }}" class="btn btn-sm btn-outline-secondary">Hardware-Liste</a>
</h2>
{% if not rows %}
<div class="card-body text-muted">Dem Cluster sind keine Hosts (Geräte) zugeordnet.</div>
{% else %}
<div class="card-body pb-0">
<div class="row g-3">
{# Hosts #}
<div class="col-6 col-xl-3">
<div class="border rounded p-3 h-100">
<div class="text-muted small text-uppercase">Hosts</div>
<div class="fs-3 fw-semibold lh-sm">{{ rows|length }}</div>
<div class="small text-muted">
{% if capacity.cores %}{{ capacity.cores }} Kerne · {{ capacity.threads }} Threads · {{ memory }}{% else %}keine CPU erfasst{% endif %}
</div>
</div>
</div>
{# vCPU ratio #}
<div class="col-6 col-xl-3">
<div class="border rounded p-3 h-100">
<div class="text-muted small text-uppercase">vCPU : Kern</div>
<div class="fs-3 fw-semibold lh-sm text-{{ cluster_ratio_level }}">{{ vcpu_per_core }}</div>
<div class="small text-muted">
{{ capacity.vcpus|floatformat:"-1" }} vCPUs in {{ capacity.vm_count }} VM{{ capacity.vm_count|pluralize:",s" }}
{% if ratio_limit %}· Grenze {{ ratio_limit }} : 1{% endif %}
</div>
</div>
</div>
{# RAM #}
<div class="col-6 col-xl-3">
<div class="border rounded p-3 h-100">
<div class="text-muted small text-uppercase">RAM belegt</div>
<div class="fs-3 fw-semibold lh-sm text-{{ cluster_memory_level }}">
{% if capacity.memory_percent is not None %}{{ capacity.memory_percent }} %{% else %}—{% endif %}
</div>
<div class="progress my-1" style="height: .4rem">
<div class="progress-bar bg-{{ cluster_memory_level }}" style="width: {{ cluster_memory_bar }}%"></div>
</div>
<div class="small text-muted">{{ vm_memory }} von {{ memory }}</div>
</div>
</div>
{# N+1 #}
<div class="col-6 col-xl-3">
<div class="border rounded p-3 h-100">
<div class="text-muted small text-uppercase">Ausfall größter Host (N+1)</div>
{% if capacity.failover_memory_gb is None %}
<div class="fs-3 fw-semibold lh-sm text-muted">—</div>
<div class="small text-muted">braucht mindestens 2 Hosts mit erfasstem RAM</div>
{% else %}
<div class="fs-3 fw-semibold lh-sm text-{% if capacity.failover_ok %}success{% else %}warning{% endif %}">
{% if capacity.failover_ok %}OK{% else %}Nicht erfüllt{% endif %}
</div>
<div class="small text-muted">{{ failover_memory }} verbleiben · {{ vm_memory }} benötigt</div>
{% endif %}
</div>
</div>
</div>
{% if capacity_warnings %}
<div class="alert alert-warning mt-3 mb-0 py-2">
<ul class="mb-0 ps-3 small">
{% for level, text in capacity_warnings %}<li>{{ text }}</li>{% endfor %}
</ul>
</div>
{% endif %}
</div>
<div class="table-responsive mt-3">
<table class="table table-hover align-middle mb-0">
<thead>
<tr>
<th>Host</th>
<th>CPU</th>
<th class="text-end">Kerne / Threads</th>
<th class="text-end">RAM</th>
<th>VMs</th>
<th class="text-end">vCPU : Kern</th>
<th style="min-width: 11rem">RAM belegt</th>
</tr>
</thead>
<tbody>
{% for row in rows %}
<tr>
<td class="text-nowrap"><a href="{{ row.device.get_absolute_url }}">{{ row.device }}</a></td>
<td class="small">
{% if row.record and row.record.cpu %}{{ row.record.cpu_display }}
{% elif can_add %}<a href="{% url 'plugins:netbox_utilities:devicehardware_add' %}?device={{ row.device.pk }}&return_url={{ request.path|urlencode }}" class="text-warning"><i class="mdi mdi-plus-circle-outline"></i> erfassen</a>
{% else %}<span class="text-warning">fehlt</span>{% endif %}
</td>
<td class="text-end text-nowrap">{% if row.host.cores %}{{ row.host.cores }} / {{ row.host.threads }}{% else %}—{% endif %}</td>
<td class="text-end text-nowrap">{{ row.memory }}</td>
<td class="text-nowrap">
{% if row.host.vm_count or row.host.total_vcpus %}
{{ row.host.vm_count }} VM{{ row.host.vm_count|pluralize:",s" }}{% if row.host.shared_vcpus or row.host.shared_memory_gb %} <span class="badge text-bg-light border">+ anteilig</span>{% endif %}
<span class="text-muted small">· {{ row.host.total_vcpus|floatformat:"-1" }} vCPU · {{ row.vm_memory }}</span>
{% else %}
<span class="text-muted">keine VMs</span>
{% endif %}
</td>
<td class="text-end text-nowrap">
{% if row.host.cores %}<span class="fw-semibold text-{{ row.ratio_level }}">{{ row.vcpu_per_core }}</span>{% else %}—{% endif %}
</td>
<td>
{% if row.memory_percent is not None %}
<div class="d-flex align-items-center gap-2">
<div class="progress flex-grow-1" style="height: .5rem">
<div class="progress-bar bg-{{ row.memory_level }}" style="width: {{ row.memory_bar }}%"></div>
</div>
<span class="small text-nowrap" style="min-width: 2.75rem">{{ row.memory_percent }} %</span>
</div>
{% else %}—{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="card-footer small text-muted">
Gezählt werden alle VMs außer „Offline“ und „Außer Betrieb“.
{% if capacity.distributed %}
VMs ohne festen Host sind anteilig nach Größe auf die Hosts verteilt: vCPUs nach Threads, RAM nach Host-RAM
(zu gleichen Teilen, wenn bei keinem Host CPU/RAM erfasst ist).
{% elif capacity.unplaced_vm_count %}
{{ capacity.unplaced_vm_count }} VM{{ capacity.unplaced_vm_count|pluralize:",s" }} ohne festen Host
{{ capacity.unplaced_vm_count|pluralize:"zählt,zählen" }} nur zur Cluster-Summe: Im Cluster sind VMs fest Hosts
zugewiesen, deshalb wird nicht automatisch verteilt.
{% endif %}
</div>
{% endif %}
</div>
@@ -0,0 +1,46 @@
{% extends 'generic/object.html' %}
{% load helpers %}
{% load render_table from django_tables2 %}
{% block content %}
<div class="row mb-3">
<div class="col col-12 col-xl-6">
<div class="card">
<h2 class="card-header">CPU-Modell</h2>
<table class="table table-hover attr-table">
<tr><th scope="row">Hersteller</th><td>{{ object.get_manufacturer_display }}</td></tr>
<tr><th scope="row">Modell</th><td>{{ object.name }}</td></tr>
<tr><th scope="row">Familie</th><td>{{ object.family|placeholder }}</td></tr>
<tr><th scope="row">Sockel</th><td>{{ object.socket|placeholder }}</td></tr>
<tr><th scope="row">Erscheinungsjahr</th><td>{{ object.launch_year|placeholder }}</td></tr>
<tr><th scope="row">Max. Sockel</th><td>{{ object.max_sockets }}</td></tr>
<tr><th scope="row">Beschreibung</th><td>{{ object.description|placeholder }}</td></tr>
<tr>
<th scope="row">Herkunft</th>
<td>
{% if object.builtin %}Katalog{% if object.customized %} <span class="badge text-bg-warning">angepasst</span>{% endif %}
{% else %}Selbst angelegt{% endif %}
</td>
</tr>
</table>
</div>
{% include 'inc/panels/tags.html' %}
{% include 'inc/panels/custom_fields.html' %}
</div>
<div class="col col-12 col-xl-6">
<div class="card">
<h2 class="card-header">Leistung</h2>
<table class="table table-hover attr-table">
<tr><th scope="row">Kerne</th><td>{{ object.cores }}</td></tr>
<tr><th scope="row">Threads</th><td>{{ object.threads }}</td></tr>
<tr><th scope="row">Takt (Basis / Turbo)</th><td>{{ object.clock_display }}</td></tr>
<tr><th scope="row">TDP</th><td>{% if object.tdp_watts %}{{ object.tdp_watts }} W{% else %}{{ ""|placeholder }}{% endif %}</td></tr>
</table>
</div>
</div>
</div>
<div class="card">
<h2 class="card-header">Geräte mit diesem Modell <span class="badge text-bg-secondary">{{ device_count }}</span></h2>
<div class="table-responsive">{% render_table devices_table 'inc/table.html' %}</div>
</div>
{% endblock content %}
@@ -116,6 +116,11 @@
<a href="{% url 'plugins:netbox_utilities:disk_list' %}?device_id={{ object.pk }}" class="btn btn-sm btn-outline-secondary">
<i class="mdi mdi-table" aria-hidden="true"></i> Liste &amp; Export
</a>
{% if perms.netbox_utilities.add_disk %}
<a href="{% url 'plugins:netbox_utilities:disk_msa_import' %}" class="btn btn-sm btn-outline-secondary" title="Datenträger-Export einer HPE MSA importieren">
<i class="mdi mdi-database-import" aria-hidden="true"></i> MSA-Import
</a>
{% endif %}
</div>
<div id="nbu-disk-bays"
@@ -99,6 +99,16 @@
{% render_field form.vc_priority %}
</div>
{% if "utilities_switch_stack" in form.fields %}
<div class="field-group my-5">
<div class="row">
<h2 class="col-9 offset-3">Switch-Stack</h2>
</div>
{% render_field form.utilities_switch_stack %}
{% render_field form.utilities_stack_members %}
</div>
{% endif %}
<div class="field-group mb-5">
<div class="row">
<h2 class="col-9 offset-3">{% trans "Ownership" %}</h2>
@@ -0,0 +1,75 @@
{% extends 'dcim/device/base.html' %}
{% block content %}
{% if not supported and not record %}
<div class="alert alert-info">
CPU &amp; RAM werden für Geräte mit den konfigurierten Rollen (z. B. Server) und für Cluster-Hosts gepflegt.
</div>
{% endif %}
<div class="row mb-3">
<div class="col col-12 col-xl-6">
<div class="card">
<h2 class="card-header d-flex align-items-center">
<span class="me-auto"><i class="mdi mdi-chip me-1" aria-hidden="true"></i>CPU &amp; RAM</span>
{% if record and can_change %}
<a href="{% url 'plugins:netbox_utilities:devicehardware_edit' pk=record.pk %}?return_url={{ request.path|urlencode }}" class="btn btn-sm btn-outline-secondary">
<i class="mdi mdi-pencil" aria-hidden="true"></i> Bearbeiten
</a>
{% elif not record and can_add %}
<a href="{{ add_url }}" class="btn btn-sm btn-primary"><i class="mdi mdi-plus-thick" aria-hidden="true"></i> Erfassen</a>
{% endif %}
</h2>
{% if record %}
{% include 'netbox_utilities/inc/hardware_record.html' %}
{% else %}
<div class="card-body text-muted">Noch keine CPU und kein RAM erfasst.</div>
{% endif %}
</div>
</div>
<div class="col col-12 col-xl-6">
{% if capacity %}
<div class="card">
<h2 class="card-header d-flex align-items-center">
<span class="me-auto"><i class="mdi mdi-server-network me-1" aria-hidden="true"></i>Virtualisierung</span>
{% if object.cluster %}<a href="{{ object.cluster.get_absolute_url }}" class="btn btn-sm btn-outline-secondary">Cluster {{ object.cluster }}</a>{% endif %}
</h2>
{% include 'netbox_utilities/inc/hardware_capacity.html' %}
</div>
{% endif %}
</div>
</div>
{% if capacity %}
<div class="card">
<h2 class="card-header d-flex align-items-center">
<span class="me-auto">VMs auf diesem Host <span class="badge text-bg-secondary">{{ vms|length }}</span></span>
<a href="{{ vm_list_url }}" class="btn btn-sm btn-outline-secondary">In der VM-Liste öffnen</a>
</h2>
{% if vms %}
<div class="table-responsive">
<table class="table table-hover table-sm align-middle mb-0">
<thead><tr><th>Name</th><th>Status</th><th>vCPUs</th><th>RAM</th><th>Mandant</th></tr></thead>
<tbody>
{% for vm in vms %}
<tr>
<td><a href="{{ vm.get_absolute_url }}">{{ vm }}</a></td>
<td><span class="badge text-bg-{{ vm.get_status_color }}">{{ vm.get_status_display }}</span></td>
<td>{{ vm.vcpus|floatformat:"-1"|default:"—" }}</td>
<td>{% if vm.memory %}{{ vm.memory }} MB{% else %}—{% endif %}</td>
<td>{% if vm.tenant %}<a href="{{ vm.tenant.get_absolute_url }}">{{ vm.tenant }}</a>{% else %}—{% endif %}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<div class="card-body text-muted">Keine VMs mit diesem Gerät als Host.</div>
{% endif %}
{% if capacity.distributed and capacity.unplaced_vm_count %}
<div class="card-footer small text-muted">
Die Liste zeigt nur VMs, deren Gerät dieser Host ist. {{ capacity.unplaced_vm_count }} weitere VM{{ capacity.unplaced_vm_count|pluralize:",s" }}
des Clusters ohne festen Host {{ capacity.unplaced_vm_count|pluralize:"ist,sind" }} anteilig in der Auslastung enthalten.
</div>
{% endif %}
</div>
{% endif %}
{% endblock content %}
@@ -0,0 +1,77 @@
{% extends 'dcim/device/base.html' %}
{% load helpers %}
{% block content %}
<div class="card">
<div class="card-header d-flex flex-wrap gap-2 align-items-center">
<h2 class="card-title me-auto mb-0">
<i class="mdi mdi-package-variant me-1" aria-hidden="true"></i>Installierte Software
<span class="badge text-bg-secondary ms-1">{{ entries|length }}</span>
</h2>
{% if entries|length > 8 %}
<input type="search" class="form-control form-control-sm w-auto" data-nbu-sw-search="#nbu-sw-device-software"
placeholder="Software filtern …" aria-label="Software filtern">
{% endif %}
<a href="{{ overview_url }}" class="btn btn-sm btn-outline-secondary" title="Client Software Übersicht für den Mandanten dieses Geräts">
<i class="mdi mdi-chart-bar" aria-hidden="true"></i> Übersicht{% if object.tenant %} {{ object.tenant }}{% endif %}
</a>
{% if can_add %}
<a href="{{ add_url }}" class="btn btn-sm btn-primary"><i class="mdi mdi-plus-thick" aria-hidden="true"></i> Software hinzufügen</a>
{% endif %}
</div>
{% if entries %}
<div class="table-responsive">
<table class="table table-hover table-vcenter mb-0" id="nbu-sw-device-software">
<thead>
<tr>
<th data-nbu-sort="text">Software</th>
<th data-nbu-sort="text">Hersteller</th>
<th data-nbu-sort="text">Version</th>
<th>Release</th>
<th data-nbu-sort="text">Support-Ende</th>
<th></th>
</tr>
</thead>
<tbody>
{% for entry in entries %}
{% with product=entry.software_product version=entry.version %}
<tr>
<td><a href="{{ product.get_absolute_url }}" class="fw-bold">{{ product }}</a></td>
<td>{{ product.manufacturer|placeholder }}</td>
<td><a href="{{ version.get_absolute_url }}">{{ version }}</a></td>
<td>{{ version.get_release_type_display|placeholder }}</td>
<td>
{% if version.end_of_support %}
{% if version.end_of_support < today %}
<span class="badge text-bg-danger" title="Support abgelaufen">{{ version.end_of_support|isodate }}</span>
{% else %}{{ version.end_of_support|isodate }}{% endif %}
{% else %}<span class="text-muted">—</span>{% endif %}
</td>
<td class="text-end text-nowrap">
{% if can_change %}
<a href="{% url 'plugins:netbox_slm:softwareproductinstallation_edit' pk=entry.pk %}?return_url={{ tab_url|urlencode }}" class="btn btn-sm btn-warning" title="Bearbeiten">
<i class="mdi mdi-pencil" aria-hidden="true"></i>
</a>
{% endif %}
{% if can_delete %}
<a href="{% url 'plugins:netbox_slm:softwareproductinstallation_delete' pk=entry.pk %}?return_url={{ tab_url|urlencode }}" class="btn btn-sm btn-danger" title="Entfernen">
<i class="mdi mdi-trash-can-outline" aria-hidden="true"></i>
</a>
{% endif %}
</td>
</tr>
{% endwith %}
{% endfor %}
</tbody>
</table>
</div>
{% else %}
<div class="card-body text-center text-muted py-5">
<i class="mdi mdi-package-variant-closed mdi-48px d-block mb-2" aria-hidden="true"></i>
Für dieses Gerät ist noch keine Software erfasst.
{% if can_add %}<div class="mt-3"><a href="{{ add_url }}" class="btn btn-primary"><i class="mdi mdi-plus-thick" aria-hidden="true"></i> Software hinzufügen</a></div>{% endif %}
</div>
{% endif %}
</div>
{% include 'netbox_utilities/inc/software_table_js.html' %}
{% endblock %}
@@ -0,0 +1,69 @@
{% load static %}
<div class="card nbu-switch-card" data-nbu-switch-panel>
<div class="card-header d-flex flex-wrap align-items-center gap-2">
<h2 class="card-title mb-0 me-auto"><i class="mdi mdi-switch me-1" aria-hidden="true"></i>{{ texts.title }}</h2>
<span class="small text-muted">
{{ summary.total }} {{ texts.ports }} ·
<span class="text-success fw-semibold">{{ summary.connected }} {{ texts.connected }}</span> ·
{{ summary.free }} {{ texts.free }} ·
{{ summary.disabled }} {{ texts.disabled }}
</span>
<div class="btn-group btn-group-sm" role="group">
<button type="button" class="btn btn-outline-secondary active" data-nbu-switch-mode="status">{{ texts.status }}</button>
<button type="button" class="btn btn-outline-secondary" data-nbu-switch-mode="vlan">{{ texts.vlan }}</button>
</div>
<a href="{% url 'plugins:netbox_utilities:device_switch_ports_pdf' pk=object.pk %}" class="btn btn-sm btn-outline-secondary">
<i class="mdi mdi-file-pdf-box" aria-hidden="true"></i> {{ texts.export }}
</a>
</div>
<div class="card-body">
{% if not has_ports %}
<span class="text-muted">{{ texts.none }}</span>
{% else %}
{% for unit in units %}
{% if stack %}
<div class="nbu-stack-member small fw-semibold mb-2{% if not forloop.first %} mt-3{% endif %}">
<a href="{{ unit.device.get_absolute_url }}">{{ unit.device }}</a>{% if unit.current %} <span class="badge text-bg-secondary">{{ texts.this_device }}</span>{% endif %}
</div>
{% endif %}
<div class="nbu-faceplate">
{% for group in unit.groups %}
<div class="nbu-faceplate-group">
<div class="nbu-faceplate-label">{{ group.title }}</div>
<div class="nbu-faceplate-ports">
{% for column in group.columns %}
<div class="nbu-faceplate-column">
{% for port in column %}
<a href="{{ port.url }}"
class="nbu-jack nbu-jack-{{ port.state }}{% if group.optical %} nbu-jack-sfp{% endif %}{% if port.color %} nbu-jack-labelled{% endif %}{% if port.is_management %} nbu-jack-mgmt{% endif %}{% if port.vlan_mismatch %} nbu-jack-mismatch{% endif %}"
{% if port.color %}style="--nbu-vlan: {{ port.color }}; --nbu-ink: {{ port.ink }}"{% endif %}
data-bs-toggle="tooltip" data-bs-html="true"
title="<strong>{{ port.name|force_escape }}</strong><br>{{ port.state_text }}{% if port.label %}<br>{{ texts.vlan_label }}: {{ port.label|force_escape }}{% endif %}{% if port.cable_vlans %}<br>{{ texts.vlan_cable }}: {{ port.cable_vlan_text|force_escape }}{% endif %}{% if port.vlan_mismatch %}<br><span class='text-warning'>⚠ {{ texts.mismatch }}</span>{% endif %}{% if port.peer %}<br>{{ texts.peer }}: {{ port.peer|force_escape }}{% endif %}{% if port.description %}<br><em>{{ port.description|force_escape }}</em>{% endif %}">
<span class="nbu-jack-number">{{ port.short }}</span>
<span class="nbu-jack-vlan">{{ port.vlan }}</span>
</a>
{% endfor %}
</div>
{% endfor %}
</div>
</div>
{% endfor %}
</div>
{% endfor %}
<div class="nbu-switch-legend small mt-2" data-nbu-switch-legend="status">
<span><span class="nbu-jack-swatch nbu-jack-connected"></span>{{ texts.connected }}</span>
<span><span class="nbu-jack-swatch nbu-jack-free"></span>{{ texts.free }}</span>
<span><span class="nbu-jack-swatch nbu-jack-disabled"></span>{{ texts.disabled }}</span>
</div>
<div class="nbu-switch-legend small mt-2 d-none" data-nbu-switch-legend="vlan">
{% for vlan, color, total, connected in legend %}
<span>
<span class="nbu-jack-swatch" style="background: {{ color|default:'#6c757d' }}"></span>{{ vlan|default:texts.no_label }}
<span class="text-muted">({{ connected }}/{{ total }})</span>
</span>
{% endfor %}
</div>
{% endif %}
</div>
</div>
<script src="{% static 'netbox_utilities/switch_panel.js' %}?v={{ asset_version }}" defer></script>
@@ -0,0 +1,4 @@
<a href="{% url 'plugins:netbox_utilities:device_switch_ports_pdf' pk=object.pk %}" class="btn btn-outline-secondary">
<i class="mdi mdi-file-pdf-box" aria-hidden="true"></i>
{{ label }}
</a>
@@ -0,0 +1,31 @@
{% extends 'generic/object.html' %}
{% load helpers %}
{% block content %}
<div class="row mb-3">
<div class="col col-12 col-xl-6">
<div class="card">
<h2 class="card-header">Gerät</h2>
<table class="table table-hover attr-table mb-0">
<tr><th scope="row">Gerät</th><td>{{ object.device|linkify }}</td></tr>
<tr><th scope="row">Cluster</th><td>{{ object.device.cluster|linkify|placeholder }}</td></tr>
</table>
</div>
<div class="card">
<h2 class="card-header">CPU &amp; RAM</h2>
{% include 'netbox_utilities/inc/hardware_record.html' with record=object %}
</div>
{% include 'inc/panels/tags.html' %}
{% include 'inc/panels/custom_fields.html' %}
{% include 'inc/panels/comments.html' %}
</div>
<div class="col col-12 col-xl-6">
{% if capacity %}
<div class="card">
<h2 class="card-header">Virtualisierung</h2>
{% include 'netbox_utilities/inc/hardware_capacity.html' %}
</div>
{% endif %}
</div>
</div>
{% endblock content %}
@@ -0,0 +1,231 @@
{% extends 'base/layout.html' %}
{% block title %}HPE-MSA-Export importieren{% endblock %}
{% block content %}
<div class="row mb-3">
<div class="col col-xl-10 offset-xl-1">
<ol class="nbu-msa-steps list-inline small text-muted mb-3">
<li class="list-inline-item{% if step == 'upload' %} fw-bold text-body{% endif %}">1. Export hochladen</li>
<li class="list-inline-item">›</li>
<li class="list-inline-item{% if step == 'assign' %} fw-bold text-body{% endif %}">2. Shelfs zuordnen</li>
<li class="list-inline-item">›</li>
<li class="list-inline-item{% if step == 'plan' %} fw-bold text-body{% endif %}">3. Prüfen &amp; importieren</li>
</ol>
{% if parse_errors %}
<div class="alert alert-warning">
<strong>Einige Zeilen wurden ignoriert:</strong>
<ul class="mb-0">{% for error in parse_errors %}<li>{{ error }}</li>{% endfor %}</ul>
</div>
{% endif %}
{% if step == 'upload' %}
<form method="post" action="{% url 'plugins:netbox_utilities:disk_msa_import' %}" enctype="multipart/form-data" class="card">
{% csrf_token %}
<input type="hidden" name="step" value="upload">
<h2 class="card-header"><i class="mdi mdi-database-import me-1" aria-hidden="true"></i>HPE-MSA-Export importieren</h2>
<div class="card-body">
<p class="text-muted">
In der MSA-Oberfläche unter <em>Pools → Disks</em> (bzw. <em>System → Disks</em>) die Liste als CSV exportieren.
Die Spalte <em>Location</em> (z. B. <code>1.4</code>) enthält Shelf und Steckplatz.
</p>
{% if upload_form.non_field_errors %}<div class="alert alert-danger">{{ upload_form.non_field_errors }}</div>{% endif %}
<div class="mb-3">
<label class="form-label" for="{{ upload_form.export_file.id_for_label }}">{{ upload_form.export_file.label }}</label>
{{ upload_form.export_file }}
</div>
<div class="mb-3">
<label class="form-label" for="{{ upload_form.export_text.id_for_label }}">{{ upload_form.export_text.label }}</label>
{{ upload_form.export_text }}
</div>
<div class="text-end">
<button type="submit" class="btn btn-primary">Weiter</button>
</div>
</div>
</form>
{% elif step == 'groups' %}
<form method="post" action="{% url 'plugins:netbox_utilities:disk_msa_import' %}">
{% csrf_token %}
<input type="hidden" name="step" value="groups">
<input type="hidden" name="export_data" value="{{ export_data }}">
{% if group_form.non_field_errors %}<div class="alert alert-danger">{{ group_form.non_field_errors }}</div>{% endif %}
<div class="card mb-3">
<h2 class="card-header"><i class="mdi mdi-layers-triple me-1" aria-hidden="true"></i>Disk Groups → RAID-Gruppen</h2>
<div class="card-body">
<p class="text-muted">
Das ist der Disk-Group-Export der MSA. RAID-Level und Pool werden bei den RAID-Gruppen gleichen Namens
auf den gewählten Geräten gesetzt. Am besten zuerst den Datenträger-Export importieren, dann diesen.
</p>
<div class="table-responsive mb-3">
<table class="table table-sm table-hover align-middle mb-0">
<thead><tr><th>Name</th><th>RAID-Level (MSA)</th><th>Wird zu</th><th>Pool</th><th>Größe</th><th>Datenträger</th><th>Health</th><th>Vorhanden auf</th></tr></thead>
<tbody>
{% for row in rows %}
<tr>
<td class="fw-bold">{{ row.group.name }}</td>
<td>{{ row.group.level_text }}</td>
<td>{% if row.group.level == 'other' %}<span class="badge text-bg-warning">{{ row.level_label }}</span>{% else %}{{ row.level_label }}{% endif %}</td>
<td>{{ row.group.pool|default:"—" }}</td>
<td>{{ row.group.size }}</td>
<td>{{ row.group.disk_count|default:"—" }}</td>
<td>{% if row.group.health and row.group.health != 'OK' %}<span class="badge text-bg-danger">{{ row.group.health }}</span>{% else %}{{ row.group.health }}{% endif %}</td>
<td class="small">{% for group in row.existing %}<a href="{{ group.get_absolute_url }}">{{ group.device }}</a>{% if not forloop.last %}, {% endif %}{% empty %}<span class="text-muted">noch nicht angelegt</span>{% endfor %}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="mb-3">
<label class="form-label required" for="{{ group_form.devices.id_for_label }}">{{ group_form.devices.label }}</label>
{{ group_form.devices }}
<div class="form-text">{{ group_form.devices.help_text }}</div>
{% for error in group_form.devices.errors %}<div class="text-danger small">{{ error }}</div>{% endfor %}
</div>
<div class="form-check form-switch">
{{ group_form.create_missing }}
<label class="form-check-label" for="{{ group_form.create_missing.id_for_label }}">{{ group_form.create_missing.label }}</label>
<div class="form-text">{{ group_form.create_missing.help_text }}</div>
</div>
</div>
</div>
<div class="text-end">
<a href="{% url 'plugins:netbox_utilities:disk_msa_import' %}" class="btn btn-outline-secondary">Andere Datei</a>
<button type="submit" class="btn btn-primary"><i class="mdi mdi-check" aria-hidden="true"></i> Übernehmen</button>
</div>
</form>
{% else %}
<form method="post" action="{% url 'plugins:netbox_utilities:disk_msa_import' %}">
{% csrf_token %}
<input type="hidden" name="export_data" value="{{ export_data }}">
{% if step == 'assign' %}
<input type="hidden" name="step" value="assign">
{% if assign_form.non_field_errors %}<div class="alert alert-danger">{{ assign_form.non_field_errors }}</div>{% endif %}
<div class="card mb-3">
<h2 class="card-header"><i class="mdi mdi-server me-1" aria-hidden="true"></i>Welches Gerät ist welches Shelf?</h2>
<div class="card-body">
<p class="text-muted">Shelf 1 ist in der Regel der Controller-Einschub, weitere Nummern sind Erweiterungs-Shelfs. Shelfs ohne Gerät werden übersprungen.</p>
<table class="table table-hover align-middle">
<thead><tr><th>Shelf</th><th>Datenträger</th><th>Modelle</th><th style="min-width: 20rem">Gerät in NetBox</th></tr></thead>
<tbody>
{% for enclosure in enclosures %}
<tr>
<td class="fw-bold">{{ enclosure.id }}</td>
<td>{{ enclosure.count }} <span class="text-muted small">(Steckplatz {{ enclosure.first }}–{{ enclosure.last }})</span></td>
<td class="small">{{ enclosure.models|join:", " }}</td>
<td>
{{ enclosure.field }}
{% for error in enclosure.field.errors %}<div class="text-danger small">{{ error }}</div>{% endfor %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<div class="card mb-3">
<h2 class="card-header">Optionen</h2>
<div class="card-body">
{% for field in assign_form.option_fields %}
<div class="form-check form-switch mb-2">
{{ field }}
<label class="form-check-label" for="{{ field.id_for_label }}">{{ field.label }}</label>
<div class="form-text">{{ field.help_text }}</div>
</div>
{% endfor %}
</div>
</div>
<div class="text-end">
<a href="{% url 'plugins:netbox_utilities:disk_msa_import' %}" class="btn btn-outline-secondary">Andere Datei</a>
<button type="submit" class="btn btn-primary">Weiter zur Vorschau</button>
</div>
{% else %}
<input type="hidden" name="step" value="plan">
{# Carry the assignment of step 2 along. #}
{% for enclosure, field in assign_form.device_fields %}
{% if field.value %}<input type="hidden" name="{{ field.html_name }}" value="{{ field.value }}">{% endif %}
{% endfor %}
{% for field in assign_form.option_fields %}
{% if field.value %}<input type="hidden" name="{{ field.html_name }}" value="on">{% endif %}
{% endfor %}
{% for plan in plans %}
<div class="card mb-3">
<h2 class="card-header">
<i class="mdi mdi-server me-1" aria-hidden="true"></i>
Shelf {{ plan.enclosure }} → <a href="{% url 'dcim:device_disks' pk=plan.device.pk %}" target="_blank">{{ plan.device }}</a>
<span class="badge text-bg-secondary ms-2">{{ plan.importing }} von {{ plan.rows|length }} werden importiert</span>
</h2>
<div class="card-body">
{% if plan.bay_form %}
<div class="alert alert-warning">
<i class="mdi mdi-alert" aria-hidden="true"></i>
<strong>{{ plan.device }} hat noch keine Datenträger-Steckplätze.</strong>
Der folgende Bereich wird beim Import angelegt – bitte prüfen und bei Bedarf anpassen, dann „Vorschau aktualisieren“.
</div>
{% include 'netbox_utilities/inc/disk_layout_fields.html' with form=plan.bay_form %}
{% elif plan.bays|length > 1 %}
<div class="mb-3" style="max-width: 24rem">
<label class="form-label" for="bay_{{ plan.enclosure }}">Bereich</label>
<select name="bay_{{ plan.enclosure }}" id="bay_{{ plan.enclosure }}" class="form-select">
{% for bay in plan.bays %}
<option value="{{ bay.pk }}"{% if bay.pk == plan.bay.pk %} selected{% endif %}>{{ bay.name }} ({{ bay.first_slot }}–{{ bay.last_slot }})</option>
{% endfor %}
</select>
</div>
{% else %}
<input type="hidden" name="bay_{{ plan.enclosure }}" value="{{ plan.bay.pk }}">
<p class="text-muted">Bereich: <strong>{{ plan.bay.name }}</strong> (Steckplatz {{ plan.bay.first_slot }}–{{ plan.bay.last_slot }})</p>
{% endif %}
{% if plan.groups and assign_form.cleaned_data.create_raid_groups %}
<p class="small text-muted mb-2">Disk Groups: {{ plan.groups|join:", " }}</p>
{% endif %}
<div class="table-responsive">
<table class="table table-sm table-hover align-middle mb-0">
<thead>
<tr><th>Slot</th><th>Aktion</th><th>Status</th><th>Typ</th><th>Größe</th><th>Modell</th><th>Seriennummer</th><th>Disk Group</th><th>Firmware</th></tr>
</thead>
<tbody>
{% for row in plan.rows %}
<tr{% if row.action == 'conflict' or row.action == 'skip' %} class="text-muted"{% endif %}>
<td>{{ row.item.slot }}</td>
<td>
<span class="badge text-bg-{{ row.color }}">{{ row.label }}</span>
{% if row.reason %}<div class="small">{{ row.reason }}</div>{% endif %}
</td>
<td>{{ row.item.usage }}{% if row.item.health and row.item.health != 'OK' %} <span class="badge text-bg-danger">{{ row.item.health }}</span>{% endif %}</td>
<td>{{ row.item.disk_type|upper }} {{ row.item.interface|upper }}</td>
<td>{{ row.capacity }}</td>
<td>{{ row.item.manufacturer }} {{ row.item.model }}</td>
<td class="font-monospace">{{ row.item.serial }}</td>
<td>{{ row.item.disk_group|default:"—" }}</td>
<td>{{ row.item.firmware }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
{% endfor %}
<div class="d-flex flex-wrap gap-2">
<button type="submit" name="step" value="back" class="btn btn-outline-secondary me-auto">Zurück</button>
<button type="submit" class="btn btn-outline-primary">Vorschau aktualisieren</button>
<button type="submit" name="do_import" value="1" class="btn btn-primary">
<i class="mdi mdi-check" aria-hidden="true"></i> Importieren
</button>
</div>
{% endif %}
</form>
{% endif %}
</div>
</div>
{% endblock content %}
@@ -0,0 +1,56 @@
{# Capacity of one host or a whole cluster versus its VMs; expects the context of hardware_views.capacity_context. #}
{% for level, text in capacity_warnings %}
<div class="alert alert-{{ level }} py-2 mb-2 small"><i class="mdi mdi-alert" aria-hidden="true"></i> {{ text }}</div>
{% endfor %}
<table class="table table-hover attr-table mb-0">
<tr>
<th scope="row">Physisch</th>
<td>
{% if capacity.cores %}{{ capacity.cores }} Kerne / {{ capacity.threads }} Threads{% else %}<span class="text-muted">—</span>{% endif %}
· {{ memory }} RAM
</td>
</tr>
<tr>
<th scope="row">VMs</th>
<td>
{{ capacity.vm_count }} VM{{ capacity.vm_count|pluralize:",s" }} · {{ capacity.vcpus|floatformat:"-1" }} vCPUs · {{ vm_memory }} RAM
{% if capacity.unplaced_vm_count %}
<div class="small text-muted">
{% if capacity.host_share and capacity.distributed %}
inkl. anteiliger Last aus {{ capacity.unplaced_vm_count }} Cluster-VM{{ capacity.unplaced_vm_count|pluralize:",s" }} ohne festen Host
{% elif capacity.host_share %}
{{ capacity.unplaced_vm_count }} Cluster-VM{{ capacity.unplaced_vm_count|pluralize:",s" }} ohne festen Host nicht enthalten, weil im Cluster VMs fest Hosts zugewiesen sind
{% elif capacity.distributed %}
davon {{ capacity.unplaced_vm_count }} ohne festen Host, anteilig nach Größe auf die Hosts verteilt
{% else %}
davon {{ capacity.unplaced_vm_count }} ohne festen Host, nicht auf die Hosts verteilt (es sind VMs fest zugewiesen)
{% endif %}
</div>
{% endif %}
</td>
</tr>
<tr>
<th scope="row">vCPU : Kern</th>
<td>{{ vcpu_per_core }} <span class="text-muted small">({{ vcpu_per_thread }} je Thread)</span></td>
</tr>
<tr>
<th scope="row">RAM zugewiesen</th>
<td>
{% if capacity.memory_percent is not None %}
<div class="progress" role="progressbar" aria-valuenow="{{ capacity.memory_percent }}" aria-valuemin="0" aria-valuemax="100" style="height: 1.1rem">
<div class="progress-bar {% if capacity.memory_percent > 100 %}bg-danger{% elif capacity.memory_percent > 85 %}bg-warning{% else %}bg-success{% endif %}"
style="width: {% if capacity.memory_percent > 100 %}100{% else %}{{ capacity.memory_percent }}{% endif %}%">{{ capacity.memory_percent }} %</div>
</div>
{% else %}<span class="text-muted">—</span>{% endif %}
</td>
</tr>
{% if capacity.failover_memory_gb is not None %}
<tr>
<th scope="row">RAM bei Host-Ausfall</th>
<td>
{{ failover_memory }}
{% if capacity.failover_ok %}<span class="badge text-bg-success">N+1 OK</span>{% else %}<span class="badge text-bg-warning">N+1 nicht erfüllt</span>{% endif %}
</td>
</tr>
{% endif %}
</table>
@@ -0,0 +1,23 @@
{# CPU and RAM rows of one DeviceHardware record. #}
<table class="table table-hover attr-table mb-0">
<tr>
<th scope="row">CPU</th>
<td>
{% if record.cpu %}
{% if record.cpu_count > 1 %}{{ record.cpu_count }} × {% endif %}<a href="{{ record.cpu.get_absolute_url }}">{{ record.cpu }}</a>
<div class="small text-muted">{{ record.cpu.summary }}{% if record.cpu.socket %} · {{ record.cpu.socket }}{% endif %}</div>
{% else %}<span class="text-muted">—</span>{% endif %}
</td>
</tr>
{% if record.cpu %}
<tr><th scope="row">Gesamt</th><td>{{ record.total_cores }} Kerne / {{ record.total_threads }} Threads</td></tr>
{% endif %}
<tr>
<th scope="row">RAM</th>
<td>
{{ record.memory_display }}
{% if record.memory_detail %}<div class="small text-muted">{{ record.memory_detail }}</div>{% endif %}
</td>
</tr>
{% if record.description %}<tr><th scope="row">Beschreibung</th><td>{{ record.description }}</td></tr>{% endif %}
</table>
@@ -0,0 +1,115 @@
{% load helpers %}
<nav class="mb-2" aria-label="Navigation">
<a href="?{{ filter_query }}" class="btn btn-sm btn-outline-secondary">
<i class="mdi mdi-arrow-left" aria-hidden="true"></i> Alle Software-Produkte
</a>
</nav>
<div class="row row-cards mb-3">
<div class="col-12 col-xl-5">
<div class="card h-100">
<div class="card-header d-flex align-items-center">
<div class="me-auto">
<h2 class="card-title mb-0">{{ product.name }}</h2>
<div class="text-muted small">{{ product.manufacturer|default:"Kein Hersteller" }}</div>
</div>
{% if product_obj %}
<a href="{{ product_obj.get_absolute_url }}" class="btn btn-sm btn-outline-primary" title="Produkt in netbox-slm öffnen">
<i class="mdi mdi-open-in-new" aria-hidden="true"></i> Produkt
</a>
{% endif %}
</div>
<div class="card-body">
<div class="row text-center mb-3">
<div class="col"><div class="nbu-sw-kpi-value">{{ product.device_count }}</div><div class="nbu-sw-kpi-label">Rechner</div></div>
<div class="col"><div class="nbu-sw-kpi-value">{{ product.share }} %</div><div class="nbu-sw-kpi-label">der Rechner</div></div>
<div class="col"><div class="nbu-sw-kpi-value">{{ product.version_count }}</div><div class="nbu-sw-kpi-label">Versionen</div></div>
</div>
{% with item=product %}{% include 'netbox_utilities/inc/software_version_stack.html' %}{% endwith %}
</div>
</div>
</div>
<div class="col-12 col-xl-7">
<div class="card h-100">
<h2 class="card-header">Rechner je Version <span class="text-muted fw-normal small ms-1">anklicken zum Filtern</span></h2>
<div class="card-body">
<ul class="nbu-sw-bars list-unstyled mb-0">
{% for version in product.versions_by_name %}
<li>
<a href="?{{ filter_query }}&product={{ product.id }}{% if selected_version.id != version.id %}&version={{ version.id }}{% endif %}"
class="nbu-sw-bar-row{% if selected_version.id == version.id %} active{% endif %}"
aria-current="{% if selected_version.id == version.id %}true{% else %}false{% endif %}">
<span class="nbu-sw-bar-label">
{{ version.name }}
{% if forloop.first %}<span class="badge text-bg-green ms-1">neueste</span>{% endif %}
{% if version.support_expired %}<span class="badge text-bg-danger ms-1" title="Support-Ende {{ version.end_of_support|isodate }}">EoS</span>{% endif %}
</span>
<span class="nbu-sw-bar-track"><span class="nbu-sw-bar-fill{% if version.support_expired %} nbu-sw-expired{% endif %}" style="width: {{ version.share }}%; --nbu-sw-shade: {{ version.shade }}%"></span></span>
<span class="nbu-sw-bar-value">{{ version.device_count }}<span class="text-muted"> · {{ version.share }} %</span></span>
</a>
</li>
{% endfor %}
</ul>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header d-flex flex-wrap gap-2 align-items-center">
<h2 class="card-title me-auto mb-0">
Installiert auf
<span class="badge text-bg-secondary ms-1">{{ entries|length }}</span>
{% if selected_version %}
<a href="?{{ filter_query }}&product={{ product.id }}" class="badge text-bg-primary ms-1 text-decoration-none" title="Versionsfilter entfernen">
Version {{ selected_version.name }} <i class="mdi mdi-close" aria-hidden="true"></i>
</a>
{% endif %}
</h2>
<input type="search" class="form-control form-control-sm w-auto" data-nbu-sw-search="#nbu-sw-devices"
placeholder="Rechner, Mandant, Standort …" aria-label="Rechnerliste filtern">
</div>
<div class="table-responsive">
<table class="table table-hover table-vcenter mb-0" id="nbu-sw-devices">
<thead>
<tr>
<th data-nbu-sort="text">Rechner</th>
<th data-nbu-sort="text">Mandant</th>
<th data-nbu-sort="text">Standort</th>
<th data-nbu-sort="text">Rolle</th>
<th data-nbu-sort="text">Version</th>
<th data-nbu-sort="text">Support-Ende</th>
<th></th>
</tr>
</thead>
<tbody>
{% for entry in entries %}
{% with device=entry.device version=entry.version %}
<tr>
<td><a href="{% url 'dcim:device_software' pk=device.pk %}" class="fw-bold">{{ device }}</a></td>
<td>{{ device.tenant|linkify|placeholder }}</td>
<td>{{ device.site|linkify|placeholder }}</td>
<td>{{ device.role|placeholder }}</td>
<td>
{{ version.name }}
{% if product.latest_version.id == version.id %}<span class="badge text-bg-green ms-1">neueste</span>{% endif %}
</td>
<td>
{% if version.end_of_support %}
<span class="{% if version.end_of_support < today %}text-danger fw-bold{% endif %}">{{ version.end_of_support|isodate }}</span>
{% else %}<span class="text-muted">—</span>{% endif %}
</td>
<td class="text-end">
<a href="{{ entry.get_absolute_url }}" class="btn btn-sm btn-outline-secondary" title="Installation öffnen">
<i class="mdi mdi-open-in-new" aria-hidden="true"></i>
</a>
</td>
</tr>
{% endwith %}
{% empty %}
<tr><td colspan="7" class="text-muted text-center py-4">Keine Installationen.</td></tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
@@ -0,0 +1,41 @@
<script>
document.addEventListener("DOMContentLoaded", () => {
// Liste filtern: Zeilen ausblenden, deren Suchtext nicht passt
for (const input of document.querySelectorAll("[data-nbu-sw-search]")) {
const rows = document.querySelectorAll(`${input.dataset.nbuSwSearch} tbody tr`);
input.addEventListener("input", () => {
const terms = input.value.toLowerCase().split(/\s+/).filter(Boolean);
for (const row of rows) {
const text = row.dataset.nbuSearch || row.textContent.toLowerCase();
row.hidden = !terms.every((term) => text.includes(term));
}
});
}
// Sortieren per Klick auf den Spaltenkopf
for (const header of document.querySelectorAll("th[data-nbu-sort]")) {
header.classList.add("nbu-sw-sortable");
header.tabIndex = 0;
const sort = () => {
const table = header.closest("table");
const index = [...header.parentElement.children].indexOf(header);
const numeric = header.dataset.nbuSort === "number";
const ascending = header.getAttribute("aria-sort") !== "ascending";
for (const other of header.parentElement.children) other.removeAttribute("aria-sort");
header.setAttribute("aria-sort", ascending ? "ascending" : "descending");
const body = table.tBodies[0];
const value = (row) => {
const cell = row.children[index];
return numeric ? Number(cell.dataset.value ?? cell.textContent) || 0 : cell.textContent.trim().toLowerCase();
};
const rows = [...body.rows].sort((a, b) => {
const [x, y] = [value(a), value(b)];
const result = numeric ? x - y : x.localeCompare(y, "de", { numeric: true });
return ascending ? result : -result;
});
body.append(...rows);
};
header.addEventListener("click", sort);
header.addEventListener("keydown", (event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); sort(); } });
}
});
</script>
@@ -0,0 +1,7 @@
<span class="nbu-sw-stack" role="img" aria-label="Versionsverteilung {{ item.name }}: {% for version in item.versions_by_name %}{{ version.name }} {{ version.device_count }} Rechner{% if not forloop.last %}, {% endif %}{% endfor %}">
{% for version in item.versions_by_name %}
<span class="nbu-sw-stack-part{% if version.support_expired %} nbu-sw-expired{% endif %}"
style="flex-grow: {{ version.device_count }}; --nbu-sw-shade: {{ version.shade }}%"
title="{{ version.name }}: {{ version.device_count }} Rechner ({{ version.share }} %){% if version.support_expired %} · Support abgelaufen{% endif %}"></span>
{% endfor %}
</span>
@@ -0,0 +1,219 @@
{% extends 'base/layout.html' %}
{% load helpers %}
{% block title %}{% if product %}{{ product.name }} · {% endif %}Client Software Übersicht{% endblock %}
{% block controls %}
<div class="btn-list">
<a href="?{{ filter_query }}{% if product %}&product={{ product.id }}{% if selected_version %}&version={{ selected_version.id }}{% endif %}{% endif %}&export=csv"
class="btn btn-purple" title="Aktuelle Auswahl als CSV (Excel) herunterladen">
<i class="mdi mdi-download" aria-hidden="true"></i> CSV exportieren
</a>
{% if can_add %}
<a href="{% url 'plugins:netbox_slm:softwareproductinstallation_add' %}?return_url={{ request.get_full_path|urlencode }}" class="btn btn-primary">
<i class="mdi mdi-plus-thick" aria-hidden="true"></i> Installation erfassen
</a>
{% endif %}
</div>
{% endblock controls %}
{% block content %}
{# Filter #}
<form method="get" class="card mb-3 nbu-sw-filter">
<input type="hidden" name="submitted" value="1">
{% if product %}<input type="hidden" name="product" value="{{ product.id }}">{% endif %}
<div class="card-body">
<div class="row g-3 align-items-end">
<div class="col-12 col-md-6 col-xl-3">
<label class="form-label" for="{{ form.tenant_group_id.id_for_label }}">Mandantengruppe</label>
{{ form.tenant_group_id }}
</div>
<div class="col-12 col-md-6 col-xl-3">
<label class="form-label" for="{{ form.tenant_id.id_for_label }}">Mandant</label>
{{ form.tenant_id }}
</div>
<div class="col-12 col-md-8 col-xl-4">
<label class="form-label" for="id_q">Software suchen</label>
<div class="input-icon">
<span class="input-icon-addon"><i class="mdi mdi-magnify" aria-hidden="true"></i></span>
<input type="search" name="q" id="id_q" value="{{ form.q.value|default:'' }}" class="form-control"
placeholder="Produkt, Hersteller oder Version">
</div>
</div>
<div class="col-12 col-md-4 col-xl-2 d-flex gap-2">
<button type="submit" class="btn btn-primary flex-grow-1">
<i class="mdi mdi-filter" aria-hidden="true"></i> Anwenden
</button>
<a href="{% url 'plugins:netbox_utilities:software_overview' %}" class="btn btn-outline-secondary btn-icon"
title="Filter zurücksetzen" aria-label="Filter zurücksetzen">
<i class="mdi mdi-filter-remove-outline" aria-hidden="true"></i>
</a>
</div>
</div>
<div class="nbu-sw-filter-footer">
<div class="nbu-sw-roles" role="group" aria-label="Gerätrolle">
<span class="nbu-sw-roles-label">Gerätrolle</span>
{% for choice in form.role_id %}
<input type="checkbox" class="btn-check" name="{{ form.role_id.html_name }}" value="{{ choice.data.value }}"
id="{{ choice.id_for_label }}" autocomplete="off" onchange="this.form.requestSubmit()"
{% if choice.data.selected %}checked{% endif %}>
<label class="btn btn-sm btn-pill nbu-sw-role" for="{{ choice.id_for_label }}">
<i class="mdi mdi-laptop" aria-hidden="true"></i> {{ choice.choice_label }}
</label>
{% empty %}
<span class="text-danger small">Keine Client-Rolle gefunden – <code>software_device_roles</code> prüfen.</span>
{% endfor %}
</div>
<div class="nbu-sw-filter-hint">
{% if scope_label %}
<span class="badge bg-primary-lt"><i class="mdi mdi-filter-check" aria-hidden="true"></i> Globaler Filter: {{ scope_label }}</span>
<span class="text-secondary">Eigene Auswahl hat Vorrang.</span>
{% else %}
<span class="text-secondary">Gruppen schließen Untergruppen ein. Ohne Rollenauswahl: alle Client-Rollen.</span>
{% endif %}
</div>
</div>
</div>
</form>
{# Kennzahlen #}
<div class="row row-cards mb-3">
<div class="col-6 col-lg-3">
<div class="card nbu-sw-kpi"><div class="card-body">
<div class="nbu-sw-kpi-label">Rechner</div>
<div class="nbu-sw-kpi-value">{{ summary.device_total }}</div>
<div class="nbu-sw-kpi-hint">{{ summary.devices_with_software }} mit erfasster Software</div>
</div></div>
</div>
<div class="col-6 col-lg-3">
<div class="card nbu-sw-kpi"><div class="card-body">
<div class="nbu-sw-kpi-label">Erfassungsgrad</div>
<div class="nbu-sw-kpi-value">{{ summary.coverage }} %</div>
<div class="progress progress-sm mt-2" role="progressbar" aria-label="Erfassungsgrad" aria-valuenow="{{ summary.coverage }}" aria-valuemin="0" aria-valuemax="100">
<div class="progress-bar" style="width: {{ summary.coverage }}%"></div>
</div>
<div class="nbu-sw-kpi-hint">{{ summary.devices_without_software }} Rechner ohne Software</div>
</div></div>
</div>
<div class="col-6 col-lg-3">
<div class="card nbu-sw-kpi"><div class="card-body">
<div class="nbu-sw-kpi-label">Software-Produkte</div>
<div class="nbu-sw-kpi-value">{{ summary.product_count }}</div>
<div class="nbu-sw-kpi-hint">{{ summary.version_count }} Version{{ summary.version_count|pluralize:"en" }} · {{ summary.installations }} Installation{{ summary.installations|pluralize:"en" }}</div>
</div></div>
</div>
<div class="col-6 col-lg-3">
<div class="card nbu-sw-kpi{% if summary.expired_device_count %} nbu-sw-kpi-warning{% endif %}"><div class="card-body">
<div class="nbu-sw-kpi-label">Support abgelaufen</div>
<div class="nbu-sw-kpi-value">{{ summary.expired_device_count }}</div>
<div class="nbu-sw-kpi-hint">Rechner mit mindestens einer Version nach Support-Ende</div>
</div></div>
</div>
</div>
{% if product_missing %}
<div class="alert alert-warning">Dieses Produkt ist mit der aktuellen Auswahl auf keinem Rechner installiert.
<a href="?{{ filter_query }}">Zur Übersicht</a></div>
{% endif %}
{% if product %}
{% include 'netbox_utilities/inc/software_product.html' %}
{% elif summary.products %}
<div class="row row-cards mb-3">
{# Diagramm: Top-Produkte #}
<div class="col-12 col-xl-6">
<div class="card h-100">
<h2 class="card-header">Verbreitetste Software <span class="text-muted fw-normal small ms-1">Rechner je Produkt</span></h2>
<div class="card-body">
<ul class="nbu-sw-bars list-unstyled mb-0">
{% for item in summary.top_products %}
<li>
<a href="?{{ filter_query }}&product={{ item.id }}" class="nbu-sw-bar-row" title="{{ item.name }}: {{ item.device_count }} Rechner ({{ item.share }} %)">
<span class="nbu-sw-bar-label">{{ item.name }}</span>
<span class="nbu-sw-bar-track"><span class="nbu-sw-bar-fill" style="width: {{ item.bar }}%"></span></span>
<span class="nbu-sw-bar-value">{{ item.device_count }}<span class="text-muted"> · {{ item.share }} %</span></span>
</a>
</li>
{% endfor %}
</ul>
</div>
</div>
</div>
{# Diagramm: Versionsverteilung #}
<div class="col-12 col-xl-6">
<div class="card h-100">
<h2 class="card-header">Versionsverteilung <span class="text-muted fw-normal small ms-1">neueste Version am kräftigsten</span></h2>
<div class="card-body">
<ul class="nbu-sw-bars list-unstyled mb-0">
{% for item in summary.top_products %}
<li>
<a href="?{{ filter_query }}&product={{ item.id }}" class="nbu-sw-bar-row">
<span class="nbu-sw-bar-label">{{ item.name }}</span>
{% include 'netbox_utilities/inc/software_version_stack.html' %}
<span class="nbu-sw-bar-value">{{ item.version_count }} Version{{ item.version_count|pluralize:"en" }}</span>
</a>
</li>
{% endfor %}
</ul>
</div>
</div>
</div>
</div>
{# Tabelle aller Produkte #}
<div class="card">
<div class="card-header d-flex flex-wrap gap-2 align-items-center">
<h2 class="card-title me-auto mb-0">Alle Software-Produkte <span class="badge text-bg-secondary ms-1">{{ summary.product_count }}</span></h2>
<input type="search" class="form-control form-control-sm w-auto" data-nbu-sw-search="#nbu-sw-products"
placeholder="In Liste filtern …" aria-label="Produktliste filtern">
</div>
<div class="table-responsive">
<table class="table table-hover table-vcenter mb-0 nbu-sw-table" id="nbu-sw-products">
<thead>
<tr>
<th data-nbu-sort="text">Produkt</th>
<th data-nbu-sort="text">Hersteller</th>
<th data-nbu-sort="number" class="text-end">Rechner</th>
<th data-nbu-sort="number" class="text-end">Anteil</th>
<th data-nbu-sort="number" class="text-end">Versionen</th>
<th style="min-width: 12rem">Verteilung</th>
<th>Neueste Version</th>
<th data-nbu-sort="number" class="text-end">Support abgelaufen</th>
</tr>
</thead>
<tbody>
{% for item in summary.products %}
<tr data-nbu-search="{{ item.name|lower }} {{ item.manufacturer|lower }}{% for version in item.versions_by_name %} {{ version.name|lower }}{% endfor %}">
<td><a href="?{{ filter_query }}&product={{ item.id }}" class="fw-bold">{{ item.name }}</a></td>
<td>{{ item.manufacturer|placeholder }}</td>
<td class="text-end" data-value="{{ item.device_count }}">{{ item.device_count }}</td>
<td class="text-end" data-value="{{ item.share }}">{{ item.share }} %</td>
<td class="text-end" data-value="{{ item.version_count }}">{{ item.version_count }}</td>
<td>{% include 'netbox_utilities/inc/software_version_stack.html' %}</td>
<td>{% with latest=item.latest_version %}{{ latest.name }} <span class="text-muted small">({{ latest.device_count }})</span>{% endwith %}</td>
{% with expired=item.expired_devices|length %}
<td class="text-end" data-value="{{ expired }}">{% if expired %}<span class="badge text-bg-danger">{{ expired }}</span>{% else %}<span class="text-muted">—</span>{% endif %}</td>
{% endwith %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="card-footer text-muted small">Spaltenköpfe anklicken zum Sortieren, Produkt anklicken für Versionen und Rechner.</div>
</div>
{% else %}
<div class="card"><div class="card-body text-center text-muted py-5">
<i class="mdi mdi-package-variant-closed mdi-48px d-block mb-2" aria-hidden="true"></i>
<div class="fs-3 fw-semibold text-body mb-1">Für diese Auswahl ist keine Software erfasst</div>
<div class="mx-auto" style="max-width: 36rem;">
Softwarelisten des Windows-Agents und des NetBox Synchronizers werden beim Speichern eines Geräts übernommen.
Bereits vorhandene Berichte überträgt einmalig
<code>manage.py netbox_utilities_sync_software</code>.
</div>
{% if can_add %}<div class="mt-3"><a href="{% url 'plugins:netbox_slm:softwareproductinstallation_add' %}" class="btn btn-primary"><i class="mdi mdi-plus-thick" aria-hidden="true"></i> Installation erfassen</a></div>{% endif %}
</div></div>
{% endif %}
{% include 'netbox_utilities/inc/software_table_js.html' %}
{% endblock content %}
@@ -0,0 +1,29 @@
<div class="card">
<h2 class="card-header"><i class="mdi mdi-chip me-1" aria-hidden="true"></i>Host-Hardware</h2>
{% if not records %}
<div class="card-body text-muted">
{% if device %}Für den Host <a href="{{ device.get_absolute_url }}">{{ device }}</a> ist noch keine CPU erfasst.
{% else %}Die VM hat keinen Host und ihr Cluster keine Hosts mit erfasster CPU.{% endif %}
</div>
{% else %}
<table class="table table-hover attr-table mb-0">
<tr>
<th scope="row">{% if device %}Host{% else %}Cluster-Hosts{% endif %}</th>
<td>
{% for record in records %}<a href="{{ record.device.get_absolute_url }}">{{ record.device }}</a>{% if not forloop.last %}, {% endif %}{% endfor %}
</td>
</tr>
<tr><th scope="row">CPU</th><td>{{ cpus|join:", "|default:"—" }}</td></tr>
{% if smallest_threads %}
<tr>
<th scope="row">vCPUs</th>
<td>
{{ vcpus|floatformat:"-1"|default:"—" }} von {{ smallest_threads }} Threads{% if not device %} (kleinster Host){% endif %}
{% if vcpu_share is not None %}<span class="text-muted small">· {{ vcpu_share }} %</span>{% endif %}
{% if oversized %}<div class="text-danger small">Die VM hat mehr vCPUs, als der Host Threads hat.</div>{% endif %}
</td>
</tr>
{% endif %}
</table>
{% endif %}
</div>
+35
View File
@@ -16,8 +16,14 @@ PARENT_RELATIONS = (
"l2vpn",
"wireless_lan",
"power_panel",
# netbox-inventory assets: modules and inventory items belong to a device
"module",
"inventoryitem",
)
# Hardware a netbox-inventory asset can be assigned to, in the plugin's order.
ASSET_HARDWARE_RELATIONS = ("device", "module", "inventoryitem", "rack")
def tenant_id_from_object(obj, depth=0):
if obj is None or depth > 3:
@@ -133,6 +139,35 @@ def _cable_form_tenant_result(form):
return None, False
def _is_inventory_asset(instance):
meta = getattr(instance, "_meta", None)
return bool(
meta and getattr(meta, "app_label", None) == "netbox_inventory" and getattr(meta, "model_name", None) == "asset"
)
def apply_asset_instance_tenant(instance):
"""
Give a netbox-inventory asset without tenant the tenant of its assigned hardware.
The plugin's "assign", "reassign" and "create hardware from asset" views save the
asset without a tenant field; with mandatory tenancy they would fail although the
tenant of the device, module, inventory item or rack is known. Existing tenants are
never overwritten.
"""
if not _is_inventory_asset(instance) or getattr(instance, "tenant_id", None):
return None
for relation in ASSET_HARDWARE_RELATIONS:
try:
hardware = getattr(instance, relation, None)
except (AttributeError, ObjectDoesNotExist, ValueError):
continue
if tenant_id := tenant_id_from_object(hardware):
instance.tenant_id = tenant_id
return tenant_id
return None
def apply_cable_instance_tenant(instance):
"""Assign a cable's tenant when all derivable terminations agree."""
if not _is_cable(instance) or getattr(instance, "tenant_id", None):
+4 -1
View File
@@ -7,7 +7,7 @@ from django.forms.models import BaseModelForm
from tenancy.models import Tenant
from .runtime import tenant_required
from .tenant_autofill import apply_cable_instance_tenant, apply_tenant_autofill
from .tenant_autofill import apply_asset_instance_tenant, apply_cable_instance_tenant, apply_tenant_autofill
VALIDATION_MESSAGE = "Für dieses Objekt muss ein Mandant angegeben werden."
@@ -37,6 +37,7 @@ def _install_model_clean_validation(model):
@wraps(original_clean)
def tenant_aware_clean(instance, *args, **kwargs):
apply_cable_instance_tenant(instance)
apply_asset_instance_tenant(instance)
result = original_clean(instance, *args, **kwargs)
validate_tenant_assignment(instance)
return result
@@ -65,6 +66,8 @@ def _install_form_validation():
def _enforce_before_save(sender, instance, raw=False, **kwargs):
if not raw:
# netbox-inventory saves assets in several views without calling clean()
apply_asset_instance_tenant(instance)
validate_tenant_assignment(instance)
+177
View File
@@ -0,0 +1,177 @@
from collections import Counter
from types import SimpleNamespace
from django.test import SimpleTestCase
from netbox_utilities import cpu_catalog, hardware
class CatalogTest(SimpleTestCase):
entries = list(cpu_catalog.entries())
def test_covers_intel_and_amd_since_2012(self):
self.assertGreater(len(self.entries), 600)
self.assertEqual({entry["manufacturer"] for entry in self.entries}, {"intel", "amd"})
self.assertEqual(min(entry["launch_year"] for entry in self.entries), 2012)
def test_names_are_unique(self):
names = Counter((entry["manufacturer"], entry["name"].casefold()) for entry in self.entries)
self.assertEqual([name for name, count in names.items() if count > 1], [])
def test_values_are_plausible(self):
for entry in self.entries:
with self.subTest(cpu=entry["name"]):
self.assertIn(entry["threads"], (entry["cores"], entry["cores"] * 2))
self.assertTrue(1 <= entry["base_clock_ghz"] <= 5)
if entry["boost_clock_ghz"]:
self.assertGreaterEqual(entry["boost_clock_ghz"], entry["base_clock_ghz"])
self.assertIn(entry["max_sockets"], (1, 2, 4, 8))
def test_verified_samples(self):
by_name = {entry["name"]: entry for entry in self.entries}
samples = {
"Xeon Gold 6338": (32, 64, 2.0, 3.2),
"Xeon E5-2690 v4": (14, 28, 2.6, 3.5),
"Xeon Platinum 8480+": (56, 112, 2.0, 3.8),
"Xeon 6740E": (96, 96, 2.4, 3.2),
"EPYC 7543": (32, 64, 2.8, 3.7),
"EPYC 9655": (96, 192, 2.5, 4.5),
"Opteron 6380": (16, 16, 2.5, 3.4),
}
for name, (cores, threads, base, boost) in samples.items():
with self.subTest(cpu=name):
entry = by_name[name]
self.assertEqual(
(entry["cores"], entry["threads"], entry["base_clock_ghz"], entry["boost_clock_ghz"]),
(cores, threads, base, boost),
)
def test_epyc_p_models_are_single_socket(self):
by_name = {entry["name"]: entry for entry in self.entries}
self.assertEqual(by_name["EPYC 7402P"]["max_sockets"], 1)
self.assertEqual(by_name["EPYC 4484PX"]["max_sockets"], 1)
self.assertEqual(by_name["EPYC 7402"]["max_sockets"], 2)
class FormatTest(SimpleTestCase):
def test_memory(self):
self.assertEqual(hardware.format_memory(768), "768 GB")
self.assertEqual(hardware.format_memory(1536), "1,5 TB")
self.assertEqual(hardware.format_memory(12.5), "12,5 GB")
self.assertEqual(hardware.format_memory(None), "—")
def test_clock_and_ratio(self):
self.assertEqual(hardware.format_clock(2.0), "2 GHz")
self.assertEqual(hardware.format_clock(3.35), "3,35 GHz")
self.assertEqual(hardware.format_ratio(3.25), "3,2 : 1")
self.assertEqual(hardware.format_ratio(None), "—")
class SupportTest(SimpleTestCase):
def test_servers_and_cluster_hosts(self):
server = SimpleNamespace(cluster_id=None, role=SimpleNamespace(name="server"))
host = SimpleNamespace(cluster_id=3, role=SimpleNamespace(name="Hypervisor"))
switch = SimpleNamespace(cluster_id=None, role=SimpleNamespace(name="Switch"))
self.assertTrue(hardware.supports_hardware(server, ["Server"]))
self.assertTrue(hardware.supports_hardware(host, ["Server"]))
self.assertFalse(hardware.supports_hardware(switch, ["Server"]))
class CapacityTest(SimpleTestCase):
def hosts(self):
return [
hardware.Host("esx01", cores=32, threads=64, memory_gb=512),
hardware.Host("esx02", cores=32, threads=64, memory_gb=512),
hardware.Host("esx03", cores=32, threads=64, memory_gb=768),
]
def test_totals_ratio_and_failover(self):
vms = [
("esx01", 8, 64 * 1024, "active"),
("esx02", 16, 128 * 1024, "active"),
(None, 4, 32 * 1024, "planned"),
("esx03", 64, 512 * 1024, "offline"),
]
capacity = hardware.build_capacity(self.hosts(), vms)
self.assertEqual((capacity.cores, capacity.threads, capacity.memory_gb), (96, 192, 1792))
self.assertEqual((capacity.vm_count, capacity.vcpus, capacity.vm_memory_gb), (3, 28, 224))
self.assertEqual(capacity.unplaced_vm_count, 1)
self.assertAlmostEqual(capacity.vcpu_per_core, 28 / 96)
self.assertEqual(capacity.memory_percent, 12)
self.assertEqual(capacity.failover_memory_gb, 1024)
self.assertTrue(capacity.failover_ok)
self.assertEqual(capacity.warnings(), [])
self.assertEqual(capacity.hosts[0].vcpus, 8)
def test_warnings(self):
hosts = [*self.hosts(), hardware.Host("esx04")]
vms = [("esx01", 600, 1200 * 1024, "active")]
levels = [level for level, _ in hardware.build_capacity(hosts, vms).warnings(ratio_warning=4)]
self.assertEqual(levels, ["warning", "warning", "warning"])
vms = [("esx01", 8, 2000 * 1024, "active")]
texts = [text for _, text in hardware.build_capacity(self.hosts(), vms).warnings()]
self.assertIn("Die VMs haben mehr RAM zugewiesen, als die Hosts haben.", texts)
def test_single_host_has_no_failover(self):
capacity = hardware.build_capacity(self.hosts()[:1], [])
self.assertIsNone(capacity.failover_memory_gb)
self.assertEqual(capacity.vcpu_per_core, 0)
class UnplacedVMTest(SimpleTestCase):
def test_spread_by_host_size(self):
hosts = [
hardware.Host("small", cores=16, threads=32, memory_gb=256, key=1),
hardware.Host("big", cores=48, threads=96, memory_gb=768, key=2),
]
vms = [(None, 16, 100 * 1024, "active"), (None, 4, 8 * 1024, "active")]
capacity = hardware.build_capacity(hosts, vms)
small, big = capacity.hosts
self.assertTrue(capacity.distributed)
self.assertEqual(capacity.unplaced_vm_count, 2)
self.assertAlmostEqual(small.shared_vcpus, 5)
self.assertAlmostEqual(big.shared_vcpus, 15)
self.assertAlmostEqual(small.shared_memory_gb, 27)
self.assertAlmostEqual(big.shared_memory_gb, 81)
# The cluster sums count every VM exactly once.
self.assertEqual((capacity.vcpus, capacity.vm_memory_gb), (20, 108))
def test_no_spreading_once_a_vm_is_pinned(self):
for status in ("active", "offline"):
with self.subTest(pinned_vm_status=status):
hosts = [
hardware.Host("a", cores=32, threads=64, memory_gb=512, key=1),
hardware.Host("b", cores=32, threads=64, memory_gb=512, key=2),
]
vms = [(None, 16, 64 * 1024, "active"), (2, 4, 8 * 1024, status)]
capacity = hardware.build_capacity(hosts, vms)
self.assertTrue(capacity.manual_placement)
self.assertFalse(capacity.distributed)
self.assertEqual([host.shared_vcpus for host in capacity.hosts], [0, 0])
self.assertEqual(capacity.unplaced_vm_count, 1)
self.assertEqual(capacity.vcpus, 20 if status == "active" else 16)
single = hardware.host_capacity(capacity, capacity.hosts[0])
self.assertEqual(single.vcpus, 0)
def test_equal_shares_without_recorded_hardware(self):
hosts = [hardware.Host("a", key=1), hardware.Host("b", key=2)]
capacity = hardware.build_capacity(hosts, [(None, 8, 16 * 1024, "active")])
self.assertEqual([host.shared_vcpus for host in capacity.hosts], [4, 4])
self.assertEqual([host.shared_memory_gb for host in capacity.hosts], [8, 8])
def test_host_capacity_includes_share(self):
hosts = [
hardware.Host("a", cores=32, threads=64, memory_gb=512, key=1),
hardware.Host("b", cores=32, threads=64, memory_gb=512, key=2),
]
cluster = hardware.build_capacity(hosts, [(None, 32, 512 * 1024, "active")])
single = hardware.host_capacity(cluster, cluster.hosts[0])
self.assertTrue(single.host_share and single.distributed)
self.assertEqual((single.vm_count, single.vcpus, single.vm_memory_gb), (0, 16, 256))
self.assertEqual(single.memory_percent, 50)
self.assertEqual(single.vcpu_per_core, 0.5)
def test_hosts_are_matched_by_key_not_name(self):
hosts = [hardware.Host("esx", key=1), hardware.Host("esx", key=2)]
capacity = hardware.build_capacity(hosts, [(2, 4, 1024, "active")])
self.assertEqual([host.vcpus for host in capacity.hosts], [0, 4])
@@ -0,0 +1,51 @@
from types import SimpleNamespace
from django.test import SimpleTestCase
from netbox_utilities.inventory_assets import add_to_default_columns
def fake_table(*default_columns):
return SimpleNamespace(Meta=SimpleNamespace(default_columns=default_columns))
class AssetTenantColumnTest(SimpleTestCase):
def test_tenant_is_shown_after_status(self):
table = fake_table("pk", "id", "name", "asset_tag", "status", "hardware", "tags")
add_to_default_columns(table)
self.assertEqual(table.Meta.default_columns, ("pk", "id", "name", "asset_tag", "status", "tenant", "hardware", "tags"))
def test_tenant_is_not_duplicated_and_appended_without_anchor(self):
table = fake_table("pk", "tenant", "name")
add_to_default_columns(table)
self.assertEqual(table.Meta.default_columns, ("pk", "name", "tenant"))
class AssetTenantFallbackTest(SimpleTestCase):
def test_own_tenant_wins_then_hardware_then_hardware_device(self):
from netbox_utilities.inventory_assets import asset_tenant
def asset(**kwargs):
values = dict(tenant=None, device=None, module=None, inventoryitem=None, rack=None)
return SimpleNamespace(**{**values, **kwargs})
self.assertEqual(asset_tenant(asset(tenant="A", device=SimpleNamespace(tenant="B"))), "A")
self.assertEqual(asset_tenant(asset(device=SimpleNamespace(tenant="B"))), "B")
module = SimpleNamespace(device=SimpleNamespace(tenant="C"))
self.assertEqual(asset_tenant(asset(module=module)), "C")
self.assertIsNone(asset_tenant(asset()))
class AssetTenantQueryTest(SimpleTestCase):
def test_query_includes_inherited_tenants_only_without_own_tenant(self):
from netbox_utilities.inventory_assets import asset_tenant_query
query = str(asset_tenant_query([7]))
for lookup in ("tenant_id__in", "tenant__isnull", "device__tenant_id__in", "module__device__tenant_id__in",
"inventoryitem__device__tenant_id__in", "rack__tenant_id__in"):
self.assertIn(f"'{lookup}'", query)
+132
View File
@@ -0,0 +1,132 @@
from types import SimpleNamespace
from django.test import SimpleTestCase
from netbox_utilities import disks, msa_import
EXPORT = """Location,Health,Type,Size,Usage,Disk Group,Status,Serial Number,r/min,Manufacturer,Model,Revision,Power On Hours,FDE State,FDE Lock Key,Sector Format
1.1,OK,SSD SAS,745.2GiB,VIRTUAL POOL,rcA1,Up,Z8713PT50000822150Z3,0k,SEAGATE,ST800FM0403,0007,70425,Not FDE Capable,00000000,512e
1.11,OK,SAS,558.9GiB,GLOBAL SP,-,Up,X4T0A00LFJVL,10k,HPE,EG000600JWJNH,HPD5,1803,Not FDE Capable,00000000,512n
1.3,Fault,SAS,558.9GiB,VIRTUAL POOL,dgA01,Up,WFJ0KKMY,10k,HP,EG000600JWJNP,HPD1,70425,Not FDE Capable,00000000,512n
2.1,OK,SAS,558.9GiB,VIRTUAL POOL,dgB01,Up,WFJ0KGPR,10k,HP,EG000600JWJNP,HPD1,70425,Not FDE Capable,00000000,512n
"""
class ParseExportTest(SimpleTestCase):
def test_parses_enclosures_slots_and_fields(self):
export = msa_import.parse_export(EXPORT.encode("utf-8"))
self.assertEqual(export.errors, [])
enclosures = export.enclosures
self.assertEqual(list(enclosures), ["1", "2"])
self.assertEqual([disk.slot for disk in enclosures["1"]], [1, 3, 11])
ssd = enclosures["1"][0]
self.assertEqual((ssd.disk_type, ssd.interface), ("ssd", "sas"))
self.assertEqual(ssd.capacity_gb, 800)
self.assertEqual(ssd.disk_group, "rcA1")
self.assertEqual(ssd.firmware, "0007")
self.assertEqual(ssd.power_on_hours, 70425)
self.assertEqual(ssd.status, disks.STATUS_ACTIVE)
def test_maps_spares_failed_disks_and_missing_groups(self):
by_slot = {disk.slot: disk for disk in msa_import.parse_export(EXPORT).enclosures["1"]}
self.assertEqual(by_slot[11].status, disks.STATUS_SPARE)
self.assertEqual(by_slot[11].disk_group, "")
self.assertEqual(by_slot[3].status, disks.STATUS_FAILED)
self.assertEqual((by_slot[3].disk_type, by_slot[3].capacity_gb), ("hdd", 600))
def test_semicolon_csv_from_excel(self):
text = "Location;Type;Serial Number\n1.4;SATA;ABC\n"
disk = msa_import.parse_export(text).disks[0]
self.assertEqual((disk.enclosure, disk.slot, disk.serial, disk.interface), ("1", 4, "ABC", "sata"))
def test_rejects_other_files_and_bad_rows(self):
self.assertTrue(msa_import.parse_export("Name,Serial\nfoo,bar\n").errors)
export = msa_import.parse_export("Location\n1.x\n1.2\n1.2\n")
self.assertEqual(len(export.disks), 1)
self.assertEqual(len(export.errors), 2)
class SuggestionTest(SimpleTestCase):
def test_slot_count_rounds_up_to_enclosure_sizes(self):
self.assertEqual(msa_import.suggest_slot_count(11), 12)
self.assertEqual(msa_import.suggest_slot_count(21), 24)
self.assertEqual(msa_import.suggest_slot_count(30), 30)
self.assertEqual(msa_import.suggest_form_factor(24), "2.5")
class ClassifyTest(SimpleTestCase):
disk = SimpleNamespace(slot=4, serial="ABC")
def test_free_slot_is_new(self):
self.assertEqual(msa_import.classify(self.disk, 1, 24)[0], msa_import.ACTION_NEW)
def test_same_serial_updates(self):
self.assertEqual(msa_import.classify(self.disk, 1, 24, occupant_serial="abc")[0], msa_import.ACTION_UPDATE)
def test_other_disk_is_skipped_or_replaced(self):
self.assertEqual(msa_import.classify(self.disk, 1, 24, occupant_serial="XYZ")[0], msa_import.ACTION_SKIP)
self.assertEqual(
msa_import.classify(self.disk, 1, 24, occupant_serial="XYZ", replace=True)[0], msa_import.ACTION_REPLACE
)
def test_conflicts(self):
self.assertEqual(msa_import.classify(self.disk, 1, 3)[0], msa_import.ACTION_CONFLICT)
self.assertEqual(
msa_import.classify(self.disk, 1, 24, serial_elsewhere="MSA2 – Front 7")[0], msa_import.ACTION_CONFLICT
)
class DetectionTest(SimpleTestCase):
def test_recognises_msa_header_only(self):
self.assertTrue(msa_import.looks_like_export(EXPORT))
self.assertTrue(msa_import.looks_like_export("\ufeffLocation;Serial Number\n1.1;X"))
self.assertFalse(msa_import.looks_like_export("device,slot,serial\nsrv-01,0,ABC"))
GROUP_EXPORT = """Name,Health,Pool,RAID Level,Class,Disk Type,Total Size,Free,Status,Disks,Serial Number,Sector Format
dgA01,OK,A,RAID10,Virtual,sSAS,1596.5GB,63.9GB,FTOL,4,00c0ff3c47f90000e1892b5b00000000,512e
dgA02,OK,A,RAID5,Virtual,SAS,14.3TB,221.0GB,FTOL,9,00c0ff3c47f90000bf8a2b5b00000000,512e
"""
class GroupExportTest(SimpleTestCase):
def test_detects_and_parses_disk_group_export(self):
self.assertEqual(msa_import.detect_kind(GROUP_EXPORT), msa_import.KIND_GROUPS)
export = msa_import.parse_export(GROUP_EXPORT)
self.assertEqual(export.errors, [])
first, second = export.groups
self.assertEqual((first.name, first.level, first.pool, first.disk_count), ("dgA01", "raid10", "A", 4))
self.assertEqual(second.level, "raid5")
self.assertEqual(second.description, "Pool A, 14.3TB, 9 Datenträger")
def test_raid_level_spellings(self):
cases = {
"RAID10": "raid10",
"raid-6": "raid6",
"R5": "raid5",
"NRAID": "jbod",
"ADAPT": "other",
"RAID 1": "raid1",
}
for text, expected in cases.items():
with self.subTest(text=text):
self.assertEqual(msa_import.map_raid_level(text), expected)
class LooseHeaderTest(SimpleTestCase):
def test_alternative_column_names_and_split_position(self):
text = "Enclosure ID;Slot;Serial;Capacity;Drive Type;Vendor;Firmware\n2;7;ABC;4TB;SATA;WD;81.00\n"
self.assertEqual(msa_import.detect_kind(text), msa_import.KIND_DISKS)
disk = msa_import.parse_export(text).disks[0]
self.assertEqual((disk.enclosure, disk.slot, disk.serial, disk.capacity_gb), ("2", 7, "ABC", 4000))
self.assertEqual((disk.interface, disk.manufacturer, disk.firmware), ("sata", "WD", "81.00"))
def test_location_spellings(self):
for text in ("1.4", "1:4", "1/4", "Enclosure 1, Slot 4", "01.04"):
with self.subTest(text=text):
self.assertEqual(msa_import.parse_location(text), ("1", 4))
self.assertIsNone(msa_import.parse_location("x"))
def test_unknown_files_are_not_detected(self):
self.assertIsNone(msa_import.detect_kind("device,slot,serial\nsrv-01,0,ABC"))
+85
View File
@@ -0,0 +1,85 @@
from datetime import date
from types import SimpleNamespace
from django.test import SimpleTestCase
from netbox_utilities import software
def row(product, version, device, *, product_name=None, version_name=None, eos=None):
return {
"product_id": product,
"product_name": product_name or f"Produkt {product}",
"manufacturer": "Hersteller",
"version_id": version,
"version_name": version_name or str(version),
"end_of_support": eos,
"release_type": "S",
"device_id": device,
}
class SoftwareSummaryTest(SimpleTestCase):
def test_counts_devices_once_and_orders_products_by_spread(self):
summary = software.summarize(
[
row(1, 10, 100),
row(1, 10, 100), # same software recorded twice on one device
row(2, 20, 100),
row(2, 21, 101),
row(2, 21, 102),
],
device_total=4,
)
self.assertEqual([product.id for product in summary.products], [2, 1])
self.assertEqual(summary.products[0].device_count, 3)
self.assertEqual(summary.products[0].share, 75)
self.assertEqual(summary.products[1].bar, 33)
self.assertEqual(summary.installations, 5)
self.assertEqual(summary.devices_with_software, 3)
self.assertEqual(summary.devices_without_software, 1)
self.assertEqual(summary.coverage, 75)
self.assertEqual(summary.version_count, 3)
def test_versions_are_sorted_naturally_newest_first(self):
summary = software.summarize(
[row(1, 1, 1, version_name="9.11"), row(1, 2, 2, version_name="10.2"), row(1, 3, 3, version_name="10.10")]
)
product = summary.products[0]
self.assertEqual([version.name for version in product.versions_by_name], ["10.10", "10.2", "9.11"])
self.assertEqual(product.latest_version.name, "10.10")
self.assertEqual([version.shade for version in product.versions_by_name], [100, 68, 35])
def test_expired_support_counts_affected_devices(self):
summary = software.summarize(
[row(1, 1, 1, eos=date(2000, 1, 1)), row(1, 2, 2), row(2, 3, 1, eos=date(2001, 1, 1))]
)
self.assertEqual(summary.expired_device_count, 1)
self.assertEqual(summary.products[0].expired_devices, {1})
def test_empty_selection(self):
summary = software.summarize([], device_total=0)
self.assertEqual(summary.products, [])
self.assertEqual(summary.coverage, 0)
def test_client_role_detection_is_case_insensitive(self):
client = SimpleNamespace(role=SimpleNamespace(name="clients"))
server = SimpleNamespace(role=SimpleNamespace(name="Server"))
self.assertTrue(software.supports_software(client, roles=["Clients"]))
self.assertFalse(software.supports_software(server, roles=["Clients"]))
self.assertFalse(software.supports_software(SimpleNamespace(role=None), roles=["Clients"]))
def test_default_client_roles_match_name_or_slug_but_not_servers(self):
def role(name, slug):
return SimpleNamespace(name=name, slug=slug)
roles = software.DEFAULT_SOFTWARE_DEVICE_ROLES
self.assertTrue(software.is_client_role(role("Client", "client"), roles))
self.assertTrue(software.is_client_role(role("Windows Client", "windows-client"), roles))
self.assertTrue(software.is_client_role(role("Windows-Clients", "windows-client"), roles))
self.assertFalse(software.is_client_role(role("Server", "server"), roles))
@@ -0,0 +1,70 @@
from django.test import SimpleTestCase
from netbox_utilities.software_sync import (
UNKNOWN_VERSION,
SoftwareEntry,
clean_name,
has_software_report,
parse_software_report,
)
AGENT_REPORT = """Updated automatically by the NetBox Windows Agent.
## Hardware
- System: LENOVO 21MW
## Installed software (4)
- 7-Zip 23.01 (x64) 23.01 — Igor Pavlov
- Microsoft Visual C++ 2015-2022 Redistributable (x64) - 14.38.33130 14.38.33130.0 — Microsoft Corporation
- Microsoft Office Professional Plus 2024 — Microsoft Corporation
- Notepad++ (64-bit x64) 8.6.2
"""
SYNCHRONIZER_REPORT = """Handnotiz
<!-- netbox-sync:inventory -->
## Inventar (NetBox Windows Agent)
### Installierte Software (2)
| Programm | Version | Hersteller |
|---|---|---|
| Mozilla Firefox (x64 de) | 120.0 | Mozilla |
| Mozilla Firefox (x64 de) | 120.0 | Mozilla |
| Google Chrome | 119.0.6045.160 | Google LLC |
<!-- /netbox-sync:inventory -->
"""
class SoftwareReportParserTest(SimpleTestCase):
def test_agent_bullets(self):
self.assertEqual(
parse_software_report(AGENT_REPORT),
[
SoftwareEntry("7-Zip 23.01 (x64)", "23.01", "Igor Pavlov"),
SoftwareEntry(
"Microsoft Visual C++ 2015-2022 Redistributable (x64)", "14.38.33130.0", "Microsoft Corporation"
),
SoftwareEntry("Microsoft Office Professional Plus 2024", UNKNOWN_VERSION, "Microsoft Corporation"),
SoftwareEntry("Notepad++ (64-bit x64)", "8.6.2", ""),
],
)
def test_synchronizer_table_without_duplicates(self):
self.assertEqual(
parse_software_report(SYNCHRONIZER_REPORT),
[
SoftwareEntry("Mozilla Firefox (x64 de)", "120.0", "Mozilla"),
SoftwareEntry("Google Chrome", "119.0.6045.160", "Google LLC"),
],
)
def test_without_report(self):
self.assertFalse(has_software_report("Nur eine Notiz\n## Hardware"))
self.assertEqual(parse_software_report("## Hardware\n- CPU: x"), [])
self.assertTrue(has_software_report(AGENT_REPORT))
def test_clean_name_strips_appended_version_only(self):
self.assertEqual(clean_name("Foo Tool 1.2.3", "1.2.3"), "Foo Tool")
self.assertEqual(clean_name("Bar - 14.38", "14.38.1"), "Bar")
self.assertEqual(clean_name("Office 2024", "16.0"), "Office 2024")
+203
View File
@@ -0,0 +1,203 @@
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}
)
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)
class InkTest(SimpleTestCase):
def test_text_colour_contrasts_with_vlan_colour(self):
self.assertEqual(switch_ports.ink_for("#ff7f0e"), "#000000")
self.assertEqual(switch_ports.ink_for("#1f77b4"), "#ffffff")
self.assertEqual(port("1", label="10", assigned_color="#2ca02c").ink, "#000000")
self.assertEqual(port("2").ink, "")
class ManagementTest(SimpleTestCase):
def test_management_ports_are_abbreviated_and_grouped_last(self):
ports = [port("Management"), port("Gi1/0/1"), port("mgmt0"), port("oobm"), port("eth0", mgmt_only=True)]
self.assertEqual([p.short for p in ports], ["MGMT", "1", "MGMT", "MGMT", "MGMT"])
groups = switch_ports.build_groups(ports)
self.assertEqual([group.title for group in groups], ["Gi1/0", "Management"])
self.assertEqual(len(groups[-1].ports), 4)
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)])
def test_lag_note_in_label_is_no_vlan(self):
lag = port("1", label="30 (LAG 1)", cable_vlans=[(30, "")])
self.assertEqual((lag.vlan, lag.vlan_group, lag.vlan_mismatch), ("30", "30", False))
trunk = port("2", label="10,20 (LAG 2)")
self.assertEqual(trunk.vlan_group, "10,20")
self.assertEqual(port("3", label="(LAG 1)").vlan, "")
@@ -6,6 +6,7 @@ from django.test import SimpleTestCase
from tenancy.models import TenantGroup
from netbox_utilities.tenant_autofill import (
apply_asset_instance_tenant,
apply_cable_instance_tenant,
apply_tenant_autofill,
infer_tenant_id,
@@ -44,6 +45,20 @@ class FakeCable(FakeObject):
self.b_terminations = b_terminations or []
class FakeAssetMeta(FakeMeta):
app_label = "netbox_inventory"
model_name = "asset"
class FakeAsset(FakeObject):
"""netbox-inventory asset: tenant plus one of device, module, inventoryitem or rack."""
def __init__(self, *, tenant_id=None, device=None, module=None, inventoryitem=None, rack=None):
super().__init__(tenant_id=tenant_id)
self._meta = FakeAssetMeta("tenant", "device", "module", "inventoryitem", "rack")
self.device, self.module, self.inventoryitem, self.rack = device, module, inventoryitem, rack
class FakeQuerySet:
def __init__(self, model):
self.model = model
@@ -99,6 +114,36 @@ class TenantAutofillTest(SimpleTestCase):
self.assertEqual(apply_cable_instance_tenant(cable), 42)
self.assertEqual(cable.tenant_id, 42)
def test_asset_takes_tenant_of_assigned_device(self):
asset = FakeAsset(device=FakeObject(tenant_id=42))
self.assertEqual(apply_asset_instance_tenant(asset), 42)
self.assertEqual(asset.tenant_id, 42)
def test_asset_takes_tenant_of_module_device_inventory_item_and_rack(self):
device = FakeObject(tenant_id=7)
for asset in (
FakeAsset(module=FakeObject(device=device)),
FakeAsset(inventoryitem=FakeObject(device=device)),
FakeAsset(rack=FakeObject(tenant_id=7)),
):
self.assertEqual(apply_asset_instance_tenant(asset), 7)
def test_asset_keeps_existing_tenant_and_stays_empty_without_hardware(self):
asset = FakeAsset(tenant_id=5, device=FakeObject(tenant_id=42))
self.assertIsNone(apply_asset_instance_tenant(asset))
self.assertEqual(asset.tenant_id, 5)
stored = FakeAsset()
self.assertIsNone(apply_asset_instance_tenant(stored))
self.assertIsNone(stored.tenant_id)
def test_other_models_are_not_assigned_a_tenant_from_their_device(self):
interface_like = FakeObject(device=FakeObject(tenant_id=42))
self.assertIsNone(apply_asset_instance_tenant(interface_like))
self.assertIsNone(interface_like.tenant_id)
def test_prefers_cable_terminations_over_global_scope(self):
form = SimpleNamespace(
fields={"tenant": forms.IntegerField()},
@@ -48,3 +48,44 @@ class TenantValidationTest(SimpleTestCase):
@patch("netbox_utilities.tenant_validation.tenant_required", return_value=False)
def test_allows_missing_tenant_when_disabled(self, _tenant_required):
validate_tenant_assignment(TenantModel())
class FakeAssetMeta(FakeMeta):
app_label = "netbox_inventory"
model_name = "asset"
def get_fields(self):
return [SimpleNamespace(name=name) for name in ("tenant", "device", "module", "inventoryitem", "rack")]
class FakeAsset(TenantModel):
_meta = FakeAssetMeta()
def __init__(self, tenant_id=None, device=None):
super().__init__(tenant_id)
self.device, self.module, self.inventoryitem, self.rack = device, None, None, None
class FakeDevice:
_meta = SimpleNamespace(get_fields=lambda: [SimpleNamespace(name="tenant")])
def __init__(self, tenant_id):
self.tenant_id = tenant_id
class InventoryAssetTenantTest(SimpleTestCase):
@patch("netbox_utilities.tenant_validation.tenant_required", return_value=True)
def test_reassigned_asset_takes_device_tenant_before_save(self, _tenant_required):
from netbox_utilities.tenant_validation import _enforce_before_save
asset = FakeAsset(device=FakeDevice(42))
_enforce_before_save(FakeAsset, asset)
self.assertEqual(asset.tenant_id, 42)
@patch("netbox_utilities.tenant_validation.tenant_required", return_value=True)
def test_unassigned_asset_without_tenant_is_still_rejected(self, _tenant_required):
from netbox_utilities.tenant_validation import _enforce_before_save
with self.assertRaises(ValidationError):
_enforce_before_save(FakeAsset, FakeAsset())
@@ -0,0 +1,71 @@
from types import SimpleNamespace
from unittest.mock import patch
from django.test import SimpleTestCase
from netbox_utilities import wireless_trace
class Interface(SimpleNamespace):
pass
def iface(pk, device_id, wireless_link_id=None, trace=()):
return Interface(pk=pk, device_id=device_id, wireless_link_id=wireless_link_id, trace=lambda: list(trace))
class WirelessTraceTest(SimpleTestCase):
def setUp(self):
# Switch port 1 --cable--> TG ether1 (10); TG wlan60 (11) ~~ Funk wlan60 (21);
# Funk ether1 (20) --cable--> Switch2 port (30)
self.switch_port = iface(1, 1)
self.tg_ether = iface(10, 2)
self.tg_wlan = iface(11, 2, wireless_link_id=99)
self.funk_wlan = iface(21, 3, wireless_link_id=99)
self.switch2_port = iface(30, 4)
self.funk_ether = iface(20, 3, trace=[([iface(20, 3)], ["cable34"], [self.switch2_port])])
self.link = SimpleNamespace(pk=99)
def hop(device_id, visited):
if device_id == 2 and 11 not in visited:
return self.tg_wlan, self.link, self.funk_wlan
if device_id == 3 and 21 not in visited:
return self.funk_wlan, self.link, self.tg_wlan
return None
def cabled(device_id, visited):
if device_id == 3 and 20 not in visited:
return self.funk_ether
return None
patches = [
patch.object(wireless_trace, "_wireless_hop", side_effect=hop),
patch.object(wireless_trace, "_cabled_interface", side_effect=cabled),
patch("dcim.models.Interface", Interface),
]
for p in patches:
p.start()
self.addCleanup(p.stop)
def test_appends_radio_hop_and_peer_cable(self):
trace = [([self.switch_port], ["cable48"], [self.tg_ether])]
result = wireless_trace.extended_trace(self.switch_port, trace)
self.assertEqual(len(result), 3)
self.assertEqual(result[1], ([self.tg_wlan], [self.link], [self.funk_wlan]))
self.assertEqual(result[2][1], ["cable34"])
self.assertIs(result[2][2][0], self.switch2_port)
def test_prepends_reversed_chain_for_radio_origin_side(self):
trace = [([self.tg_ether], ["cable48"], [self.switch_port])]
result = wireless_trace.extended_trace(self.tg_ether, trace)
self.assertEqual(len(result), 3)
self.assertIs(result[0][0][0], self.switch2_port)
self.assertEqual(result[1], ([self.funk_wlan], [self.link], [self.tg_wlan]))
self.assertEqual(result[2][1], ["cable48"])
def test_empty_trace_is_left_alone(self):
self.assertEqual(wireless_trace.extended_trace(self.tg_ether, []), [])
+21 -1
View File
@@ -1,7 +1,9 @@
from django.apps import apps
from django.urls import include, path
from netbox.plugins import get_plugin_config
from utilities.urls import get_model_urls
from . import disk_views, views
from . import disk_views, hardware_views, switch_port_views, views # noqa: F401 - hardware_views registers its model views
app_name = "netbox_utilities"
@@ -18,6 +20,7 @@ urlpatterns = [
path("settings/", views.UtilitiesSettingsView.as_view(), name="settings"),
path("tenant/select/", views.SelectTenantView.as_view(), name="select_tenant"),
# Datenträger
path("disks/import-msa/", disk_views.MSADiskImportView.as_view(), name="disk_msa_import"),
path("disks/by-device/", disk_views.DiskByDeviceView.as_view(), name="disk_by_device"),
path("disks/", include(get_model_urls("netbox_utilities", "disk", detail=False))),
path("disks/<int:pk>/", include(get_model_urls("netbox_utilities", "disk"))),
@@ -26,7 +29,24 @@ urlpatterns = [
path("raid-groups/<int:pk>/", include(get_model_urls("netbox_utilities", "raidgroup"))),
path("disk-templates/", include(get_model_urls("netbox_utilities", "diskbaytemplate", detail=False))),
path("disk-templates/<int:pk>/", include(get_model_urls("netbox_utilities", "diskbaytemplate"))),
# CPU & RAM
path("cpu-models/", include(get_model_urls("netbox_utilities", "cpumodel", detail=False))),
path("cpu-models/<int:pk>/", include(get_model_urls("netbox_utilities", "cpumodel"))),
path("hardware/", include(get_model_urls("netbox_utilities", "devicehardware", detail=False))),
path("hardware/<int:pk>/", include(get_model_urls("netbox_utilities", "devicehardware"))),
path(
"devices/<int:pk>/switch-ports.pdf",
switch_port_views.SwitchPortsPDFView.as_view(),
name="device_switch_ports_pdf",
),
path("devices/<int:pk>/disks/setup/", disk_views.DeviceDiskSetupView.as_view(), name="device_disk_setup"),
path("devices/<int:pk>/disks/fill/", disk_views.DeviceDiskBulkFillView.as_view(), name="device_disk_fill"),
path("devices/<int:pk>/disks/move/", disk_views.DeviceDiskMoveView.as_view(), name="device_disk_move"),
]
if get_plugin_config("netbox_utilities", "software_enabled") and apps.is_installed("netbox_slm"):
from . import software_views
urlpatterns.append(
path("software/", software_views.SoftwareOverviewView.as_view(), name="software_overview"),
)
+143
View File
@@ -0,0 +1,143 @@
"""Continue NetBox cable traces across wireless links (radio bridges).
NetBox stops a trace at the interface a cable ends on. For a point-to-point
radio such as a MikroTik Cube, the interesting part continues on the far side:
the device's wireless interface is linked to a peer radio, whose cabled
interface leads on to the next switch. This module extends the cable trace
SVG at both ends with these hops:
... cable -> ether1 [Radio A] wlan60 ~~ wlan60 [Radio B] ether1 -> cable ...
"""
MAX_HOPS = 8
def _single_interface(terminations):
from dcim.models import Interface
if len(terminations) == 1 and isinstance(terminations[0], Interface):
return terminations[0]
return None
def _wireless_hop(device_id, visited):
"""Return (local, link, peer) for a not yet visited wireless link of the device."""
from dcim.models import Interface
candidates = (
Interface.objects.filter(device_id=device_id, wireless_link__isnull=False)
.exclude(pk__in=visited)
.select_related("wireless_link")
)
for local in candidates:
link = local.wireless_link
peer_id = link.interface_b_id if link.interface_a_id == local.pk else link.interface_a_id
if peer_id in visited:
continue
peer = Interface.objects.select_related("device").filter(pk=peer_id).first()
if peer is not None:
return local, link, peer
return None
def _cabled_interface(device_id, visited):
"""Return the device's first not yet visited interface that carries a cable."""
from dcim.models import Interface
return (
Interface.objects.filter(device_id=device_id, cable__isnull=False, wireless_link__isnull=True)
.exclude(pk__in=visited)
.first()
)
def _collect_ids(segments):
ids = set()
for near_ends, _links, far_ends in segments:
for termination in (*near_ends, *far_ends):
if termination.__class__.__name__ == "Interface":
ids.add(termination.pk)
return ids
def extend_outwards(interface, visited, max_hops=MAX_HOPS):
"""Segments continuing from `interface` through radio links, away from it.
`interface` is the outermost interface of a trace; the returned segments
start on another interface of the same device. `visited` (interface pks)
is updated in place and prevents loops.
"""
segments = []
current = interface
arrived_by_radio = bool(getattr(interface, "wireless_link_id", None))
for _ in range(max_hops):
if arrived_by_radio:
# Leave the radio through its cabled port.
cabled = _cabled_interface(current.device_id, visited)
if cabled is None:
break
trace = [tuple(list(part) for part in segment) for segment in cabled.trace()]
visited.add(cabled.pk)
if not trace:
break
visited |= _collect_ids(trace)
segments.extend(trace)
current = _single_interface(trace[-1][2])
if current is None:
break
arrived_by_radio = bool(current.wireless_link_id)
else:
hop = _wireless_hop(current.device_id, visited)
if hop is None:
break
local, link, peer = hop
visited.update({local.pk, peer.pk})
segments.append(([local], [link], [peer]))
current = peer
arrived_by_radio = True
return segments
def reverse_segments(segments):
return [(list(far_ends), list(links), list(near_ends)) for near_ends, links, far_ends in reversed(segments)]
def extended_trace(origin, trace, max_hops=MAX_HOPS):
"""Return `trace` with radio hops prepended and appended where possible."""
from dcim.models import Interface
trace = [tuple(list(part) for part in segment) for segment in trace]
if not trace or not isinstance(origin, Interface):
return trace
visited = {origin.pk} | _collect_ids(trace)
tail = []
last = _single_interface(trace[-1][2])
if last is not None:
tail = extend_outwards(last, visited, max_hops)
head = reverse_segments(extend_outwards(origin, visited, max_hops))
return head + trace + tail
def install_wireless_trace():
from dcim.svg import CableTraceSVG
if getattr(CableTraceSVG, "_netbox_utilities_wireless_trace", False):
return
original_render = CableTraceSVG.render
def render(self, *args, **kwargs):
origin = self.origin
native_trace = origin.trace
try:
origin.trace = lambda: extended_trace(origin, native_trace())
except AttributeError:
return original_render(self, *args, **kwargs)
try:
return original_render(self, *args, **kwargs)
finally:
del origin.trace
CableTraceSVG.render = render
CableTraceSVG._netbox_utilities_wireless_trace = True
+5 -2
View File
@@ -4,10 +4,13 @@ build-backend = "hatchling.build"
[project]
name = "netbox-utilities"
version = "0.16.0"
description = "Navigation, tenant utilities, connection VLANs, partial-width racks, disks and bulk operations for NetBox 4.6/4.7"
version = "0.29.2"
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,<5",
]
license = { text = "MIT" }
authors = [
{ name = "MrBlake" }