diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 9f5d8e5..8728028 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -23,6 +23,8 @@ jobs: timeout-minutes: 120 steps: - uses: actions/checkout@v7 + with: + fetch-depth: 0 # last commit date of each extra-mibs/ file, for the sitemap's - uses: actions/cache@v6 with: path: .cache/net-snmp diff --git a/README.md b/README.md index 55a81e3..ddaa712 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ uv run pytest # tests ## How it works -Each MIB is parsed by the first tier that succeeds: pysmi → net-snmp `snmptranslate` → regex scrape → raw. Every MIB gets a page; the badge shows which tier was used and any parser messages are listed. Import aliases follow net-snmp's `module_map` (e.g. `RFC-1213` → `RFC1213-MIB`). Vendors come from the IANA enterprise number of the MIB's root OID. Example values come from LibreNMS `tests/snmpsim/*.snmprec`. Search is a static, prefix-sharded JSON index under `/data/search/`. +Each MIB is parsed by the first tier that succeeds: pysmi → net-snmp `snmptranslate` → regex scrape → raw. Every MIB gets a page; the badge shows which tier was used and any parser messages are listed. Import aliases follow net-snmp's `module_map` (e.g. `RFC-1213` → `RFC1213-MIB`). Vendors come from the IANA enterprise number of the MIB's root OID. Example values come from LibreNMS `tests/snmpsim/*.snmprec`. Search is a static, prefix-sharded JSON index under `/data/search/`. The sitemap's `` (and the page's `dateModified`) is the last git commit date of the MIB file, so the LibreNMS clone keeps its full history (without blobs); a shallow clone gives no dates. ## External MIBs diff --git a/scripts/fetch-librenms.sh b/scripts/fetch-librenms.sh index 089219b..006d842 100755 --- a/scripts/fetch-librenms.sh +++ b/scripts/fetch-librenms.sh @@ -1,14 +1,17 @@ #!/usr/bin/env bash # Sparse-clone (or update) LibreNMS with only what mibsite reads: mibs/ (the MIBs), tests/snmpsim/ # (snmprec device recordings, the source of the example values) and the OS definitions and PHP code -# (which MIB objects LibreNMS uses; see usage.py). +# (which MIB objects LibreNMS uses; see usage.py). Full commit history without blobs: the build reads the +# last commit date of each MIB for the sitemap's . set -euo pipefail dest="${1:-.cache/librenms}" if [ -d "$dest/.git" ]; then - git -C "$dest" fetch --quiet --depth 1 origin master + unshallow="" + [ "$(git -C "$dest" rev-parse --is-shallow-repository)" = true ] && unshallow="--unshallow" + git -C "$dest" fetch --quiet $unshallow origin master git -C "$dest" reset --quiet --hard FETCH_HEAD else - git clone --quiet --depth 1 --filter=blob:none --sparse https://github.com/librenms/librenms.git "$dest" + git clone --quiet --filter=blob:none --sparse https://github.com/librenms/librenms.git "$dest" fi git -C "$dest" sparse-checkout set --no-cone "/mibs/" "/tests/snmpsim/" "/resources/definitions/" "/LibreNMS/" \ "/includes/" "/app/" diff --git a/src/mibsite/build.py b/src/mibsite/build.py index 7b30957..5ee3c4d 100644 --- a/src/mibsite/build.py +++ b/src/mibsite/build.py @@ -37,6 +37,29 @@ def _sha(repo: Path) -> str: return "master" +def file_dates(folder: Path) -> dict[str, str]: + """Last commit date (YYYY-MM-DD) of each file under `folder`, keyed by its path relative to `folder`. + Empty when `folder` is not in a git repository or the clone is shallow (every file would get the date of + the one commit there is).""" + def git(*args: str) -> str: + return subprocess.run(["git", "-C", str(folder), *args], capture_output=True, text=True, check=True).stdout + try: + if git("rev-parse", "--is-shallow-repository").strip() != "false": + return {} + # --no-renames: rename detection would fetch blobs in a blob-less (partial) clone + log = git("-c", "core.quotepath=off", "log", "--no-renames", "--relative", "--name-only", "--format=@%cs", "--", ".") + except (OSError, subprocess.CalledProcessError): + return {} + dates: dict[str, str] = {} + date = "" + for line in log.splitlines(): + if line.startswith("@"): + date = line[1:] + elif line: + dates.setdefault(line, date) # newest commit first + return dates + + def restore_descriptions(modules, mibs_root: Path, extra: Path | None) -> None: """Replace parser-normalised descriptions with the text as the MIB lays it out (line breaks kept).""" by_file = defaultdict(list) @@ -87,10 +110,14 @@ def build(librenms: Path, out: Path, base_url: str, jobs: int, only: str | None, with phase("Collecting LibreNMS usage"): usage = collect_usage(librenms, modules) print(f" {len(usage.modules):,} MIBs used by LibreNMS") + with phase("Reading MIB file dates"): + dates = {"": file_dates(mibs_root), EXTERNAL_DIR: file_dates(extra) if extra else {}} + modified = {m.id: d for m in modules if (d := dates[EXTERNAL_DIR if m.dir == EXTERNAL_DIR else ""].get(m.file))} + print(f" {len(modified):,} MIBs with a date") cfg = SiteConfig(base_url.rstrip("/"), _sha(librenms), dt.date.today().isoformat()) safe_clean(out) with phase("Rendering pages"): - render_site(out, modules, table, vendors, examples, cfg, jobs, usage) + render_site(out, modules, table, vendors, examples, cfg, jobs, usage, modified) with phase("Writing search index"): write_search_index(out / "data" / "search", modules, vendors) stats = {"modules": len(modules), "objects": sum(len(m.objects) for m in modules), diff --git a/src/mibsite/jsonld.py b/src/mibsite/jsonld.py new file mode 100644 index 0000000..65b3dda --- /dev/null +++ b/src/mibsite/jsonld.py @@ -0,0 +1,56 @@ +"""schema.org JSON-LD for the pages. Every page points at the one WebSite (described on the home page) and at +LibreNMS, the publisher, by @id, so the graph links up without repeating them.""" +from __future__ import annotations + +from jinja2.utils import htmlsafe_json_dumps +from markupsafe import Markup + +ORG_ID = "https://www.librenms.org/#org" +CONTEXT = "https://schema.org" + + +def ld(data: dict) -> Markup: + """A ") + + +def website_id(cfg) -> str: + return cfg.base_url + "/#website" + + +def home(cfg, description: str) -> Markup: + return ld({"@context": CONTEXT, "@graph": [ + {"@type": "WebSite", "@id": website_id(cfg), "name": "LibreNMS MIB Browser", "url": cfg.base_url + "/", + "description": description, "inLanguage": "en", "publisher": {"@id": ORG_ID}, + "potentialAction": {"@type": "SearchAction", "target": cfg.base_url + "/search/?q={search_term_string}", + "query-input": "required name=search_term_string"}}, + {"@type": "Organization", "@id": ORG_ID, "name": "LibreNMS", "url": "https://www.librenms.org/", + "logo": cfg.base_url + "/assets/logo-light.svg", "sameAs": ["https://github.com/librenms/librenms"]}, + ]}) + + +def breadcrumbs(cfg, crumbs: list[tuple[str, str]]) -> Markup: + """crumbs: [(name, URL path)] from the top down; the last is the page itself.""" + return ld({"@context": CONTEXT, "@type": "BreadcrumbList", "itemListElement": [ + {"@type": "ListItem", "position": i, "name": name, "item": cfg.base_url + path} + for i, (name, path) in enumerate(crumbs, 1)]}) + + +def collection(cfg, name: str, description: str, path: str, items: list | None = None) -> Markup: + """A list page; items: the MIBs (anything with .name and .url) it lists, when few enough to be worth naming.""" + page = {"@context": CONTEXT, "@type": "CollectionPage", "name": name, "description": description, + "url": cfg.base_url + path, "isPartOf": {"@id": website_id(cfg)}, "publisher": {"@id": ORG_ID}, + "inLanguage": "en"} + if items is not None: + page["mainEntity"] = {"@type": "ItemList", "numberOfItems": len(items), "itemListElement": [ + {"@type": "ListItem", "position": i, "name": x.name, "url": cfg.base_url + x.url} for i, x in enumerate(items, 1)]} + return ld(page) + + +def article(cfg, headline: str, description: str, path: str, about: str, modified: str | None) -> Markup: + data = {"@context": CONTEXT, "@type": "TechArticle", "headline": headline, "description": description, + "url": cfg.base_url + path, "about": about, "isPartOf": {"@id": website_id(cfg)}, + "publisher": {"@id": ORG_ID}, "inLanguage": "en"} + if modified: + data["dateModified"] = modified + return ld(data) diff --git a/src/mibsite/render.py b/src/mibsite/render.py index 137b2a6..c130b3a 100644 --- a/src/mibsite/render.py +++ b/src/mibsite/render.py @@ -1,6 +1,7 @@ from __future__ import annotations import hashlib +import re import minify_html import shutil @@ -14,6 +15,7 @@ from jinja2 import Environment, PackageLoader, select_autoescape from markupsafe import Markup, escape as html_escape +from . import jsonld from .discover import EXTERNAL_DIR, ROOT_DIR from .model import Module, Obj, TextualConvention from .parse_pysmi import BASE_MIBS @@ -85,7 +87,7 @@ def smi_date(value: str) -> tuple[str, str] | None: def make_env(root: str = "") -> Environment: env = Environment(loader=PackageLoader("mibsite", "templates"), autoescape=select_autoescape(["j2", "html"]), trim_blocks=True, lstrip_blocks=True) - env.globals.update(KIND_ABBR=KIND_ABBR, ACCESS_ABBR=ACCESS_ABBR, TIER_LABEL=TIER_LABEL, root=root, + env.globals.update(jsonld=jsonld, KIND_ABBR=KIND_ABBR, ACCESS_ABBR=ACCESS_ABBR, TIER_LABEL=TIER_LABEL, root=root, asset_v=asset_version()) env.filters["slug"] = slugify env.filters["enum_label"] = enum_label @@ -100,10 +102,34 @@ def source_url(m: Module, cfg: SiteConfig) -> str: return f"https://github.com/librenms/librenms/blob/{cfg.librenms_sha}/mibs/{m.file}" +META_DESCRIPTION_MAX = 160 # search results show about this much + + +def clip(text: str, limit: int = META_DESCRIPTION_MAX) -> str: + """Whitespace collapsed, cut at a word boundary to at most `limit` characters ("…" marks a cut).""" + text = " ".join(text.split()) + if len(text) <= limit: + return text + cut = text[:limit - 1] + return (cut.rsplit(" ", 1)[0] if " " in cut else cut).rstrip(" ,;:.-") + "…" + + +_COPYRIGHT = re.compile(r"\s*\bCopyright\b.*", re.I | re.S) + + +def summary(m: Module) -> str: + """The MIB's own description on one line, without the copyright notice many MIBs end it with.""" + return " ".join(_COPYRIGHT.sub("", (m.identity or {}).get("description") or "").split()) + + def _meta_description(m: Module, vendor: str) -> str: - desc = ((m.identity or {}).get("description") or "").strip() - base = f"{m.name} SNMP MIB ({vendor}): {len(m.objects)} objects with OIDs, types and descriptions." - return (base + " " + " ".join(desc.split()))[:300].strip() + """The MIB's own description first (what a searcher wants to read), then what the page holds.""" + desc = summary(m) + of = "" if vendor == "Other" else f" ({vendor})" + facts = f"{len(m.objects):,} objects with OIDs, types and descriptions." + if not desc: + return clip(f"{m.name} SNMP MIB{of}: {facts}") + return clip(f"{m.name}: {desc}" + (f" {facts}" if len(desc) < 80 else "")) MAX_HINT_VALUES = 40 # enumerations listed in a Type tooltip (IANAifType alone has ~280) @@ -147,7 +173,7 @@ def defined_names_of(m: Module) -> frozenset[str]: def mib_context(m: Module, table: SymbolTable, vendor: str, examples: dict[str, list], cfg: SiteConfig, - all_tcs: dict[str, TextualConvention] | None = None) -> dict: + all_tcs: dict[str, TextualConvention] | None = None, modified: str | None = None) -> dict: root = site_root(cfg) imports, defined_in = [], {} # defined_in: imported symbol -> link to its definition for modname, syms in m.imports.items(): @@ -176,7 +202,7 @@ def mib_context(m: Module, table: SymbolTable, vendor: str, examples: dict[str, "notifications": [o for o in objs if o.kind == "notification"], "groups": [o for o in objs if o.kind in ("group", "compliance")], "examples": examples, "hints": hints, "type_links": type_links, "root_oid": module_root_oid(m), "source_url": source_url(m, cfg), - "description": _meta_description(m, vendor), + "description": _meta_description(m, vendor), "modified": modified, } @@ -259,7 +285,11 @@ def usage_stats(mods: list[Module], table: SymbolTable, examples: dict, usage: U def render_site(out: Path, modules: list[Module], table: SymbolTable, vendors: dict[str, str], examples: dict, - cfg: SiteConfig, jobs: int, usage: Usage | None = None) -> list[str]: + cfg: SiteConfig, jobs: int, usage: Usage | None = None, + modified: dict[str, str] | None = None) -> list[str]: + """Write the site to `out`; returns the page paths. modified: module id -> date (YYYY-MM-DD) its MIB file + last changed, for the sitemap's and the page's dateModified.""" + modified = modified or {} out.mkdir(parents=True, exist_ok=True) (out / ".mibsite-output").write_text("generated by mibsite\n") assets = out / "assets" @@ -269,7 +299,8 @@ def render_site(out: Path, modules: list[Module], table: SymbolTable, vendors: d mods = sorted(modules, key=lambda m: (m.name.lower(), m.id)) all_tcs = {t.name: t for m in mods for t in m.tcs} - contexts = [mib_context(m, table, vendors.get(m.id, "Other"), examples.get(m.id, {}), cfg, all_tcs) for m in mods] + contexts = [mib_context(m, table, vendors.get(m.id, "Other"), examples.get(m.id, {}), cfg, all_tcs, + modified.get(m.id)) for m in mods] with Pool(jobs or None, initializer=_init, initargs=(cfg, out)) as pool: progress = Progress("MIB pages", len(contexts)) pages = [] @@ -295,9 +326,13 @@ def render_site(out: Path, modules: list[Module], table: SymbolTable, vendors: d vendor_list = sorted(((vendor_name[s], s, vm) for s, vm in by_vendor.items()), key=lambda v: v[0].lower()) vendor_cards = [{"name": v, "slug": s, "count": len(vm), "oid": vendor_oid(vm)} for v, s, vm in vendor_list] - top_vendors = sorted((c for c in vendor_cards if c["name"] != "Other"), key=lambda c: -c["count"])[:10] + top_vendors = sorted((c for c in vendor_cards if c["name"] != "Other"), key=lambda c: -c["count"])[:20] - pages.append(_page(env, out, "/", "home.html.j2", cfg, stats=stats, letters=letters, top_vendors=top_vendors)) + used = usage_stats(mods, table, examples, usage, top=12) + popular = [{"m": m, "vendor": vendors.get(m.id, "Other"), + "desc": clip(summary(m), 110)} for m, _ in used["top_used"]] + pages.append(_page(env, out, "/", "home.html.j2", cfg, stats=stats, letters=letters, top_vendors=top_vendors, + popular=popular, used_mibs=used["used_mibs"])) pages.append(_page(env, out, "/mibs/", "letters.html.j2", cfg, groups=mib_groups, vendors=vendors)) pages.append(_page(env, out, "/vendors/", "vendors.html.j2", cfg, @@ -316,7 +351,9 @@ def render_site(out: Path, modules: list[Module], table: SymbolTable, vendors: d if not site_root(cfg): # a custom domain serves from "/"; project pages need no CNAME file (out / "CNAME").write_text(host + "\n") (out / "robots.txt").write_text(f"User-agent: *\nAllow: /\nSitemap: {cfg.base_url}/sitemap.xml\n") - urls = "".join(f"{escape(cfg.base_url + p)}" for p in pages) + lastmod = {m.url: modified[m.id] for m in mods if m.id in modified} + urls = "".join(f"{escape(cfg.base_url + p)}" + + (f"{lastmod[p]}" if p in lastmod else "") + "" for p in pages) (out / "sitemap.xml").write_text( '\n' f'{urls}\n') diff --git a/src/mibsite/static/style.css b/src/mibsite/static/style.css index f7dc056..ea70688 100644 --- a/src/mibsite/static/style.css +++ b/src/mibsite/static/style.css @@ -60,6 +60,9 @@ form.big .live-list{right:auto;width:100%} .letters a{min-width:36px;height:36px;display:flex;align-items:center;justify-content:center;padding:0 6px;border:1px solid var(--border);border-radius:6px;background:var(--surface);font-weight:600;color:var(--text)} .letters a:hover{border-color:var(--red);color:var(--red)} .letters.sticky{position:sticky;top:0;z-index:5;background:var(--bg);padding:10px 0;border-bottom:1px solid var(--border)} +.plist{list-style:none;margin:0;padding:0;display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:12px 24px} +.plist a{font-weight:600}.plist small{color:var(--muted);margin-left:6px}.plist span{display:block;font-size:14px;color:var(--muted)} +.about p{max-width:820px} .pills{display:flex;flex-wrap:wrap;gap:8px} .pills a{padding:8px 12px;border:1px solid var(--border);border-radius:999px;font-size:14px;color:var(--text)} .pills a.more{border-color:transparent;color:var(--link);font-weight:600} diff --git a/src/mibsite/templates/home.html.j2 b/src/mibsite/templates/home.html.j2 index 42e8c28..c5948f9 100644 --- a/src/mibsite/templates/home.html.j2 +++ b/src/mibsite/templates/home.html.j2 @@ -1,4 +1,8 @@ {% extends "base.html.j2" %} +{% block description %}Browse all {{ "{:,}".format(stats.modules) }} SNMP MIBs in LibreNMS from {{ "{:,}".format(stats.vendors) }} vendors: OID trees, object types, descriptions, traps and example values. Search by MIB, object name or OID.{% endblock %} +{% block head %} +{{ jsonld.home(cfg, self.description()) }} +{% endblock %} {% block main %}

All SNMP MIBs in LibreNMS

@@ -11,6 +15,13 @@
{{ "{:,}".format(stats.objects) }}Objects with an OID
{{ "{:,}".format(stats.examples) }}MIBs with example values
+{% if popular %} +
+

Popular MIBs

+

The MIBs from which LibreNMS uses the most objects to discover and monitor devices.

+
    {% for p in popular %}
  • {{ p.m.name }}{% if p.vendor != "Other" %} {{ p.vendor }}{% endif %}{% if p.desc %}{{ p.desc }}{% endif %}
  • {% endfor %}
+
+{% endif %}

MIBs from A to Z

@@ -23,4 +34,10 @@
{% for v in top_vendors %}{{ v.name }}{% endfor %}See all vendors →
+
+

About the LibreNMS MIB Browser

+

A MIB (Management Information Base) describes the data that a network device makes available over SNMP. Each object in a MIB has a name, such as ifHCInOctets, and a numeric object identifier (OID), such as 1.3.6.1.2.1.31.1.1.1.6. The MIB also gives the type of each object, whether it can be read or written, and a description of what it means. Monitoring tools such as LibreNMS use MIBs to turn the numbers that a router, switch, firewall, UPS or server returns into named values with units.

+

This site shows all {{ "{:,}".format(stats.modules) }} MIBs that LibreNMS ships, from {{ "{:,}".format(stats.vendors) }} vendors and standards organizations such as the IETF. {% if used_mibs %}LibreNMS uses {{ "{:,}".format(used_mibs) }} of them to poll devices. {% endif %}For each MIB you can browse the OID tree, read the description of every object, table and notification (trap), see the textual conventions and imports, and see example values recorded from real devices in the LibreNMS test data.

+

To find an object, type its name, the name of its MIB or a numeric OID in the search box. An instance OID from an snmpwalk output, such as 1.3.6.1.2.1.2.2.1.10.5, also finds the object that defines it. Each MIB page shows the snmptranslate and snmpwalk commands to query the MIB with net-snmp. The site is rebuilt automatically each time the MIBs in LibreNMS change.

+
{% endblock %} diff --git a/src/mibsite/templates/letters.html.j2 b/src/mibsite/templates/letters.html.j2 index be86b19..e1f6ba1 100644 --- a/src/mibsite/templates/letters.html.j2 +++ b/src/mibsite/templates/letters.html.j2 @@ -1,6 +1,10 @@ {% extends "base.html.j2" %} {% from "_letters.html.j2" import letter_groups %} {% block title %}All MIBs A–Z | LibreNMS MIB Browser{% endblock %} +{% block description %}All {{ "{:,}".format(groups|map(attribute="1")|map("length")|sum) }} SNMP MIBs in LibreNMS from A to Z. Open a MIB to see its OID tree, object types, descriptions and example values.{% endblock %} +{% block head %} +{{ jsonld.collection(cfg, "All SNMP MIBs A–Z", self.description(), path) }} +{% endblock %} {% block main %}

All MIBs

All MIBs, in order of the first letter.

diff --git a/src/mibsite/templates/mib.html.j2 b/src/mibsite/templates/mib.html.j2 index 922ad12..1c176cc 100644 --- a/src/mibsite/templates/mib.html.j2 +++ b/src/mibsite/templates/mib.html.j2 @@ -1,15 +1,10 @@ {% extends "base.html.j2" %} {% from "_tree.html.j2" import node %} -{% block title %}{{ m.name }} – SNMP MIB ({{ vendor }}) | LibreNMS MIB Browser{% endblock %} +{% block title %}{{ m.name }}{% if root_oid %} ({{ root_oid }}){% endif %} – {% if vendor != "Other" %}{{ vendor }} {% endif %}SNMP MIB | LibreNMS MIB Browser{% endblock %} {% block description %}{{ description }}{% endblock %} {% block head %} - - +{{ jsonld.breadcrumbs(cfg, [("MIBs", "/mibs/"), (vendor, "/vendors/" ~ vendor_slug ~ "/"), (m.name, path)]) }} +{{ jsonld.article(cfg, m.name ~ " SNMP MIB", description, path, (m.identity or {}).get("organization") or vendor, modified) }} {% endblock %} {% block main %} diff --git a/src/mibsite/templates/search.html.j2 b/src/mibsite/templates/search.html.j2 index 4edcfec..55f1dc0 100644 --- a/src/mibsite/templates/search.html.j2 +++ b/src/mibsite/templates/search.html.j2 @@ -1,5 +1,6 @@ {% extends "base.html.j2" %} {% block title %}Find MIBs and OIDs | LibreNMS MIB Browser{% endblock %} +{% block description %}Find an SNMP MIB, object or OID in the MIBs of LibreNMS. Type a name, or a numeric OID (an instance OID too) to find the object that defines it.{% endblock %} {% block main %}

Find

diff --git a/src/mibsite/templates/stats.html.j2 b/src/mibsite/templates/stats.html.j2 index fe0da88..3b5c243 100644 --- a/src/mibsite/templates/stats.html.j2 +++ b/src/mibsite/templates/stats.html.j2 @@ -1,5 +1,6 @@ {% extends "base.html.j2" %} {% block title %}Statistics | LibreNMS MIB Browser{% endblock %} +{% block description %}Statistics on the {{ "{:,}".format(stats.modules) }} SNMP MIBs in LibreNMS: objects, vendors, how well each MIB parses, which MIBs LibreNMS uses and which MIBs other MIBs import most.{% endblock %} {% block main %}

Statistics

diff --git a/src/mibsite/templates/vendor.html.j2 b/src/mibsite/templates/vendor.html.j2 index 0a15271..a30ee1a 100644 --- a/src/mibsite/templates/vendor.html.j2 +++ b/src/mibsite/templates/vendor.html.j2 @@ -2,6 +2,10 @@ {% from "_letters.html.j2" import letter_groups %} {% block title %}{{ vendor }} SNMP MIBs | LibreNMS MIB Browser{% endblock %} {% block description %}{{ mods|length }} SNMP MIBs from {{ vendor }}: OID trees, object types and descriptions.{% endblock %} +{% block head %} +{{ jsonld.collection(cfg, vendor ~ " SNMP MIBs", self.description(), path, mods) }} +{{ jsonld.breadcrumbs(cfg, [("Vendors", "/vendors/"), (vendor, path)]) }} +{% endblock %} {% block main %}

{{ vendor }}

diff --git a/src/mibsite/templates/vendors.html.j2 b/src/mibsite/templates/vendors.html.j2 index b484161..e7bb051 100644 --- a/src/mibsite/templates/vendors.html.j2 +++ b/src/mibsite/templates/vendors.html.j2 @@ -1,6 +1,10 @@ {% extends "base.html.j2" %} {% from "_letters.html.j2" import letter_groups %} {% block title %}MIBs by vendor | LibreNMS MIB Browser{% endblock %} +{% block description %}SNMP MIBs in LibreNMS by vendor, with the IANA private enterprise OID (1.3.6.1.4.1.n) of each vendor and the number of MIBs it has.{% endblock %} +{% block head %} +{{ jsonld.collection(cfg, "SNMP MIBs by vendor", self.description(), path) }} +{% endblock %} {% block main %}

Vendors

The IANA private enterprise number (1.3.6.1.4.1.n) of a MIB shows its vendor. Standards organizations show with their OID branch.

diff --git a/tests/test_build.py b/tests/test_build.py index 66b12c7..1a27f76 100644 --- a/tests/test_build.py +++ b/tests/test_build.py @@ -35,3 +35,21 @@ def test_build_end_to_end(fixtures_dir, tmp_path, monkeypatch): # rebuild into the same dir is allowed (marker present) build(lib, out, "https://mibs.example.org", jobs=2, only="GOOD-MIB", extra=None, cache=tmp_path / "cache") assert not (out / "mib/acme/NOT-A-MIB/index.html").exists() + + +def test_file_dates(tmp_path): + import subprocess + from mibsite.build import file_dates + def git(*a, date="2024-01-02T00:00:00Z"): + env = {"GIT_AUTHOR_DATE": date, "GIT_COMMITTER_DATE": date, "PATH": "/usr/bin:/bin", "HOME": str(tmp_path)} + subprocess.run(["git", "-C", str(tmp_path), "-c", "user.name=t", "-c", "user.email=t@t", *a], check=True, + capture_output=True, env=env) + git("init", "-q") + (tmp_path / "mibs" / "acme").mkdir(parents=True) + (tmp_path / "mibs" / "A-MIB").write_text("a") + (tmp_path / "mibs" / "acme" / "B-MIB").write_text("b") + git("add", "."); git("commit", "-qm", "one") + (tmp_path / "mibs" / "acme" / "B-MIB").write_text("b2") + git("commit", "-qam", "two", date="2025-06-07T00:00:00Z") + assert file_dates(tmp_path / "mibs") == {"A-MIB": "2024-01-02", "acme/B-MIB": "2025-06-07"} + assert file_dates(tmp_path / "nowhere") == {} diff --git a/tests/test_render.py b/tests/test_render.py index 831e31b..43223b4 100644 --- a/tests/test_render.py +++ b/tests/test_render.py @@ -144,3 +144,94 @@ def test_smi_date(): assert smi_date("200006140000Z") == ("2000-06-14T00:00Z", "2000-06-14") assert smi_date("9809281000Z") == ("1998-09-28T10:00Z", "1998-09-28") assert smi_date("garbage") is None and smi_date("201313010000Z") is None + + +def test_seo_titles_descriptions_and_lastmod(tmp_path): + import json + import re + long_desc = "The MIB module for managing widgets. " * 10 + good = Module("GOOD-MIB", "_root", "GOOD-MIB", "pysmi", identity={"description": long_desc}, + objects=[Obj("goodMIB", "1.3.6.1.4.1.99999", "identity")]) + bare = Module("BARE-MIB", "acme", "acme/BARE-MIB", "pysmi", objects=[Obj("b", "1.3.6.1.4.1.5", "node")]) + mods = [good, bare] + pages = render_site(tmp_path, mods, SymbolTable(mods), {good.id: "Example"}, {}, + SiteConfig("https://x.test", "abc", "d"), jobs=1, modified={good.id: "2025-03-04"}) + page = canon((tmp_path / "mib/GOOD-MIB/index.html").read_text()) + assert "GOOD-MIB (1.3.6.1.4.1.99999) – Example SNMP MIB | LibreNMS MIB Browser" in page + desc = re.search(r'(.*?)', page)][1] + assert article["dateModified"] == "2025-03-04" and article["publisher"] == {"@id": "https://www.librenms.org/#org"} + bare_page = canon((tmp_path / "mib/acme/BARE-MIB/index.html").read_text()) + assert "BARE-MIB (1.3.6.1.4.1.5) – SNMP MIB |" in bare_page # vendor "Other" is left out + assert 'content="BARE-MIB SNMP MIB: 1 objects with OIDs' in bare_page and "dateModified" not in bare_page + sitemap = (tmp_path / "sitemap.xml").read_text() + assert "<loc>https://x.test/mib/GOOD-MIB/</loc><lastmod>2025-03-04</lastmod></url>" in sitemap + assert "<loc>https://x.test/mib/acme/BARE-MIB/</loc></url>" in sitemap + descriptions = set() + for p in pages: + if p.startswith("/mib/"): + continue + html = canon((tmp_path / p.strip("/") / "index.html").read_text()) + descriptions.add(re.search(r'<meta content="([^"]*)" name="description"', html).group(1)) + assert len(descriptions) == len([p for p in pages if not p.startswith("/mib/")]) # no two pages share one + assert any(d.startswith("All 2 SNMP MIBs") for d in descriptions) + + +def test_clip(): + from mibsite.render import clip + assert clip("short text") == "short text" + assert clip("one two three four", 12) == "one two…" + assert clip("x" * 20, 10) == "x" * 9 + "…" + + +def test_home_page_has_popular_mibs_and_about_text(tmp_path): + import re + good = Module("GOOD-MIB", "_root", "GOOD-MIB", "pysmi", + identity={"description": "Widgets on a device. Copyright (c) 2009 IETF Trust and others."}, + objects=[Obj("goodMIB", "1.3.6.1.4.1.99999", "identity")]) + render_site(tmp_path, [good], SymbolTable([good]), {}, {}, SiteConfig("https://x.test", "abc", "d"), jobs=1, + usage=Usage(objects={good.id: {"goodMIB"}})) + home = canon((tmp_path / "index.html").read_text()) + assert "Popular MIBs" in home and '<a href="/mib/GOOD-MIB/">GOOD-MIB</a>' in home + assert "Widgets on a device." in home and "Copyright" not in home + assert "About the LibreNMS MIB Browser" in home + text = re.sub(r"<[^>]+>", " ", home.split("<main>")[1].split("</main>")[0]) + assert len(text.split()) >= 250 + + +def test_home_meta_description_length(tmp_path): + import re + m = Module("GOOD-MIB", "_root", "GOOD-MIB", "pysmi", objects=[Obj("goodMIB", "1.3.6.1.4.1.99999", "identity")]) + render_site(tmp_path, [m], SymbolTable([m]), {}, {}, SiteConfig("https://x.test", "abc", "d"), jobs=1) + desc = re.search(r'<meta content="([^"]*)" name="description"', canon((tmp_path / "index.html").read_text())).group(1) + assert desc.startswith("Browse all 1 SNMP MIBs in LibreNMS from 1 vendors:") and 140 <= len(desc) <= 160 + + +def test_json_ld(tmp_path): + import json + import re + good = Module("GOOD-MIB", "_root", "GOOD-MIB", "pysmi", identity={"description": "Has </script> in it."}, + objects=[Obj("goodMIB", "1.3.6.1.4.1.99999", "identity")]) + render_site(tmp_path, [good], SymbolTable([good]), {good.id: "Example"}, {}, + SiteConfig("https://x.test", "abc", "d"), jobs=1, modified={good.id: "2025-01-02"}) + + def blocks(path): + html = (tmp_path / path).read_text() + return [json.loads(j) for j in re.findall(r'<script type="?application/ld\+json"?>(.*?)</script>', html, re.S)] + + graph = blocks("index.html")[0]["@graph"] + site = next(x for x in graph if x["@type"] == "WebSite") + assert site["@id"] == "https://x.test/#website" and site["description"].startswith("Browse all 1 SNMP MIBs") + assert site["potentialAction"]["target"] == "https://x.test/search/?q={search_term_string}" + assert any(x["@type"] == "Organization" for x in graph) + mib = blocks("mib/GOOD-MIB/index.html") + assert [b["@type"] for b in mib] == ["BreadcrumbList", "TechArticle"] + assert mib[1]["isPartOf"] == {"@id": "https://x.test/#website"} and mib[1]["dateModified"] == "2025-01-02" + assert "</script>" in mib[1]["description"] # escaped in the HTML, intact as JSON + vendor = blocks("vendors/example/index.html") + assert vendor[0]["@type"] == "CollectionPage" and vendor[0]["mainEntity"]["numberOfItems"] == 1 + assert vendor[0]["mainEntity"]["itemListElement"][0]["url"] == "https://x.test/mib/GOOD-MIB/" + assert vendor[1]["itemListElement"][-1]["item"] == "https://x.test/vendors/example/" + assert blocks("mibs/index.html")[0]["@type"] == "CollectionPage" + assert blocks("vendors/index.html")[0]["@type"] == "CollectionPage"
MIBs{{ stats.modules }}
Objects{{ stats.objects }}
Vendors{{ stats.vendors }}
MIBs with example values{{ stats.examples }}