fix(packages): leave removed packages with leftover config out of apt

dpkg-query -W also lists packages that were removed but whose
configuration dpkg keeps (state rc), and the driver marked every line
installed: old kernels and a removed agent showed up as installed
software. The query now asks for db:Status-Abbrev and drops packages
that are not installed or only left their configuration; held, unpacked
and half-configured packages keep counting, their files are on disk.

The dpkg query and its parse move to napalm_linux/_dpkg.py, a pure
function under strict mypy, which keeps linux.py inside its line count.

Closes #17
This commit is contained in:
Christian Manivong committed 2026-11-01 21:48:05 +01:00
1 parent 54f6844d84
commit 024f68c543
5 files changed
+108 -51

No files matched your search

+4
View File
@@ -61,6 +61,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
(`Tue Oct 6 08:47:15 2026`) and only the command line in `command` (#21). `started` (`Tue Oct 6 08:47:15 2026`) and only the command line in `command` (#21). `started`
held the weekday alone and `command` began with the rest of the date. The start time held the weekday alone and `command` began with the rest of the date. The start time
is read in the C locale, so its words are English on every host. is read in the C locale, so its words are English on every host.
- `get_packages()` on apt hosts no longer lists removed packages whose configuration
dpkg still keeps (state `rc`) (#17). They were reported as installed: old kernels, or
an agent that had been removed. A package that is held, unpacked or half-configured
still counts, since its files are on disk.
## [0.15.1] - 2026-10-23 ## [0.15.1] - 2026-10-23
+73
View File
@@ -0,0 +1,73 @@
"""The packages dpkg has on a Debian-family host: the query and its parse."""
from __future__ import annotations
from napalm_device_types.models import PackageDict
#: One line per package dpkg knows, its state first (``ii``, ``rc``, ``hi``, …):
#: dpkg also lists removed packages whose configuration it still keeps (#17).
DPKG_QUERY_COMMAND = (
"dpkg-query -W -f='${db:Status-Abbrev}\\t${Package}\\t${Version}\\t${Installed-Size}"
"\\t${source:Package}\\t${source:Version}\\t${binary:Summary}\\n' 2>/dev/null"
)
#: The second letter of ``db:Status-Abbrev`` for a package whose files are gone:
#: ``n`` not installed, ``c`` only its configuration left (``rc``). Every other
#: state -- half-installed, unpacked, half-configured, awaiting triggers -- has
#: its files on disk.
_NOT_ON_DISK = frozenset("nc")
class DpkgPackageDict(PackageDict):
"""A dpkg package with the source package it was built from."""
source_package: str
source_version: str
def parse_dpkg_query(out: str) -> list[PackageDict]:
"""The packages in ``DPKG_QUERY_COMMAND``'s output whose files are on disk."""
packages: list[PackageDict] = []
for line in out.splitlines():
# Summary stays last and keeps whatever it contains: maxsplit must
# equal the number of tabs the format writes, not the field count.
status, _, line = line.partition("\t")
if status[1:2] in _NOT_ON_DISK:
continue
package = _package(line.split("\t", 5))
if package is not None:
packages.append(package)
return packages
def _package(parts: list[str]) -> DpkgPackageDict | None:
if len(parts) < 2:
return None
name = parts[0].strip()
version = parts[1].strip()
size = int(parts[2].strip()) * 1024 if len(parts) > 2 and parts[2].strip().isdigit() else 0
# Debian source package (e.g. openssh-server → openssh) for OSV matching.
source_package = parts[3].strip() if len(parts) > 3 and parts[3].strip() else name
# And its version, which is a different number from this package's.
#
# OSV states Debian ranges in *source* versions. A source package
# that ships several binaries gives each its own upstream version:
# libldb2 is 2:2.11.0+samba4.22.11+dfsg-… while its source, samba,
# is 2:4.22.11+dfsg-…. A consumer matching on source_package and
# comparing `version` compares two unrelated numbers — dpkg reads
# ldb's 2.11.0 as older than the 2:4.17.4+dfsg-1 that fixed
# CVE-2022-44640, and a host five releases past the fix was reported
# vulnerable on four packages at once.
#
# dpkg leaves this empty when it equals `Version`; so does an older
# dpkg that does not know the field at all.
source_version = parts[4].strip() if len(parts) > 4 and parts[4].strip() else version
return {
"name": name,
"version": version,
"installed": True,
"description": parts[5].strip() if len(parts) > 5 else "",
"size": size,
"source": "apt",
"source_package": source_package,
"source_version": source_version,
}
+2 -46
View File
@@ -71,6 +71,7 @@ from napalm_device_types.ssh_host_keys import HostKeyCheck, retry_refused
from netmiko import ConnectHandler from netmiko import ConnectHandler
from netmiko.exceptions import NetmikoAuthenticationException, NetmikoTimeoutException from netmiko.exceptions import NetmikoAuthenticationException, NetmikoTimeoutException
from napalm_linux._dpkg import DPKG_QUERY_COMMAND, parse_dpkg_query
from napalm_linux._hostname import HostnameMixin from napalm_linux._hostname import HostnameMixin
from napalm_linux._local_accounts import LinuxLocalAccountsMixin from napalm_linux._local_accounts import LinuxLocalAccountsMixin
from napalm_linux._shell import expect_for, prepare_shell from napalm_linux._shell import expect_for, prepare_shell
@@ -1237,52 +1238,7 @@ class LinuxDriver(
raise NotImplementedError(f"Package manager '{self._pkg_manager}' is not supported") raise NotImplementedError(f"Package manager '{self._pkg_manager}' is not supported")
def _get_packages_apt(self) -> list[PackageDict]: def _get_packages_apt(self) -> list[PackageDict]:
out = self._send( return parse_dpkg_query(self._send(DPKG_QUERY_COMMAND))
"dpkg-query -W -f='${Package}\\t${Version}\\t${Installed-Size}"
"\\t${source:Package}\\t${source:Version}\\t${binary:Summary}\\n' 2>/dev/null"
)
packages: list[PackageDict] = []
for line in out.splitlines():
# Summary stays last and keeps whatever it contains: maxsplit must
# equal the number of tabs the format writes, not the field count.
parts = line.split("\t", 5)
if len(parts) < 2:
continue
name = parts[0].strip()
version = parts[1].strip()
size = (
int(parts[2].strip()) * 1024 if len(parts) > 2 and parts[2].strip().isdigit() else 0
)
# Debian source package (e.g. openssh-server → openssh) for OSV matching.
source_package = parts[3].strip() if len(parts) > 3 and parts[3].strip() else name
# And its version, which is a different number from this package's.
#
# OSV states Debian ranges in *source* versions. A source package
# that ships several binaries gives each its own upstream version:
# libldb2 is 2:2.11.0+samba4.22.11+dfsg-… while its source, samba,
# is 2:4.22.11+dfsg-…. A consumer matching on source_package and
# comparing `version` compares two unrelated numbers — dpkg reads
# ldb's 2.11.0 as older than the 2:4.17.4+dfsg-1 that fixed
# CVE-2022-44640, and a host five releases past the fix was reported
# vulnerable on four packages at once.
#
# dpkg leaves this empty when it equals `Version`; so does an older
# dpkg that does not know the field at all.
source_version = parts[4].strip() if len(parts) > 4 and parts[4].strip() else version
description = parts[5].strip() if len(parts) > 5 else ""
packages.append(
{
"name": name,
"version": version,
"installed": True,
"description": description,
"size": size,
"source": "apt",
"source_package": source_package,
"source_version": source_version,
}
)
return packages
def _get_packages_rpm(self) -> list[PackageDict]: def _get_packages_rpm(self) -> list[PackageDict]:
out = self._send( out = self._send(
+1 -1
View File
@@ -22,7 +22,7 @@
"napalm_linux.linux" "napalm_linux.linux"
], ],
"python_file_lines": { "python_file_lines": {
"napalm_linux/linux.py": 2257 "napalm_linux/linux.py": 2213
}, },
"untyped_public": [] "untyped_public": []
} }
+28 -4
View File
@@ -259,17 +259,41 @@ def test_parse_uptime_invalid(driver):
#: assertion noticed. A fixture simpler than the data cannot fail the way the #: assertion noticed. A fixture simpler than the data cannot fail the way the
#: data does. #: data does.
APT_PKG_OUTPUT = ( APT_PKG_OUTPUT = (
"openssh-server\t1:9.2p1-2+deb12u2\t512\topenssh\t1:9.2p1-2+deb12u2" "ii \topenssh-server\t1:9.2p1-2+deb12u2\t512\topenssh\t1:9.2p1-2+deb12u2"
"\tsecure shell server\n" "\tsecure shell server\n"
"curl\t7.88.1-10+deb12u5\t1024\tcurl\t7.88.1-10+deb12u5" "ii \tcurl\t7.88.1-10+deb12u5\t1024\tcurl\t7.88.1-10+deb12u5"
"\tcommand line tool for transferring data\n" "\tcommand line tool for transferring data\n"
# The shape that matters: a binary package whose own upstream version has # The shape that matters: a binary package whose own upstream version has
# nothing to do with its source package's. ldb 2.11.0 is built from samba # nothing to do with its source package's. ldb 2.11.0 is built from samba
# 4.22.11, and OSV states Debian ranges in source versions. # 4.22.11, and OSV states Debian ranges in source versions.
"libldb2\t2:2.11.0+samba4.22.11+dfsg-0+deb13u1\t2048\tsamba" "ii \tlibldb2\t2:2.11.0+samba4.22.11+dfsg-0+deb13u1\t2048\tsamba"
"\t2:4.22.11+dfsg-0+deb13u1\tLDB shared library\n" "\t2:4.22.11+dfsg-0+deb13u1\tLDB shared library\n"
) )
#: Removed packages whose configuration dpkg still keeps (state ``rc``), next to
#: a held one and one whose postinst failed -- both still on disk (#17).
APT_PKG_STATES = (
"rc \twazuh-agent\t4.14.7-1\t\twazuh-agent\t4.14.7-1\tWazuh agent\n"
"rc \tlinux-image-6.8.0-117-generic\t6.8.0-117.117\t\tlinux-signed\t6.8.0-117.117\tSigned kernel image generic\n"
"hi \tdocker-ce\t5:28.5.1-1~debian.13~trixie\t104858\tdocker-ce\t5:28.5.1-1~debian.13~trixie\tDocker: the open-source application container engine\n"
"iU \tzabbix-agent\t1:7.0.10-1\t1550\tzabbix\t1:7.0.10-1\tZabbix network monitoring solution - agent\n"
"ii \tcurl\t8.14.1-2\t512\tcurl\t8.14.1-2\tcommand line tool for transferring data with URL syntax\n"
)
def test_get_packages_apt_reads_the_package_state(driver):
driver._pkg_manager = "apt"
with patch.object(driver, "_send", return_value=APT_PKG_STATES) as send:
driver.get_packages()
assert send.call_args[0][0].startswith("dpkg-query -W -f='${db:Status-Abbrev}\\t${Package}")
def test_get_packages_apt_leaves_out_what_only_left_its_configuration(driver):
driver._pkg_manager = "apt"
with patch.object(driver, "_send", return_value=APT_PKG_STATES):
names = [p["name"] for p in driver.get_packages()]
assert names == ["docker-ce", "zabbix-agent", "curl"]
def test_get_packages_apt(driver): def test_get_packages_apt(driver):
driver._pkg_manager = "apt" driver._pkg_manager = "apt"
@@ -309,7 +333,7 @@ def test_get_packages_apt_falls_back_when_dpkg_gives_no_source(driver):
"""`source:Package` is empty for a package whose source name equals its own. """`source:Package` is empty for a package whose source name equals its own.
Older dpkg builds leave `source:Version` empty in that case too.""" Older dpkg builds leave `source:Version` empty in that case too."""
driver._pkg_manager = "apt" driver._pkg_manager = "apt"
with patch.object(driver, "_send", return_value="curl\t7.88.1-10\t1024\t\t\ttool\n"): with patch.object(driver, "_send", return_value="ii \tcurl\t7.88.1-10\t1024\t\t\ttool\n"):
(pkg,) = driver.get_packages() (pkg,) = driver.get_packages()
assert pkg["source_package"] == "curl" assert pkg["source_package"] == "curl"