diff --git a/README.md b/README.md index a853430..6de3281 100644 --- a/README.md +++ b/README.md @@ -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 | | `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 @@ -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 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 diff --git a/netbox_utilities/__init__.py b/netbox_utilities/__init__.py index 595c988..76aafda 100644 --- a/netbox_utilities/__init__.py +++ b/netbox_utilities/__init__.py @@ -1,6 +1,6 @@ from netbox.plugins import PluginConfig, get_plugin_config -__version__ = "0.31.0" +__version__ = "0.32.0" 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", diff --git a/netbox_utilities/software_latest.py b/netbox_utilities/software_latest.py new file mode 100644 index 0000000..67d1bd8 --- /dev/null +++ b/netbox_utilities/software_latest.py @@ -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/

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} diff --git a/netbox_utilities/software_views.py b/netbox_utilities/software_views.py index 0412fce..241b62b 100644 --- a/netbox_utilities/software_views.py +++ b/netbox_utilities/software_views.py @@ -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 diff --git a/netbox_utilities/templates/netbox_utilities/inc/software_latest_js.html b/netbox_utilities/templates/netbox_utilities/inc/software_latest_js.html new file mode 100644 index 0000000..f46294e --- /dev/null +++ b/netbox_utilities/templates/netbox_utilities/inc/software_latest_js.html @@ -0,0 +1,83 @@ + diff --git a/netbox_utilities/templates/netbox_utilities/inc/software_product.html b/netbox_utilities/templates/netbox_utilities/inc/software_product.html index a6986c5..4ee5c9c 100644 --- a/netbox_utilities/templates/netbox_utilities/inc/software_product.html +++ b/netbox_utilities/templates/netbox_utilities/inc/software_product.html @@ -26,6 +26,13 @@

{{ product.version_count }}
Versionen
{% with item=product %}{% include 'netbox_utilities/inc/software_version_stack.html' %}{% endwith %} + {% if latest_enabled %} +
+ Neueste Version laut Internet wird abgefragt … +
+ {% endif %} @@ -42,6 +49,7 @@ {{ version.name }} {% if forloop.first %}neueste{% endif %} + {% if version.support_expired %}EoS{% endif %} @@ -93,6 +101,7 @@ {{ version.name }} {% if product.latest_version.id == version.id %}neueste{% endif %} + {% if version.end_of_support %} diff --git a/netbox_utilities/templates/netbox_utilities/software_overview.html b/netbox_utilities/templates/netbox_utilities/software_overview.html index 0d4ac59..09b7a17 100644 --- a/netbox_utilities/templates/netbox_utilities/software_overview.html +++ b/netbox_utilities/templates/netbox_utilities/software_overview.html @@ -5,6 +5,12 @@ {% block controls %}
+ {% if latest_enabled and summary.products %} + + {% endif %} CSV exportieren @@ -179,6 +185,8 @@ Versionen Verteilung Neueste Version + {% if latest_enabled %}Laut Internet + Veraltet{% endif %} Support abgelaufen @@ -192,6 +200,13 @@ {{ item.version_count }} {% include 'netbox_utilities/inc/software_version_stack.html' %} {% with latest=item.latest_version %}{{ latest.name }} ({{ latest.device_count }}){% endwith %} + {% if latest_enabled %} + + wartet … + + — + {% endif %} {% with expired=item.expired_devices|length %} {% if expired %}{{ expired }}{% else %}—{% endif %} {% endwith %} @@ -216,4 +231,5 @@ {% endif %} {% include 'netbox_utilities/inc/software_table_js.html' %} + {% if latest_enabled %}{% include 'netbox_utilities/inc/software_latest_js.html' %}{% endif %} {% endblock content %} diff --git a/netbox_utilities/tests/test_software_latest.py b/netbox_utilities/tests/test_software_latest.py new file mode 100644 index 0000000..2080fed --- /dev/null +++ b/netbox_utilities/tests/test_software_latest.py @@ -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"]) diff --git a/netbox_utilities/urls.py b/netbox_utilities/urls.py index e48b241..88799cd 100644 --- a/netbox_utilities/urls.py +++ b/netbox_utilities/urls.py @@ -57,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//latest/", + software_views.SoftwareLatestVersionView.as_view(), + name="software_latest_version", + ), + ] ) diff --git a/pyproject.toml b/pyproject.toml index 49c543c..63aa701 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] 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" readme = "README.md" requires-python = ">=3.12"