Files
pruefwerk/scripts/check-eol-tables.py
sharang 70125b4556
CI / Check (push) Skipped
CI / Detect Changes (push) Successful in 6s
CI / Deploy Dashboard (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Docs (push) Successful in 1m12s
CI / Deploy Agent (push) Successful in 5m25s
ci: a weekly check compares the bundled end-of-life tables with endoflife.date (#563)
2026-10-15 10:19:49 +00:00

284 lines
12 KiB
Python

#!/usr/bin/env python3
"""Compare the bundled end-of-life tables with endoflife.date.
The tables in compliance-agent/data/eol/ are what the lifecycle findings
judge by (Yocto releases, .NET target frameworks, the oldest patched Android
and iOS releases). This script fetches the matching endoflife.date products
and lists every difference: a release endoflife.date has and the table does
not, a changed release or end-of-life date, a changed LTS flag, a moved
platform floor.
With differences it opens one Gitea issue, or updates the open one (found by
its title), labelled "eol-tables". It never edits the tables: someone checks
the difference against the vendor's own page and updates the JSON.
Usage:
check-eol-tables.py [--data-dir DIR] [--dry-run]
Environment (not needed with --dry-run):
GITEA_TOKEN a token with issue write access on the repository
GITEA_API the API base, e.g. https://git.breakpilot.com/api/v1
GITEA_REPO owner/name, e.g. platform/pruefwerk
Exit status: 0 when the check ran (with or without differences), 1 when a
source could not be read or the issue could not be written.
"""
from __future__ import annotations
import argparse
import datetime as dt
import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
from typing import Any
ENDOFLIFE_API = "https://endoflife.date/api/{product}.json"
ISSUE_TITLE = "[eol-tables] Bundled end-of-life tables differ from endoflife.date"
LABEL = "eol-tables"
LABEL_COLOR = "fbca04"
TIMEOUT = 30
Cycle = dict[str, Any]
def fetch_json(url: str, token: str | None = None, method: str = "GET",
body: Any = None) -> Any:
"""GET (or send) JSON; raises on an HTTP or network error."""
data = None if body is None else json.dumps(body).encode()
request = urllib.request.Request(url, data=data, method=method)
request.add_header("Accept", "application/json")
request.add_header("User-Agent", "pruefwerk-eol-check")
if data is not None:
request.add_header("Content-Type", "application/json")
if token:
request.add_header("Authorization", f"token {token}")
with urllib.request.urlopen(request, timeout=TIMEOUT) as response:
text = response.read().decode()
return json.loads(text) if text.strip() else None
def cycles(product: str) -> list[Cycle]:
"""The release cycles endoflife.date lists for `product`."""
found: list[Cycle] = fetch_json(ENDOFLIFE_API.format(product=product))
return found
def eol_date(cycle: Cycle) -> str | None:
"""The cycle's end of life as YYYY-MM-DD, None when it has no date."""
eol = cycle.get("eol")
return eol if isinstance(eol, str) else None
def is_supported(cycle: Cycle, today: dt.date) -> bool:
"""Whether the cycle still gets security updates on `today`."""
eol = cycle.get("eol")
if isinstance(eol, bool):
return not eol
return isinstance(eol, str) and dt.date.fromisoformat(eol) >= today
def compare_yocto(table: dict[str, Any], upstream: list[Cycle]) -> list[str]:
"""Differences between the bundled Yocto releases and endoflife.date."""
bundled = {r["codename"]: r for r in table["releases"]}
out: list[str] = []
for cycle in upstream:
codename = str(cycle.get("codename", "")).lower()
mine = bundled.get(codename)
name = f"Yocto {cycle.get('codename')} ({cycle['cycle']})"
if mine is None:
out.append(f"{name}: on endoflife.date (released {cycle.get('releaseDate')}, "
f"end of life {cycle.get('eol')}), not in the table")
continue
checks = [
("version", mine["version"], cycle["cycle"]),
("LTS", mine["lts"], bool(cycle.get("lts"))),
("release date", mine["released"], cycle.get("releaseDate")),
("end of life", mine["end_of_life"], eol_date(cycle)),
]
out.extend(f"{name}: {what} is {theirs} on endoflife.date, {ours} in the table"
for what, ours, theirs in checks if ours != theirs)
return out
def dotnet_cycle(moniker: str) -> tuple[str, str] | None:
"""The endoflife.date product and cycle of a target framework moniker."""
if moniker.startswith("netcoreapp"):
return "dotnet", moniker.removeprefix("netcoreapp")
rest = moniker.removeprefix("net")
if "." in rest:
return "dotnet", rest.split(".")[0]
if rest == "35":
return "dotnetfx", "3.5-sp1"
if rest in ("11", "20", "30"):
# .NET Framework 1.1 to 3.0 are not on endoflife.date.
return None
return "dotnetfx", ".".join(rest)
def compare_dotnet(table: dict[str, Any], upstream: dict[str, list[Cycle]]) -> list[str]:
"""Differences between the bundled .NET table and endoflife.date."""
out: list[str] = []
bundled: dict[tuple[str, str], dict[str, Any]] = {}
for framework in table["frameworks"]:
key = dotnet_cycle(framework["moniker"])
if key is not None:
bundled.setdefault(key, framework)
for product, product_cycles in upstream.items():
for cycle in product_cycles:
mine = bundled.get((product, cycle["cycle"]))
theirs = eol_date(cycle)
label = f"{product} {cycle['cycle']}"
if mine is None:
if theirs is not None:
out.append(f"{label}: end of support {theirs} on endoflife.date, "
"not in the table")
elif mine["end_of_support"] != theirs:
out.append(f"{label} ({mine['moniker']}): end of support is {theirs} on "
f"endoflife.date, {mine['end_of_support']} in the table")
return out
def oldest_supported(product_cycles: list[Cycle], today: dt.date, key: str) -> int | None:
"""The smallest `key` (as a whole number) of the cycles still supported."""
values = [int(float(c[key])) for c in product_cycles
if c.get(key) is not None and is_supported(c, today)]
return min(values) if values else None
def compare_platforms(table: dict[str, Any], android: list[Cycle], ios: list[Cycle],
today: dt.date) -> list[str]:
"""Differences between the bundled platform floors and endoflife.date."""
out: list[str] = []
api = oldest_supported(android, today, "apiVersion")
ours = table["android"]["oldest_patched_api"]
if api is not None and api != ours:
out.append(f"Android: the oldest release with security updates is API {api} on "
f"endoflife.date, API {ours} in the table")
major = oldest_supported(ios, today, "cycle")
ours_ios = int(table["ios"]["oldest_patched"].split(".")[0])
if major is not None and major != ours_ios:
out.append(f"iOS: the oldest release with security updates is iOS {major} on "
f"endoflife.date, iOS {ours_ios} in the table")
return out
def load(data_dir: Path, name: str) -> dict[str, Any]:
"""A bundled table."""
table: dict[str, Any] = json.loads((data_dir / name).read_text())
return table
def differences(data_dir: Path, today: dt.date) -> dict[str, list[str]]:
"""Every difference, by table file."""
dotnet = load(data_dir, "dotnet.json")
platforms = load(data_dir, "platforms.json")
return {
"yocto.json": compare_yocto(load(data_dir, "yocto.json"), cycles("yocto")),
"dotnet.json": compare_dotnet(
dotnet, {p: cycles(p) for p in dotnet["endoflife_products"]}),
"platforms.json": compare_platforms(
platforms, cycles(platforms["android"]["endoflife_product"]),
cycles(platforms["ios"]["endoflife_product"]), today),
}
def issue_body(diff: dict[str, list[str]], today: dt.date) -> str:
"""The issue text for `diff`."""
lines = [
"The weekly check (`scripts/check-eol-tables.py`) found the bundled end-of-life "
"tables in `compliance-agent/data/eol/` differ from endoflife.date. Check each "
"against the vendor's own page, update the JSON (and its `checked_on`), and "
"close this issue with that PR.",
"",
]
for file, found in diff.items():
if found:
lines.append(f"### `{file}`")
lines.extend(f"- {line}" for line in found)
lines.append("")
lines.append(f"Last checked: {today.isoformat()}")
return "\n".join(lines)
def without_check_date(body: str) -> str:
"""`body` without its "Last checked" line, to see whether the diff changed."""
return "\n".join(
line for line in body.splitlines() if not line.startswith("Last checked:"))
def label_id(api: str, token: str) -> int | None:
"""The id of the issue label, created if missing; None if that fails."""
try:
labels = fetch_json(f"{api}/labels?limit=100", token)
found = next((label["id"] for label in labels if label["name"] == LABEL), None)
if found is not None:
return int(found)
created = fetch_json(f"{api}/labels", token, "POST",
{"name": LABEL, "color": f"#{LABEL_COLOR}",
"description": "Bundled end-of-life tables need an update"})
return int(created["id"])
except urllib.error.URLError as error:
print(f"::warning::label {LABEL} not available ({error}); the issue is unlabelled")
return None
def file_issue(body: str, token: str, api_base: str, repo: str) -> None:
"""Open the issue, or update the open one when the differences changed."""
api = f"{api_base.rstrip('/')}/repos/{repo}"
query = urllib.parse.quote(ISSUE_TITLE)
open_issues = fetch_json(f"{api}/issues?state=open&type=issues&q={query}", token)
existing = next((i for i in open_issues if i["title"] == ISSUE_TITLE), None)
if existing is None:
label = label_id(api, token)
payload = {"title": ISSUE_TITLE, "body": body,
"labels": [label] if label is not None else []}
created = fetch_json(f"{api}/issues", token, "POST", payload)
print(f"opened issue #{created['number']}")
elif without_check_date(existing.get("body") or "") != without_check_date(body):
fetch_json(f"{api}/issues/{existing['number']}", token, "PATCH", {"body": body})
print(f"updated issue #{existing['number']}")
else:
print(f"issue #{existing['number']} already lists these differences")
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--data-dir", type=Path,
default=Path(__file__).resolve().parent.parent
/ "compliance-agent/data/eol")
parser.add_argument("--dry-run", action="store_true",
help="print the differences, write no issue")
args = parser.parse_args()
today = dt.date.today()
try:
diff = differences(args.data_dir, today)
except (urllib.error.URLError, OSError, ValueError, KeyError) as error:
print(f"::error::could not compare the tables: {error}")
return 1
if not any(diff.values()):
print("the bundled end-of-life tables match endoflife.date")
return 0
body = issue_body(diff, today)
print(body)
if args.dry_run:
return 0
token = os.environ.get("GITEA_TOKEN", "")
if not token:
print("::warning::GITEA_TOKEN is not set; not writing the issue")
return 0
try:
file_issue(body, token, os.environ["GITEA_API"], os.environ["GITEA_REPO"])
except (urllib.error.URLError, KeyError) as error:
print(f"::error::could not write the issue: {error}")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())