Compare commits
5
Commits
7d267ec05d
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f426283e10 | ||
|
|
2c35147dca | ||
|
|
1d6b16c0e4 | ||
|
|
280c0e0315 | ||
|
|
713556a33e |
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.
|
||||
@@ -228,6 +229,10 @@ sudo systemctl restart netbox netbox-rq
|
||||
| `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 |
|
||||
| `software_latest_enabled` | `True` | Look up the newest version of each product online (endoflife.date, Repology) |
|
||||
| `software_latest_sources` | `["endoflife", "repology"]` | Online sources to ask |
|
||||
| `software_latest_mapping` | `{}` | Project names per product name, e.g. `{"Google Chrome": {"endoflife": "chrome", "repology": "chromium"}}`; `False` skips a product |
|
||||
| `software_latest_cache_hours` | `24` | How long online results are cached |
|
||||
| `wireless_trace_enabled` | `True` | Cable trace continues across wireless links (radio bridges) to the cabled port of the peer radio |
|
||||
|
||||
## Usage
|
||||
@@ -543,6 +548,20 @@ 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.
|
||||
|
||||
**Newest version according to the internet.** The product list gets the columns
|
||||
*Laut Internet* and *Veraltet*, and a product's page shows the newest version
|
||||
next to its own versions, each marked *aktuell* or *veraltet*. The versions come
|
||||
from [endoflife.date](https://endoflife.date) (latest patch of the supported
|
||||
release cycles) and [Repology](https://repology.org) (newest upstream version,
|
||||
preferring winget, Chocolatey and Scoop); the newer of both wins. Product names
|
||||
are guessed (`Mozilla Firefox (x64 de)` → `firefox`, then `mozilla-firefox`);
|
||||
where the guess fails, set `software_latest_mapping`. Only the precision of the
|
||||
online version counts: `128.0.3.8945` is current against `128.0.3`. Results are
|
||||
loaded in the background after the page and cached (`software_latest_cache_hours`,
|
||||
failed lookups one hour); *Online neu prüfen* asks again. NetBox needs outbound
|
||||
HTTPS to `endoflife.date` and `repology.org`; `HTTP_PROXIES` from the NetBox
|
||||
configuration is used. Repology is queried at most once per second.
|
||||
|
||||
Devices that already have a report are transferred once with:
|
||||
|
||||
```bash
|
||||
@@ -666,6 +685,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
|
||||
|
||||
@@ -763,6 +786,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
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from netbox.plugins import PluginConfig, get_plugin_config
|
||||
|
||||
__version__ = "0.29.1"
|
||||
__version__ = "0.32.1"
|
||||
|
||||
|
||||
class NetBoxUtilitiesConfig(PluginConfig):
|
||||
@@ -34,6 +34,10 @@ class NetBoxUtilitiesConfig(PluginConfig):
|
||||
"wireless_trace_enabled": True,
|
||||
"software_enabled": True,
|
||||
"software_device_roles": ["Client", "Windows Client"],
|
||||
"software_latest_enabled": True,
|
||||
"software_latest_sources": ["endoflife", "repology"],
|
||||
"software_latest_mapping": {},
|
||||
"software_latest_cache_hours": 24,
|
||||
}
|
||||
middleware = [
|
||||
"netbox_utilities.middleware.GlobalTenantFilterMiddleware",
|
||||
|
||||
@@ -3,9 +3,10 @@ from netbox.api.serializers import NetBoxModelSerializer
|
||||
from rest_framework import serializers
|
||||
from tenancy.api.serializers import TenantSerializer
|
||||
|
||||
from dcim.models import Device
|
||||
from dcim.models import Cable, Device
|
||||
from ipam.models import VLAN
|
||||
|
||||
from ..models import CPUModel, DeviceHardware, Disk, DiskBayLayout, DiskBayTemplate, RAIDGroup, SwitchStack
|
||||
from ..models import CableVLANAssignment, CPUModel, DeviceHardware, Disk, DiskBayLayout, DiskBayTemplate, RAIDGroup, SwitchStack
|
||||
|
||||
LAYOUT_FIELDS = ("name", "weight", "slot_count", "rows", "first_slot", "numbering", "form_factor")
|
||||
|
||||
@@ -215,3 +216,14 @@ class SwitchStackSerializer(serializers.ModelSerializer):
|
||||
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")
|
||||
@@ -12,5 +12,6 @@ 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
|
||||
@@ -3,7 +3,7 @@ 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, SwitchStack
|
||||
from ..models import CableVLANAssignment, CPUModel, DeviceHardware, Disk, DiskBayLayout, DiskBayTemplate, RAIDGroup, SwitchStack
|
||||
from . import serializers
|
||||
|
||||
|
||||
@@ -58,3 +58,17 @@ class SwitchStackViewSet(ModelViewSet):
|
||||
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,280 @@
|
||||
"""
|
||||
Newest software version according to online sources, compared with the installed versions.
|
||||
|
||||
Sources:
|
||||
- endoflife.date (https://endoflife.date/docs/api/v1/): release cycles with their latest patch version.
|
||||
- Repology (https://repology.org/api): aggregates 300+ package repositories, among them winget,
|
||||
Chocolatey and Scoop, and marks the newest known upstream version.
|
||||
|
||||
The pure helpers (name candidates, response parsing, version comparison) carry no NetBox
|
||||
dependency; lookup() adds HTTP, NetBox's HTTP_PROXIES and the Django cache.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import ssl
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from collections import Counter
|
||||
|
||||
from .software import version_key
|
||||
|
||||
SOURCES = ("endoflife", "repology")
|
||||
SOURCE_LABELS = {"endoflife": "endoflife.date", "repology": "Repology"}
|
||||
DEFAULT_CACHE_HOURS = 24
|
||||
TIMEOUT = 10
|
||||
# Repositories whose packages are what Windows clients actually install.
|
||||
WINDOWS_REPOS = ("winget", "chocolatey", "scoop")
|
||||
# Repology asks for at most one API request per second.
|
||||
REPOLOGY_INTERVAL = 1.1
|
||||
# Words that describe the build, not the product: "Firefox (x64 de)", "Notepad++ 64-bit".
|
||||
NOISE = re.compile(
|
||||
r"\((?:[^)]*)\)|\b(?:x64|x86|amd64|arm64|win64|win32|64-bit|32-bit|64 bit|32 bit|en-us|de-de|de|en)\b",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
VERSION_TOKEN = re.compile(r"\bv?\d+(?:\.\d+)+\w*\b")
|
||||
VENDORS = {"microsoft", "mozilla", "google", "adobe", "oracle", "videolan", "the", "apache", "igor"}
|
||||
|
||||
_repology_lock = threading.Lock()
|
||||
_repology_last = 0.0
|
||||
|
||||
|
||||
def clean_name(name):
|
||||
"""Product name without architecture, language and version noise."""
|
||||
text = NOISE.sub(" ", str(name or ""))
|
||||
text = VERSION_TOKEN.sub(" ", text)
|
||||
return re.sub(r"\s+", " ", text).strip(" -_,.")
|
||||
|
||||
|
||||
def slugify(text):
|
||||
return re.sub(r"[^a-z0-9+]+", "-", text.casefold()).strip("-")
|
||||
|
||||
|
||||
def name_candidates(name, manufacturer=""):
|
||||
"""Project names to try, most specific guess first ("Mozilla Firefox (x64 de)" -> firefox, mozilla-firefox)."""
|
||||
cleaned = clean_name(name)
|
||||
words = cleaned.split()
|
||||
vendor_words = {word.casefold() for word in str(manufacturer or "").split()} | VENDORS
|
||||
without_vendor = words
|
||||
while len(without_vendor) > 1 and without_vendor[0].casefold() in vendor_words:
|
||||
without_vendor = without_vendor[1:]
|
||||
candidates = []
|
||||
for words_variant in (without_vendor, words):
|
||||
slug = slugify(" ".join(words_variant))
|
||||
for candidate in (slug, slug.replace("-", "")):
|
||||
if candidate and candidate not in candidates:
|
||||
candidates.append(candidate)
|
||||
# Last resort: the first word ("VLC media player" -> vlc); the tooltip shows which project matched.
|
||||
if len(without_vendor) > 1 and (first := slugify(without_vendor[0])) and first not in candidates:
|
||||
candidates.append(first)
|
||||
return candidates[:5]
|
||||
|
||||
|
||||
def numbers(version):
|
||||
return tuple(int(part) for part in re.findall(r"\d+", str(version or "")))
|
||||
|
||||
|
||||
def compare(installed, latest):
|
||||
"""
|
||||
"current", "outdated" or "unknown".
|
||||
|
||||
Only the precision of the online version counts: an installed "128.0.3.8945" is current
|
||||
against "128.0.3", "127.0" is outdated against "128.0.3".
|
||||
"""
|
||||
have, want = numbers(installed), numbers(latest)
|
||||
if not have or not want:
|
||||
return "unknown"
|
||||
have = (have + (0,) * len(want))[: len(want)]
|
||||
return "current" if have >= want else "outdated"
|
||||
|
||||
|
||||
def newest(versions):
|
||||
versions = [version for version in versions if version]
|
||||
return max(versions, key=lambda version: (numbers(version), version_key(version))) if versions else None
|
||||
|
||||
|
||||
def parse_endoflife(payload):
|
||||
"""Latest patch version of a non-EOL release cycle (or of any cycle) from an /api/v1/products/<p> answer."""
|
||||
result = (payload or {}).get("result") or {}
|
||||
releases = result.get("releases") or []
|
||||
names = [(release.get("latest") or {}).get("name") for release in releases if not release.get("isEol")]
|
||||
return newest(names) or newest((release.get("latest") or {}).get("name") for release in releases)
|
||||
|
||||
|
||||
def parse_repology(packages):
|
||||
"""Newest version of a Repology project, preferring what the Windows repositories ship."""
|
||||
newest_packages = [package for package in packages or () if package.get("status") == "newest"]
|
||||
if not newest_packages:
|
||||
return None
|
||||
windows = [package for package in newest_packages if package.get("repo") in WINDOWS_REPOS]
|
||||
counts = Counter(package.get("version") for package in (windows or newest_packages) if package.get("version"))
|
||||
if not counts:
|
||||
return None
|
||||
top = max(counts.values())
|
||||
return newest(version for version, count in counts.items() if count == top)
|
||||
|
||||
|
||||
def combine(found):
|
||||
"""found: list of {"source", "version", ...}; returns the overall newest version."""
|
||||
return newest(entry["version"] for entry in found)
|
||||
|
||||
|
||||
#
|
||||
# Configuration
|
||||
#
|
||||
|
||||
|
||||
def plugin_setting(name, default):
|
||||
try:
|
||||
from netbox.plugins import get_plugin_config
|
||||
|
||||
value = get_plugin_config("netbox_utilities", name)
|
||||
except Exception: # noqa: BLE001 - outside NetBox (tests)
|
||||
value = None
|
||||
return default if value is None else value
|
||||
|
||||
|
||||
def lookup_enabled():
|
||||
return bool(plugin_setting("software_latest_enabled", True))
|
||||
|
||||
|
||||
def configured_sources():
|
||||
return [source for source in plugin_setting("software_latest_sources", list(SOURCES)) if source in SOURCES]
|
||||
|
||||
|
||||
def mapping_for(name, mapping=None):
|
||||
"""
|
||||
Manual project names per product, e.g. {"Mozilla Firefox": {"endoflife": "firefox", "repology": "firefox"}}.
|
||||
|
||||
Keys match the product name case-insensitively; False/None as value disables the lookup.
|
||||
"""
|
||||
mapping = plugin_setting("software_latest_mapping", {}) if mapping is None else mapping
|
||||
for key, value in (mapping or {}).items():
|
||||
if str(key).casefold() == str(name).casefold():
|
||||
return value if value else False
|
||||
return None
|
||||
|
||||
|
||||
#
|
||||
# HTTP
|
||||
#
|
||||
|
||||
|
||||
def user_agent():
|
||||
from . import __version__
|
||||
|
||||
return f"netbox-utilities/{__version__} (software version check)"
|
||||
|
||||
|
||||
def ssl_context():
|
||||
"""
|
||||
Certificates are verified against the system CA store, like curl and requests do.
|
||||
|
||||
Python 3.13 turned on VERIFY_X509_STRICT, which rejects CA certificates of many TLS-inspecting
|
||||
firewalls ("Basic Constraints of CA cert not marked critical") that the rest of the system accepts.
|
||||
"""
|
||||
context = ssl.create_default_context()
|
||||
context.verify_flags &= ~getattr(ssl, "VERIFY_X509_STRICT", 0)
|
||||
return context
|
||||
|
||||
|
||||
def opener():
|
||||
handlers = [urllib.request.HTTPSHandler(context=ssl_context())]
|
||||
try:
|
||||
from django.conf import settings
|
||||
|
||||
proxies = getattr(settings, "HTTP_PROXIES", None)
|
||||
except Exception: # noqa: BLE001
|
||||
proxies = None
|
||||
if proxies:
|
||||
handlers.append(urllib.request.ProxyHandler(proxies))
|
||||
return urllib.request.build_opener(*handlers)
|
||||
|
||||
|
||||
def fetch_json(url):
|
||||
"""Parsed JSON, or None for 404. Other failures raise."""
|
||||
request = urllib.request.Request(url, headers={"User-Agent": user_agent(), "Accept": "application/json"})
|
||||
try:
|
||||
with opener().open(request, timeout=TIMEOUT) as response:
|
||||
return json.loads(response.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as error:
|
||||
if error.code == 404:
|
||||
return None
|
||||
raise
|
||||
|
||||
|
||||
def query_endoflife(project, fetch=fetch_json):
|
||||
payload = fetch(f"https://endoflife.date/api/v1/products/{urllib.parse.quote(project)}/")
|
||||
version = parse_endoflife(payload) if payload else None
|
||||
return {"version": version, "url": f"https://endoflife.date/{project}"} if version else None
|
||||
|
||||
|
||||
def query_repology(project, fetch=fetch_json):
|
||||
global _repology_last
|
||||
with _repology_lock:
|
||||
wait = _repology_last + REPOLOGY_INTERVAL - time.monotonic()
|
||||
if wait > 0:
|
||||
time.sleep(wait)
|
||||
try:
|
||||
packages = fetch(f"https://repology.org/api/v1/project/{urllib.parse.quote(project, safe='+')}")
|
||||
finally:
|
||||
_repology_last = time.monotonic()
|
||||
version = parse_repology(packages) if packages else None
|
||||
return {"version": version, "url": f"https://repology.org/project/{project}/versions"} if version else None
|
||||
|
||||
|
||||
QUERIES = {"endoflife": query_endoflife, "repology": query_repology}
|
||||
|
||||
|
||||
def find_latest(name, manufacturer="", sources=None, mapping=None, fetch=fetch_json):
|
||||
"""
|
||||
Ask every source for the product; returns {"latest", "found": [...], "errors": [...]}.
|
||||
|
||||
Without a manual mapping the guessed names are tried one after another until a source knows one.
|
||||
"""
|
||||
sources = configured_sources() if sources is None else sources
|
||||
manual = mapping_for(name, mapping)
|
||||
found, errors = [], []
|
||||
if manual is False:
|
||||
return {"latest": None, "found": [], "errors": [], "disabled": True}
|
||||
for source in sources:
|
||||
if isinstance(manual, dict):
|
||||
if not manual.get(source):
|
||||
continue
|
||||
projects = [manual[source]]
|
||||
else:
|
||||
projects = name_candidates(name, manufacturer)
|
||||
for project in projects:
|
||||
try:
|
||||
hit = QUERIES[source](project, fetch=fetch)
|
||||
except Exception as error: # noqa: BLE001 - network problems must not break the page
|
||||
errors.append(f"{SOURCE_LABELS[source]}: {error}")
|
||||
break
|
||||
if hit:
|
||||
found.append({"source": source, "label": SOURCE_LABELS[source], "project": project, **hit})
|
||||
break
|
||||
return {"latest": combine(found), "found": found, "errors": errors}
|
||||
|
||||
|
||||
def cache_key(name, manufacturer):
|
||||
digest = hashlib.sha1(f"{name}|{manufacturer}".casefold().encode()).hexdigest()
|
||||
return f"netbox_utilities:software_latest:{digest}"
|
||||
|
||||
|
||||
def lookup(name, manufacturer="", refresh=False):
|
||||
"""find_latest() with the Django cache; failed lookups are cached for one hour only."""
|
||||
from django.core.cache import cache
|
||||
from django.utils import timezone
|
||||
|
||||
key = cache_key(name, manufacturer)
|
||||
if not refresh and (cached := cache.get(key)) is not None:
|
||||
return {**cached, "cached": True}
|
||||
result = find_latest(name, manufacturer)
|
||||
result["checked"] = timezone.now().isoformat(timespec="minutes")
|
||||
hours = float(plugin_setting("software_latest_cache_hours", DEFAULT_CACHE_HOURS))
|
||||
cache.set(key, result, int(3600 if result["errors"] and not result["found"] else hours * 3600))
|
||||
return {**result, "cached": False}
|
||||
@@ -5,7 +5,7 @@ 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.http import HttpResponse, JsonResponse
|
||||
from django.shortcuts import render
|
||||
from django.urls import reverse
|
||||
from django.utils import timezone
|
||||
@@ -133,6 +133,7 @@ class SoftwareOverviewView(ContentTypePermissionRequiredMixin, View):
|
||||
"filter_query": filter_query,
|
||||
"today": timezone.localdate(),
|
||||
"can_add": request.user.has_perm("netbox_slm.add_softwareproductinstallation"),
|
||||
"latest_enabled": software_latest_enabled(),
|
||||
}
|
||||
if product_id:
|
||||
product = next((item for item in summary.products if item.id == product_id), None)
|
||||
@@ -157,6 +158,12 @@ class SoftwareOverviewView(ContentTypePermissionRequiredMixin, View):
|
||||
return set(scope.tenant_ids), str(selected) if selected else "aktiv"
|
||||
|
||||
|
||||
def software_latest_enabled():
|
||||
from . import software_latest
|
||||
|
||||
return software_latest.lookup_enabled()
|
||||
|
||||
|
||||
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:
|
||||
@@ -177,6 +184,32 @@ def product_context(request, installations, product, version_id):
|
||||
}
|
||||
|
||||
|
||||
class SoftwareLatestVersionView(ContentTypePermissionRequiredMixin, View):
|
||||
"""JSON: newest version of a product according to the online sources, and the state of each version."""
|
||||
|
||||
def get_required_permission(self):
|
||||
return INSTALLATION_PERMISSION
|
||||
|
||||
def get(self, request, pk):
|
||||
from netbox_slm.models import SoftwareProductVersion
|
||||
|
||||
from . import software_latest
|
||||
|
||||
product = product_object(request, pk)
|
||||
if product is None:
|
||||
return JsonResponse({"error": "not found"}, status=404)
|
||||
if not software_latest.lookup_enabled():
|
||||
return JsonResponse({"error": "disabled"}, status=404)
|
||||
manufacturer = str(product.manufacturer or "") if getattr(product, "manufacturer_id", None) else ""
|
||||
result = software_latest.lookup(product.name, manufacturer, refresh=request.GET.get("refresh") == "1")
|
||||
latest = result.get("latest")
|
||||
versions = SoftwareProductVersion.objects.filter(software_product=product).values_list("pk", "name")
|
||||
result["versions"] = {
|
||||
str(version_id): software_latest.compare(name, latest) if latest else "unknown" for version_id, name in versions
|
||||
}
|
||||
return JsonResponse(result)
|
||||
|
||||
|
||||
def product_object(request, product_id):
|
||||
from netbox_slm.models import SoftwareProduct
|
||||
|
||||
|
||||
@@ -564,6 +564,63 @@ a.nbu-disk-slot[draggable="true"] {
|
||||
}
|
||||
|
||||
/* 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;
|
||||
|
||||
@@ -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,
|
||||
]
|
||||
@@ -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,83 @@
|
||||
<script>
|
||||
// Neueste Version laut Internet (endoflife.date, Repology) nachladen und mit den installierten Versionen vergleichen.
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
const targets = [...document.querySelectorAll("[data-nbu-sw-latest]")];
|
||||
if (!targets.length) return;
|
||||
const PARALLEL = 3;
|
||||
const STATE = {
|
||||
current: '<span class="badge text-bg-green ms-1" title="Entspricht der neuesten Version laut Internet">aktuell</span>',
|
||||
outdated: '<span class="badge text-bg-warning ms-1" title="Älter als die neueste Version laut Internet">veraltet</span>',
|
||||
unknown: "",
|
||||
};
|
||||
const escape = (text) => String(text ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
|
||||
const links = (data) => data.found.map((hit) =>
|
||||
`<a href="${escape(hit.url)}" target="_blank" rel="noopener noreferrer" title="${escape(hit.label)}: ${escape(hit.version)} (Projekt ${escape(hit.project)})">${escape(hit.label)}</a>`
|
||||
).join(", ");
|
||||
|
||||
const render = (cell, data) => {
|
||||
const counts = JSON.parse(cell.dataset.nbuSwCounts || "{}");
|
||||
let outdated = 0;
|
||||
for (const [id, state] of Object.entries(data.versions || {})) {
|
||||
if (state === "outdated") outdated += counts[id] || 0;
|
||||
}
|
||||
for (const slot of document.querySelectorAll("[data-nbu-sw-state]")) {
|
||||
if (cell.dataset.nbuSwDetail !== undefined && data.versions?.[slot.dataset.nbuSwState]) {
|
||||
slot.innerHTML = STATE[data.versions[slot.dataset.nbuSwState]] || "";
|
||||
}
|
||||
}
|
||||
const outdatedCell = cell.parentElement.querySelector("[data-nbu-sw-outdated]");
|
||||
if (!data.latest) {
|
||||
const reason = data.disabled ? "Abfrage abgeschaltet" : data.errors?.length ? `Fehler: ${data.errors.join("; ")}` : "Keine Quelle kennt dieses Produkt";
|
||||
cell.innerHTML = `<span class="text-muted small" title="${escape(reason)}">${data.errors?.length && !data.found?.length ? '<i class="mdi mdi-alert-outline text-warning"></i> nicht erreichbar' : "nicht gefunden"}</span>`;
|
||||
if (outdatedCell) { outdatedCell.dataset.value = "-1"; outdatedCell.innerHTML = '<span class="text-muted">—</span>'; }
|
||||
return;
|
||||
}
|
||||
const badge = outdated
|
||||
? `<span class="badge text-bg-warning ms-1">${outdated} veraltet</span>`
|
||||
: '<span class="badge text-bg-green ms-1">alle aktuell</span>';
|
||||
if (cell.dataset.nbuSwDetail !== undefined) {
|
||||
cell.innerHTML = `<div class="d-flex flex-wrap align-items-center gap-1">
|
||||
<i class="mdi mdi-web" aria-hidden="true"></i> Neueste Version laut Internet:
|
||||
<strong>${escape(data.latest)}</strong>${badge}</div>
|
||||
<div class="text-muted small">Quelle: ${links(data)} · geprüft ${escape((data.checked || "").replace("T", " "))}</div>`;
|
||||
} else {
|
||||
cell.innerHTML = `<strong>${escape(data.latest)}</strong> <span class="small text-muted">${links(data)}</span>`;
|
||||
if (outdatedCell) {
|
||||
outdatedCell.dataset.value = String(outdated);
|
||||
outdatedCell.innerHTML = outdated ? badge.replace(" veraltet", "") : '<span class="badge text-bg-green">0</span>';
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const load = async (refresh) => {
|
||||
const queue = [...targets];
|
||||
for (const cell of queue) {
|
||||
if (refresh) cell.innerHTML = '<span class="text-muted small">wartet …</span>';
|
||||
}
|
||||
const worker = async () => {
|
||||
while (queue.length) {
|
||||
const cell = queue.shift();
|
||||
cell.innerHTML = '<span class="spinner-border spinner-border-sm text-muted" role="status"></span>';
|
||||
try {
|
||||
const response = await fetch(cell.dataset.nbuSwLatest + (refresh ? "?refresh=1" : ""), { headers: { Accept: "application/json" } });
|
||||
if (!response.ok) throw new Error(response.status);
|
||||
render(cell, await response.json());
|
||||
} catch (error) {
|
||||
cell.innerHTML = `<span class="text-muted small" title="${escape(error)}">nicht abrufbar</span>`;
|
||||
}
|
||||
}
|
||||
};
|
||||
await Promise.all(Array.from({ length: PARALLEL }, worker));
|
||||
};
|
||||
|
||||
load(false);
|
||||
const button = document.querySelector("[data-nbu-sw-refresh]");
|
||||
if (button) {
|
||||
button.addEventListener("click", async () => {
|
||||
button.disabled = true;
|
||||
await load(true);
|
||||
button.disabled = false;
|
||||
});
|
||||
}
|
||||
});
|
||||
</script>
|
||||
@@ -26,6 +26,13 @@
|
||||
<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 %}
|
||||
{% if latest_enabled %}
|
||||
<div class="nbu-sw-online mt-3" data-nbu-sw-latest="{% url 'plugins:netbox_utilities:software_latest_version' pk=product.id %}"
|
||||
data-nbu-sw-counts='{ {% for version in product.versions_by_name %}"{{ version.id }}": {{ version.device_count }}{% if not forloop.last %}, {% endif %}{% endfor %} }'
|
||||
data-nbu-sw-detail>
|
||||
<span class="text-muted small"><i class="mdi mdi-web" aria-hidden="true"></i> Neueste Version laut Internet wird abgefragt …</span>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -42,6 +49,7 @@
|
||||
<span class="nbu-sw-bar-label">
|
||||
{{ version.name }}
|
||||
{% if forloop.first %}<span class="badge text-bg-green ms-1">neueste</span>{% endif %}
|
||||
<span data-nbu-sw-state="{{ version.id }}"></span>
|
||||
{% 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>
|
||||
@@ -93,6 +101,7 @@
|
||||
<td>
|
||||
{{ version.name }}
|
||||
{% if product.latest_version.id == version.id %}<span class="badge text-bg-green ms-1">neueste</span>{% endif %}
|
||||
<span data-nbu-sw-state="{{ version.id }}"></span>
|
||||
</td>
|
||||
<td>
|
||||
{% if version.end_of_support %}
|
||||
|
||||
@@ -5,6 +5,12 @@
|
||||
|
||||
{% block controls %}
|
||||
<div class="btn-list">
|
||||
{% if latest_enabled and summary.products %}
|
||||
<button type="button" class="btn btn-outline-primary" data-nbu-sw-refresh
|
||||
title="Neueste Versionen erneut bei endoflife.date und Repology abfragen (Ergebnisse werden sonst zwischengespeichert)">
|
||||
<i class="mdi mdi-web-refresh" aria-hidden="true"></i> Online neu prüfen
|
||||
</button>
|
||||
{% endif %}
|
||||
<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
|
||||
@@ -32,36 +38,47 @@
|
||||
<label class="form-label" for="{{ form.tenant_id.id_for_label }}">Mandant</label>
|
||||
{{ form.tenant_id }}
|
||||
</div>
|
||||
<div class="col-12 col-md-6 col-xl-2">
|
||||
<span class="form-label d-block">Gerätrolle</span>
|
||||
{% for choice in form.role_id %}
|
||||
<div class="form-check form-check-inline">
|
||||
{{ choice.tag }}
|
||||
<label class="form-check-label" for="{{ choice.id_for_label }}">{{ choice.choice_label }}</label>
|
||||
</div>
|
||||
{% empty %}
|
||||
<div class="text-danger small">Keine Client-Rolle gefunden (<code>software_device_roles</code>)</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
<div class="col-12 col-md-6 col-xl-2">
|
||||
<div class="col-12 col-md-8 col-xl-4">
|
||||
<label class="form-label" for="id_q">Software suchen</label>
|
||||
<input type="search" name="q" id="id_q" value="{{ form.q.value|default:'' }}" class="form-control"
|
||||
placeholder="Produkt, Hersteller, Version">
|
||||
<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-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" title="Filter zurücksetzen">
|
||||
<i class="mdi mdi-backspace" aria-hidden="true"></i>
|
||||
<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="form-text mt-2">
|
||||
{% if scope_label %}
|
||||
<i class="mdi mdi-filter-check text-primary" aria-hidden="true"></i>
|
||||
Es gilt der globale Mandantenfilter <strong>{{ scope_label }}</strong>. Eine eigene Auswahl hier hat Vorrang.
|
||||
{% else %}
|
||||
Mandantengruppen schließen alle Untergruppen ein. Ohne Gerätrolle werden alle Geräte berücksichtigt.
|
||||
{% endif %}
|
||||
|
||||
<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>
|
||||
@@ -168,6 +185,8 @@
|
||||
<th data-nbu-sort="number" class="text-end">Versionen</th>
|
||||
<th style="min-width: 12rem">Verteilung</th>
|
||||
<th>Neueste Version</th>
|
||||
{% if latest_enabled %}<th data-nbu-sort="text" title="Neueste Version laut endoflife.date und Repology">Laut Internet</th>
|
||||
<th data-nbu-sort="number" class="text-end" title="Rechner mit einer älteren Version als der neuesten laut Internet">Veraltet</th>{% endif %}
|
||||
<th data-nbu-sort="number" class="text-end">Support abgelaufen</th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -181,6 +200,13 @@
|
||||
<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>
|
||||
{% if latest_enabled %}
|
||||
<td data-nbu-sw-latest="{% url 'plugins:netbox_utilities:software_latest_version' pk=item.id %}"
|
||||
data-nbu-sw-counts='{ {% for version in item.versions_by_name %}"{{ version.id }}": {{ version.device_count }}{% if not forloop.last %}, {% endif %}{% endfor %} }'>
|
||||
<span class="text-muted small">wartet …</span>
|
||||
</td>
|
||||
<td class="text-end" data-value="-1" data-nbu-sw-outdated><span class="text-muted">—</span></td>
|
||||
{% endif %}
|
||||
{% 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 %}
|
||||
@@ -194,10 +220,16 @@
|
||||
{% 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>
|
||||
Für diese Auswahl ist keine Software erfasst.
|
||||
<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' %}
|
||||
{% if latest_enabled %}{% include 'netbox_utilities/inc/software_latest_js.html' %}{% endif %}
|
||||
{% endblock content %}
|
||||
@@ -0,0 +1,121 @@
|
||||
from django.test import SimpleTestCase
|
||||
|
||||
from netbox_utilities import software_latest as latest
|
||||
|
||||
|
||||
class NameCandidatesTest(SimpleTestCase):
|
||||
def test_strips_vendor_architecture_language_and_version(self):
|
||||
self.assertEqual(
|
||||
latest.name_candidates("Mozilla Firefox (x64 de)", "Mozilla"),
|
||||
["firefox", "mozilla-firefox", "mozillafirefox"],
|
||||
)
|
||||
self.assertEqual(latest.name_candidates("7-Zip 23.01 (x64)")[:2], ["7-zip", "7zip"])
|
||||
self.assertEqual(latest.name_candidates("Notepad++ (64-bit x64)")[0], "notepad++")
|
||||
self.assertEqual(latest.name_candidates("VLC media player", "VideoLAN")[0], "vlc-media-player")
|
||||
self.assertEqual(latest.name_candidates("VLC media player", "VideoLAN")[-1], "vlc")
|
||||
|
||||
def test_single_word_is_kept_even_if_it_is_a_vendor(self):
|
||||
self.assertEqual(latest.name_candidates("Google")[0], "google")
|
||||
|
||||
|
||||
class CompareTest(SimpleTestCase):
|
||||
def test_precision_of_online_version_counts(self):
|
||||
self.assertEqual(latest.compare("128.0.3.8945", "128.0.3"), "current")
|
||||
self.assertEqual(latest.compare("128.0", "128.0.3"), "outdated")
|
||||
self.assertEqual(latest.compare("129.0", "128.0.3"), "current")
|
||||
self.assertEqual(latest.compare("9.11", "10.2"), "outdated")
|
||||
self.assertEqual(latest.compare("unbekannt", "10.2"), "unknown")
|
||||
|
||||
def test_newest_is_numeric(self):
|
||||
self.assertEqual(latest.newest(["9.11", "10.2", "10.10", None]), "10.10")
|
||||
|
||||
|
||||
class ParseTest(SimpleTestCase):
|
||||
def test_endoflife_prefers_supported_cycles(self):
|
||||
payload = {
|
||||
"result": {
|
||||
"releases": [
|
||||
{"name": "esr", "isEol": False, "latest": {"name": "128.5.0"}},
|
||||
{"name": "133", "isEol": False, "latest": {"name": "133.0.3"}},
|
||||
{"name": "old", "isEol": True, "latest": {"name": "200.0"}},
|
||||
]
|
||||
}
|
||||
}
|
||||
self.assertEqual(latest.parse_endoflife(payload), "133.0.3")
|
||||
self.assertIsNone(latest.parse_endoflife({"result": {"releases": []}}))
|
||||
|
||||
def test_repology_prefers_windows_repositories(self):
|
||||
packages = [
|
||||
{"repo": "arch", "version": "24.09", "status": "newest"},
|
||||
{"repo": "debian", "version": "24.09", "status": "newest"},
|
||||
{"repo": "winget", "version": "24.08", "status": "newest"},
|
||||
{"repo": "chocolatey", "version": "24.08", "status": "newest"},
|
||||
{"repo": "ubuntu", "version": "23.01", "status": "outdated"},
|
||||
]
|
||||
self.assertEqual(latest.parse_repology(packages), "24.08")
|
||||
self.assertEqual(latest.parse_repology(packages[:2]), "24.09")
|
||||
self.assertIsNone(latest.parse_repology([{"repo": "x", "version": "1", "status": "outdated"}]))
|
||||
|
||||
|
||||
class FindLatestTest(SimpleTestCase):
|
||||
def fake_fetch(self, answers):
|
||||
calls = []
|
||||
|
||||
def fetch(url):
|
||||
calls.append(url)
|
||||
for fragment, answer in answers.items():
|
||||
if fragment in url:
|
||||
if isinstance(answer, Exception):
|
||||
raise answer
|
||||
return answer
|
||||
return None
|
||||
|
||||
return fetch, calls
|
||||
|
||||
def test_tries_candidates_and_combines_sources(self):
|
||||
latest.REPOLOGY_INTERVAL = 0
|
||||
fetch, calls = self.fake_fetch(
|
||||
{
|
||||
"endoflife.date/api/v1/products/firefox/": {
|
||||
"result": {"releases": [{"isEol": False, "latest": {"name": "133.0.3"}}]}
|
||||
},
|
||||
"repology.org/api/v1/project/firefox": [{"repo": "winget", "version": "133.0.3", "status": "newest"}],
|
||||
}
|
||||
)
|
||||
result = latest.find_latest(
|
||||
"Mozilla Firefox (x64 de)", "Mozilla", sources=["endoflife", "repology"], mapping={}, fetch=fetch
|
||||
)
|
||||
|
||||
self.assertEqual(result["latest"], "133.0.3")
|
||||
self.assertEqual([hit["source"] for hit in result["found"]], ["endoflife", "repology"])
|
||||
self.assertEqual(len(calls), 2)
|
||||
|
||||
def test_manual_mapping_and_disabling(self):
|
||||
fetch, calls = self.fake_fetch(
|
||||
{"products/chrome/": {"result": {"releases": [{"isEol": False, "latest": {"name": "131.0.6778.86"}}]}}}
|
||||
)
|
||||
mapping = {"google chrome": {"endoflife": "chrome"}, "Intern Tool": False}
|
||||
|
||||
result = latest.find_latest("Google Chrome", sources=["endoflife", "repology"], mapping=mapping, fetch=fetch)
|
||||
self.assertEqual(result["latest"], "131.0.6778.86")
|
||||
self.assertEqual(len(calls), 1) # repology has no mapping entry and is skipped
|
||||
|
||||
self.assertTrue(latest.find_latest("Intern Tool", mapping=mapping, fetch=fetch)["disabled"])
|
||||
|
||||
def test_network_errors_are_reported_not_raised(self):
|
||||
fetch, _ = self.fake_fetch({"endoflife": OSError("timeout")})
|
||||
result = latest.find_latest("Firefox", sources=["endoflife"], mapping={}, fetch=fetch)
|
||||
|
||||
self.assertIsNone(result["latest"])
|
||||
self.assertIn("endoflife.date: timeout", result["errors"])
|
||||
|
||||
|
||||
class SslContextTest(SimpleTestCase):
|
||||
def test_verifies_certificates_without_strict_x509_checks(self):
|
||||
import ssl
|
||||
|
||||
context = latest.ssl_context()
|
||||
|
||||
self.assertEqual(context.verify_mode, ssl.CERT_REQUIRED)
|
||||
self.assertTrue(context.check_hostname)
|
||||
self.assertFalse(context.verify_flags & getattr(ssl, "VERIFY_X509_STRICT", 0))
|
||||
@@ -3,7 +3,7 @@ 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"
|
||||
|
||||
@@ -17,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
|
||||
@@ -47,6 +57,13 @@ urlpatterns = [
|
||||
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"),
|
||||
urlpatterns.extend(
|
||||
[
|
||||
path("software/", software_views.SoftwareOverviewView.as_view(), name="software_overview"),
|
||||
path(
|
||||
"software/<int:pk>/latest/",
|
||||
software_views.SoftwareLatestVersionView.as_view(),
|
||||
name="software_latest_version",
|
||||
),
|
||||
]
|
||||
)
|
||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "netbox-utilities"
|
||||
version = "0.29.1"
|
||||
version = "0.32.1"
|
||||
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"
|
||||
|
||||
Reference in new issue
Block a user