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

+402
View File
@@ -0,0 +1,402 @@
"""apt's history log as past transactions (NetOrk/netork#2728).
The blocks below are written as apt writes them (``apt-pkg/deb/dpkgpm.cc``): two
spaces between date and time, ``name:arch (version[, ...])`` entries joined by
``, ``, ``Install``'s ``automatic``, ``Upgrade``/``Downgrade`` with old and new,
``Remove``/``Purge`` with the version that was installed, ``Error`` before
``End-Date``. The ids follow Proxmox VE 9.3's ``GET /nodes/{node}/apt/history``:
start time, and the count of earlier transactions with that start in the same file.
"""
from __future__ import annotations
import gzip
import os
import subprocess
from datetime import UTC, datetime, timedelta, timezone
from pathlib import Path
import pytest
from napalm_device_types import (
APT_HISTORY_COMMAND,
AptHistoryMixin,
AptHistoryUnreadable,
apt_history_command,
host_zone,
parse_apt_history,
)
from napalm_device_types.channel import CommandResult
def _utc(text: str) -> int:
return int(datetime.strptime(text, "%Y-%m-%d %H:%M:%S").replace(tzinfo=UTC).timestamp())
CURRENT = """
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), linux-headers-6.12.57+deb13-common:all (6.12.57-1, automatic), htop:amd64 (3.4.1-5)
Upgrade: openssh-server:amd64 (1:10.0p1-7, 1:10.0p1-7+deb13u1), libssl3t64:amd64 (3.5.1-1, 3.5.1-1+deb13u1), libssl3t64:i386 (3.5.1-1, 3.5.1-1+deb13u1)
End-Date: 2026-11-26 10:01:00
Start-Date: 2026-11-26 10:01:00
Commandline: /usr/bin/apt remove wazuh-agent
Remove: wazuh-agent:amd64 (4.14.8-1)
Error: Sub-process /usr/bin/dpkg returned an error code (1)
End-Date: 2026-11-26 10:01:00
Start-Date: 2026-11-26 10:01:00
Commandline: /usr/bin/apt purge wazuh-agent
Purge: wazuh-agent:amd64 (4.14.8-1), linux-image-6.12.48+deb13-amd64:amd64 ()
End-Date: 2026-11-26 10:01:00
Start-Date: 2026-11-26 10:05:13
Commandline: /usr/bin/unattended-upgrade
Upgrade: tzdata:all (2025b-4, 2025b-4+deb13u1)
"""
ROTATED = """
Start-Date: 2026-07-14 03:12:40
Commandline: apt-get install --reinstall libvulkan1
Requested-By: admin (1000)
Reinstall: libvulkan1:amd64 (1.4.309.0-1), libvulkan1:i386 (1.4.309.0-1)
End-Date: 2026-07-14 03:12:41
Start-Date: 2026-07-14 03:13:05
Commandline: apt-get install pve-manager=9.0.10
Downgrade: pve-manager:amd64 (9.0.11, 9.0.10)
Disappeared: libfoo1 (1.2-3), libbar0
End-Date: 2026-07-14 03:13:20
"""
OLDEST = """
Start-Date: 2026-01-12 06:25:01
Commandline: apt-get dist-upgrade
Remove: caribou (0.4.21-9)
End-Date: 2026-01-12 06:25:30
"""
def _report(files: dict[str, str], zone: str = "/usr/share/zoneinfo/Europe/Berlin") -> str:
"""What :data:`APT_HISTORY_COMMAND` prints for *files* (path -> content)."""
lines = [f"### apt-history zone {zone}", "### apt-history offset +0100"]
for path, content in files.items():
lines += [f"### apt-history file {path}", content, "", "### apt-history status 0"]
return "\n".join([*lines, "### apt-history end", ""])
LOGS = {
"/var/log/apt/history.log": CURRENT,
"/var/log/apt/history.log.1.gz": ROTATED,
"/var/log/apt/history.log.10.gz": OLDEST,
}
class TestParse:
def test_newest_first_over_every_file(self):
ids = [t["id"] for t in parse_apt_history(_report(LOGS))]
assert ids == [
f"{_utc('2026-11-26 09:05:13')}-0",
f"{_utc('2026-11-26 09:01:00')}-1",
f"{_utc('2026-11-26 09:01:00')}-0",
f"{_utc('2026-11-26 09:00:00')}-0",
f"{_utc('2026-07-14 01:13:05')}-0",
f"{_utc('2026-07-14 01:12:40')}-0",
f"{_utc('2026-01-12 05:25:01')}-0",
]
def test_a_transaction_with_its_packages(self):
upgrade = parse_apt_history(_report(LOGS))[3]
assert upgrade == {
"id": f"{_utc('2026-11-26 09:00:00')}-0",
"start": _utc("2026-11-26 09:00:00"),
"end": _utc("2026-11-26 09:01:00"),
"packages": [
{
"name": "linux-image-6.12.57+deb13-amd64",
"action": "install",
"old_version": None,
"new_version": "6.12.57-1",
},
{
"name": "linux-headers-6.12.57+deb13-common",
"action": "install",
"old_version": None,
"new_version": "6.12.57-1",
},
{
"name": "htop",
"action": "install",
"old_version": None,
"new_version": "3.4.1-5",
},
{
"name": "openssh-server",
"action": "upgrade",
"old_version": "1:10.0p1-7",
"new_version": "1:10.0p1-7+deb13u1",
},
{
"name": "libssl3t64",
"action": "upgrade",
"old_version": "3.5.1-1",
"new_version": "3.5.1-1+deb13u1",
},
{
"name": "libssl3t64",
"action": "upgrade",
"old_version": "3.5.1-1",
"new_version": "3.5.1-1+deb13u1",
},
],
"requested_by": "admin",
"command": "apt-get -y upgrade",
"error": None,
}
def test_the_error_a_run_ended_with(self):
failed = parse_apt_history(_report(LOGS))[2]
assert failed["error"] == "Sub-process /usr/bin/dpkg returned an error code (1)"
assert failed["requested_by"] is None
assert failed["packages"] == [
{
"name": "wazuh-agent",
"action": "remove",
"old_version": "4.14.8-1",
"new_version": None,
}
]
def test_a_purge_of_what_was_removed_before_had_no_version(self):
purge = parse_apt_history(_report(LOGS))[1]
assert [(p["name"], p["action"], p["old_version"]) for p in purge["packages"]] == [
("wazuh-agent", "purge", "4.14.8-1"),
("linux-image-6.12.48+deb13-amd64", "purge", None),
]
def test_a_run_without_end_is_running_or_interrupted(self):
newest = parse_apt_history(_report(LOGS))[0]
assert newest["end"] is None
assert newest["command"] == "/usr/bin/unattended-upgrade"
def test_reinstall_downgrade_disappeared_and_arch_less_names(self):
history = parse_apt_history(_report(LOGS))
downgrade, reinstall, oldest = history[4], history[5], history[6]
assert [(p["name"], p["old_version"], p["new_version"]) for p in reinstall["packages"]] == [
("libvulkan1", "1.4.309.0-1", "1.4.309.0-1"),
("libvulkan1", "1.4.309.0-1", "1.4.309.0-1"),
]
assert [
(p["action"], p["name"], p["old_version"], p["new_version"])
for p in downgrade["packages"]
] == [
("downgrade", "pve-manager", "9.0.11", "9.0.10"),
("disappear", "libfoo1", "1.2-3", None),
("disappear", "libbar0", None, None),
]
assert oldest["packages"] == [
{"name": "caribou", "action": "remove", "old_version": "0.4.21-9", "new_version": None}
]
def test_summer_time_is_the_zones(self):
reinstall = parse_apt_history(_report(LOGS))[5]
assert reinstall["start"] == _utc("2026-07-14 01:12:40") # CEST, UTC+2
def test_since_filters_by_start_and_keeps_the_ids(self):
since = _utc("2026-11-26 09:01:00")
ids = [t["id"] for t in parse_apt_history(_report(LOGS), since=since)]
assert ids == [f"{_utc('2026-11-26 09:05:13')}-0", f"{since}-1", f"{since}-0"]
def test_nothing_logged_is_an_empty_list(self):
assert parse_apt_history(_report({})) == []
assert parse_apt_history(_report({"/var/log/apt/history.log": ""})) == []
def test_the_index_is_counted_per_file(self):
same = "\nStart-Date: 2026-11-26 10:00:00\nInstall: htop:amd64 (3.4.1-5)\nEnd-Date: 2026-11-26 10:00:00\n"
history = parse_apt_history(
_report({"/var/log/apt/history.log": same * 2, "/var/log/apt/history.log.1.gz": same})
)
start = _utc("2026-11-26 09:00:00")
assert [t["id"] for t in history] == [f"{start}-1", f"{start}-0", f"{start}-0"]
class TestStrict:
@pytest.mark.parametrize(
"line",
[
"Upgrade: openssh-server:amd64 (1:10.0p1-7)", # an upgrade names old and new
"Install: htop:amd64 (3.4.1-5, manual)",
"Remove: htop:amd64 (3.4.1-5), ",
"Install: htop:amd64 (3.4.1-5", # cut short
"Upgrade: htop:amd64 (, 3.4.1-5)",
"Disappeared: libfoo1 (1.2-3) (1.2-4)",
"a line apt never writes",
],
)
def test_a_malformed_block_is_left_out_but_counted(self, line):
log = (
f"Start-Date: 2026-11-26 10:00:00\n{line}\nEnd-Date: 2026-11-26 10:00:01\n\n"
"Start-Date: 2026-11-26 10:00:00\nInstall: htop:amd64 (3.4.1-5)\n"
"End-Date: 2026-11-26 10:00:02\n"
)
history = parse_apt_history(_report({"/var/log/apt/history.log": log}))
assert [t["id"] for t in history] == [f"{_utc('2026-11-26 09:00:00')}-1"]
def test_an_unreadable_date_is_no_transaction(self):
log = (
"Start-Date: yesterday\nInstall: htop:amd64 (3.4.1-5)\n\n"
"Start-Date: 2026-11-26 10:00:00\nInstall: htop:amd64 (3.4.1-5)\n"
"End-Date: soon\n"
)
assert parse_apt_history(_report({"/var/log/apt/history.log": log})) == []
def test_lines_before_the_first_block_are_ignored(self):
log = "Install: htop:amd64 (3.4.1-5)\n" + OLDEST
assert len(parse_apt_history(_report({"/var/log/apt/history.log": log}))) == 1
def test_a_report_cut_short_raises(self):
with pytest.raises(ValueError, match="cut short"):
parse_apt_history(_report(LOGS).replace("### apt-history end\n", ""))
def test_a_file_that_could_not_be_read_raises(self):
report = _report(LOGS).replace("status 0", "status 1", 1)
with pytest.raises(ValueError, match="exit 1"):
parse_apt_history(report)
def test_a_file_the_user_may_not_read_raises(self):
report = _report(LOGS).replace(
"### apt-history end",
"### apt-history unreadable /var/log/apt/history.log.2.gz\n### apt-history end",
)
with pytest.raises(AptHistoryUnreadable, match="history.log.2.gz"):
parse_apt_history(report)
def test_other_files_in_the_directory_are_not_read(self):
report = _report({**LOGS, "/var/log/apt/history.log.dpkg-old": OLDEST}).replace(
"### apt-history end",
"### apt-history unreadable /var/log/apt/history.log.bak\n### apt-history end",
)
assert len(parse_apt_history(report)) == 7
class TestZone:
def test_a_named_zone(self):
assert str(host_zone("Europe/Berlin\n", "+0100")) == "Europe/Berlin"
assert str(host_zone("/usr/share/zoneinfo/America/New_York", "-0500")) == "America/New_York"
@pytest.mark.parametrize("name", ["", "Mars/Olympus_Mons", "../../etc/passwd"])
def test_without_a_known_name_the_offset(self, name):
assert host_zone(name, "+0530") == timezone(timedelta(hours=5, minutes=30))
assert host_zone(name, "-0300\n") == timezone(-timedelta(hours=3))
def test_neither_raises(self):
with pytest.raises(ValueError, match="no time zone"):
host_zone("", "")
def test_a_host_on_its_offset_alone(self):
history = parse_apt_history(_report({"/var/log/apt/history.log": OLDEST}, zone=""))
assert history[0]["start"] == _utc("2026-01-12 05:25:01") # +0100
class TestCommand:
"""The command run for real with ``sh`` against a log directory in a temp directory."""
@staticmethod
def _run(log_dir: Path) -> str:
done = subprocess.run(
["sh", "-c", apt_history_command(str(log_dir))],
capture_output=True,
text=True,
check=True,
)
return done.stdout
@staticmethod
def _logs(log_dir: Path) -> None:
(log_dir / "history.log").write_text(CURRENT)
(log_dir / "history.log.1.gz").write_bytes(gzip.compress(ROTATED.encode()))
(log_dir / "history.log.10.gz").write_bytes(gzip.compress(OLDEST.encode()))
(log_dir / "term.log").write_text("Log started: 2026-11-26 10:00:00\n")
def test_every_file_rotated_or_not(self, tmp_path):
self._logs(tmp_path)
history = parse_apt_history(self._run(tmp_path))
# Dated in this machine's zone: the order and the fields, not the seconds.
assert len(history) == 7
assert history[0]["command"] == "/usr/bin/unattended-upgrade"
assert history[-1]["command"] == "apt-get dist-upgrade"
def test_the_zone_and_offset_are_printed(self, tmp_path):
out = self._run(tmp_path)
assert "### apt-history zone " in out
assert "### apt-history offset " in out
assert out.endswith("### apt-history end\n")
def test_no_log_is_no_transaction(self, tmp_path):
assert parse_apt_history(self._run(tmp_path / "missing")) == []
@pytest.mark.skipif(os.geteuid() == 0, reason="root reads every file")
def test_an_unreadable_file_is_named(self, tmp_path):
self._logs(tmp_path)
(tmp_path / "history.log.1.gz").chmod(0)
with pytest.raises(AptHistoryUnreadable):
parse_apt_history(self._run(tmp_path))
def test_the_constant_reads_apts_own_directory(self):
assert APT_HISTORY_COMMAND == apt_history_command("/var/log/apt")
class _Host(AptHistoryMixin):
def __init__(self, *answers: CommandResult) -> None:
self.answers = list(answers)
self.ran: list[bool] = []
def run_command(
self,
command: str,
*,
privileged: bool = False,
timeout: float = 60,
stdin: bytes | None = None,
) -> CommandResult:
assert command == APT_HISTORY_COMMAND
assert stdin is None
self.ran.append(privileged)
return self.answers.pop(0)
UNREADABLE = _report(LOGS).replace(
"### apt-history end",
"### apt-history unreadable /var/log/apt/history.log.2.gz\n### apt-history end",
)
class TestMixin:
def test_read_as_the_login_user(self):
host = _Host(CommandResult(_report(LOGS), "", 0))
assert len(host.get_update_history()) == 7
assert host.ran == [False]
def test_since_is_applied(self):
host = _Host(CommandResult(_report(LOGS), "", 0))
assert len(host.get_update_history(since=_utc("2026-11-26 09:01:00"))) == 3
def test_a_file_only_root_may_read_is_read_as_root(self):
host = _Host(CommandResult(UNREADABLE, "", 0), CommandResult(_report(LOGS), "", 0))
assert len(host.get_update_history()) == 7
assert host.ran == [False, True]
def test_unreadable_even_as_root_raises(self):
host = _Host(CommandResult(UNREADABLE, "", 0), CommandResult(UNREADABLE, "", 0))
with pytest.raises(AptHistoryUnreadable):
host.get_update_history()
def test_a_failed_run_raises(self):
host = _Host(
CommandResult(UNREADABLE, "", 0),
CommandResult("", "sudo: a password is required", 1),
)
with pytest.raises(RuntimeError, match="password is required"):
host.get_update_history()