367. Cleaning up the root
This page explains what is removed from the root before it becomes the image, and why each removal is needed. Read it if you are wondering why a file you saw in build/fs is missing from the ISO, or if the image phase stopped with a complaint about Python bytecode.
By the time the image phase starts, build/fs has been the working root of every package build, and it holds what those builds left behind: scratch files, caches, built package archives, Python bytecode written by build tools, a container store, and whatever a tool wrote into root’s home. script/phases/70_image/020_cleanup.sh does three things:
- it removes all of that, so that the root carries only what a package or
fs/put there; - it removes the translations and HTML manuals that no package owns;
- it fails the image when a packaged Python module has no compiled bytecode.
This page goes through the script in order.
The switches
# ── Phase gates ─────────────────────────────────────────────────────────
CLEAN_BUILD_CACHE=1 # /tmp, /var/tmp (holds the build's HOME), /root's caches, kpkg work dir
CLEAN_KPKG_PACKAGES=1 # /var/cache/kpkg/packages (built .tar.xz cache, .pending records)
CHECK_PYCACHE=1 # unowned __pycache__ / *.pyc / *.pyo removed; owned .py checked
CLEAN_UNOWNED_DOCS=1 # unowned catalogs, translated manuals, HTML, and the bootstrap's extras
script/phases/70_image/020_cleanup.sh, lines 30–34
Each of the four passes below is guarded by one of these variables, set in the script itself:
| Variable | Pass |
|---|---|
CLEAN_BUILD_CACHE |
The build cache |
CLEAN_KPKG_PACKAGES |
The package cache |
CHECK_PYCACHE |
Python bytecode |
CLEAN_UNOWNED_DOCS |
Unowned documentation and catalogues |
No make variable reaches them; turning a pass off means editing its line to 0. The removal of podman’s stores and the reset of /root have no switch.
Every pass works on the chroot’s own root, /:
- Under
KDOS_IMAGE=base,/is the image stage. The removals land in its upper layer, sobuild/fskeeps its caches and its home for the next build, and the bytecode and documentation passes read the stage’s package database, which lists only the base’s packages. - Under
KDOS_IMAGE=full,/isbuild/fsitself.
The step never works on /kdos/build/fs: in the stage that path is the overlay’s lower layer.
In its log, the step reports the size of the root’s own directories (/usr, /etc, /var, /opt, /srv, /root, /tmp) before and after, and the bytes each pass freed. /kdos, the repository bound into the chroot, is not counted.
The build cache
if [ "$CLEAN_BUILD_CACHE" = 1 ]; then
section "Build cache"
# var/tmp/* belongs here: it is scratch by definition, and the appbox
# bake leaves podman<pid>/ directories there, multi-gigabyte, which would
# otherwise ride into the ISO.
for p in root/.cache root/.cargo root/.npm tmp/* var/tmp/* var/cache/kpkg/work; do
target="$FS/$p"
if compgen -G "$target" >/dev/null 2>&1; then
before=$(size_of "$target")
rm -rf $target # unquoted to honour glob
report "$p" "${before:-0}" 0
fi
done
fi
script/phases/70_image/020_cleanup.sh, lines 55–68
The pass removes:
root/.cache,root/.cargoandroot/.npm, the caches tools write into root’s home;- the contents of
/tmpand/var/tmp, which are scratch./var/tmpalso holds theHOMEof every chroot command (HOME=/var/tmp/kdos-home, set byscript/chroot/exec.sh), and the multi-gigabytepodman<pid>directories an appbox bake leaves; /var/cache/kpkg/work, kpkg’s work directory, where each port is unpacked and staged. A build that failed leaves its directory there.
Without this pass, all of it would go into system.sfs, the image’s root filesystem.
$target is deliberately unquoted in the rm, so that tmp/* and var/tmp/* expand to the directories’ contents and the directories themselves stay.
The package cache
if [ "$CLEAN_KPKG_PACKAGES" = 1 ]; then
section "kpkg package cache"
target="$FS/var/cache/kpkg/packages"
if [ -d "$target" ]; then
before=$(size_of "$target")
find "$target" -maxdepth 1 \( -name "*.tar.*" -o -name "*.pending*" \) -delete
after=$(size_of "$target")
report "var/cache/kpkg/packages/{*.tar.*,*.pending*}" "$before" "$after"
fi
fi
script/phases/70_image/020_cleanup.sh, lines 75–84
/var/cache/kpkg/packages holds the package archives kpkg keeps: every package of the build when KDOS_MAKE_BINHOST=1 (which is why 010_binhost.sh runs first), and the packages a build with --port-jobs above 1 has built and not yet installed (see Building in levels). A .pending record names a package in this directory that is waiting to be committed, so the two are removed together. A record left without its package would read as a build to commit that cannot be found.
Python bytecode
kpkg compiles every Python module a package ships into checked-hash bytecode inside the package, so each .pyc is owned by the package database and an upgrade or removal replaces it. /usr is read-only on the live medium, so a module with no .pyc would be compiled again on every import. The pass is one embedded Python program, run only when python3 is installed. Its first half reads every package’s file list and removes the bytecode no package owns, anywhere under /usr, /opt, /etc, /var and /srv:
if [ "$CHECK_PYCACHE" = 1 ]; then
section "Python bytecode"
if command -v python3 >/dev/null 2>&1; then
python3 -I - "$FS" <<'PY'
import importlib.util, os, sys
fs = sys.argv[1]
dbdir = os.path.join(fs, "var/lib/kpkg/db")
def canon(p):
p = p[2:] if p.startswith("./") else p.lstrip("/")
p = p.rstrip("/")
for a in ("bin", "sbin", "lib"):
if p == a or p.startswith(a + "/"):
return "usr/" + p
return p
owned = set()
for n in os.listdir(dbdir):
f = os.path.join(dbdir, n)
if n.startswith(".") or not os.path.isfile(f):
continue
with open(f, encoding="utf-8", errors="surrogateescape") as h:
for line in h:
if line.startswith("./"):
owned.add(canon(line.rstrip("\n")))
removed = size = 0
caches = []
for top in ("usr", "opt", "etc", "var", "srv"):
for d, dirs, files in os.walk(os.path.join(fs, top)):
rd = os.path.relpath(d, fs)
if os.path.basename(d) == "__pycache__":
caches.append((d, rd))
for f in files:
if not f.endswith((".pyc", ".pyo")):
continue
rel = os.path.join(rd, f)
if rel in owned:
continue
p = os.path.join(d, f)
size += os.lstat(p).st_size
os.unlink(p)
removed += 1
for d, rd in reversed(caches):
if rd not in owned and not os.listdir(d):
os.rmdir(d)
print(f" removed {removed} unowned bytecode file(s), {size // 1024} KiB")
script/phases/70_image/020_cleanup.sh, lines 112–159
canon folds the merged-/usr aliases, because a package may list ./lib/x for the file that is on disk at usr/lib/x. The bytecode no package owns is what build tools wrote while importing modules in the chroot, with the build’s time in it; no package would ever remove it. A __pycache__ directory left empty by the removal goes too.
The second half is the check:
missing, foreign = [], []
for rel in sorted(owned):
if not rel.endswith(".py") or rel.endswith(".tmpl.py"):
continue
if rel.startswith("usr/share/gdb/auto-load/") or (
rel.startswith("usr/share/gcc-") and "/python/" in rel):
continue
if not (rel.startswith("usr/") or rel.startswith("opt/")):
continue
if rel.startswith(("usr/bin/", "usr/sbin/")):
continue
p = os.path.join(fs, rel)
if os.path.islink(p) or not os.path.isfile(p):
continue
if os.path.exists(importlib.util.cache_from_source(p)):
continue
try:
with open(p, "rb") as h:
compile(h.read(), p, "exec", dont_inherit=True)
except (SyntaxError, ValueError):
foreign.append(rel)
continue
missing.append(rel)
for rel in foreign:
print(f" not Python 3 source, no bytecode: /{rel}")
if missing:
for rel in missing:
print(f" no bytecode: /{rel}", file=sys.stderr)
print(f"FATAL: {len(missing)} packaged .py file(s) have no .pyc; "
"the package that owns each was built by a kpkg that does not "
"compile bytecode, or compiled it under another interpreter",
file=sys.stderr)
sys.exit(1)
print(" every packaged module has checked-hash bytecode")
PY
fi
fi
script/phases/70_image/020_cleanup.sh, lines 161–198
Every .py a package owns under /usr or /opt must have bytecode for this interpreter at the path importlib.util.cache_from_source gives. Four kinds of file are exempt:
- scripts in
/usr/binand/usr/sbin, which are run and never imported; *.tmpl.pytemplates;- gcc’s libstdc++ pretty printers under
/usr/share/gcc-*/pythonand gdb’s auto-load scripts: gcc is built in20_selfhostand30_foundation, beforepython3exists, so kpkg has nothing to compile them with, and gdb reads them only in a debugging session; - a file this interpreter cannot compile, such as Python 2 source, which is listed in the log and passes, because there is no bytecode for it to have.
Any other module without bytecode stops the phase, and the log lists each path. The package that owns it was built by a kpkg that does not compile bytecode, or compiled it under another interpreter. See Databases stamped into the image.
Unowned documentation and catalogues
kpkg applies its size and language policy to each package it makes, and drops every non-English message catalogue, translated manual page and HTML manual. Part III installs its tools with no package, and a port installed over them later adopts only the paths it ships, so a bootstrap copy of a file the policy prunes is adopted by nothing. The bootstrap steps install none of these themselves; this pass removes any the tree carries, whatever wrote it. It is a second embedded Python program, and like the first it runs only when python3 is installed; without one the step prints that it skipped the pass and leaves what is there for 087_gates.sh to report. The program reads the package file lists the same way, adds the paths of fs/ from /var/lib/kdos/fs-manifest, and then decides what to remove:
EXTRA = {
"usr/share/info/gawknotes.info",
"usr/share/man/man1/dlltool.1",
"usr/share/man/man1/windres.1",
"usr/share/man/man1/windmc.1",
}
def english(tag):
return tag == "en" or tag.startswith(("en_", "en-", "en@"))
def policy(rel):
if rel in EXTRA:
return True
parts = rel.split("/")
if rel.startswith("usr/share/locale/"):
return (len(parts) == 6 and parts[4] == "LC_MESSAGES"
and parts[5].endswith((".mo", ".gmo", ".qm"))
and not english(parts[3]))
if rel.startswith("usr/share/man/"):
return len(parts) > 4 and not parts[3].startswith("man")
if rel.startswith("usr/share/doc/"):
return rel.endswith((".html", ".htm", ".pdf"))
return False
removed = size = 0
emptied = set()
for top in ("usr/share/locale", "usr/share/man", "usr/share/doc", "usr/share/info"):
base = os.path.join(fs, top)
for d, dirs, files in os.walk(base, topdown=False):
for f in files:
p = os.path.join(d, f)
rel = os.path.relpath(p, fs)
if rel in owned or not policy(rel):
continue
size += os.lstat(p).st_size
os.unlink(p)
removed += 1
emptied.add(d)
if (d in emptied and d != base and os.path.relpath(d, fs) not in owned
and not os.listdir(d)):
os.rmdir(d)
emptied.add(os.path.dirname(d))
print(f" removed {removed} unowned file(s), {size // 1024} KiB")
script/phases/70_image/020_cleanup.sh, lines 254–296
A file is removed only when no package owns it and fs/ does not provide it, and only when the policy would have pruned it from a package: a catalogue under usr/share/locale/<lang>/LC_MESSAGES whose language is not English, anything under a usr/share/man directory that is not a man<section> one, and an .html, .htm or .pdf under usr/share/doc. EXTRA adds the files the gawk and binutils ports delete from their packages, which the policy does not cover. A directory the pass empties is removed with it; one that was empty before is left. The pass walks usr/share/locale, usr/share/man, usr/share/doc and usr/share/info, and 087_gates.sh stops the image on any unowned file still under one of those four.
podman’s stores
if [ -d "$FS/home/kdos/.local/share/containers" ]; then
section "podman's container store"
before=$(size_of "$FS/home/kdos/.local/share/containers")
rm -rf "$FS/home/kdos/.local/share/containers"
report "home/kdos/.local/share/containers" "$before" 0
fi
# The rootful store goes for the same reason: an image or layer a build pulled
# as root is not something the shipped system asked for.
if [ -d "$FS/var/lib/containers/storage" ]; then
section "podman's rootful store"
before=$(size_of "$FS/var/lib/containers/storage")
rm -rf "$FS/var/lib/containers/storage"
report "var/lib/containers/storage" "$before" 0
fi
script/phases/70_image/020_cleanup.sh, lines 309–323
A shipped root carries no container store. An application’s box is built on the machine that asks for it, in that user’s home, so images in /home/kdos/.local/share/containers or in the root store /var/lib/containers/storage are something a build pulled, and would be copied onto every installed system. No package owns these paths, so they are removed with rm and not with kpkgdel.
root’s home
section "root's home"
before=$(size_of "$FS/root")
rm -rf "$FS/root"
mkdir -p "$FS/root"
cp -R /kdos/fs/root/. "$FS/root/"
chmod -R go-w "$FS/root"
chmod 0700 "$FS/root"
report "root (reset to fs/root)" "$before" "$(size_of "$FS/root")"
script/phases/70_image/020_cleanup.sh, lines 333–340
/root is replaced with exactly what fs/root holds, with no file writable by group or others and the directory itself at mode 0700. The chroot’s HOME is a scratch directory, but a tool that names /root itself still writes there: a CMake package registry pointing into kpkg’s work directories, which a later find_package run as root would consult, git’s safe.directory, logs and telemetry dated by the build. The installer copies the live root onto the disk, so each of these would reach every installed system.
What it leaves
The removals are all in the root the step runs in, the stage or build/fs, and so in system.sfs. /root on the image is fs/root. Nothing is written outside that root.
See also
- The packaging steps: the step among the others
- The package lint: what kpkg checks in a package before it is installed
- Anatomy of a kpkg install: where the bytecode is compiled into a package