Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 <lastmod>
- uses: actions/cache@v6
with:
path: .cache/net-snmp
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<lastmod>` (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

Expand Down
9 changes: 6 additions & 3 deletions scripts/fetch-librenms.sh
Original file line number Diff line number Diff line change
@@ -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 <lastmod>.
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/"
Expand Down
29 changes: 28 additions & 1 deletion src/mibsite/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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),
Expand Down
56 changes: 56 additions & 0 deletions src/mibsite/jsonld.py
Original file line number Diff line number Diff line change
@@ -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 <script type="application/ld+json"> block (escaped so a description can never close the script)."""
return Markup('<script type="application/ld+json">') + htmlsafe_json_dumps(data) + Markup("</script>")


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)
59 changes: 48 additions & 11 deletions src/mibsite/render.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import hashlib
import re

import minify_html
import shutil
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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():
Expand Down Expand Up @@ -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,
}


Expand Down Expand Up @@ -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 <lastmod> 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"
Expand All @@ -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 = []
Expand All @@ -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,
Expand All @@ -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"<url><loc>{escape(cfg.base_url + p)}</loc></url>" for p in pages)
lastmod = {m.url: modified[m.id] for m in mods if m.id in modified}
urls = "".join(f"<url><loc>{escape(cfg.base_url + p)}</loc>"
+ (f"<lastmod>{lastmod[p]}</lastmod>" if p in lastmod else "") + "</url>" for p in pages)
(out / "sitemap.xml").write_text(
'<?xml version="1.0" encoding="UTF-8"?>\n'
f'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">{urls}</urlset>\n')
Expand Down
3 changes: 3 additions & 0 deletions src/mibsite/static/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down
17 changes: 17 additions & 0 deletions src/mibsite/templates/home.html.j2
Original file line number Diff line number Diff line change
@@ -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 %}
<section class="hero">
<h1>All SNMP MIBs in LibreNMS</h1>
Expand All @@ -11,6 +15,13 @@
<div class="card"><b>{{ "{:,}".format(stats.objects) }}</b><span>Objects with an OID</span></div>
<div class="card"><b>{{ "{:,}".format(stats.examples) }}</b><span>MIBs with example values</span></div>
</section>
{% if popular %}
<section class="card">
<h2>Popular MIBs</h2>
<p class="muted">The MIBs from which LibreNMS uses the most objects to discover and monitor devices.</p>
<ul class="plist">{% for p in popular %}<li><a href="{{ root }}{{ p.m.url }}">{{ p.m.name }}</a>{% if p.vendor != "Other" %} <small>{{ p.vendor }}</small>{% endif %}{% if p.desc %}<span>{{ p.desc }}</span>{% endif %}</li>{% endfor %}</ul>
</section>
{% endif %}
<section class="two">
<div class="card">
<h2>MIBs from A to Z</h2>
Expand All @@ -23,4 +34,10 @@
<div class="pills">{% for v in top_vendors %}<a href="{{ root }}/vendors/{{ v.slug }}/">{{ v.name }}</a>{% endfor %}<a class="more" href="{{ root }}/vendors/">See all vendors →</a></div>
</div>
</section>
<section class="card about">
<h2>About the LibreNMS MIB Browser</h2>
<p>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 <code>ifHCInOctets</code>, and a numeric object identifier (OID), such as <code>1.3.6.1.2.1.31.1.1.1.6</code>. 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.</p>
<p>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.</p>
<p>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 <code>snmpwalk</code> output, such as <code>1.3.6.1.2.1.2.2.1.10.5</code>, also finds the object that defines it. Each MIB page shows the <code>snmptranslate</code> and <code>snmpwalk</code> commands to query the MIB with net-snmp. The site is rebuilt automatically each time the MIBs in LibreNMS change.</p>
</section>
{% endblock %}
4 changes: 4 additions & 0 deletions src/mibsite/templates/letters.html.j2
Original file line number Diff line number Diff line change
@@ -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 %}
<h1>All MIBs</h1>
<p class="muted">All MIBs, in order of the first letter.</p>
Expand Down
Loading