feat: compare client software versions with the newest version online

The client software overview looks up the newest version of every product at
endoflife.date (latest patch of supported release cycles) and Repology (newest
upstream version, preferring winget, Chocolatey and Scoop) and takes the newer
of both. The product list gets the columns "Laut Internet" and "Veraltet"
(clients on an older version), a product's page shows the online version and
marks each installed version as current or outdated. Only the precision of the
online version counts, so 128.0.3.8945 is current against 128.0.3.

Lookups run in the background via a JSON endpoint per product, are cached
(software_latest_cache_hours, failures for one hour), respect NetBox's
HTTP_PROXIES and query Repology at most once per second. Product names are
guessed from the installed name; software_latest_mapping sets project names
by hand or skips a product. "Online neu prüfen" bypasses the cache.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
MrBlakeandClaude Opus 5.5 committed 2026-11-27 11:00:18 +01:00
1 parent 1d6b16c0e4
commit 2c35147dca
10 files changed
+552 -5

No files matched your search

+18
View File
@@ -229,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 | | `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_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_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 | | `wireless_trace_enabled` | `True` | Cable trace continues across wireless links (radio bridges) to the cabled port of the peer radio |
## Usage ## Usage
@@ -544,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 device removes its automatic installations first, so netbox-slm does not block
the deletion. 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: Devices that already have a report are transferred once with:
```bash ```bash
+5 -1
View File
@@ -1,6 +1,6 @@
from netbox.plugins import PluginConfig, get_plugin_config from netbox.plugins import PluginConfig, get_plugin_config
__version__ = "0.31.0" __version__ = "0.32.0"
class NetBoxUtilitiesConfig(PluginConfig): class NetBoxUtilitiesConfig(PluginConfig):
@@ -34,6 +34,10 @@ class NetBoxUtilitiesConfig(PluginConfig):
"wireless_trace_enabled": True, "wireless_trace_enabled": True,
"software_enabled": True, "software_enabled": True,
"software_device_roles": ["Client", "Windows Client"], "software_device_roles": ["Client", "Windows Client"],
"software_latest_enabled": True,
"software_latest_sources": ["endoflife", "repology"],
"software_latest_mapping": {},
"software_latest_cache_hours": 24,
} }
middleware = [ middleware = [
"netbox_utilities.middleware.GlobalTenantFilterMiddleware", "netbox_utilities.middleware.GlobalTenantFilterMiddleware",
+267
View File
@@ -0,0 +1,267 @@
"""
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 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 opener():
handlers = []
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}
+34 -1
View File
@@ -5,7 +5,7 @@ import csv
from dcim.models import Device, DeviceRole from dcim.models import Device, DeviceRole
from django import forms from django import forms
from django.db.models import Q from django.db.models import Q
from django.http import HttpResponse from django.http import HttpResponse, JsonResponse
from django.shortcuts import render from django.shortcuts import render
from django.urls import reverse from django.urls import reverse
from django.utils import timezone from django.utils import timezone
@@ -133,6 +133,7 @@ class SoftwareOverviewView(ContentTypePermissionRequiredMixin, View):
"filter_query": filter_query, "filter_query": filter_query,
"today": timezone.localdate(), "today": timezone.localdate(),
"can_add": request.user.has_perm("netbox_slm.add_softwareproductinstallation"), "can_add": request.user.has_perm("netbox_slm.add_softwareproductinstallation"),
"latest_enabled": software_latest_enabled(),
} }
if product_id: if product_id:
product = next((item for item in summary.products if item.id == product_id), None) 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" 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): def product_context(request, installations, product, version_id):
"""Drill-down of one product: its versions and the devices it is installed on.""" """Drill-down of one product: its versions and the devices it is installed on."""
if product is None: 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): def product_object(request, product_id):
from netbox_slm.models import SoftwareProduct from netbox_slm.models import SoftwareProduct
@@ -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) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[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 class="col"><div class="nbu-sw-kpi-value">{{ product.version_count }}</div><div class="nbu-sw-kpi-label">Versionen</div></div>
</div> </div>
{% with item=product %}{% include 'netbox_utilities/inc/software_version_stack.html' %}{% endwith %} {% 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> </div>
</div> </div>
@@ -42,6 +49,7 @@
<span class="nbu-sw-bar-label"> <span class="nbu-sw-bar-label">
{{ version.name }} {{ version.name }}
{% if forloop.first %}<span class="badge text-bg-green ms-1">neueste</span>{% endif %} {% 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 %} {% 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>
<span class="nbu-sw-bar-track"><span class="nbu-sw-bar-fill{% if version.support_expired %} nbu-sw-expired{% endif %}" style="width: {{ version.share }}%; --nbu-sw-shade: {{ version.shade }}%"></span></span> <span class="nbu-sw-bar-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> <td>
{{ version.name }} {{ version.name }}
{% if product.latest_version.id == version.id %}<span class="badge text-bg-green ms-1">neueste</span>{% endif %} {% 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>
<td> <td>
{% if version.end_of_support %} {% if version.end_of_support %}
@@ -5,6 +5,12 @@
{% block controls %} {% block controls %}
<div class="btn-list"> <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" <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"> class="btn btn-purple" title="Aktuelle Auswahl als CSV (Excel) herunterladen">
<i class="mdi mdi-download" aria-hidden="true"></i> CSV exportieren <i class="mdi mdi-download" aria-hidden="true"></i> CSV exportieren
@@ -179,6 +185,8 @@
<th data-nbu-sort="number" class="text-end">Versionen</th> <th data-nbu-sort="number" class="text-end">Versionen</th>
<th style="min-width: 12rem">Verteilung</th> <th style="min-width: 12rem">Verteilung</th>
<th>Neueste Version</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> <th data-nbu-sort="number" class="text-end">Support abgelaufen</th>
</tr> </tr>
</thead> </thead>
@@ -192,6 +200,13 @@
<td class="text-end" data-value="{{ item.version_count }}">{{ item.version_count }}</td> <td class="text-end" data-value="{{ item.version_count }}">{{ item.version_count }}</td>
<td>{% include 'netbox_utilities/inc/software_version_stack.html' %}</td> <td>{% 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> <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 %} {% 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> <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 %} {% endwith %}
@@ -216,4 +231,5 @@
{% endif %} {% endif %}
{% include 'netbox_utilities/inc/software_table_js.html' %} {% include 'netbox_utilities/inc/software_table_js.html' %}
{% if latest_enabled %}{% include 'netbox_utilities/inc/software_latest_js.html' %}{% endif %}
{% endblock content %} {% endblock content %}
@@ -0,0 +1,110 @@
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"])
+9 -2
View File
@@ -57,6 +57,13 @@ urlpatterns = [
if get_plugin_config("netbox_utilities", "software_enabled") and apps.is_installed("netbox_slm"): if get_plugin_config("netbox_utilities", "software_enabled") and apps.is_installed("netbox_slm"):
from . import software_views from . import software_views
urlpatterns.append( urlpatterns.extend(
path("software/", software_views.SoftwareOverviewView.as_view(), name="software_overview"), [
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
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project] [project]
name = "netbox-utilities" name = "netbox-utilities"
version = "0.31.0" version = "0.32.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" 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" readme = "README.md"
requires-python = ">=3.12" requires-python = ">=3.12"