From 9efc3275b188bc698fd12902dfaaf7f005014532 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Thu, 3 Dec 2026 13:03:41 +0100 Subject: [PATCH] feat: apt's errors come through, unreadable sources raise PackageSourcesUnreadable, 4.57.0 (NetOrk/netork#3087) One bad apt source line, two Signed-By for one repository, makes apt refuse every source. The update read then failed with "exit status 100" and nothing else, because APT_UPGRADABLE_COMMAND threw stderr away. The command now passes apt's E: lines on, marked __APT_E:, and still keeps its warnings out. parse_apt_upgradable raises PackageSourcesUnreadable, a ValueError, with apt's errors when apt could not read its sources, and names them after the exit status for any other failure. --- CHANGELOG.md | 14 ++++++ napalm_device_types/__init__.py | 2 + napalm_device_types/package_updates.py | 29 +++++++++--- napalm_device_types/updates.py | 10 +++++ pyproject.toml | 2 +- tests/test_package_updates.py | 61 ++++++++++++++++++++++++++ 6 files changed, 111 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 688bf4f..1bbc7c5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,20 @@ recorded here; their history is the git log. ## [Unreleased] +## [4.57.0] - 2026-12-03 + +### Added +- `PackageSourcesUnreadable`, a `ValueError`: `parse_apt_upgradable` raises it when apt + could not read its list of sources, and with it read no package at all -- one bad line, + two `Signed-By` for one repository say, makes apt refuse every source (NetOrk/netork#3087). + Its message is what apt said, its errors joined by `"; "`. A caller that catches + `ValueError` catches it as before. + +### Changed +- `APT_UPGRADABLE_COMMAND` passes apt's errors on, each `E:` line marked `__APT_E:`; + its warnings stay out as before. Any other failed read now names apt's errors after + the exit status. + ## [4.56.0] - 2026-12-02 ### Added diff --git a/napalm_device_types/__init__.py b/napalm_device_types/__init__.py index ad24871..a1d562f 100644 --- a/napalm_device_types/__init__.py +++ b/napalm_device_types/__init__.py @@ -499,6 +499,7 @@ from napalm_device_types.time_sync import ( from napalm_device_types.time_sync_posix import PosixTimeSyncMixin, parse_time_sync from napalm_device_types.updates import ( PackageIndexMissing, + PackageSourcesUnreadable, UpdateHistoryAction, UpdateHistoryDict, UpdateHistoryPackageDict, @@ -813,6 +814,7 @@ __all__ = [ "SystemdUnavailable", "parse_systemd_services", "PackageIndexMissing", + "PackageSourcesUnreadable", "UpdateMixin", "VIRTUAL_IPS_COMMAND", "VirtualIpsMixin", diff --git a/napalm_device_types/package_updates.py b/napalm_device_types/package_updates.py index 60856f2..57ef304 100644 --- a/napalm_device_types/package_updates.py +++ b/napalm_device_types/package_updates.py @@ -18,13 +18,23 @@ import re from napalm_device_types.models import UpdateDict from napalm_device_types.terminal import strip_terminal_codes +from napalm_device_types.updates import PackageSourcesUnreadable #: Read-only, no root needed, in a fixed language so the parse holds, and #: through a pipe: without a terminal apt draws no progress and no terminal #: codes, one of which (``ESC >``) a screen-scraping transport took for a shell #: prompt and stopped reading at. Its exit status is printed inside the group, -#: so it is apt's, not cat's. -APT_UPGRADABLE_COMMAND = "{ LC_ALL=C apt list --upgradable 2>/dev/null; echo __APT_RC=$?; } | cat" +#: so it is apt's, not cat's. Its errors (``E:``) come through marked +#: ``__APT_E:``, so a failed read says why (netOrk #3087); the rest of what it +#: writes to stderr, its warnings, stays out. Plain ``sh``: stdout goes round +#: the pipe on descriptor 3. +APT_UPGRADABLE_COMMAND = ( + "{ { LC_ALL=C apt list --upgradable 2>&1 1>&3 3>&-; echo __APT_RC=$? 1>&3; }" + " | sed -n 's/^E: /__APT_E: /p'; } 3>&1 | cat" +) + +#: apt's last word when it cannot read its sources, in ``LC_ALL=C``. +_SOURCES_UNREADABLE = "The list of sources could not be read." #: Read-only. Lists the packages that a pending security advisory covers. A #: failed dnf prints nothing, the same as no advisories, so its exit status is @@ -52,6 +62,7 @@ DNF_INSTALLED_CVES_COMMAND = ( _APT_LINE = re.compile(r"^(\S+)/(\S+)\s+(\S+)\s+\S+\s+\[upgradable from:\s+(\S+)\]") _SECURITY_SUITE = "-security" _APT_STATUS = re.compile(r"^__APT_RC=(\d+)\s*$", re.MULTILINE) +_APT_ERROR = re.compile(r"^__APT_E: (.*?)\s*$", re.MULTILINE) _DNF_STATUS = re.compile(r"^__DNF_RC=(\d+)\s*$", re.MULTILINE) _CVE_ID = re.compile(r"^CVE-\d{4}-\d{4,}$") @@ -71,14 +82,19 @@ def _joined_lines(output: str) -> list[str]: def _listing(output: str, status: re.Pattern[str], what: str) -> str: """The listing without its exit status, or ``ValueError`` when the command failed or the output was cut short -- "could not read" must never look like - "nothing pending".""" + "nothing pending". apt's marked errors go into the failure's message, and + unreadable sources raise :exc:`PackageSourcesUnreadable`.""" text = strip_terminal_codes(output) statuses = status.findall(text) if not statuses: raise ValueError(f"{what} reported no exit status; the output was cut short") + errors = [e for e in _APT_ERROR.findall("\n".join(_joined_lines(text))) if e] if statuses[-1] != "0": - raise ValueError(f"{what} failed with exit status {statuses[-1]}") - return status.sub("", text) + if _SOURCES_UNREADABLE in errors: + raise PackageSourcesUnreadable("; ".join(errors)) + said = f": {'; '.join(errors)}" if errors else "" + raise ValueError(f"{what} failed with exit status {statuses[-1]}{said}") + return _APT_ERROR.sub("", status.sub("", text)) def parse_apt_upgradable(output: str) -> list[UpdateDict]: @@ -87,7 +103,8 @@ def parse_apt_upgradable(output: str) -> list[UpdateDict]: A package listed for several architectures (``libc6`` for amd64 and i386) is one entry; it counts as a security update if any of its lines does. - :raises ValueError: when apt failed or its exit status never arrived. + :raises PackageSourcesUnreadable: when apt could not read its list of sources. + :raises ValueError: when apt failed otherwise or its exit status never arrived. """ by_name: dict[str, UpdateDict] = {} for line in _joined_lines(_listing(output, _APT_STATUS, "apt list --upgradable")): diff --git a/napalm_device_types/updates.py b/napalm_device_types/updates.py index 05cc8df..a7163a3 100644 --- a/napalm_device_types/updates.py +++ b/napalm_device_types/updates.py @@ -68,6 +68,16 @@ class PackageIndexMissing(RuntimeError): """ +class PackageSourcesUnreadable(ValueError): + """apt could not read its list of sources, so it reads no package at all. + + One bad line -- two ``Signed-By`` for one repository, say -- makes apt refuse + every source, until someone fixes the line (netOrk #3087). The message is + what apt said, its errors joined by ``"; "``. A ``ValueError``, as every + failed read of :func:`parse_apt_upgradable` is. + """ + + class UpdateMixin: if TYPE_CHECKING: diff --git a/pyproject.toml b/pyproject.toml index 7e1d16c..eec1671 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "napalm-device-types" -version = "4.56.0" +version = "4.57.0" description = "Abstract device-type base classes for NAPALM drivers" readme = "README.md" requires-python = ">=3.12" diff --git a/tests/test_package_updates.py b/tests/test_package_updates.py index 7730f09..038ea84 100644 --- a/tests/test_package_updates.py +++ b/tests/test_package_updates.py @@ -12,10 +12,12 @@ Fixture lines are from real hosts (Ubuntu 24.04, Debian 13 / OMV, Proxmox VE 9). from __future__ import annotations import os +import shutil import subprocess import pytest +from napalm_device_types import PackageSourcesUnreadable from napalm_device_types.package_updates import ( APT_UPGRADABLE_COMMAND, DNF_INSTALLED_CVES_COMMAND, @@ -126,6 +128,65 @@ class TestAptUpgradable: with pytest.raises(ValueError, match="100"): parse_apt_upgradable("E: Could not get lock\n__APT_RC=100\n") + def test_a_failed_apt_says_what_apt_said(self): + """Its errors come through marked; the exit status alone names no cause.""" + output = "__APT_RC=100\n__APT_E: Could not open lock file /var/lib/apt/lists/lock\n" + + with pytest.raises(ValueError, match="100") as caught: + parse_apt_upgradable(output) + + assert "Could not open lock file /var/lib/apt/lists/lock" in str(caught.value) + assert not isinstance(caught.value, PackageSourcesUnreadable) + + def test_unreadable_sources_raise_their_own_error(self): + """Two Signed-By for one source make apt refuse every source (netOrk #3087).""" + output = ( + "__APT_RC=100\n" + "__APT_E: Conflicting values set for option Signed-By regarding source" + " http://HTTPS///download.docker.com/linux/ubuntu/ noble:" + " /etc/apt/keyrings/docker.gpg != /etc/apt/keyrings/docker.asc\n" + "__APT_E: The list of sources could not be read.\n" + ) + + with pytest.raises(PackageSourcesUnreadable) as caught: + parse_apt_upgradable(output) + + assert isinstance(caught.value, ValueError) # what a caller already catches + assert str(caught.value) == ( + "Conflicting values set for option Signed-By regarding source" + " http://HTTPS///download.docker.com/linux/ubuntu/ noble:" + " /etc/apt/keyrings/docker.gpg != /etc/apt/keyrings/docker.asc;" + " The list of sources could not be read." + ) + + def test_errors_of_a_read_that_worked_are_no_failure(self): + output = "__APT_E: The list of sources could not be read.\n" + UBUNTU + + assert len(parse_apt_upgradable(output)) == 2 + + def test_unreadable_sources_through_the_real_command(self, tmp_path): + """The command's own plumbing, in sh: apt's errors arrive marked, its + exit status is apt's, and its warnings stay out.""" + if not shutil.which("apt"): + pytest.skip("apt is not installed") + parts = tmp_path / "sources.list.d" + parts.mkdir() + (parts / "docker.list").write_text( + "deb [signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu noble stable\n" + "deb [signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu noble stable\n" + ) + config = tmp_path / "apt.conf" + config.write_text(f'Dir::Etc::sourceparts "{parts}";\nDir::Etc::sourcelist "/dev/null";\n') + env = {**os.environ, "APT_CONFIG": str(config)} + + out = subprocess.run( + ["sh", "-c", APT_UPGRADABLE_COMMAND], capture_output=True, text=True, env=env + ).stdout + + with pytest.raises(PackageSourcesUnreadable, match="Signed-By"): + parse_apt_upgradable(out) + assert "WARNING" not in out + def test_terminal_codes_around_the_status_are_dropped(self): """What a pseudo-terminal left on a Raspberry Pi OS host.""" raw = "Listing... 0%\n\x1b[?1h\x1b=\n" + UBUNTU.replace("__APT_RC=0", "\x1b>__APT_RC=0")