feat(updates): the update history from apt's own log, with Proxmox VE 9.3's ids (NetOrk/netork#2728)

AptHistoryMixin implements get_update_history over run_command: history.log and its
rotations in one round trip as the login user, root only for a file that user may not
read. Dates are read in the host's zone; a transaction's id is its start and the number
of earlier ones with that start in the same file, as GET /nodes/{node}/apt/history names
it. Malformed blocks are left out, a report cut short raises.
This commit is contained in:
christianmanivong committed 2026-11-26 23:04:41 +01:00
1 parent 5985c87cc8
commit e3420269b7
6 files changed
+843

No files matched your search

+15
View File
@@ -37,6 +37,7 @@ Function classes -- what a device *can do*. Shared behaviour lives here once
instead of being restated on every role that happens to need it:
* :class:`~napalm_device_types.channel.CommandChannelMixin`
* :class:`~napalm_device_types.apt_history.AptHistoryMixin`
* :class:`~napalm_device_types.config_lifecycle.ConfigLifecycleMixin`
* :class:`~napalm_device_types.config_revisions.ConfigRevisionsMixin`
* :class:`~napalm_device_types.config_sync.ConfigSyncMixin`
@@ -80,6 +81,14 @@ Introspection -- :func:`~napalm_device_types.roles.roles_of`,
"""
from napalm_device_types.access_point import AccessPointDriver
from napalm_device_types.apt_history import (
APT_HISTORY_COMMAND,
AptHistoryMixin,
AptHistoryUnreadable,
apt_history_command,
host_zone,
parse_apt_history,
)
from napalm_device_types.apt_proxy import (
APT_PROXY_COMMAND,
AptProxyMixin,
@@ -442,6 +451,12 @@ __all__ = [
"FixStepOutcomeDict",
"LldpAgentMixin",
"PackageProxyMixin",
"APT_HISTORY_COMMAND",
"AptHistoryMixin",
"AptHistoryUnreadable",
"apt_history_command",
"host_zone",
"parse_apt_history",
"APT_PROXY_COMMAND",
"AptProxyMixin",
"https_proxy_for",
+402
View File
@@ -0,0 +1,402 @@
"""apt's history log as past transactions (``UpdateMixin.get_update_history``, NetOrk/netork#2728).
apt appends a block to ``/var/log/apt/history.log`` for every run that changed a
package, also those no caller started (an operator's ``apt``, unattended-upgrades,
PackageKit)::
Start-Date: 2026-11-26 10:00:00
Commandline: apt-get -y upgrade
Requested-By: admin (1000)
Install: linux-image-6.12.57+deb13-amd64:amd64 (6.12.57-1, automatic)
Upgrade: openssh-server:amd64 (1:10.0p1-7, 1:10.0p1-7+deb13u1)
Remove: ifupdown:amd64 (0.8.44)
Error: Sub-process /usr/bin/dpkg returned an error code (1)
End-Date: 2026-11-26 10:01:00
logrotate moves it to ``history.log.1.gz`` and on, monthly, twelve deep by default.
The file is 0644 on Debian and Ubuntu, so :data:`APT_HISTORY_COMMAND` reads it
as the login user; :class:`AptHistoryMixin` asks for root only where a file is
not readable that way. One round trip prints every file behind a marker line,
the host's time zone (``/etc/localtime``'s link, ``/etc/timezone``) and its UTC
offset (``date +%z``), which stands in where the zone has no name.
The dates are the host's local time. A transaction is named like Proxmox VE 9.3's
``GET /nodes/{node}/apt/history`` names it: its start in unix seconds and the
number of earlier transactions with the same start **in the same log file**, so
a Proxmox VE node that moves to 9.3 keeps the ids it had. The count takes every
block with a readable start, also one skipped below; it never depends on *since*.
Strict: a block whose package lines or end do not read as apt writes them is left
out, never guessed at; a block without ``End-Date`` is one that is running or was
interrupted (``end`` None). A report cut short, or a file that could not be read,
raises: an empty list means no transaction, never "could not read".
"""
from __future__ import annotations
import re
from collections.abc import Callable
from datetime import datetime, timedelta, timezone, tzinfo
from typing import TYPE_CHECKING
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from napalm_device_types._time_sync_reading import _zone_name
from napalm_device_types.updates import (
UpdateHistoryAction,
UpdateHistoryDict,
UpdateHistoryPackageDict,
)
if TYPE_CHECKING: # pragma: no cover - for type checkers only
from napalm_device_types.channel import CommandResult
#: Where apt keeps its history log.
APT_HISTORY_DIR = "/var/log/apt"
_MARK = "### apt-history"
#: Seconds the read may take: twelve rotated months of a busy host.
_READ_TIMEOUT = 120
def apt_history_command(log_dir: str = APT_HISTORY_DIR) -> str:
"""``sh`` that prints the time zone, the UTC offset and every history file in *log_dir*.
Each file follows a ``### apt-history file <path>`` line and ends with a
``### apt-history status <exit code>`` line; one the login user may not read
is only named (``unreadable``). ``### apt-history end`` closes the report.
"""
return (
f"m='{_MARK}'; "
"z=$( { readlink /etc/localtime || cat /etc/timezone; } 2>/dev/null | head -n 1); "
'printf "%s zone %s\\n" "$m" "$z"; '
'printf "%s offset %s\\n" "$m" "$(date +%z)"; '
f"for f in {log_dir}/history.log {log_dir}/history.log.*; do "
'[ -f "$f" ] || continue; '
'if [ ! -r "$f" ]; then printf "%s unreadable %s\\n" "$m" "$f"; continue; fi; '
'printf "%s file %s\\n" "$m" "$f"; '
'case "$f" in *.gz) zcat -- "$f";; *) cat -- "$f";; esac 2>/dev/null; '
'printf "\\n%s status %s\\n" "$m" "$?"; '
"done; "
'printf "%s end\\n" "$m"'
)
#: Prints apt's history log, rotated files too, with the host's time zone.
APT_HISTORY_COMMAND = apt_history_command()
class AptHistoryUnreadable(PermissionError):
"""A history file the user that read the log may not read."""
#: The package lines apt writes, and the action each stands for.
_ACTIONS: dict[str, UpdateHistoryAction] = {
"Install": "install",
"Reinstall": "reinstall",
"Upgrade": "upgrade",
"Downgrade": "downgrade",
"Remove": "remove",
"Purge": "purge",
"Disappeared": "disappear",
}
#: ``name[:arch] (versions)``; neither a name nor a Debian version holds ``,``, ``(`` or ``)``.
_ENTRY = re.compile(r"([^\s,()]+) \(([^()]*)\)")
#: ``Disappeared`` names a package without a version where apt no longer knows it.
_DISAPPEARED = re.compile(r"([^\s,()]+)(?: \(([^\s,()]+)\))?")
_REQUESTED_BY = re.compile(r"(.+) \(\d+\)")
_DATE = "%Y-%m-%d %H:%M:%S"
_OFFSET = re.compile(r"([+-])(\d\d)(\d\d)")
#: ``history.log``, ``history.log.<n>`` and ``history.log.<n>.gz``.
_ROTATED = re.compile(r"history\.log(?:\.(\d+)(?:\.gz)?)?")
def host_zone(name: str, offset: str) -> tzinfo:
"""The host's zone from its name, else the fixed UTC offset ``date +%z`` printed.
:raises ValueError: when neither says.
"""
zone = _zone_name(name)
if zone:
try:
return ZoneInfo(zone)
except (ZoneInfoNotFoundError, ValueError):
pass
match = _OFFSET.fullmatch(offset.strip())
if match is None:
raise ValueError(f"the host named no time zone ({name!r}) and no UTC offset ({offset!r})")
sign = -1 if match.group(1) == "-" else 1
return timezone(sign * timedelta(hours=int(match.group(2)), minutes=int(match.group(3))))
def _local(value: str, zone: tzinfo) -> int | None:
"""apt's ``YYYY-MM-DD HH:MM:SS`` in *zone* as unix seconds; None for anything else."""
try:
when = datetime.strptime(" ".join(value.split()), _DATE)
except ValueError:
return None
return int(when.replace(tzinfo=zone).timestamp())
_Versions = tuple[str | None, str | None] | None
def _installed(v: list[str]) -> _Versions:
return (None, v[0]) if v[1:] in ([], ["automatic"]) else None
def _changed(v: list[str]) -> _Versions:
return (v[0], v[1]) if len(v) == 2 else None
def _same(v: list[str]) -> _Versions:
return (v[0], v[0]) if len(v) == 1 else None
def _removed(v: list[str]) -> _Versions:
# A package removed earlier and purged now has no installed version: ``Purge: name ()``.
return (v[0] or None, None) if len(v) == 1 else None
def _gone(v: list[str]) -> _Versions:
return ((v[0] if v else None), None) if len(v) <= 1 else None
#: Per action: ``(old, new)`` from the versions apt wrote in a package's brackets.
_VERSIONS: dict[UpdateHistoryAction, Callable[[list[str]], _Versions]] = {
"install": _installed,
"reinstall": _same,
"upgrade": _changed,
"downgrade": _changed,
"remove": _removed,
"purge": _removed,
"disappear": _gone,
}
def _versions(action: UpdateHistoryAction, versions: list[str]) -> _Versions:
"""``(old, new)`` of one package; None where what apt wrote does not fit *action*."""
if action not in ("remove", "purge") and not all(versions):
return None
return _VERSIONS[action](versions)
def _disappeared(value: str) -> list[tuple[str, list[str]]] | None:
found = [_DISAPPEARED.fullmatch(item) for item in value.split(", ")]
if not all(found):
return None
return [(m.group(1), [m.group(2)] if m.group(2) else []) for m in found if m]
def _entries(action: UpdateHistoryAction, value: str) -> list[tuple[str, list[str]]] | None:
"""``(name[:arch], versions)`` per package of a line; None unless all of it reads."""
if action == "disappear":
return _disappeared(value)
matches = list(_ENTRY.finditer(value))
if not matches or ", ".join(m.group(0) for m in matches) != value:
return None
return [(m.group(1), [v.strip() for v in m.group(2).split(",")]) for m in matches]
def _packages(action: UpdateHistoryAction, value: str) -> list[UpdateHistoryPackageDict] | None:
"""The packages of one ``Install:``-style line; None unless every one reads."""
entries = _entries(action, value.strip())
if entries is None:
return None
packages: list[UpdateHistoryPackageDict] = []
for name, versions in entries:
pair = _versions(action, versions)
if pair is None:
return None
packages.append(
{
"name": name.split(":", 1)[0],
"action": action,
"old_version": pair[0],
"new_version": pair[1],
}
)
return packages
def _transaction(start: int, lines: list[str], zone: tzinfo) -> UpdateHistoryDict | None:
"""One block after its ``Start-Date``; None where a line does not read."""
found: UpdateHistoryDict = {
"id": "",
"start": start,
"end": None,
"packages": [],
"requested_by": None,
"command": None,
"error": None,
}
for line in lines:
key, sep, value = line.partition(": ")
if not sep:
return None
if key in _ACTIONS:
packages = _packages(_ACTIONS[key], value)
if packages is None:
return None
found["packages"].extend(packages)
elif key == "End-Date":
found["end"] = _local(value, zone)
if found["end"] is None:
return None
elif key in ("Commandline", "Requested-By", "Error"):
_text(found, key, value.strip())
return found
def _text(found: UpdateHistoryDict, key: str, value: str) -> None:
if key == "Commandline":
found["command"] = value or None
elif key == "Requested-By":
match = _REQUESTED_BY.fullmatch(value)
found["requested_by"] = (match.group(1) if match else value) or None
else:
found["error"] = value or None
def _blocks(lines: list[str]) -> list[tuple[str, list[str]]]:
"""``(Start-Date value, the lines after it)`` per block of one file."""
blocks: list[tuple[str, list[str]]] = []
for line in lines:
line = line.rstrip("\r")
if line.startswith("Start-Date:"):
blocks.append((line.partition(":")[2], []))
elif blocks and line.strip():
blocks[-1][1].append(line)
return blocks
def _file_transactions(lines: list[str], zone: tzinfo) -> list[UpdateHistoryDict]:
"""One file's transactions in the order it holds them, each with its id."""
seen: dict[int, int] = {}
found: list[UpdateHistoryDict] = []
for date, body in _blocks(lines):
start = _local(date, zone)
if start is None:
continue
index = seen.get(start, 0)
seen[start] = index + 1
transaction = _transaction(start, body, zone)
if transaction is not None:
transaction["id"] = f"{start}-{index}"
found.append(transaction)
return found
def _rotation(path: str) -> int | None:
"""0 for ``history.log``, *n* for its *n*-th rotation; None for another file."""
match = _ROTATED.fullmatch(path.rpartition("/")[2])
if match is None:
return None
return int(match.group(1) or 0)
def _marker(
kind: str, rest: str, values: dict[str, str], files: dict[int, list[str]]
) -> list[str] | None:
"""Take one marker line; the lines of the history file it opens, if it opens one.
:raises AptHistoryUnreadable: for a history file the user may not read.
"""
rotation = _rotation(rest.strip())
if kind == "unreadable" and rotation is not None:
raise AptHistoryUnreadable(f"{rest.strip()} is not readable")
if kind == "file" and rotation is not None:
return files.setdefault(rotation, [])
if kind in ("zone", "offset"):
values[kind] = rest
return None
def _report(text: str) -> tuple[dict[str, str], dict[int, list[str]]]:
"""The report's ``zone`` and ``offset``, and each history file's lines by rotation.
:raises ValueError: for a report cut short or a file that could not be read.
:raises AptHistoryUnreadable: for a file the user may not read.
"""
values: dict[str, str] = {}
files: dict[int, list[str]] = {}
current: list[str] | None = None
for line in text.splitlines():
if not line.startswith(_MARK + " "):
if current is not None:
current.append(line)
continue
kind, _, rest = line[len(_MARK) + 1 :].partition(" ")
if kind == "end":
return values, files
if kind == "status" and current is not None and rest.strip() != "0":
raise ValueError(f"apt's history log could not be read (exit {rest.strip()})")
current = _marker(kind, rest, values, files)
raise ValueError("apt's history log came back cut short")
def parse_apt_history(text: str, since: int | None = None) -> list[UpdateHistoryDict]:
""":data:`APT_HISTORY_COMMAND`'s report as transactions, newest first.
:param since: Unix seconds; only transactions that started at or after it.
:raises ValueError: for a report cut short, a file that could not be read, or
a host that named neither its time zone nor its UTC offset.
:raises AptHistoryUnreadable: for a file the user may not read.
"""
values, files = _report(text)
zone = host_zone(values.get("zone", ""), values.get("offset", ""))
oldest_first: list[UpdateHistoryDict] = []
for rotation in sorted(files, reverse=True):
oldest_first.extend(_file_transactions(files[rotation], zone))
newest = sorted(reversed(oldest_first), key=lambda t: t["start"], reverse=True)
return [t for t in newest if since is None or t["start"] >= since]
class AptHistoryMixin:
"""Adds :meth:`get_update_history` from apt's log, over the driver's ``run_command``.
Mixed in by the drivers of Debian-family hosts, so
``hasattr(driver, "get_update_history")`` stays a truthful answer. The log is
read as the login user; only a file that user may not read makes it read as root.
"""
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
def run_command(
self,
command: str,
*,
privileged: bool = False,
timeout: float = 60,
stdin: bytes | None = None,
) -> CommandResult: ...
def get_update_history(self, since: int | None = None) -> list[UpdateHistoryDict]:
"""apt's transactions on the host, newest first, from *since* (unix seconds) on.
:raises RuntimeError: when the log could not be read.
:raises ValueError: when the report came back cut short.
:raises AptHistoryUnreadable: when even root could not read a file.
"""
try:
return parse_apt_history(self._read_apt_history(privileged=False), since)
except AptHistoryUnreadable:
return parse_apt_history(self._read_apt_history(privileged=True), since)
def _read_apt_history(self, *, privileged: bool) -> str:
result = self.run_command(APT_HISTORY_COMMAND, privileged=privileged, timeout=_READ_TIMEOUT)
if result.exit_code != 0:
said = (result.stderr or result.stdout).strip()[-300:]
raise RuntimeError(f"cannot read apt's history log: {said or result.exit_code}")
return result.stdout
__all__ = [
"APT_HISTORY_COMMAND",
"APT_HISTORY_DIR",
"AptHistoryMixin",
"AptHistoryUnreadable",
"apt_history_command",
"host_zone",
"parse_apt_history",
]