diff --git a/README.md b/README.md index 1b5257c..c0e4a92 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,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 +226,8 @@ 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` | `["Clients"]` | Device roles (case-insensitive) that show the **Software** tab and are pre-selected in the overview | | `wireless_trace_enabled` | `True` | Cable trace continues across wireless links (radio bridges) to the cabled port of the peer radio | ## Usage @@ -506,6 +509,31 @@ 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. +The device role filter is pre-set to `software_device_roles`; clearing it +includes all devices. + +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** diff --git a/netbox_utilities/__init__.py b/netbox_utilities/__init__.py index e4516f2..6782ee8 100644 --- a/netbox_utilities/__init__.py +++ b/netbox_utilities/__init__.py @@ -1,12 +1,12 @@ from netbox.plugins import PluginConfig, get_plugin_config -__version__ = "0.27.3" +__version__ = "0.28.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" @@ -32,6 +32,8 @@ class NetBoxUtilitiesConfig(PluginConfig): "switch_ports_enabled": True, "switch_device_roles": ["Switch"], "wireless_trace_enabled": True, + "software_enabled": True, + "software_device_roles": ["Clients"], } middleware = [ "netbox_utilities.middleware.GlobalTenantFilterMiddleware", @@ -80,6 +82,10 @@ class NetBoxUtilitiesConfig(PluginConfig): 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 diff --git a/netbox_utilities/runtime.py b/netbox_utilities/runtime.py index 2738223..1be0f8b 100644 --- a/netbox_utilities/runtime.py +++ b/netbox_utilities/runtime.py @@ -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")) diff --git a/netbox_utilities/software.py b/netbox_utilities/software.py new file mode 100644 index 0000000..77bcbff --- /dev/null +++ b/netbox_utilities/software.py @@ -0,0 +1,170 @@ +"""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 = ("Clients",) +# 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 supports_software(device, roles=None): + """Devices with a configured client role get the "Software" tab.""" + role = getattr(device, "role", None) + return bool(role and str(getattr(role, "name", "")).casefold() in configured_roles(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), + ) diff --git a/netbox_utilities/software_integration.py b/netbox_utilities/software_integration.py new file mode 100644 index 0000000..cd53285 --- /dev/null +++ b/netbox_utilities/software_integration.py @@ -0,0 +1,64 @@ +"""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 + + request_started.connect(_install_menu_on_first_request, dispatch_uid=__name__) diff --git a/netbox_utilities/software_views.py b/netbox_utilities/software_views.py new file mode 100644 index 0000000..e3424f7 --- /dev/null +++ b/netbox_utilities/software_views.py @@ -0,0 +1,269 @@ +"""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(): + roles = software.configured_roles() + return [role.pk for role in DeviceRole.objects.all() if role.name.casefold() in roles] + + +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"}, + ) + role_id = DynamicModelMultipleChoiceField(queryset=DeviceRole.objects.all(), required=False, label="Gerätrolle") + q = forms.CharField(required=False, label="Software suchen") + + +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() + submitted = params.pop("submitted", None) is not None + if not submitted and "role_id" not in params: + # First visit: clients only. An emptied role field afterwards means all roles. + params.setlist("role_id", [str(pk) for pk in client_role_ids()]) + 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) + if roles := data.get("role_id"): + devices = devices.filter(role__in=roles) + + 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"), + } diff --git a/netbox_utilities/static/netbox_utilities/netbox_utilities.css b/netbox_utilities/static/netbox_utilities/netbox_utilities.css index 56fd4f5..049c78b 100644 --- a/netbox_utilities/static/netbox_utilities/netbox_utilities.css +++ b/netbox_utilities/static/netbox_utilities/netbox_utilities.css @@ -562,3 +562,146 @@ a.nbu-disk-slot[draggable="true"] { border-color: #fd7e14 transparent transparent transparent; background: none; } + +/* Client Software Übersicht */ +.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; + } +} diff --git a/netbox_utilities/templates/netbox_utilities/device_software.html b/netbox_utilities/templates/netbox_utilities/device_software.html new file mode 100644 index 0000000..e12e61b --- /dev/null +++ b/netbox_utilities/templates/netbox_utilities/device_software.html @@ -0,0 +1,77 @@ +{% extends 'dcim/device/base.html' %} +{% load helpers %} + +{% block content %} +
+
+

+ Installierte Software + {{ entries|length }} +

+ {% if entries|length > 8 %} + + {% endif %} + + Übersicht{% if object.tenant %} {{ object.tenant }}{% endif %} + + {% if can_add %} + Software hinzufügen + {% endif %} +
+ {% if entries %} +
+ + + + + + + + + + + + + {% for entry in entries %} + {% with product=entry.software_product version=entry.version %} + + + + + + + + + {% endwith %} + {% endfor %} + +
SoftwareHerstellerVersionReleaseSupport-Ende
{{ product }}{{ product.manufacturer|placeholder }}{{ version }}{{ version.get_release_type_display|placeholder }} + {% if version.end_of_support %} + {% if version.end_of_support < today %} + {{ version.end_of_support|isodate }} + {% else %}{{ version.end_of_support|isodate }}{% endif %} + {% else %}—{% endif %} + + {% if can_change %} + + + + {% endif %} + {% if can_delete %} + + + + {% endif %} +
+
+ {% else %} +
+ + Für dieses Gerät ist noch keine Software erfasst. + {% if can_add %}{% endif %} +
+ {% endif %} +
+{% include 'netbox_utilities/inc/software_table_js.html' %} +{% endblock %} diff --git a/netbox_utilities/templates/netbox_utilities/inc/software_product.html b/netbox_utilities/templates/netbox_utilities/inc/software_product.html new file mode 100644 index 0000000..a6986c5 --- /dev/null +++ b/netbox_utilities/templates/netbox_utilities/inc/software_product.html @@ -0,0 +1,115 @@ +{% load helpers %} + + +
+
+
+
+
+

{{ product.name }}

+
{{ product.manufacturer|default:"Kein Hersteller" }}
+
+ {% if product_obj %} + + Produkt + + {% endif %} +
+
+
+
{{ product.device_count }}
Rechner
+
{{ product.share }} %
der Rechner
+
{{ product.version_count }}
Versionen
+
+ {% with item=product %}{% include 'netbox_utilities/inc/software_version_stack.html' %}{% endwith %} +
+
+
+
+
+

Rechner je Version anklicken zum Filtern

+ +
+
+
+ +
+
+

+ Installiert auf + {{ entries|length }} + {% if selected_version %} + + Version {{ selected_version.name }} + + {% endif %} +

+ +
+
+ + + + + + + + + + + + + + {% for entry in entries %} + {% with device=entry.device version=entry.version %} + + + + + + + + + + {% endwith %} + {% empty %} + + {% endfor %} + +
RechnerMandantStandortRolleVersionSupport-Ende
{{ device }}{{ device.tenant|linkify|placeholder }}{{ device.site|linkify|placeholder }}{{ device.role|placeholder }} + {{ version.name }} + {% if product.latest_version.id == version.id %}neueste{% endif %} + + {% if version.end_of_support %} + {{ version.end_of_support|isodate }} + {% else %}—{% endif %} + + + + +
Keine Installationen.
+
+
diff --git a/netbox_utilities/templates/netbox_utilities/inc/software_table_js.html b/netbox_utilities/templates/netbox_utilities/inc/software_table_js.html new file mode 100644 index 0000000..16aa043 --- /dev/null +++ b/netbox_utilities/templates/netbox_utilities/inc/software_table_js.html @@ -0,0 +1,41 @@ + diff --git a/netbox_utilities/templates/netbox_utilities/inc/software_version_stack.html b/netbox_utilities/templates/netbox_utilities/inc/software_version_stack.html new file mode 100644 index 0000000..673fda5 --- /dev/null +++ b/netbox_utilities/templates/netbox_utilities/inc/software_version_stack.html @@ -0,0 +1,7 @@ + + {% for version in item.versions_by_name %} + + {% endfor %} + diff --git a/netbox_utilities/templates/netbox_utilities/software_overview.html b/netbox_utilities/templates/netbox_utilities/software_overview.html new file mode 100644 index 0000000..ca33a39 --- /dev/null +++ b/netbox_utilities/templates/netbox_utilities/software_overview.html @@ -0,0 +1,196 @@ +{% extends 'base/layout.html' %} +{% load helpers %} + +{% block title %}{% if product %}{{ product.name }} · {% endif %}Client Software Übersicht{% endblock %} + +{% block controls %} +
+ + CSV exportieren + + {% if can_add %} + + Installation erfassen + + {% endif %} +
+{% endblock controls %} + +{% block content %} + {# Filter #} +
+ + {% if product %}{% endif %} +
+
+
+ + {{ form.tenant_group_id }} +
+
+ + {{ form.tenant_id }} +
+
+ + {{ form.role_id }} +
+
+ + +
+
+ + + + +
+
+
+ {% if scope_label %} + + Es gilt der globale Mandantenfilter {{ scope_label }}. Eine eigene Auswahl hier hat Vorrang. + {% else %} + Mandantengruppen schließen alle Untergruppen ein. Ohne Gerätrolle werden alle Geräte berücksichtigt. + {% endif %} +
+
+
+ + {# Kennzahlen #} +
+
+
+
Rechner
+
{{ summary.device_total }}
+
{{ summary.devices_with_software }} mit erfasster Software
+
+
+
+
+
Erfassungsgrad
+
{{ summary.coverage }} %
+
+
+
+
{{ summary.devices_without_software }} Rechner ohne Software
+
+
+
+
+
Software-Produkte
+
{{ summary.product_count }}
+
{{ summary.version_count }} Version{{ summary.version_count|pluralize:"en" }} · {{ summary.installations }} Installation{{ summary.installations|pluralize:"en" }}
+
+
+
+
+
Support abgelaufen
+
{{ summary.expired_device_count }}
+
Rechner mit mindestens einer Version nach Support-Ende
+
+
+
+ + {% if product_missing %} +
Dieses Produkt ist mit der aktuellen Auswahl auf keinem Rechner installiert. + Zur Übersicht
+ {% endif %} + + {% if product %} + {% include 'netbox_utilities/inc/software_product.html' %} + {% elif summary.products %} +
+ {# Diagramm: Top-Produkte #} +
+
+

Verbreitetste Software Rechner je Produkt

+
+ +
+
+
+ {# Diagramm: Versionsverteilung #} +
+
+

Versionsverteilung neueste Version am kräftigsten

+ +
+
+
+ + {# Tabelle aller Produkte #} +
+
+

Alle Software-Produkte {{ summary.product_count }}

+ +
+
+ + + + + + + + + + + + + + + {% for item in summary.products %} + + + + + + + + + {% with expired=item.expired_devices|length %} + + {% endwith %} + + {% endfor %} + +
ProduktHerstellerRechnerAnteilVersionenVerteilungNeueste VersionSupport abgelaufen
{{ item.name }}{{ item.manufacturer|placeholder }}{{ item.device_count }}{{ item.share }} %{{ item.version_count }}{% include 'netbox_utilities/inc/software_version_stack.html' %}{% with latest=item.latest_version %}{{ latest.name }} ({{ latest.device_count }}){% endwith %}{% if expired %}{{ expired }}{% else %}—{% endif %}
+
+ +
+ {% else %} +
+ + Für diese Auswahl ist keine Software erfasst. + {% if can_add %}{% endif %} +
+ {% endif %} + + {% include 'netbox_utilities/inc/software_table_js.html' %} +{% endblock content %} diff --git a/netbox_utilities/tests/test_software.py b/netbox_utilities/tests/test_software.py new file mode 100644 index 0000000..62a0644 --- /dev/null +++ b/netbox_utilities/tests/test_software.py @@ -0,0 +1,75 @@ +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"])) diff --git a/netbox_utilities/urls.py b/netbox_utilities/urls.py index 6602040..e482fa6 100644 --- a/netbox_utilities/urls.py +++ b/netbox_utilities/urls.py @@ -1,4 +1,6 @@ +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 @@ -41,3 +43,10 @@ urlpatterns = [ path("devices//disks/fill/", disk_views.DeviceDiskBulkFillView.as_view(), name="device_disk_fill"), path("devices//disks/move/", disk_views.DeviceDiskMoveView.as_view(), name="device_disk_move"), ] + +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"), + ) diff --git a/pyproject.toml b/pyproject.toml index 0daa47f..acf85c5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "netbox-utilities" -version = "0.27.3" +version = "0.28.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"