Compare commits
21
Commits
6906bf6ed6
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1d6b16c0e4 | ||
|
|
280c0e0315 | ||
|
|
713556a33e | ||
|
|
7d267ec05d | ||
|
|
e24a12164c | ||
|
|
63b3b31763 | ||
|
|
5d6c4c9cd8 | ||
|
|
bfcfff60e4 | ||
|
|
204bb235a4 | ||
|
|
f86306e686 | ||
|
|
cf1cafb632 | ||
|
|
4dd01b82e3 | ||
|
|
2ea1dcaec3 | ||
|
|
cc2546b332 | ||
|
|
102b161356 | ||
|
|
d49c4c6ee7 | ||
|
|
5fcd7799e3 | ||
|
|
a87d3b1cdf | ||
|
|
356034fe98 | ||
|
|
ce174c6541 | ||
|
|
567daf7963 |
No files matched your search
@@ -41,6 +41,7 @@ Plugin settings:
|
||||
- The rack view of the optional [MrBlake NetBox Topology Views](https://git.mrblake.cc/MrBlake/mrb-netbox-topology-views) plugin renders partial-width devices correctly.
|
||||
- Upload multiple images at once in an object's **Images** tab.
|
||||
- Install multiple modules of the same type into free module bays in one step.
|
||||
- Export device types as YAML in the devicetype-library format (single type or the filtered list as ZIP).
|
||||
- Optional bulk save for devices moved in NetBox Reorder Rack.
|
||||
- Rack widths are preserved by the optional [NetBox-Export](https://git.mrblake.cc/MrBlake/NetBox-Export) export/import.
|
||||
- Cables and wireless links can be assigned to one or more VLANs.
|
||||
@@ -49,6 +50,7 @@ Plugin settings:
|
||||
- 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.
|
||||
@@ -225,6 +227,9 @@ sudo systemctl restart netbox netbox-rq
|
||||
| `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
|
||||
|
||||
@@ -505,6 +510,51 @@ 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**
|
||||
@@ -540,11 +590,22 @@ account, in the front panel and in the PDF:
|
||||
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
|
||||
@@ -606,6 +667,10 @@ interfaces, since both ends can use different interface modes.
|
||||
- An optional **VLAN group** field acts as a dynamic filter for the VLAN selection; it is not stored.
|
||||
- Empty selections create no record; deleting a connection removes its VLAN assignment.
|
||||
- With NetBox-Export installed, the assignments are exported and imported together with connections and VLANs.
|
||||
- Cable VLANs can be read and written through `/api/plugins/utilities/cable-vlans/`
|
||||
(`cable` = cable ID, `vlans` = VLAN IDs, filter with `?cable_id=`; permissions
|
||||
`netbox_utilities.*_cablevlanassignment`). NetBox Synchronizer uses it to keep
|
||||
the cable VLANs of switch ports in step with the port.
|
||||
|
||||
### Multiple devices in one rack unit
|
||||
|
||||
@@ -703,6 +768,18 @@ error occurs, the whole rack stays unchanged. Every moved device still gets a
|
||||
normal changelog entry. Versions other than `1.1.4` are left untouched and only
|
||||
produce a log message.
|
||||
|
||||
### Exporting device types as YAML
|
||||
|
||||
Device type detail pages get an **Export YAML** button that downloads the type
|
||||
in the [devicetype-library](https://github.com/netbox-community/devicetype-library)
|
||||
format (manufacturer, model, slug, dimensions, airflow, weight and all component
|
||||
templates: console/power ports, outlets, interfaces, front/rear ports incl. their
|
||||
mapping, module/device bays and inventory items). Fields at their default value are
|
||||
omitted. The file can be imported again via *Device Types → Import*.
|
||||
|
||||
The device type list gets the same button: it exports every type matching the
|
||||
current filters as `device-types.zip`, laid out as `<Manufacturer>/<slug>.yaml`.
|
||||
|
||||
### Uploading multiple images
|
||||
|
||||
In the **Images** tab of supported objects, the single upload is replaced by
|
||||
@@ -771,6 +848,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.
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
from netbox.plugins import PluginConfig, get_plugin_config
|
||||
|
||||
__version__ = "0.20.0"
|
||||
__version__ = "0.31.0"
|
||||
|
||||
|
||||
class NetBoxUtilitiesConfig(PluginConfig):
|
||||
name = "netbox_utilities"
|
||||
verbose_name = "NetBox Utilities"
|
||||
description = "Navigation, tenant utilities, connection VLANs, partial-width racks, disks, CPU & RAM, switch port export 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"
|
||||
@@ -31,6 +31,9 @@ class NetBoxUtilitiesConfig(PluginConfig):
|
||||
"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",
|
||||
@@ -67,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
|
||||
|
||||
|
||||
@@ -3,7 +3,10 @@ from netbox.api.serializers import NetBoxModelSerializer
|
||||
from rest_framework import serializers
|
||||
from tenancy.api.serializers import TenantSerializer
|
||||
|
||||
from ..models import CPUModel, DeviceHardware, Disk, DiskBayLayout, DiskBayTemplate, RAIDGroup
|
||||
from dcim.models import Cable, Device
|
||||
from ipam.models import VLAN
|
||||
|
||||
from ..models import CableVLANAssignment, CPUModel, DeviceHardware, Disk, DiskBayLayout, DiskBayTemplate, RAIDGroup, SwitchStack
|
||||
|
||||
LAYOUT_FIELDS = ("name", "weight", "slot_count", "rows", "first_slot", "numbering", "form_factor")
|
||||
|
||||
@@ -196,3 +199,31 @@ class DeviceHardwareSerializer(NetBoxModelSerializer):
|
||||
"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
|
||||
|
||||
|
||||
class CableVLANAssignmentSerializer(serializers.ModelSerializer):
|
||||
"""VLANs of a cable connection as VLAN IDs (one assignment per cable)."""
|
||||
|
||||
cable = serializers.PrimaryKeyRelatedField(queryset=Cable.objects.all())
|
||||
vlans = serializers.PrimaryKeyRelatedField(queryset=VLAN.objects.all(), many=True, required=False)
|
||||
|
||||
class Meta:
|
||||
model = CableVLANAssignment
|
||||
fields = ("id", "cable", "vlans", "updated")
|
||||
@@ -11,5 +11,7 @@ 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)
|
||||
router.register("cable-vlans", views.CableVLANAssignmentViewSet)
|
||||
|
||||
urlpatterns = router.urls
|
||||
@@ -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, hardware_filtersets
|
||||
from ..models import CPUModel, DeviceHardware, Disk, DiskBayLayout, DiskBayTemplate, RAIDGroup
|
||||
from ..models import CableVLANAssignment, CPUModel, DeviceHardware, Disk, DiskBayLayout, DiskBayTemplate, RAIDGroup, SwitchStack
|
||||
from . import serializers
|
||||
|
||||
|
||||
@@ -39,3 +41,34 @@ 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
|
||||
|
||||
|
||||
class CableVLANAssignmentViewSet(ModelViewSet):
|
||||
"""VLANs of cable connections; filter with ``?cable_id=``."""
|
||||
|
||||
queryset = CableVLANAssignment.objects.prefetch_related("vlans").order_by("pk")
|
||||
serializer_class = serializers.CableVLANAssignmentSerializer
|
||||
permission_classes = [TokenPermissions]
|
||||
|
||||
def get_queryset(self):
|
||||
queryset = super().get_queryset()
|
||||
if self.request.query_params.get("cable_id"):
|
||||
queryset = queryset.filter(cable_id__in=self.request.query_params.getlist("cable_id"))
|
||||
return queryset
|
||||
@@ -0,0 +1,142 @@
|
||||
"""Export device types as YAML in the community devicetype-library format.
|
||||
|
||||
The output can be re-imported through NetBox's own "Device Types > Import"
|
||||
form or contributed to https://github.com/netbox-community/devicetype-library.
|
||||
"""
|
||||
|
||||
import io
|
||||
import zipfile
|
||||
|
||||
import yaml
|
||||
from django.apps import apps
|
||||
from django.utils.text import slugify
|
||||
|
||||
# (YAML key, related manager on DeviceType, fields exported per component)
|
||||
COMPONENTS = [
|
||||
("console-ports", "consoleporttemplates", ["type"]),
|
||||
("console-server-ports", "consoleserverporttemplates", ["type"]),
|
||||
("power-ports", "powerporttemplates", ["type", "maximum_draw", "allocated_draw"]),
|
||||
("power-outlets", "poweroutlettemplates", ["type", "power_port", "feed_leg"]),
|
||||
("interfaces", "interfacetemplates", ["type", "mgmt_only", "poe_mode", "poe_type"]),
|
||||
("rear-ports", "rearporttemplates", ["type", "color", "positions"]),
|
||||
("front-ports", "frontporttemplates", ["type", "color", "positions"]),
|
||||
("module-bays", "modulebaytemplates", ["position"]),
|
||||
("device-bays", "devicebaytemplates", []),
|
||||
("inventory-items", "inventoryitemtemplates", ["manufacturer", "part_id"]),
|
||||
]
|
||||
|
||||
DEVICE_TYPE_FIELDS = [
|
||||
"part_number",
|
||||
"u_height",
|
||||
"exclude_from_utilization",
|
||||
"is_full_depth",
|
||||
"subdevice_role",
|
||||
"airflow",
|
||||
"weight",
|
||||
"weight_unit",
|
||||
"description",
|
||||
"comments",
|
||||
]
|
||||
|
||||
# Values that equal NetBox's defaults are dropped to keep the files short.
|
||||
DEFAULTS = {
|
||||
"exclude_from_utilization": False,
|
||||
"mgmt_only": False,
|
||||
"positions": 1,
|
||||
"color": "",
|
||||
}
|
||||
|
||||
|
||||
def _plain(value):
|
||||
if value is None or value == "":
|
||||
return None
|
||||
if hasattr(value, "is_finite"): # Decimal
|
||||
return int(value) if value == value.to_integral_value() else float(value)
|
||||
if hasattr(value, "_meta"): # FK (power_port, manufacturer)
|
||||
return getattr(value, "name", str(value))
|
||||
return value
|
||||
|
||||
|
||||
def _put(target, key, value):
|
||||
value = _plain(value)
|
||||
if value is None or DEFAULTS.get(key, object()) == value:
|
||||
return
|
||||
target[key] = value
|
||||
|
||||
|
||||
def _front_port_mappings(device_type):
|
||||
"""{front_port_id: (rear_port_name, rear_port_position)} for single mappings (NetBox >= 4.5)."""
|
||||
try:
|
||||
model = apps.get_model("dcim", "PortTemplateMapping")
|
||||
except LookupError:
|
||||
return {}
|
||||
mappings = {}
|
||||
for mapping in model.objects.filter(device_type=device_type).select_related("rear_port"):
|
||||
mappings.setdefault(mapping.front_port_id, []).append(mapping)
|
||||
return {
|
||||
front_id: (items[0].rear_port.name, items[0].rear_port_position)
|
||||
for front_id, items in mappings.items()
|
||||
if len(items) == 1
|
||||
}
|
||||
|
||||
|
||||
def device_type_to_dict(device_type):
|
||||
data = {
|
||||
"manufacturer": device_type.manufacturer.name,
|
||||
"model": device_type.model,
|
||||
"slug": device_type.slug,
|
||||
}
|
||||
for field in DEVICE_TYPE_FIELDS:
|
||||
_put(data, field, getattr(device_type, field, None))
|
||||
|
||||
mappings = None
|
||||
for key, manager, fields in COMPONENTS:
|
||||
items = []
|
||||
for component in getattr(device_type, manager).all():
|
||||
item = {"name": component.name}
|
||||
label = getattr(component, "label", "")
|
||||
if label:
|
||||
item["label"] = label
|
||||
for field in fields:
|
||||
if hasattr(component, field):
|
||||
_put(item, field, getattr(component, field))
|
||||
if key == "front-ports":
|
||||
if mappings is None:
|
||||
mappings = _front_port_mappings(device_type)
|
||||
legacy_rear = getattr(component, "rear_port", None)
|
||||
if component.pk in mappings:
|
||||
item["rear_port"], item["rear_port_position"] = mappings[component.pk]
|
||||
elif legacy_rear is not None: # NetBox < 4.5
|
||||
item["rear_port"] = legacy_rear.name
|
||||
item["rear_port_position"] = component.rear_port_position
|
||||
if component.description:
|
||||
item["description"] = component.description
|
||||
items.append(item)
|
||||
if items:
|
||||
data[key] = items
|
||||
return data
|
||||
|
||||
|
||||
def device_type_to_yaml(device_type):
|
||||
return yaml.safe_dump(
|
||||
device_type_to_dict(device_type),
|
||||
sort_keys=False,
|
||||
allow_unicode=True,
|
||||
default_flow_style=False,
|
||||
)
|
||||
|
||||
|
||||
def filename(device_type):
|
||||
return f"{device_type.slug or slugify(device_type.model)}.yaml"
|
||||
|
||||
|
||||
def device_types_to_zip(device_types):
|
||||
"""ZIP laid out like the devicetype-library: <Manufacturer>/<slug>.yaml"""
|
||||
buffer = io.BytesIO()
|
||||
with zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) as archive:
|
||||
for device_type in device_types:
|
||||
archive.writestr(
|
||||
f"{device_type.manufacturer.name}/{filename(device_type)}",
|
||||
device_type_to_yaml(device_type),
|
||||
)
|
||||
return buffer.getvalue()
|
||||
@@ -0,0 +1,46 @@
|
||||
from dcim.filtersets import DeviceTypeFilterSet
|
||||
from dcim.models import DeviceType
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.http import HttpResponse
|
||||
from django.shortcuts import get_object_or_404
|
||||
from django.views import View
|
||||
|
||||
from . import devicetype_export
|
||||
|
||||
PREFETCH = [
|
||||
"consoleporttemplates",
|
||||
"consoleserverporttemplates",
|
||||
"powerporttemplates",
|
||||
"poweroutlettemplates__power_port",
|
||||
"interfacetemplates",
|
||||
"rearporttemplates",
|
||||
"frontporttemplates",
|
||||
"modulebaytemplates",
|
||||
"devicebaytemplates",
|
||||
"inventoryitemtemplates__manufacturer",
|
||||
]
|
||||
|
||||
|
||||
def _queryset(request):
|
||||
if not request.user.has_perm("dcim.view_devicetype"):
|
||||
raise PermissionDenied
|
||||
return DeviceType.objects.restrict(request.user, "view").select_related("manufacturer").prefetch_related(*PREFETCH)
|
||||
|
||||
|
||||
class DeviceTypeYAMLExportView(LoginRequiredMixin, View):
|
||||
def get(self, request, pk):
|
||||
device_type = get_object_or_404(_queryset(request), pk=pk)
|
||||
response = HttpResponse(devicetype_export.device_type_to_yaml(device_type), content_type="application/yaml; charset=utf-8")
|
||||
response["Content-Disposition"] = f'attachment; filename="{devicetype_export.filename(device_type)}"'
|
||||
return response
|
||||
|
||||
|
||||
class DeviceTypeBulkYAMLExportView(LoginRequiredMixin, View):
|
||||
"""Exports the current (filtered) device type list, or ?id=... selections, as a ZIP."""
|
||||
|
||||
def get(self, request):
|
||||
device_types = DeviceTypeFilterSet(request.GET, queryset=_queryset(request)).qs.order_by("manufacturer__name", "model")
|
||||
response = HttpResponse(devicetype_export.device_types_to_zip(device_types), content_type="application/zip")
|
||||
response["Content-Disposition"] = 'attachment; filename="device-types.zip"'
|
||||
return response
|
||||
@@ -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()
|
||||
@@ -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."
|
||||
)
|
||||
)
|
||||
@@ -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",
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -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",
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -19,6 +19,12 @@ 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"))
|
||||
|
||||
|
||||
@@ -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),
|
||||
)
|
||||
@@ -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__)
|
||||
@@ -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
|
||||
@@ -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"),
|
||||
}
|
||||
@@ -562,3 +562,203 @@ a.nbu-disk-slot[draggable="true"] {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -372,8 +372,12 @@ def _port_table(ports, t, styles):
|
||||
return table
|
||||
|
||||
|
||||
def build_pdf(device, ports, lang="de", generated=None):
|
||||
"""Return the PDF as bytes. ``device`` is a DeviceInfo, ``ports`` a list of switch_ports.Port."""
|
||||
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()
|
||||
@@ -414,18 +418,22 @@ def build_pdf(device, ports, lang="de", generated=None):
|
||||
]
|
||||
|
||||
switch_ports.assign_vlan_colors(ports)
|
||||
groups = switch_ports.build_groups(ports)
|
||||
if not groups:
|
||||
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 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))
|
||||
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(
|
||||
@@ -433,7 +441,13 @@ def build_pdf(device, ports, lang="de", generated=None):
|
||||
)
|
||||
story.append(CondPageBreak(40 * mm))
|
||||
story.append(Paragraph(t["list"], styles["h2"]))
|
||||
story.append(_port_table(ports, t, styles))
|
||||
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()
|
||||
@@ -77,16 +77,30 @@ def collect_ports(interfaces):
|
||||
|
||||
|
||||
def switch_panel_context(request, device):
|
||||
"""Front panel above the "Device" and "Management" cards, in the user's NetBox language."""
|
||||
ports = collect_ports(interface_queryset(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 {
|
||||
"groups": switch_ports.build_groups(ports),
|
||||
"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,
|
||||
@@ -117,10 +131,18 @@ class SwitchPortsPDFView(ContentTypePermissionRequiredMixin, View):
|
||||
device = get_object_or_404(
|
||||
Device.objects.restrict(request.user, "view").select_related("site", "rack", "device_type"), pk=pk
|
||||
)
|
||||
interfaces = interface_queryset(request, device)
|
||||
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(device), collect_ports(interfaces), lang=lang, generated=timezone.localtime()
|
||||
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")
|
||||
|
||||
@@ -46,6 +46,7 @@ VLAN_PALETTE = (
|
||||
PANEL_TEXTS = {
|
||||
"de": {
|
||||
"title": "Ports",
|
||||
"this_device": "dieses Gerät",
|
||||
"status": "Status",
|
||||
"vlan": "VLAN",
|
||||
"connected": "Belegt",
|
||||
@@ -63,6 +64,7 @@ PANEL_TEXTS = {
|
||||
},
|
||||
"en": {
|
||||
"title": "Ports",
|
||||
"this_device": "this device",
|
||||
"status": "Status",
|
||||
"vlan": "VLAN",
|
||||
"connected": "Connected",
|
||||
@@ -115,6 +117,10 @@ def split_name(name):
|
||||
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)
|
||||
@@ -202,7 +208,12 @@ class Port:
|
||||
@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.label) or self.cable_vlan_key
|
||||
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):
|
||||
@@ -217,9 +228,9 @@ class Port:
|
||||
@property
|
||||
def vlan_mismatch(self):
|
||||
"""True if the numbers in the label differ from the cable VLANs; labels without numbers never mismatch."""
|
||||
if not self.label or not self.cable_vlans:
|
||||
if not self.vlan_text or not self.cable_vlans:
|
||||
return False
|
||||
label_ids = {int(number) for number in _NATURAL.findall(self.label) if number.isdigit()}
|
||||
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
|
||||
@@ -240,9 +251,9 @@ class Port:
|
||||
A label with exactly one number is that VLAN ID, so "Server 30", "VLAN 30", "30" and a cable
|
||||
with VLAN 30 belong together; other labels ("Trunk", "10,20") stay as they are.
|
||||
"""
|
||||
if self.label:
|
||||
numbers = [number for number in _NATURAL.findall(self.label) if number.isdigit()]
|
||||
return str(int(numbers[0])) if len(numbers) == 1 else vlan_key(self.label)
|
||||
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
|
||||
|
||||
|
||||
@@ -338,7 +349,7 @@ def vlan_legend(ports):
|
||||
continue
|
||||
group = port.vlan_group
|
||||
colors.setdefault(group, port.color)
|
||||
if port.label and group not in labelled:
|
||||
if port.vlan_text and group not in labelled:
|
||||
names[group] = port.vlan
|
||||
labelled.add(group)
|
||||
names.setdefault(group, port.vlan)
|
||||
|
||||
@@ -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])
|
||||
@@ -213,6 +213,29 @@ class ConnectionVLANContent(PluginTemplateExtension):
|
||||
)
|
||||
|
||||
|
||||
class DeviceTypeExportContent(PluginTemplateExtension):
|
||||
models = ["dcim.devicetype"]
|
||||
|
||||
def _label(self, bulk=False):
|
||||
german = (translation.get_language() or "").startswith("de")
|
||||
return "YAML exportieren" if german else "Export YAML"
|
||||
|
||||
def buttons(self):
|
||||
device_type = self.context["object"]
|
||||
url = reverse("plugins:netbox_utilities:devicetype_yaml", kwargs={"pk": device_type.pk})
|
||||
return self.render("netbox_utilities/devicetype_yaml_button.html", {"url": url, "label": self._label()})
|
||||
|
||||
def list_buttons(self):
|
||||
request = self.context["request"]
|
||||
url = reverse("plugins:netbox_utilities:devicetype_bulk_yaml")
|
||||
query = request.GET.copy()
|
||||
for key in ("page", "per_page", "sort", "export"):
|
||||
query.pop(key, None)
|
||||
if query:
|
||||
url = f"{url}?{query.urlencode()}"
|
||||
return self.render("netbox_utilities/devicetype_yaml_button.html", {"url": url, "label": self._label(True)})
|
||||
|
||||
|
||||
class RackUtilitiesContent(PluginTemplateExtension):
|
||||
models = ["dcim.rack"]
|
||||
|
||||
@@ -235,6 +258,7 @@ template_extensions = [
|
||||
DeviceUtilitiesContent,
|
||||
ConnectionVLANContent,
|
||||
RackUtilitiesContent,
|
||||
DeviceTypeExportContent,
|
||||
ClusterHardwareContent,
|
||||
VirtualMachineHardwareContent,
|
||||
]
|
||||
@@ -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,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 %}
|
||||
@@ -17,32 +17,39 @@
|
||||
</a>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
{% if not groups %}
|
||||
{% if not has_ports %}
|
||||
<span class="text-muted">{{ texts.none }}</span>
|
||||
{% else %}
|
||||
<div class="nbu-faceplate">
|
||||
{% for group in 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>
|
||||
{% 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>
|
||||
{% endfor %}
|
||||
</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>
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
<a href="{{ url }}" class="btn btn-outline-secondary">
|
||||
<i class="mdi mdi-file-code-outline" aria-hidden="true"></i>
|
||||
{{ label }}
|
||||
</a>
|
||||
@@ -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 %}
|
||||
@@ -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):
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -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")
|
||||
@@ -194,3 +194,10 @@ class VlanIdentityTest(SimpleTestCase):
|
||||
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, []), [])
|
||||
@@ -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, hardware_views, switch_port_views, views # noqa: F401 - hardware_views registers its model views
|
||||
from . import devicetype_views, disk_views, hardware_views, switch_port_views, views # noqa: F401 - hardware_views registers its model views
|
||||
|
||||
app_name = "netbox_utilities"
|
||||
|
||||
@@ -15,6 +17,16 @@ urlpatterns = [
|
||||
views.RackElevationOfflineSVGView.as_view(),
|
||||
name="rack_elevation_offline_svg",
|
||||
),
|
||||
path(
|
||||
"device-types/export-yaml/",
|
||||
devicetype_views.DeviceTypeBulkYAMLExportView.as_view(),
|
||||
name="devicetype_bulk_yaml",
|
||||
),
|
||||
path(
|
||||
"device-types/<int:pk>/export.yaml",
|
||||
devicetype_views.DeviceTypeYAMLExportView.as_view(),
|
||||
name="devicetype_yaml",
|
||||
),
|
||||
path("settings/", views.UtilitiesSettingsView.as_view(), name="settings"),
|
||||
path("tenant/select/", views.SelectTenantView.as_view(), name="select_tenant"),
|
||||
# Datenträger
|
||||
@@ -41,3 +53,10 @@ urlpatterns = [
|
||||
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"),
|
||||
)
|
||||
@@ -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
|
||||
+2
-2
@@ -4,12 +4,12 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "netbox-utilities"
|
||||
version = "0.20.0"
|
||||
version = "0.31.0"
|
||||
description = "Navigation, tenant utilities, connection VLANs, partial-width racks, disks, CPU & RAM, switch port export and bulk operations for NetBox 4.6/4.7"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"reportlab>=4.0",
|
||||
"reportlab>=4.0,<5",
|
||||
]
|
||||
license = { text = "MIT" }
|
||||
authors = [
|
||||
|
||||
Reference in new issue
Block a user