diff --git a/README.md b/README.md index 14e93e2..ca38e37 100644 --- a/README.md +++ b/README.md @@ -129,9 +129,9 @@ On Windows, a flag marked "Unix" prints a warning. The run goes on without it, e | `-ni`, `--no-info` | Hide the system line | all | | `-w`, `--weather` | Show a weather line from wttr.in | all | | `--ascii` | ASCII glyphs only | all | -| `-nc`, `--keep-cache` | Skip user cache cleaning (Windows: `%TEMP%`) | all | +| `-nc`, `--keep-cache` | Skip user cache cleaning (Windows: `%TEMP%`) and, on Linux, the warning about space still held by deleted files that a program keeps open | all | | `-nt`, `--keep-trash` | Skip trash cleaning (Windows: Recycle Bin) | all | -| `--deep-clean` | Also clean the journal, old kernels, leftover configs, snap revisions, container images, crash dumps, npm and Go caches, asking for each | Unix | +| `--deep-clean` | Also clean the journal, old kernels, leftover configs, snap revisions, crash dumps, npm and Go caches and unused docker and podman data, asking for each | Unix | | `--changed` | Show the last run's package changes | Unix | | `--changelog PKG` | Show the upstream changelog of `PKG` | Unix | | `--history` | Show the last runs | all | diff --git a/completions/_up b/completions/_up index 36922bd..3261136 100644 --- a/completions/_up +++ b/completions/_up @@ -45,11 +45,11 @@ _up() { '--no-logo[no logo]' '-ni[no system info]' '--no-info[no system info]' - '-nc[no cache clean]' - '--keep-cache[no cache clean]' + '-nc[skip cache cleaning and the deleted-but-open files warning]' + '--keep-cache[skip cache cleaning and the deleted-but-open files warning]' '-nt[no trash clean]' '--keep-trash[no trash clean]' - '--deep-clean[clean journal, old kernels, containers, crash dumps]' + '--deep-clean[clean journal, old kernels, containers]' '-w[weather]' '--weather[weather]' '--changed[show package diff]' diff --git a/completions/up.fish b/completions/up.fish index abf9e8c..5ed0beb 100644 --- a/completions/up.fish +++ b/completions/up.fish @@ -33,7 +33,7 @@ complete -c up -l parallel -d 'parallel user-space' complete -c up -l ascii -d 'ASCII glyphs only' complete -c up -o nl -l no-logo -d 'hide logo' complete -c up -o ni -l no-info -d 'hide system info' -complete -c up -o nc -l keep-cache -d 'skip cache cleaning' +complete -c up -o nc -l keep-cache -d 'skip cache cleaning and the deleted-but-open files warning' complete -c up -o nt -l keep-trash -d 'skip trash cleaning' complete -c up -l json -d 'JSON summary on stdout' complete -c up -l only -d 'only these managers' -xa 'pacman yay paru apt dnf yum zypper xbps apk eopkg emerge nix softwareupdate brew mas fwupd rpi-eeprom flatpak snap rustup cargo npm pnpm pip gem' @@ -42,7 +42,7 @@ complete -c up -l rollback -d 'revert last snapshot' complete -c up -l reboot-exit -d 'exit 4 if reboot required' complete -c up -l download-only -d 'download, do not install' complete -c up -l metrics -d 'export Prometheus textfile' -r -complete -c up -l deep-clean -d 'journal, old kernels, containers, crash dumps' +complete -c up -l deep-clean -d 'journal, old kernels, containers' complete -c up -l profile -d 'load profile' -xa '(__up_profiles)' complete -c up -l list-profiles -d 'list profiles' complete -c up -l snapshot -d 'pre-update snapshot' diff --git a/doc/documentation.pdf b/doc/documentation.pdf index 38b4d2d..c1d127c 100644 Binary files a/doc/documentation.pdf and b/doc/documentation.pdf differ diff --git a/doc/documentation.tex b/doc/documentation.tex index afd4757..54c83b6 100644 --- a/doc/documentation.tex +++ b/doc/documentation.tex @@ -487,7 +487,8 @@ \section{Execution flow}\label{sec:flow} user-space ones when \texttt{-{}-parallel} is active. \item Optionally clear user cache and trash (skippable with \texttt{-nc} and \texttt{-nt}), then, with - \texttt{-{}-deep-clean}, the system leftovers (Unix). + \texttt{-{}-deep-clean}, the system leftovers and the container + data (Unix). \item Execute \texttt{post.d} hooks. \item Snapshot the installed-packages list into \texttt{pkgs.after} and compute \texttt{pkgs.diff}. @@ -519,7 +520,7 @@ \subsection{All flags} \texttt{-{}-deep-clean} & System leftovers (see \S\ref{sec:deepclean}) & Linux/macOS \\ \texttt{-nl}, \texttt{-{}-no-logo} & Hide logo & all \\ \texttt{-ni}, \texttt{-{}-no-info} & Hide system info line & all \\ -\texttt{-nc}, \texttt{-{}-keep-cache} & Skip user cache cleaning & all \\ +\texttt{-nc}, \texttt{-{}-keep-cache} & Skip user cache cleaning and the warning about space held by deleted files still open & all \\ \texttt{-nt}, \texttt{-{}-keep-trash} & Skip trash cleaning & all \\ \texttt{-{}-security} & Security-only updates & supported managers \\ \texttt{-{}-firmware} & Include \texttt{fwupdmgr} & Linux \\ @@ -725,6 +726,12 @@ \subsection{Cache cleaning} own cache is always kept; \verb|CACHE_EXCLUDE="mozilla,pip*"| keeps more. With \texttt{-y} everything not excluded is cleaned. +On Linux the step then reports the deleted files a running process +still keeps open on the filesystems of \texttt{/} and +\verb|$HOME|, when they hold 1M or more: the five biggest holders, by +command. That space comes back only when the holder closes the files or +exits, so nothing is deleted; restart the program named. + \subsection{Deep clean}\label{sec:deepclean} \texttt{up -{}-deep-clean} goes after system-level leftovers a normal run doesn't touch, asking about each one and showing how much it would free. @@ -738,13 +745,31 @@ \subsection{Deep clean}\label{sec:deepclean} \texttt{kernels} & dnf: keep the 2 newest kernels; zypper: \texttt{purge-kernels} \\ \texttt{residual} & \texttt{dpkg -{}-purge} config files of removed packages \\ \texttt{snap} & remove disabled snap revisions \\ -\texttt{docker}, \texttt{podman} & \texttt{image prune -f} + \texttt{builder prune -f} - (dangling images and build cache only) \\ \texttt{coredumps} & delete \verb|/var/lib/systemd/coredump| files \\ \texttt{npm}, \texttt{go} & \texttt{npm cache clean -{}-force}, \texttt{go clean -cache} \\ \bottomrule \end{longtable} +Two more sections follow, with the same prompts and skip keys. + +\begin{longtable}{@{}p{0.22\linewidth} p{0.70\linewidth}@{}} +\toprule +\textbf{Key} & \textbf{Task} \\ +\midrule \endhead +\texttt{docker}, \texttt{podman} & Containers section, per local docker + context (\texttt{unix://}; remote ones are skipped): \texttt{container prune -f}, \texttt{image prune -af}, + \texttt{builder prune -af} (docker only) and \texttt{volume prune} + (\texttt{-af} on docker), each with its reclaimable size, a kind at + 0B not offered, sizes read again after the container prune. Stopped + containers (toolbox, distrobox) and volumes hold data: never pruned + under \texttt{-y}. Only the Linux system docker daemon is tried + through \texttt{sudo}. Docker Desktop's data + (\verb|~/.docker/desktop|, on macOS + \verb|~/Library/Containers/com.docker.docker|) is shown from 1M, + since its disk image shrinks only from Docker Desktop \\ +\bottomrule +\end{longtable} + Respects \texttt{-n}; space freed on \texttt{/} goes into the summary. \subsection{Parallel mode} @@ -1483,8 +1508,9 @@ \section{Security model}\label{sec:security} the \texttt{-{}-metrics} file, and deletions inside \verb|~/.cache| and the Trash when cleaning. \texttt{-{}-deep-clean} also deletes journal entries, old kernels, - leftover configs, snap revisions, container images and crash dumps - (\verb|/var/lib/systemd/coredump|), after asking for each. + leftover configs, snap revisions, crash dumps + (\verb|/var/lib/systemd/coredump|), unused containers, images, + build cache and volumes, after asking for each. \item On Windows, UAC elevation happens only for the managers that need admin. They run in an elevated child that loads no config, profile or hook. That child runs the code of the checkout: clone it into a @@ -1812,8 +1838,10 @@ \subsection{Bash library modules (\texttt{src/lib/})} \texttt{state/lock.sh} & Global \texttt{flock}, \texttt{mkdir} fallback \\ \texttt{clean/size.sh} & Size of a path, short size format \\ \texttt{clean/cache.sh} & Selective \texttt{\textasciitilde{}/.cache} menu \\ +\texttt{clean/open.sh} & Report of deleted files still open \\ \texttt{clean/trash.sh} & Trash \\ \texttt{clean/deep.sh} & \texttt{-{}-deep-clean} tasks \\ +\texttt{clean/containers.sh} & \texttt{-{}-deep-clean} Containers section \\ \bottomrule \end{longtable} \end{center} diff --git a/man/up.1 b/man/up.1 index 462a131..106049d 100644 --- a/man/up.1 +++ b/man/up.1 @@ -12,7 +12,7 @@ the Windows build are in the eMerger manual, \fIdoc/documentation.pdf\fR. eMerger detects the package managers installed on the host and runs each of them in turn to refresh, upgrade and clean the system, then prints a summary. It can also clean the user cache, the trash and, with \fB\-\-deep\-clean\fR, -system leftovers. Every cleaning step asks first unless \fB\-y\fR is given. +system leftovers and unused container data. Every cleaning step asks first unless \fB\-y\fR is given. .PP Short flags from the set \fBh V n v q y w\fR can be bundled: \fB\-nv\fR is \fB\-n \-v\fR. Other short flags (\fB\-nl\fR, \fB\-qq\fR, \fB\-up\fR and so on) @@ -132,7 +132,7 @@ ASCII glyphs only. The spinner becomes the ".:" pulse. .SH CLEANING .TP .B \-nc, \-\-keep\-cache -Skip user cache cleaning. +Skip user cache cleaning and the warning about space held by deleted files still open. .TP .B \-nt, \-\-keep\-trash Skip trash cleaning. @@ -140,8 +140,11 @@ Skip trash cleaning. .B \-\-deep\-clean Also clean system leftovers, asking for each: journal above \fBJOURNAL_MAX_SIZE\fR, old kernels (dnf, zypper), config files of removed -packages, disabled snap revisions, dangling docker/podman images and build -cache, crash dumps, npm and Go caches. +packages, disabled snap revisions, crash dumps, npm and Go caches. Then the +Containers section: stopped containers, unused images, build cache and +unused volumes of every local docker context (remote ones skipped) and of +podman (stopped containers and volumes never under \fB\-y\fR), and the size +of Docker Desktop's data. .SH INSPECTION .TP .B \-\-changed diff --git a/src/emerger.sh b/src/emerger.sh index 7e72dd3..923734d 100755 --- a/src/emerger.sh +++ b/src/emerger.sh @@ -261,9 +261,9 @@ main() { run_parallel "$((step+1))" "$total" "${parallel[@]}" fi - (( ARG_KEEP_CACHE )) || clean_cache + if (( ! ARG_KEEP_CACHE )); then clean_cache; clean_open_deleted; fi (( ARG_KEEP_TRASH )) || clean_trash - if (( ARG_DEEP_CLEAN )); then clean_deep; fi + if (( ARG_DEEP_CLEAN )); then clean_deep; clean_containers; fi hooks_run post diff --git a/src/lib/clean/containers.sh b/src/lib/clean/containers.sh new file mode 100644 index 0000000..c551323 --- /dev/null +++ b/src/lib/clean/containers.sh @@ -0,0 +1,164 @@ +#!/usr/bin/env bash +# --deep-clean, Containers section: what docker (every local context) and +# podman keep without using it. Every task asks first unless -y. Stopped +# containers (toolbox, distrobox) and unused volumes hold data: never offered +# under -y. Remote contexts (ssh://, tcp://) are left alone. + +# Offer to prune stopped containers, unused images, build cache and unused +# volumes of every local docker context and of podman, then add the +# growth of free space on / to SUMMARY_FREED_KB. Silent when neither tool is +# installed or DEEP_CLEAN_SKIP lists both. +clean_containers() { + local -a engines=() + local bin context endpoint free_before + for bin in docker podman; do + if sys_has "$bin" && ! _deep_is_skipped "$bin"; then engines+=("$bin"); fi + done + (( ${#engines[@]} > 0 )) || return 0 + ui_title "Containers" + _DEEP_TASK_COUNT=0 + free_before=$(sys_free_space k /) + + for bin in "${engines[@]}"; do + if [[ $bin == docker ]]; then + # On fd 3: a probe or prune reading stdin cannot eat the list. + while IFS='|' read -r context endpoint <&3; do + if [[ -n $endpoint && $endpoint != unix://* && $endpoint != npipe://* ]]; then + ui_muted "docker ($context): remote engine at $endpoint, skipped" + else + _containers_target docker "$context" + fi + done 3< <(_containers_docker_contexts) + _containers_desktop_note + else + _containers_target "$bin" "" + fi + done + + if (( _DEEP_TASK_COUNT == 0 )); then + ui_ok "nothing to clean" + return 0 + fi + _deep_report_freed "$free_before" + return 0 +} + +# Print the docker contexts as name|endpoint, one per line, or one empty line +# when docker lists none (an engine older than contexts, or a failing call). +_containers_docker_contexts() { + local list + list=$(docker context ls --format '{{.Name}}|{{.DockerEndpoint}}' 2>/dev/null || true) + if [[ -z $list ]]; then + printf '\n' + else + printf '%s\n' "$list" + fi +} + +# Print the command line reaching engine $1 through docker context $2 (none +# when empty), one word per line: plain if the daemon answers, else sudo +# (probed with sudo -n, never under --dry-run, where sudo is assumed). Only +# the Linux system docker daemon (no context or "default") is tried through +# sudo: other contexts are user sockets, and root's podman has its own +# storage. Empty when the daemon is not reachable. +_containers_cmd() { + local -a base=("$1") + [[ -n $2 ]] && base+=(--context "$2") + if "${base[@]}" info >/dev/null 2>&1; then + printf '%s\n' "${base[@]}" + elif sys_is_root || [[ $1 != docker || ( -n $2 && $2 != default ) ]] || sys_is_macos; then + return 0 + elif (( DRY_RUN )) || sudo -n "${base[@]}" info >/dev/null 2>&1; then + printf '%s\n' sudo "${base[@]}" + fi + return 0 +} + +# Set _containers_target's free_images, free_containers, free_volumes and +# free_build to the reclaimable sizes `system df` reports through command +# $@ ("4.978GB"), empty for a kind it does not list. +_containers_reclaimable() { + local type value + free_images="" free_containers="" free_volumes="" free_build="" + while IFS='|' read -r type value; do + value=${value%% (*} + case "$type" in + Images) free_images=$value ;; + Containers) free_containers=$value ;; + 'Local Volumes') free_volumes=$value ;; + 'Build Cache') free_build=$value ;; + esac + done < <("$@" system df --format '{{.Type}}|{{.Reclaimable}}' 2>/dev/null || true) + return 0 +} + +# Offer the prune tasks of engine $1 through docker context $2 (empty for +# podman or an engine without contexts), each with its reclaimable size. +# A kind reclaiming 0B is not offered. +_containers_target() { + local bin="$1" context="$2" name="$1" + [[ -n $context && $context != default ]] && name="$bin ($context)" + local -a command=() + mapfile -t command < <(_containers_cmd "$bin" "$context") + if (( ${#command[@]} == 0 )); then + if [[ -n $context && $context != default ]]; then + ui_muted "$name: daemon not running, skipped" + elif [[ $bin == docker ]]; then + ui_muted "$name: daemon not reachable (not in the docker group?), skipped" + else + ui_muted "$name: not reachable, skipped" + fi + return 0 + fi + + local free_images="" free_containers="" free_volumes="" free_build="" read_sizes=1 + # Under --dry-run a sudo command line is not run, not even to read. + [[ ${command[0]} == sudo ]] && (( DRY_RUN )) && read_sizes=0 + (( read_sizes )) && _containers_reclaimable "${command[@]}" + _containers_offer "$bin" "Remove stopped $name containers (their files are lost)" "$free_containers" \ + "$name stopped containers kept under -y: they hold files" "${command[@]}" container prune -f + # Pruned containers free their images and volumes: read the sizes again. + if (( read_sizes && ! ARG_YES )) && [[ $free_containers != 0B ]]; then + _containers_reclaimable "${command[@]}" + fi + _containers_offer "$bin" "Remove unused $name images" "$free_images" "" \ + "${command[@]}" image prune -af + if [[ $bin == docker ]]; then + _containers_offer "$bin" "Clear $name build cache" "$free_build" "" \ + "${command[@]}" builder prune -af + fi + # podman volume prune has no -a: it always removes every unused volume. + local -a volume_args=(volume prune -f) + [[ $bin == docker ]] && volume_args=(volume prune -af) + _containers_offer "$bin" "Remove unused $name volumes (their data is lost)" "$free_volumes" \ + "$name unused volumes kept under -y: they hold data" "${command[@]}" "${volume_args[@]}" + return 0 +} + +# Offer task $2 of DEEP_CLEAN_SKIP key $1 running command $5... with +# reclaimable size $3 in its detail ("?" when unknown). Nothing when $3 is +# 0B. A non-empty $4 makes the task ask even under -y: there it prints $4. +_containers_offer() { + local key="$1" label="$2" free="$3" kept="$4"; shift 4 + [[ $free == 0B ]] && return 0 + if [[ -n $kept ]]; then + _deep_task_asked "$key" "$label" "(reclaimable: ${free:-?})" "$kept" "$@" + else + _deep_task "$key" "$label" "(reclaimable: ${free:-?})" "$@" + fi +} + +# Report the size of Docker Desktop's data (~/.docker/desktop on Linux, +# ~/Library/Containers/com.docker.docker on macOS) when it holds 1M or more: +# its disk image does not shrink when the engine prunes, only from Docker +# Desktop. +_containers_desktop_note() { + local dir kb + for dir in "$HOME/.docker/desktop" "$HOME/Library/Containers/com.docker.docker"; do + [[ -d $dir ]] || continue + kb=$(_clean_size_kb "$dir") + (( kb >= 1024 )) || continue + ui_muted "Docker Desktop keeps $(_clean_format_kb "$kb") in $dir: shrink it from Docker Desktop (Troubleshoot, Clean / Purge data)" + done + return 0 +} diff --git a/src/lib/clean/deep.sh b/src/lib/clean/deep.sh index 18e1111..e6b73d9 100644 --- a/src/lib/clean/deep.sh +++ b/src/lib/clean/deep.sh @@ -1,6 +1,7 @@ #!/usr/bin/env bash # --deep-clean: system leftovers a normal run does not touch. Every task -# asks first unless -y. +# asks first unless -y. The Containers section of --deep-clean +# (clean/containers.sh) shares these helpers. # --deep-clean. Task names for DEEP_CLEAN_SKIP: # journal kernels residual snap docker podman coredumps npm go @@ -32,24 +33,22 @@ _deep_task() { fi } -# Print the docker/podman command line for $1, one word per line: plain if -# the daemon answers, else sudo (probed with sudo -n, never under --dry-run, -# where sudo is assumed). Empty when the daemon is not reachable. -_deep_container_cmd() { - local bin="$1" - if "$bin" info >/dev/null 2>&1; then - printf '%s' "$bin" - elif sys_is_root; then +# _deep_task running command $5... for data the user may want: never +# offered under -y, where message $4 is printed instead. +_deep_task_asked() { + local key="$1" label="$2" detail="$3" kept="$4"; shift 4 + _deep_is_skipped "$key" && return 0 + if (( ARG_YES )); then + ui_muted "$kept" return 0 - elif (( DRY_RUN )) || sudo -n "$bin" info >/dev/null 2>&1; then - printf 'sudo\n%s' "$bin" fi + _deep_task "$key" "$label" "$detail" "$@" } -# Offer each --deep-clean task that has something to remove, then add the +# Offer each Deep clean task that has something to remove, then add the # growth of free space on / to SUMMARY_FREED_KB (not under --dry-run). clean_deep() { - local sudo_cmd free_before free_after + local sudo_cmd free_before sudo_cmd=$(sys_sudo_prefix) ui_title "Deep clean" _DEEP_TASK_COUNT=0 @@ -59,7 +58,6 @@ clean_deep() { _deep_kernels _deep_residual _deep_snap - _deep_containers _deep_coredumps _deep_devcaches @@ -67,6 +65,15 @@ clean_deep() { ui_ok "nothing to clean" return 0 fi + _deep_report_freed "$free_before" + return 0 +} + +# Add the growth of free space on / since reading $1 (KiB, from +# sys_free_space) to SUMMARY_FREED_KB and report it. Nothing under +# --dry-run, when $1 is empty or when the space did not grow. +_deep_report_freed() { + local free_before="$1" free_after free_after=$(sys_free_space k /) if [[ -n $free_before && -n $free_after ]] && (( ! DRY_RUN )) && (( free_after > free_before )); then SUMMARY_FREED_KB=$(( SUMMARY_FREED_KB + free_after - free_before )) @@ -139,32 +146,6 @@ _deep_snap() { return 0 } -# Offer to prune dangling images and build cache of docker and podman. -_deep_containers() { - local bin - for bin in docker podman; do - sys_has "$bin" || continue - local -a command=() - mapfile -t command < <(_deep_container_cmd "$bin") - if (( ${#command[@]} == 0 )); then - ui_muted "$bin: daemon not reachable (not in the $bin group?), skipped" - continue - fi - local reclaim="" - # Under --dry-run a sudo command line is not run, not even to read. - if [[ ${command[0]} != sudo ]] || (( ! DRY_RUN )); then - reclaim=$({ "${command[@]}" system df --format '{{.Type}}|{{.Reclaimable}}' 2>/dev/null || true; } | awk -F'|' ' - $1 == "Images" || $1 ~ /^Build/ { - v = $2; sub(/ *\(.*/, "", v) - printf "%s%s %s", sep, ($1 == "Images" ? "images" : "build cache"), v; sep = ", " - }') - fi - _deep_task "$bin" "Prune $bin dangling images + build cache" "(reclaimable: ${reclaim:-?})" \ - bash -c '"$@" image prune -f && { "$@" builder prune -f 2>/dev/null || true; }' _ "${command[@]}" - done - return 0 -} - # Offer to delete systemd crash dumps. _deep_coredumps() { if [[ -d /var/lib/systemd/coredump ]]; then diff --git a/src/lib/clean/open.sh b/src/lib/clean/open.sh new file mode 100644 index 0000000..6120556 --- /dev/null +++ b/src/lib/clean/open.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# Disk space held by deleted files a running process still keeps open +# (Linux): reported in the cache step, freed only when the holder closes +# them or exits. + +# /proc read by the scan, a variable so a test can point it at a missing one. +: "${_CLEAN_PROC:=/proc}" + +# Rows of the report: the biggest holders, the rest left out. +CLEAN_OPEN_ROWS=5 + +# Report the deleted files the processes readable here keep open on the +# filesystems of / and $HOME, per command, biggest first, when they hold 1M +# or more. +# Each file counts once, however many descriptors point at it. Silent +# without /proc (macOS). +clean_open_deleted() { + [[ -d $_CLEAN_PROC/self/fd ]] || return 0 + local devs fd pid dev ino blocks unit kb comm + devs=" $(stat -c %d / 2>/dev/null || true) $(stat -c %d "$HOME" 2>/dev/null || true) " + local -A seen=() held=() + while IFS= read -r -d '' fd; do + IFS='|' read -r dev ino blocks unit < <(stat -L -c '%d|%i|%b|%B' -- "$fd" 2>/dev/null) || continue + [[ $devs == *" $dev "* ]] || continue + [[ -n ${seen[$dev:$ino]:-} ]] && continue + seen[$dev:$ino]=1 + kb=$(( blocks * unit / 1024 )) + pid=${fd#"$_CLEAN_PROC"/} + pid=${pid%%/*} + comm=$(cat "$_CLEAN_PROC/$pid/comm" 2>/dev/null) || comm="pid $pid" + held[$comm]=$(( ${held[$comm]:-0} + kb )) + done < <(find "$_CLEAN_PROC"/[0-9]*/fd -mindepth 1 -maxdepth 1 -lname '*(deleted)' -print0 2>/dev/null) + + local total=0 + for comm in "${!held[@]}"; do total=$(( total + held[$comm] )); done + (( total >= 1024 )) || return 0 + ui_info "$(_clean_format_kb "$total") held by deleted files still open, freed when their holders close" + while IFS=$'\t' read -r kb comm; do + ui_sub "$(printf '%-24.24s %6s' "$comm" "$(_clean_format_kb "$kb")")" + done < <(for comm in "${!held[@]}"; do printf '%s\t%s\n' "${held[$comm]}" "$comm"; done \ + | sort -rn | head -n "$CLEAN_OPEN_ROWS") + return 0 +} diff --git a/src/lib/help.txt b/src/lib/help.txt index 6bad8c9..93e507f 100644 --- a/src/lib/help.txt +++ b/src/lib/help.txt @@ -50,11 +50,12 @@ DISPLAY --ascii Force ASCII glyphs only CLEANING - -nc, --keep-cache Skip user cache cleaning + -nc, --keep-cache Skip user cache cleaning and the warning about + space held by deleted files still open -nt, --keep-trash Skip trash cleaning --deep-clean Also clean journal, old kernels, leftover configs, - snap revisions, docker/podman dangling data, - crash dumps, npm/go caches (asks for each) + snap revisions, crash dumps, npm/go caches, + unused docker/podman data (asks for each) INSPECTION --changed Show packages added/removed/upgraded in the last run diff --git a/src/lib/load.sh b/src/lib/load.sh index f88c416..db55d39 100644 --- a/src/lib/load.sh +++ b/src/lib/load.sh @@ -11,7 +11,8 @@ _LOAD_MODULES=( managers/progress state/estimate run/command run/select run/parallel run/sudo args ignore managers/registry managers/detect managers/icon managers/recipes - clean/size clean/cache clean/trash clean/deep hooks selfupdate autoupdate + clean/size clean/cache clean/open clean/trash clean/deep clean/containers + hooks selfupdate autoupdate system/notify system/rpi managers/rpi_eeprom system/reboot state/diff system/preflight system/snapshot system/mirrors state/resume state/lock doctor managers/changelog profiles summary state/history quiet_hours diff --git a/tests/clean.bats b/tests/clean.bats index 5afdee8..43b778b 100644 --- a/tests/clean.bats +++ b/tests/clean.bats @@ -70,12 +70,10 @@ teardown() { stub journalctl 'echo "Archived and active journals take up 0B in the file system."' stub dnf 'exit 1' stub go 'exit 1' - stub docker 'case "$1" in info) exit 0 ;; *) exit 1 ;; esac' run sys_lib 'DRY_RUN=1; ARG_YES=1; clean_deep; echo "rc=$?"' [ "$status" -eq 0 ] [[ "$output" == *"rc=0"* ]] [[ "$output" != *"vacuum-size"* ]] - [[ "$output" == *"image prune -f"*"_ docker"* ]] } @test "deep clean: journal size in plain bytes is compared" { @@ -85,15 +83,6 @@ teardown() { [[ "$output" == *"[dry-run] journalctl --vacuum-size=100"* ]] } -@test "deep clean: dry-run never calls sudo for the docker probe" { - stub docker 'exit 1' - stub sudo 'echo "$*" >>"$HOME/sudo.calls"; exit 0' - run sys_lib 'sys_is_root() { return 1; }; DRY_RUN=1; ARG_YES=1; clean_deep; echo "rc=$?"' - [ "$status" -eq 0 ] - [[ "$output" == *"rc=0"* ]] - [ ! -e "$HOME/sudo.calls" ] -} - @test "clean_trash: macOS empties ~/.Trash" { stub uname 'echo Darwin' mkdir -p "$HOME/.Trash" @@ -168,8 +157,20 @@ teardown() { [ ! -e "$HOME/.cache/a"$'\x1f'keepme ] } -@test "--deep-clean under dry-run exits 0 and prints the Deep clean section" { +@test "--deep-clean under dry-run exits 0 and prints the Deep clean and Containers sections" { + stub docker 'case "$*" in "context ls"*) echo default ;; *info*) exit 0 ;; esac' run $EMERGER -n -y -nl -nc -nt --deep-clean --only none [ "$status" -eq 0 ] - [[ "$output" == *"Deep clean"* ]] + [[ "$output" == *"Deep clean"*"Containers"* ]] +} + +@test "the cache step reports deleted files still open, --keep-cache skips both" { + run bash -c "exec 3>\"\$HOME/held\"; head -c 3000000 /dev/zero >&3; rm \"\$HOME/held\" + $EMERGER -n -y -nl -nt --only none || echo FAILED + echo @@split@@; $EMERGER -n -y -nl -nt -nc --only none || echo FAILED" + [ "$status" -eq 0 ] + [[ "$output" != *FAILED* ]] + [[ "${output%%@@split@@*}" == *"User cache"*"held by deleted files still open"* ]] + [[ "${output#*@@split@@}" != *"User cache"* ]] + [[ "${output#*@@split@@}" != *"held by deleted files"* ]] } diff --git a/tests/containers.bats b/tests/containers.bats new file mode 100644 index 0000000..51a7438 --- /dev/null +++ b/tests/containers.bats @@ -0,0 +1,212 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env + setup_minbin +} + +teardown() { + teardown_env +} + +# Stub docker: local contexts $1 (space separated, "" for a failing context +# ls), info answering only for the contexts in $2, system df printing $3, +# remote ssh:// contexts $4, every other call logged to $HOME/docker.calls. +docker_stub() { + stub docker " +ctx=''; [ \"\$1\" = --context ] && { ctx=\$2; shift 2; } +case \"\$1\" in + context) [ -n '$1' ] || exit 1 + for c in $1; do echo \"\$c|unix:///run/\$c.sock\"; done + for c in ${4:-}; do echo \"\$c|ssh://user@\$c\"; done ;; + info) case ' $2 ' in *\" \$ctx \"*) exit 0 ;; *) exit 1 ;; esac ;; + system) printf '$3' ;; + *) echo \"docker \${ctx:+--context \$ctx }\$*\" >>\"\$HOME/docker.calls\" ;; +esac" +} + +@test "clean_containers: without docker or podman prints nothing" { + run sys_lib 'clean_containers; echo "rc=$?"' + [ "$status" -eq 0 ] + [ "$output" = "rc=0" ] +} + +@test "clean_containers: DEEP_CLEAN_SKIP naming both engines prints nothing and probes neither" { + docker_stub default default '' + stub podman 'echo "podman $*" >>"$HOME/podman.calls"' + run sys_lib 'DEEP_CLEAN_SKIP="docker,podman"; clean_containers; echo "rc=$?"' + [ "$status" -eq 0 ] + [ "$output" = "rc=0" ] + [ ! -e "$HOME/podman.calls" ] +} + +@test "clean_containers: dry-run offers each kind per reachable context, keeps stopped containers and volumes under -y" { + docker_stub "default desktop-linux" default 'Images|4.978GB (8%%)\nContainers|2.188GB (99%%)\nLocal Volumes|1.407GB (16%%)\nBuild Cache|41.92GB\n' + run sys_lib 'DRY_RUN=1; ARG_YES=1; clean_containers; echo "rc=$?"' + [ "$status" -eq 0 ] + [[ "$output" == *"Containers"* ]] + [[ "$output" == *"docker stopped containers kept under -y: they hold files"* ]] + [[ "$output" != *"container prune"* ]] + [[ "$output" == *"[dry-run] docker --context default image prune -af"* ]] + [[ "$output" == *"[dry-run] docker --context default builder prune -af"* ]] + [[ "$output" == *"docker unused volumes kept under -y: they hold data"* ]] + [[ "$output" != *"volume prune"* ]] + [[ "$output" == *"docker (desktop-linux): daemon not running, skipped"* ]] + [[ "$output" == *"rc=0"* ]] + [ ! -e "$HOME/docker.calls" ] +} + +@test "clean_containers: asks for each kind with its reclaimable size, volumes included without -y" { + docker_stub default default 'Images|4.978GB (8%%)\nContainers|2.188GB (99%%)\nLocal Volumes|1.407GB (16%%)\nBuild Cache|41.92GB\n' + run sys_lib 'ui_confirm() { echo "ASK $1 $3"; return 1; }; clean_containers' + [ "$status" -eq 0 ] + [[ "$output" == *"ASK Remove stopped docker containers (their files are lost)? (reclaimable: 2.188GB)"* ]] + [[ "$output" == *"ASK Remove unused docker images? (reclaimable: 4.978GB)"* ]] + [[ "$output" == *"ASK Clear docker build cache? (reclaimable: 41.92GB)"* ]] + [[ "$output" == *"ASK Remove unused docker volumes (their data is lost)? (reclaimable: 1.407GB)"* ]] + [ ! -e "$HOME/docker.calls" ] +} + +@test "clean_containers: a kind reclaiming 0B is not offered, an unknown size shows ?" { + docker_stub default default 'Images|0B (0%%)\nContainers|0B\nLocal Volumes|0B\n' + run sys_lib 'ui_confirm() { echo "ASK $1 $3"; return 1; }; clean_containers + ARG_YES=1; DRY_RUN=1; clean_containers' + [ "$status" -eq 0 ] + [[ "$output" != *"containers?"* ]] + [[ "$output" != *"images?"* ]] + [[ "$output" != *"volumes"* ]] + [[ "$output" == *"ASK Clear docker build cache? (reclaimable: ?)"* ]] +} + +@test "clean_containers: -y runs the prunes and adds the space freed on / to the summary" { + docker_stub default default 'Images|1GB\nContainers|0B\nLocal Volumes|0B\nBuild Cache|2GB\n' + stub df 'n=$(cat "$HOME/df.n" 2>/dev/null || echo 0); n=$((n + 1)); echo $n >"$HOME/df.n" + echo "Filesystem 1024-blocks Used Available Capacity Mounted"; echo "/dev/x 100 0 $((n * 1024)) 0% /"' + run sys_lib 'ARG_YES=1; clean_containers; echo "freed=$SUMMARY_FREED_KB"' + [ "$status" -eq 0 ] + [ "$(cat "$HOME/docker.calls")" = "docker --context default image prune -af +docker --context default builder prune -af" ] + [[ "$output" == *"freed 1M on /"* ]] + [[ "$output" == *"freed=1024"* ]] +} + +@test "clean_containers: daemon reachable only through sudo runs every call through sudo" { + stub sudo '[ "$1" = -n ] && shift; SUDO_OK=1 exec "$@"' + stub docker ' +[ "$1" = context ] && { echo "default|unix:///var/run/docker.sock"; exit 0; } +[ -n "$SUDO_OK" ] || exit 1 +case "$*" in *info*) exit 0 ;; *"system df"*) printf "Build Cache|3GB\n" ;; *) echo "sudo docker $*" >>"$HOME/docker.calls" ;; esac' + run sys_lib 'sys_is_root() { return 1; }; ui_confirm() { echo "ASK $1 $3"; return 0; }; clean_containers' + [ "$status" -eq 0 ] + [[ "$output" == *"ASK Clear docker build cache? (reclaimable: 3GB)"* ]] + grep -qx 'sudo docker --context default builder prune -af' "$HOME/docker.calls" + grep -qx 'sudo docker --context default container prune -f' "$HOME/docker.calls" +} + +@test "clean_containers: dry-run never calls sudo for the docker probe" { + stub docker 'exit 1' + stub sudo 'echo "$*" >>"$HOME/sudo.calls"; exit 0' + run sys_lib 'sys_is_root() { return 1; }; DRY_RUN=1; ARG_YES=1; clean_containers; echo "rc=$?"' + [ "$status" -eq 0 ] + [[ "$output" == *"[dry-run] sudo docker image prune -af"* ]] + [[ "$output" == *"rc=0"* ]] + [ ! -e "$HOME/sudo.calls" ] +} + +@test "clean_containers: unreachable daemon without sudo is reported, nothing to clean" { + docker_stub default '' '' + stub sudo 'exit 1' + run sys_lib 'sys_is_root() { return 1; }; ARG_YES=1; clean_containers' + [ "$status" -eq 0 ] + [[ "$output" == *"docker: daemon not reachable (not in the docker group?), skipped"* ]] + [[ "$output" == *"nothing to clean"* ]] +} + +@test "clean_containers: as root an unreachable daemon is skipped without sudo" { + docker_stub default '' '' + stub sudo 'echo "$*" >>"$HOME/sudo.calls"; exit 0' + run sys_lib 'sys_is_root() { return 0; }; ARG_YES=1; clean_containers' + [ "$status" -eq 0 ] + [[ "$output" == *"daemon not reachable"* ]] + [ ! -e "$HOME/sudo.calls" ] +} + +@test "clean_containers: failing context ls targets docker without --context" { + stub docker 'case "$1" in context) exit 1 ;; info) exit 0 ;; system) printf "Images|5MB\n" ;; *) echo "docker $*" >>"$HOME/docker.calls" ;; esac' + run sys_lib 'ARG_YES=1; clean_containers' + [ "$status" -eq 0 ] + grep -qx 'docker image prune -af' "$HOME/docker.calls" +} + +@test "clean_containers: a remote context is never probed or pruned" { + docker_stub default "default prod" 'Images|1GB\n' prod + run sys_lib 'ARG_YES=1; clean_containers' + [ "$status" -eq 0 ] + [[ "$output" == *"docker (prod): remote engine at ssh://user@prod, skipped"* ]] + grep -qx 'docker --context default image prune -af' "$HOME/docker.calls" + ! grep -q prod "$HOME/docker.calls" +} + +@test "clean_containers: sizes are read again once stopped containers are removed" { + stub docker ' +ctx=""; [ "$1" = --context ] && { ctx=$2; shift 2; } +case "$1" in + context) echo "default|unix:///run/default.sock" ;; + info) exit 0 ;; + system) if [ -e "$HOME/pruned" ]; then printf "Images|2GB\nContainers|0B\nLocal Volumes|1GB\n" + else printf "Images|0B\nContainers|1GB\nLocal Volumes|0B\n"; fi ;; + container) touch "$HOME/pruned" ;; + *) echo "docker $*" >>"$HOME/docker.calls" ;; +esac' + run sys_lib 'ui_confirm() { echo "ASK $1 $3"; return 0; }; clean_containers' + [ "$status" -eq 0 ] + [[ "$output" == *"ASK Remove unused docker images? (reclaimable: 2GB)"* ]] + [[ "$output" == *"ASK Remove unused docker volumes (their data is lost)? (reclaimable: 1GB)"* ]] +} + +@test "clean_containers: podman is never tried through sudo" { + stub podman 'exit 1' + stub sudo 'echo "$*" >>"$HOME/sudo.calls"; exit 0' + run sys_lib 'sys_is_root() { return 1; }; ARG_YES=1; clean_containers' + [ "$status" -eq 0 ] + [[ "$output" == *"podman: not reachable, skipped"* ]] + [ ! -e "$HOME/sudo.calls" ] +} + +@test "clean_containers: on macOS docker is never tried through sudo, Docker Desktop data is reported" { + stub uname 'echo Darwin' + stub docker 'exit 1' + stub du 'echo "2097152 $2"' + mkdir -p "$HOME/Library/Containers/com.docker.docker" + run sys_lib 'sys_is_root() { return 1; }; DRY_RUN=1; ARG_YES=1; clean_containers' + [ "$status" -eq 0 ] + [[ "$output" == *"docker: daemon not reachable"* ]] + [[ "$output" != *"sudo"* ]] + [[ "$output" == *"Docker Desktop keeps 2.0G in $HOME/Library/Containers/com.docker.docker"* ]] +} + +@test "clean_containers: podman has no build cache task and prunes volumes without -a" { + stub podman 'case "$1" in info) exit 0 ;; system) printf "Images|1GB\nContainers|1GB\nLocal Volumes|1GB\n" ;; *) echo "podman $*" >>"$HOME/podman.calls" ;; esac' + run sys_lib 'ui_confirm() { echo "ASK $1"; return 0; }; clean_containers' + [ "$status" -eq 0 ] + [[ "$output" != *"build cache"* ]] + [ "$(cat "$HOME/podman.calls")" = "podman container prune -f +podman image prune -af +podman volume prune -f" ] +} + +@test "clean_containers: Docker Desktop data of 1M is reported, under 1M is not" { + docker_stub default default 'Images|0B\nContainers|0B\nLocal Volumes|0B\nBuild Cache|0B\n' + mkdir -p "$HOME/.docker/desktop" + stub du 'echo "1023 $2"' + run sys_lib 'ARG_YES=1; clean_containers' + [ "$status" -eq 0 ] + [[ "$output" == *"nothing to clean"* ]] + [[ "$output" != *"Docker Desktop"* ]] + stub du 'echo "1024 $2"' + run sys_lib 'ARG_YES=1; clean_containers' + [ "$status" -eq 0 ] + [[ "$output" == *"Docker Desktop keeps 1M in $HOME/.docker/desktop"* ]] +} diff --git a/tests/open_deleted.bats b/tests/open_deleted.bats new file mode 100644 index 0000000..4b80dcf --- /dev/null +++ b/tests/open_deleted.bats @@ -0,0 +1,110 @@ +#!/usr/bin/env bats + +load test_helper + +setup() { + setup_env + setup_minbin + export FAKE_PROC="$HOME/proc" + mkdir -p "$FAKE_PROC/self/fd" +} + +teardown() { + rm -f "/dev/shm/emerger-test-$$ (deleted)" + teardown_env +} + +# Give fake process $1 named $2 descriptor $3 open on file $4, which a real +# /proc shows with " (deleted)" appended once it is unlinked. +fake_fd() { + mkdir -p "$FAKE_PROC/$1/fd" + [[ -n $2 ]] && printf '%s\n' "$2" >"$FAKE_PROC/$1/comm" + ln -s "$4" "$FAKE_PROC/$1/fd/$3" +} + +# Create file $1 of $2 MiB of real blocks. +blob() { + head -c $(( $2 * 1048576 )) /dev/zero >"$1" +} + +@test "clean_open_deleted: per command, biggest first, a file shared by two descriptors counted once" { + blob "$HOME/a (deleted)" 2 + blob "$HOME/b (deleted)" 3 + touch "$HOME/live" + fake_fd 100 code 3 "$HOME/a (deleted)" + fake_fd 100 code 4 "$HOME/a (deleted)" + fake_fd 200 tracker-miner-f 3 "$HOME/b (deleted)" + fake_fd 200 tracker-miner-f 4 "$HOME/live" + run sys_lib '_CLEAN_PROC="$FAKE_PROC"; clean_open_deleted; echo "rc=$?"' + [ "$status" -eq 0 ] + [[ "${lines[0]}" == *"5M held by deleted files still open, freed when their holders close"* ]] + [[ "${lines[1]}" == *"tracker-miner-f"*"3M"* ]] + [[ "${lines[2]}" == *"code"*"2M"* ]] + [ "${lines[3]}" = "rc=0" ] +} + +@test "clean_open_deleted: under 1M in all prints nothing" { + head -c 500000 /dev/zero >"$HOME/a (deleted)" + fake_fd 100 code 3 "$HOME/a (deleted)" + run sys_lib '_CLEAN_PROC="$FAKE_PROC"; clean_open_deleted; echo "rc=$?"' + [ "$status" -eq 0 ] + [ "$output" = "rc=0" ] +} + +@test "clean_open_deleted: unreadable comm names the pid, a vanished target is skipped" { + blob "$HOME/a (deleted)" 2 + fake_fd 300 "" 3 "$HOME/a (deleted)" + fake_fd 400 ghost 3 "$HOME/gone (deleted)" + run sys_lib '_CLEAN_PROC="$FAKE_PROC"; clean_open_deleted' + [ "$status" -eq 0 ] + [[ "$output" == *"pid 300"*"2M"* ]] + [[ "$output" != *"ghost"* ]] +} + +@test "clean_open_deleted: only the biggest CLEAN_OPEN_ROWS holders are listed" { + local n + for n in 1 2 3 4 5 6; do + blob "$HOME/f$n (deleted)" "$n" + fake_fd "$n" "proc$n" 3 "$HOME/f$n (deleted)" + done + run sys_lib '_CLEAN_PROC="$FAKE_PROC"; clean_open_deleted' + [ "$status" -eq 0 ] + [[ "$output" == *"21M held"* ]] + [[ "$output" == *"proc6"* ]] + [[ "$output" == *"proc2"* ]] + [[ "$output" != *"proc1 "* ]] +} + +@test "clean_open_deleted: a file on another filesystem than / and HOME is left out" { + [[ -d /dev/shm && -w /dev/shm ]] || skip "no writable /dev/shm" + [[ $(stat -c %d /dev/shm) != "$(stat -c %d /)" && $(stat -c %d /dev/shm) != "$(stat -c %d "$HOME")" ]] \ + || skip "/dev/shm shares a filesystem with / or HOME" + blob "/dev/shm/emerger-test-$$ (deleted)" 2 + fake_fd 100 shm 3 "/dev/shm/emerger-test-$$ (deleted)" + run sys_lib '_CLEAN_PROC="$FAKE_PROC"; clean_open_deleted; echo "rc=$?"' + [ "$status" -eq 0 ] + [ "$output" = "rc=0" ] +} + +@test "clean_open_deleted: an unreadable HOME does not stop the run" { + blob "$HOME/a (deleted)" 2 + fake_fd 100 code 3 "$HOME/a (deleted)" + run sys_lib '_CLEAN_PROC="$FAKE_PROC"; HOME="$HOME/missing"; clean_open_deleted; echo "rc=$?"' + [ "$status" -eq 0 ] + [[ "$output" == *"2M held"* ]] + [[ "$output" == *"rc=0"* ]] +} + +@test "clean_open_deleted: without /proc (macOS) prints nothing" { + run sys_lib '_CLEAN_PROC="$HOME/missing"; clean_open_deleted; echo "rc=$?"' + [ "$status" -eq 0 ] + [ "$output" = "rc=0" ] +} + +@test "clean_open_deleted: the real /proc shows a deleted file this shell holds" { + [[ -d /proc/self/fd ]] || skip "no /proc" + run sys_lib 'exec 3>"$HOME/held"; head -c 3000000 /dev/zero >&3; rm "$HOME/held"; clean_open_deleted' + [ "$status" -eq 0 ] + [[ "$output" == *"held by deleted files still open"* ]] + [[ "$output" == *"bash"* ]] +}