diff --git a/dbuild/analyze.py b/dbuild/analyze.py index 63d6420..2759f43 100644 --- a/dbuild/analyze.py +++ b/dbuild/analyze.py @@ -2,8 +2,9 @@ Inspects container image layers for size distribution and zombie layers (cleanup instructions in separate layers that fail to reclaim space), -and audits the in-container rootfs for leftover build toolchains, static -libraries, development headers, and package caches. +probes active pkg-slim configuration, and audits the in-container rootfs +for leftover build toolchains, static libraries, development headers, +Python test suites, documentation, and package caches. """ from __future__ import annotations @@ -30,11 +31,16 @@ def human_size(num_bytes: int) -> str: return f"{num:.1f} PB" -# Regex patterns matching build-only tools that shouldn't linger in production -_BUILD_TOOL_PATTERNS = [ +# Compiler/toolchain packages whose runtime shared libs (libLLVM.so, libgfortran.so) +# may be legitimately required at runtime while compiler payloads are stripped by pkg-slim. +_SLIMMABLE_TOOLCHAIN_PATTERNS = [ re.compile(r"^devel/llvm\d*", re.IGNORECASE), - re.compile(r"^devel/gcc\d*", re.IGNORECASE), + re.compile(r"^lang/gcc\d*", re.IGNORECASE), re.compile(r"^devel/binutils", re.IGNORECASE), +] + +# Build-only tools that shouldn't linger in production images (use AS builder). +_STANDALONE_BUILD_TOOL_PATTERNS = [ re.compile(r"^lang/rust", re.IGNORECASE), re.compile(r"^lang/go\d*", re.IGNORECASE), re.compile(r"^devel/cmake", re.IGNORECASE), @@ -48,6 +54,15 @@ def human_size(num_bytes: int) -> str: re.compile(r"^devel/git", re.IGNORECASE), ] +# Combined list kept for compatibility. +_BUILD_TOOL_PATTERNS = _SLIMMABLE_TOOLCHAIN_PATTERNS + _STANDALONE_BUILD_TOOL_PATTERNS + +_TIER_DROPIN_MAP = { + "10-docs.conf": "docs", + "20-dev.conf": "dev", + "30-toolchain.conf": "toolchain", +} + _STANDALONE_CLEANUP_RE = re.compile( r"(?:/bin/sh -c\s+)?(?:rm\s+-[a-zA-Z]*r[a-zA-Z]*f|pkg\s+clean)", re.IGNORECASE, @@ -74,6 +89,16 @@ class BloatItem: recommendation: str = "" +@dataclass +class PkgSlimInfo: + installed: bool = False + enabled: bool = False + tiers: list[str] = field(default_factory=list) + dropins: list[str] = field(default_factory=list) + custom_dropins: list[str] = field(default_factory=list) + pattern_count: int = 0 + + @dataclass class AnalysisReport: image: str @@ -85,6 +110,7 @@ class AnalysisReport: potential_savings_bytes: int = 0 potential_savings_human: str = "0 B" rootfs_audit_available: bool = True + pkg_slim: PkgSlimInfo | None = None error_message: str | None = None def to_dict(self) -> dict[str, Any]: @@ -125,35 +151,128 @@ def detect_zombie_layers(layers: list[LayerInfo]) -> list[dict[str, Any]]: # Check for standalone cleanup commands like `RUN rm -rf /var/cache/pkg` if _STANDALONE_CLEANUP_RE.search(cmd) and "pkg install" not in cmd and "make" not in cmd and "fetch" not in cmd and "curl" not in cmd: zombies.append({ - "layer_index": idx, - "layer_id": layer.id[:12] if len(layer.id) >= 12 else layer.id, - "command": cmd, - "reason": ( - "Separate cleanup layer does not reclaim disk space from parent " - "layers due to OCI copy-on-write semantics. Combine file deletion " - "into the same RUN instruction using '&&'." - ), - }) + "layer_index": idx, + "layer_id": layer.id[:12] if len(layer.id) >= 12 else layer.id, + "command": cmd, + "reason": ( + "Separate cleanup layer does not reclaim disk space from parent " + "layers due to OCI copy-on-write semantics. Combine file deletion " + "into the same RUN instruction using '&&'." + ), + }) return zombies -# In-container probe script using only standard FreeBSD base utilities (/bin/sh, du, find, pkg) +# In-container probe script using only standard FreeBSD base utilities (/bin/sh, du, find, pkg). +# Uses FreeBSD's apparent-size flag (-A) when available so ZFS compression does not underreport +# sizes relative to OCI layer bytes. _PROBE_SCRIPT = ( + "DU='du -skA'; du -skA / >/dev/null 2>&1 || DU='du -sk'; " + "echo '===PKG_SLIM===' && " + "(command -v pkg-slim >/dev/null 2>&1 && echo 'installed=1' || echo 'installed=0'); " + "for f in /usr/local/etc/pkg/daemonless-slim.d/*.conf; do " + " [ -e \"$f\" ] && echo \"dropin=$(basename \"$f\")\"; " + "done; " + "printf 'patterns=%s\\n' \"$(pkg config FILES_IGNORE_GLOB 2>/dev/null | awk 'NF { c++ } END { print c + 0 }')\"; " "echo '===PKGS===' && " - "pkg query '%o\t%n\t%v\t%sb\t%a' 2>/dev/null || true; " + "pkg query '%o\\t%n\\t%v\\t%sb\\t%a' 2>/dev/null || true; " + "echo '===TOOLCHAIN_PATHS===' && " + "$DU /usr/local/llvm*/bin /usr/local/llvm*/include /usr/local/llvm*/lib/clang " + "/usr/local/llvm*/lib/cmake /usr/local/llvm*/share " + "/usr/local/llvm*/lib/libclang*.so* /usr/local/llvm*/lib/libMLIR*.so* /usr/local/llvm*/lib/liblldb*.so* " + "/usr/local/libexec/gcc* /usr/local/lib/gcc*/gcc /usr/local/lib/gcc*/include " + "/usr/local/lib32/gcc* /usr/local/share/gcc-* /usr/local/*-portbld-freebsd* " + "/usr/local/bin/gcc* /usr/local/bin/g++* /usr/local/bin/gfortran* " + "/usr/local/bin/ld /usr/local/bin/ld.bfd /usr/local/bin/ld.gold " + "/usr/local/bin/as /usr/local/bin/ar /usr/local/bin/nm " + "/usr/local/bin/objdump /usr/local/bin/objcopy /usr/local/bin/readelf /usr/local/bin/strip " + "2>/dev/null || true; " "echo '===STATIC_LIBS===' && " - "find /usr/local /usr/lib -name '*.a' -exec du -k {} + 2>/dev/null || true; " + "find /usr/local /usr/lib -name '*.a' -exec $DU {} + 2>/dev/null || true; " "echo '===DIRECTORIES===' && " - "du -sk /usr/local/include /usr/local/share/doc /usr/local/share/man " + "$DU /usr/local/include /usr/local/libdata/pkgconfig " + "/usr/local/share/doc /usr/local/share/man /usr/local/man /usr/local/lib/perl5/*/man " + "/usr/local/share/examples /usr/local/share/info " + "/usr/local/lib/python*/test /usr/local/lib/python*/idlelib /usr/local/lib/python*/turtledemo " "/var/cache/pkg /var/db/pkg/repos /tmp /var/tmp 2>/dev/null || true; " "echo '===REPO_SQLITE===' && " - "du -sk /var/db/pkg/repo-*.sqlite 2>/dev/null || true; " + "$DU /var/db/pkg/repo-*.sqlite 2>/dev/null || true; " "echo '===END==='" ) -def parse_probe_output(output: str, threshold_bytes: int = 1024 * 1024) -> list[BloatItem]: - """Parse raw probe output into categorized BloatItems.""" +def _parse_pkg_slim_section(lines: list[str]) -> PkgSlimInfo: + """Parse ===PKG_SLIM=== probe output into PkgSlimInfo.""" + installed = False + dropins: list[str] = [] + tiers: list[str] = [] + custom_dropins: list[str] = [] + pattern_count = 0 + + for line in lines: + if line.startswith("installed="): + installed = line.split("=", 1)[1].strip() == "1" + elif line.startswith("dropin="): + name = line.split("=", 1)[1].strip() + if not name: + continue + dropins.append(name) + tier = _TIER_DROPIN_MAP.get(name) + if tier: + if tier not in tiers: + tiers.append(tier) + elif name not in custom_dropins: + custom_dropins.append(name) + elif line.startswith("patterns="): + try: + pattern_count = int(line.split("=", 1)[1].strip()) + except ValueError: + pattern_count = 0 + + return PkgSlimInfo( + installed=installed, + enabled=bool(dropins) and pattern_count > 0, + tiers=tiers, + dropins=dropins, + custom_dropins=custom_dropins, + pattern_count=pattern_count, + ) + + +def _parse_du_lines(lines: list[str]) -> list[tuple[str, int]]: + """Parse ``du -sk`` / ``du -skA`` tab-separated lines into ``(path, bytes)``.""" + entries: list[tuple[str, int]] = [] + for line in lines: + parts = line.split("\t", 1) + if len(parts) == 2: + try: + entries.append((parts[1], int(parts[0]) * 1024)) + except ValueError: + continue + return entries + + +def _slim_recommendation( + pkg_slim: PkgSlimInfo | None, + tier: str, + *, + note: str = "", +) -> str: + """Build a pkg-slim recommendation aware of whether the tier is already active.""" + if pkg_slim and pkg_slim.enabled and tier in pkg_slim.tiers: + return ( + f"pkg-slim '{tier}' tier is already enabled, so these files came from an earlier " + f"layer or manual install; run 'pkg upgrade -f' or enable pkg-slim before 'pkg install'." + ) + suffix = f", {note}" if note else "" + return f"Run 'pkg-slim enable' ({tier} tier{suffix}) before 'pkg install' in your Containerfile." + + +def parse_probe_report( + output: str, + threshold_bytes: int = 1024 * 1024, +) -> tuple[list[BloatItem], PkgSlimInfo | None]: + """Parse raw probe output into categorized BloatItems and optional PkgSlimInfo.""" bloat: list[BloatItem] = [] sections: dict[str, list[str]] = {} @@ -163,63 +282,123 @@ def parse_probe_output(output: str, threshold_bytes: int = 1024 * 1024) -> list[ if line.startswith("===") and line.endswith("==="): current_sec = line.strip("=") sections[current_sec] = [] - elif current_sec != "NONE": + elif current_sec != "NONE" and line: sections[current_sec].append(line) - # 1. Build Toolchain & Compilers + pkg_slim: PkgSlimInfo | None = None + if "PKG_SLIM" in sections: + pkg_slim = _parse_pkg_slim_section(sections["PKG_SLIM"]) + + # 1. Build Toolchains & Compilers pkg_lines = sections.get("PKGS", []) - build_pkgs: list[tuple[str, str, int]] = [] - build_bytes = 0 + standalone_pkgs: list[tuple[str, str, int]] = [] + slimmable_pkgs: list[tuple[str, str, int]] = [] for pl in pkg_lines: parts = pl.split("\t") - if len(parts) >= 4: - origin, name, _ver, size_str = parts[0], parts[1], parts[2], parts[3] - try: - pkg_size = int(size_str) - except ValueError: - continue - - for pat in _BUILD_TOOL_PATTERNS: - if pat.search(origin) or pat.search(name): - build_pkgs.append((origin, name, pkg_size)) - build_bytes += pkg_size - break - - if build_pkgs and build_bytes >= threshold_bytes: - details = [ - f"{orig} ({name}): {human_size(sz)}" - for orig, name, sz in sorted(build_pkgs, key=lambda x: x[2], reverse=True)[:10] + if len(parts) < 4: + continue + origin, name, _ver, size_str = parts[0], parts[1], parts[2], parts[3] + try: + pkg_size = int(size_str) + except ValueError: + continue + + if any(p.search(origin) or p.search(name) for p in _SLIMMABLE_TOOLCHAIN_PATTERNS): + slimmable_pkgs.append((origin, name, pkg_size)) + elif any(p.search(origin) or p.search(name) for p in _STANDALONE_BUILD_TOOL_PATTERNS): + standalone_pkgs.append((origin, name, pkg_size)) + + has_toolchain_probe = "TOOLCHAIN_PATHS" in sections + if has_toolchain_probe: + # Measure actual on-disk strippable compiler payloads so slimmed images + # preserving libLLVM.so / libgfortran.so do not trigger false positives. + # Exclude *.a here since static archives are accounted for in STATIC_LIBS. + tc_entries = [ + (p, sz) for p, sz in _parse_du_lines(sections["TOOLCHAIN_PATHS"]) if not p.endswith(".a") ] - bloat.append( - BloatItem( - category="toolchain", - title=f"Build Toolchains & Compilers ({len(build_pkgs)} packages)", - size_bytes=build_bytes, - size_human=human_size(build_bytes), - details=details, - recommendation=( - "Use a multi-stage build (e.g. 'AS builder') to compile artifacts, " - "or purge build tools in the same layer before finalizing: " - f"'pkg delete -y {' '.join(p[1] for p in build_pkgs[:5])}'" - ), + tc_disk_bytes = sum(sz for _, sz in tc_entries) + standalone_bytes = sum(sz for _, _, sz in standalone_pkgs) + total_tc_bytes = tc_disk_bytes + standalone_bytes + + if total_tc_bytes >= threshold_bytes: + details: list[str] = [] + for path, sz in sorted(tc_entries, key=lambda x: x[1], reverse=True)[:8]: + if sz > 0: + details.append(f"{path}: {human_size(sz)}") + if len(tc_entries) > 8: + details.append(f"... and {len(tc_entries) - 8} more toolchain paths") + for orig, name, sz in sorted(standalone_pkgs, key=lambda x: x[2], reverse=True)[:6]: + details.append(f"{orig} ({name}): {human_size(sz)}") + + if tc_disk_bytes > 0 and standalone_pkgs: + rec = ( + _slim_recommendation(pkg_slim, "toolchain") + + " Move standalone build tools (" + + ", ".join(p[1] for p in standalone_pkgs[:4]) + + ") to a multi-stage 'AS builder'." + ) + title = "Build Toolchains & Compilers" + elif tc_disk_bytes > 0: + if pkg_slim and pkg_slim.enabled and "toolchain" in pkg_slim.tiers: + rec = _slim_recommendation(pkg_slim, "toolchain") + else: + rec = ( + "Run 'pkg-slim enable' (toolchain tier) before 'pkg install' to strip " + "compiler binaries while keeping runtime libs (libLLVM.so, libgfortran.so), " + "or use a multi-stage 'AS builder'." + ) + title = f"Compiler Toolchain Payloads ({len(tc_entries)} paths)" + else: + rec = ( + "Use a multi-stage build (e.g. 'AS builder') so build-only tools (" + f"{', '.join(p[1] for p in standalone_pkgs[:5])}) do not ship in the runtime image." + ) + title = f"Build-Only Tools ({len(standalone_pkgs)} packages)" + + bloat.append( + BloatItem( + category="toolchain", + title=title, + size_bytes=total_tc_bytes, + size_human=human_size(total_tc_bytes), + details=details, + recommendation=rec, + ) + ) + else: + # Fallback for legacy probe strings without ===TOOLCHAIN_PATHS===. + build_pkgs = slimmable_pkgs + standalone_pkgs + build_bytes = sum(sz for _, _, sz in build_pkgs) + if build_pkgs and build_bytes >= threshold_bytes: + details = [ + f"{orig} ({name}): {human_size(sz)}" + for orig, name, sz in sorted(build_pkgs, key=lambda x: x[2], reverse=True)[:10] + ] + if slimmable_pkgs: + rec = ( + "Run 'pkg-slim enable' before 'pkg install' to strip compiler payloads " + "while keeping runtime libs, or use a multi-stage 'AS builder'." + ) + else: + rec = ( + "Use a multi-stage build (e.g. 'AS builder') so build-only tools (" + f"{', '.join(p[1] for p in build_pkgs[:5])}) do not ship in the runtime image." + ) + bloat.append( + BloatItem( + category="toolchain", + title=f"Build Toolchains & Compilers ({len(build_pkgs)} packages)", + size_bytes=build_bytes, + size_human=human_size(build_bytes), + details=details, + recommendation=rec, + ) ) - ) # 2. Static Libraries (*.a) - static_lines = sections.get("STATIC_LIBS", []) - static_files: list[tuple[str, int]] = [] - static_bytes = 0 - - for sl in static_lines: - parts = sl.split("\t", 1) - if len(parts) == 2: - try: - kb = int(parts[0]) - static_bytes += kb * 1024 - static_files.append((parts[1], kb * 1024)) - except ValueError: - continue + static_files = _parse_du_lines(sections.get("STATIC_LIBS", [])) + static_bytes = sum(sz for _, sz in static_files) if static_files and static_bytes >= threshold_bytes: details = [ @@ -235,64 +414,87 @@ def parse_probe_output(output: str, threshold_bytes: int = 1024 * 1024) -> list[ size_bytes=static_bytes, size_human=human_size(static_bytes), details=details, - recommendation="Add 'find /usr/local -name \"*.a\" -delete' to your installation RUN layer.", + recommendation=_slim_recommendation(pkg_slim, "dev"), ) ) - # 3. Directories (Headers, Doc, Man, Cache) - dir_lines = sections.get("DIRECTORIES", []) - dir_sizes: dict[str, int] = {} - for dl in dir_lines: - parts = dl.split("\t", 1) - if len(parts) == 2: - try: - dir_sizes[parts[1]] = int(parts[0]) * 1024 - except ValueError: - continue - - # Development Headers - inc_bytes = dir_sizes.get("/usr/local/include", 0) + # 3. Directories (Headers, Docs, Python tests, Cache) + dir_entries = _parse_du_lines(sections.get("DIRECTORIES", [])) + dir_sizes = dict(dir_entries) + + # Development Headers & pkg-config metadata + header_paths = [ + (p, sz) + for p, sz in dir_entries + if p in ("/usr/local/include", "/usr/local/libdata/pkgconfig") and sz > 0 + ] + inc_bytes = sum(sz for _, sz in header_paths) if inc_bytes >= threshold_bytes: bloat.append( BloatItem( category="headers", - title="Development Headers (/usr/local/include)", + title="Development Headers & pkg-config", size_bytes=inc_bytes, size_human=human_size(inc_bytes), - details=[f"/usr/local/include: {human_size(inc_bytes)}"], - recommendation="Remove C/C++ header files with 'rm -rf /usr/local/include' in the install layer.", + details=[f"{p}: {human_size(sz)}" for p, sz in sorted(header_paths, key=lambda x: x[1], reverse=True)], + recommendation=_slim_recommendation(pkg_slim, "dev"), + ) + ) + + # Python stdlib test suite & GUI demos + py_dev_paths = [ + (p, sz) + for p, sz in dir_entries + if sz > 0 and ( + p.startswith("/usr/local/lib/python") + and (p.endswith("/test") or p.endswith("/idlelib") or p.endswith("/turtledemo")) + ) + ] + py_dev_bytes = sum(sz for _, sz in py_dev_paths) + if py_dev_bytes >= threshold_bytes: + bloat.append( + BloatItem( + category="python_dev", + title="Python Test Suite & GUI Demos", + size_bytes=py_dev_bytes, + size_human=human_size(py_dev_bytes), + details=[f"{p}: {human_size(sz)}" for p, sz in sorted(py_dev_paths, key=lambda x: x[1], reverse=True)], + recommendation=_slim_recommendation(pkg_slim, "dev", note="pkg-slim >= 0.1.2"), ) ) - # Documentation & Man Pages - doc_bytes = dir_sizes.get("/usr/local/share/doc", 0) + dir_sizes.get("/usr/local/share/man", 0) + # Documentation, Man Pages, Examples & Info + doc_paths = [ + (p, sz) + for p, sz in dir_entries + if sz > 0 and ( + p in ( + "/usr/local/share/doc", + "/usr/local/share/man", + "/usr/local/man", + "/usr/local/share/examples", + "/usr/local/share/info", + ) + or (p.startswith("/usr/local/lib/perl5/") and p.endswith("/man")) + ) + ] + doc_bytes = sum(sz for _, sz in doc_paths) if doc_bytes >= threshold_bytes: - details = [] - if dir_sizes.get("/usr/local/share/doc"): - details.append(f"/usr/local/share/doc: {human_size(dir_sizes['usr/local/share/doc'] if 'usr/local/share/doc' in dir_sizes else dir_sizes.get('/usr/local/share/doc', 0))}") - if dir_sizes.get("/usr/local/share/man"): - details.append(f"/usr/local/share/man: {human_size(dir_sizes.get('/usr/local/share/man', 0))}") bloat.append( BloatItem( category="docs", title="Manual & Documentation Pages", size_bytes=doc_bytes, size_human=human_size(doc_bytes), - details=details, - recommendation="Remove documentation with 'rm -rf /usr/local/share/doc /usr/local/share/man'.", + details=[f"{p}: {human_size(sz)}" for p, sz in sorted(doc_paths, key=lambda x: x[1], reverse=True)], + recommendation=_slim_recommendation(pkg_slim, "docs"), ) ) # Package Caches & Repo Catalogs cache_bytes = dir_sizes.get("/var/cache/pkg", 0) + dir_sizes.get("/var/db/pkg/repos", 0) - # Repo sqlite files - for rline in sections.get("REPO_SQLITE", []): - rparts = rline.split("\t", 1) - if len(rparts) == 2: - try: - cache_bytes += int(rparts[0]) * 1024 - except ValueError: - continue + for _, sz in _parse_du_lines(sections.get("REPO_SQLITE", [])): + cache_bytes += sz # Flag cache if > 64 KB if cache_bytes > 64 * 1024: @@ -307,7 +509,13 @@ def parse_probe_output(output: str, threshold_bytes: int = 1024 * 1024) -> list[ ) ) - return bloat + return bloat, pkg_slim + + +def parse_probe_output(output: str, threshold_bytes: int = 1024 * 1024) -> list[BloatItem]: + """Parse raw probe output into categorized BloatItems.""" + items, _ = parse_probe_report(output, threshold_bytes=threshold_bytes) + return items def analyze_image( @@ -347,12 +555,13 @@ def analyze_image( # 2. In-Container Rootfs Probe bloat_items: list[BloatItem] = [] + pkg_slim: PkgSlimInfo | None = None audit_available = True if not skip_container_audit: try: probe_out = podman.run_in(image, _PROBE_SCRIPT, quiet=quiet) - bloat_items = parse_probe_output(probe_out, threshold_bytes=threshold_bytes) + bloat_items, pkg_slim = parse_probe_report(probe_out, threshold_bytes=threshold_bytes) except Exception as e: if not quiet: log.warn(f"Could not execute in-container audit on {image}: {e}") @@ -370,9 +579,27 @@ def analyze_image( potential_savings_bytes=potential_savings, potential_savings_human=human_size(potential_savings), rootfs_audit_available=audit_available, + pkg_slim=pkg_slim, ) +def _format_pkg_slim_status(info: PkgSlimInfo) -> str: + """Format PkgSlimInfo as a short human-readable summary line.""" + if info.enabled: + parts: list[str] = [] + if info.tiers: + parts.append(f"tiers: {', '.join(info.tiers)}") + if info.custom_dropins: + parts.append(f"custom: {', '.join(info.custom_dropins)}") + parts.append(f"{info.pattern_count} patterns") + return f"enabled ({'; '.join(parts)})" + if info.dropins and info.pattern_count == 0: + return f"misconfigured ({', '.join(info.dropins)} present, 0 active patterns; check pkg.conf)" + if info.installed: + return "disabled (installed, 0 active patterns)" + return "not installed" + + def print_report(report: AnalysisReport, threshold_mb: float = 5.0) -> None: """Print an analysis report to terminal.""" if report.error_message: @@ -383,6 +610,8 @@ def print_report(report: AnalysisReport, threshold_mb: float = 5.0) -> None: log.step(f"Image Analysis: {report.image}") log.info(f"Total Image Size: {report.total_size_human} ({report.total_size_bytes:,} bytes)") log.info(f"Total Layers: {len(report.layers)}") + if report.pkg_slim is not None: + log.info(f"pkg-slim: {_format_pkg_slim_status(report.pkg_slim)}") # Zombie layers if report.zombie_layers: diff --git a/tests/test_analyze.py b/tests/test_analyze.py index 356aecb..d28aa12 100644 --- a/tests/test_analyze.py +++ b/tests/test_analyze.py @@ -11,11 +11,13 @@ AnalysisReport, BloatItem, LayerInfo, + PkgSlimInfo, analyze_image, detect_zombie_layers, human_size, parse_history_json, parse_probe_output, + parse_probe_report, print_report, run_analyze, ) @@ -117,6 +119,7 @@ def test_parses_toolchains_static_libs_and_headers(self): probe_data = ( "===PKGS===\n" "devel/llvm19\tllvm19\t19.1.7\t750000000\t0\n" + "lang/gcc14\tgcc14\t14.2.0\t220000000\t1\n" "devel/git\tgit\t2.48.1\t45000000\t1\n" "sysutils/s6\ts6\t2.14.0.1\t2000000\t0\n" "===STATIC_LIBS===\n" @@ -140,15 +143,105 @@ def test_parses_toolchains_static_libs_and_headers(self): self.assertIn("docs", categories) self.assertIn("cache", categories) - # Check toolchain item details + # Check toolchain item details (includes llvm19, lang/gcc14, and git) toolchain_item = next(i for i in items if i.category == "toolchain") - self.assertEqual(len(toolchain_item.details), 2) # llvm19 and git - self.assertIn("llvm19", toolchain_item.recommendation) + self.assertEqual(len(toolchain_item.details), 3) + self.assertTrue(any("lang/gcc14" in d for d in toolchain_item.details)) + self.assertIn("pkg-slim enable", toolchain_item.recommendation) # Check static libraries item static_item = next(i for i in items if i.category == "static_libs") self.assertIn("libcrypto.a", static_item.details[0]) - self.assertIn("*.a", static_item.recommendation) + self.assertIn("pkg-slim enable", static_item.recommendation) + + def test_slimmed_image_with_runtime_libs_reports_clean(self): + """Slimmed image keeping libLLVM.so / libgfortran.so must not false-positive.""" + probe_data = ( + "===PKG_SLIM===\n" + "installed=1\n" + "dropin=10-docs.conf\n" + "dropin=20-dev.conf\n" + "dropin=30-toolchain.conf\n" + "dropin=90-local.conf\n" + "patterns=53\n" + "===PKGS===\n" + "devel/llvm19\tllvm19\t19.1.7\t1600000000\t1\n" + "lang/gcc14\tgcc14\t14.2.0\t450000000\t1\n" + "databases/postgresql18-server\tpostgresql18-server\t18.3\t45000000\t0\n" + "===TOOLCHAIN_PATHS===\n" + "===STATIC_LIBS===\n" + "===DIRECTORIES===\n" + "===REPO_SQLITE===\n" + "===END===\n" + ) + items, pkg_slim = parse_probe_report(probe_data, threshold_bytes=1024 * 1024) + self.assertEqual(items, []) + self.assertIsNotNone(pkg_slim) + assert pkg_slim is not None + self.assertTrue(pkg_slim.installed) + self.assertTrue(pkg_slim.enabled) + self.assertEqual(pkg_slim.tiers, ["docs", "dev", "toolchain"]) + self.assertEqual(pkg_slim.custom_dropins, ["90-local.conf"]) + self.assertEqual(pkg_slim.pattern_count, 53) + + def test_unslimmed_image_flags_on_disk_toolchain_and_python_test(self): + """Unslimmed image flags actual on-disk compiler payloads and python test suite.""" + probe_data = ( + "===PKG_SLIM===\n" + "installed=0\n" + "patterns=0\n" + "===PKGS===\n" + "devel/llvm19\tllvm19\t19.1.7\t1600000000\t1\n" + "===TOOLCHAIN_PATHS===\n" + "412000\t/usr/local/llvm19/bin\n" + "108000\t/usr/local/llvm19/include\n" + "90000\t/usr/local/llvm19/lib/libclang-cpp.so.19.1\n" + "===STATIC_LIBS===\n" + "45000\t/usr/local/llvm19/lib/libLLVMCore.a\n" + "===DIRECTORIES===\n" + "123000\t/usr/local/lib/python3.12/test\n" + "6700\t/usr/local/lib/python3.12/idlelib\n" + "12000\t/usr/local/include\n" + "2000\t/usr/local/libdata/pkgconfig\n" + "80000\t/usr/local/share/doc\n" + "3000\t/usr/local/share/examples\n" + "===REPO_SQLITE===\n" + "===END===\n" + ) + items, pkg_slim = parse_probe_report(probe_data, threshold_bytes=1024 * 1024) + by_cat = {i.category: i for i in items} + self.assertFalse(pkg_slim.installed if pkg_slim else True) + self.assertIn("toolchain", by_cat) + self.assertIn("static_libs", by_cat) + self.assertIn("headers", by_cat) + self.assertIn("python_dev", by_cat) + self.assertIn("docs", by_cat) + self.assertIn("pkg-slim enable", by_cat["toolchain"].recommendation) + self.assertIn("pkg-slim enable", by_cat["python_dev"].recommendation) + self.assertEqual(by_cat["toolchain"].size_bytes, (412000 + 108000 + 90000) * 1024) + + def test_already_enabled_pkg_slim_with_leftovers_recommends_upgrade_f(self): + """Leftover strippable files with pkg-slim active recommend pkg upgrade -f.""" + probe_data = ( + "===PKG_SLIM===\n" + "installed=1\n" + "dropin=10-docs.conf\n" + "dropin=20-dev.conf\n" + "dropin=30-toolchain.conf\n" + "patterns=53\n" + "===PKGS===\n" + "===TOOLCHAIN_PATHS===\n" + "50000\t/usr/local/llvm19/bin\n" + "===STATIC_LIBS===\n" + "5000\t/usr/local/lib/libfoo.a\n" + "===DIRECTORIES===\n" + "5000\t/usr/local/include\n" + "===REPO_SQLITE===\n" + "===END===\n" + ) + items, _ = parse_probe_report(probe_data, threshold_bytes=1024 * 1024) + for item in items: + self.assertIn("pkg upgrade -f", item.recommendation) class TestAnalyzeImage(unittest.TestCase): @@ -162,8 +255,14 @@ def test_analyze_image_success(self, mock_run_in, mock_history): {"id": "layer2", "size": 0, "CreatedBy": "RUN rm -rf /var/cache/pkg"}, ] mock_run_in.return_value = ( + "===PKG_SLIM===\n" + "installed=1\n" + "dropin=10-docs.conf\n" + "patterns=6\n" "===PKGS===\n" "devel/llvm19\tllvm19\t19.1.7\t20000000\t0\n" + "===TOOLCHAIN_PATHS===\n" + "20000\t/usr/local/llvm19/bin\n" "===STATIC_LIBS===\n" "===DIRECTORIES===\n" "===REPO_SQLITE===\n" @@ -178,6 +277,9 @@ def test_analyze_image_success(self, mock_run_in, mock_history): self.assertEqual(len(report.bloat_items), 1) self.assertTrue(report.rootfs_audit_available) self.assertEqual(report.bloat_items[0].category, "toolchain") + self.assertIsNotNone(report.pkg_slim) + assert report.pkg_slim is not None + self.assertEqual(report.pkg_slim.tiers, ["docs"]) @patch("dbuild.analyze.podman.history") @patch("dbuild.analyze.podman.run_in") @@ -191,6 +293,7 @@ def test_analyze_image_probe_failure_fallback(self, mock_run_in, mock_history): self.assertEqual(report.total_size_bytes, 50000000) self.assertFalse(report.rootfs_audit_available) self.assertEqual(len(report.bloat_items), 0) + self.assertIsNone(report.pkg_slim) @patch("dbuild.analyze.podman.history") def test_analyze_image_history_failure(self, mock_history): @@ -213,12 +316,19 @@ def test_print_report_does_not_crash(self): LayerInfo("l2", 0, "0 B", "RUN rm -rf /var/cache/pkg"), ], bloat_items=[ - BloatItem("toolchain", "Compilers", 150000000, "150.0 MB", ["llvm19: 150 MB"], "delete it"), + BloatItem("toolchain", "Compilers", 150000000, "150.0 MB", ["llvm19: 150 MB"], "pkg-slim enable"), ], zombie_layers=[{"layer_id": "l2", "command": "RUN rm", "reason": "COW"}], potential_savings_bytes=150000000, potential_savings_human="150.0 MB", rootfs_audit_available=True, + pkg_slim=PkgSlimInfo( + installed=True, + enabled=True, + tiers=["docs", "dev", "toolchain"], + dropins=["10-docs.conf", "20-dev.conf", "30-toolchain.conf"], + pattern_count=53, + ), ) # Should execute cleanly without error print_report(report) @@ -233,6 +343,13 @@ def test_run_analyze_json_output(self, mock_analyze): image="app:latest", total_size_bytes=100, total_size_human="100 B", + pkg_slim=PkgSlimInfo( + installed=True, + enabled=True, + tiers=["docs"], + dropins=["10-docs.conf"], + pattern_count=6, + ), ) cfg = Config(image="app", registry="localhost", variants=[Variant(tag="latest")]) args = argparse.Namespace( @@ -250,6 +367,8 @@ def test_run_analyze_json_output(self, mock_analyze): output_str = mock_print.call_args[0][0] data = json.loads(output_str) self.assertEqual(data["image"], "app:latest") + self.assertEqual(data["pkg_slim"]["tiers"], ["docs"]) + self.assertEqual(data["pkg_slim"]["pattern_count"], 6) @patch("dbuild.analyze.podman.image_exists", return_value=False) def test_run_analyze_missing_image_error(self, _mock_exists):