Files
Febe/.gitea/scripts/pulizia-docker.sh
T
Alby96andClaude Opus 5.5 009e7d6710 CI e installatore: commenti degli script in inglese (#43)
La regola del progetto è «codice e commenti in inglese; interfaccia, documenti
e messaggi in italiano», e gli script di .gitea/ (script e flussi), di
installer/ e docker/entrypoint.sh avevano ancora i commenti in italiano
(decisione di Alberto del 29 novembre 2026). Cambiano solo i commenti: i
messaggi che una persona legge (echo, ::warning::, ::error::, nomi dei passi,
note della release) restano in italiano e nessun comando cambia. I programmi
awk e gli script finti delle prove erano già in inglese.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:03:13 +01:00

924 lines
41 KiB
Bash
Executable File

#!/usr/bin/env bash
# Cleanup of the runner's Docker daemon and of the container registry. The daemon is the same one that builds
# Encelado, Mimante and Alberto's other projects (and very probably the one of the Unraid applications), and a real
# Febe may run on it too. Since 21 October 2026 (decision of Alberto) the cleanup also removes what nobody needs any
# more, of any project: the images no container uses, the build cache, the leftovers of act_runner. Never a
# container, a volume or a network that does not belong to the CI.
#
# Of the Febe CI, what can be proven to be its own is removed. The labels febe.ci.workflow, febe.ci.run, febe.ci.ref
# and febe.ci.commit say where an image comes from, but they do NOT choose what to remove: they are also in the
# published images (:main, :sha-, :X.Y.Z, :latest), and Docker copies them into every container created from those,
# so a real Febe carries them too. What is removed is recognised like this:
# - test containers: the label febe.ci.prova=<esecuzione>, which only prova-immagine.sh sets with
# «docker run --label» and which no image carries (PipelineTests checks it), AND the exact name
# febe-prova-<the same run> (the other test containers, without a name, run with --rm and Docker removes them by
# itself as soon as they end);
# - tested images: the local name febe-ci:<esecuzione>, removed by name, never by id and never with -f. If the same
# image also has a registry name, only febe-ci:<esecuzione> is removed; if a container uses it, it stays;
# - buildx builders: the container buildx_buildkit_febe-ci-<esecuzione>0, with the moby/buildkit image, and its
# …_state volume, which hold the build cache of that run;
# - the febe:ci image left by the old verification workflow (before 20 October 2026), if nobody uses it.
# Of act_runner, the leftovers of the jobs are removed: act_runner names everything it creates for a job
# GITEA-ACTIONS-TASK-<task number>… (the job container, its volumes <nome> and <nome>-env, its network
# <nome>-<lavoro>-network). Only stopped containers, and volumes and networks no container uses, older than 90
# minutes: a job that starts creates them and uses them at once. The act-toolcache volume (the tool cache, shared
# among the jobs) stays.
#
# pulizia-docker.sh esecuzione <id> everything the run <id> created (at the start and at the end of its
# «immagine» job, always)
# pulizia-docker.sh penzolanti the unnamed images no container uses and the daemon's dangling build cache
# (the part no image shares) unused for 24 hours, of all projects (at the end
# of every «immagine» job, after «esecuzione»)
# pulizia-docker.sh residui [minuti] the leftovers of interrupted runs, older than N minutes (default 90: a job
# lasts at most 60 minutes, so none of them is still alive)
# pulizia-docker.sh settimanale residui, febe:ci, unnamed images older than 72 hours: the narrow cleanup of
# before 21 October 2026, now only by hand
# pulizia-docker.sh completa residui, febe:ci, act_runner leftovers, the images no container uses
# created more than 24 hours ago, the build cache unused for 24 hours and,
# with REGISTRY_TOKEN, the registry's sha- tags beyond the 10 most recent and
# the CI artifacts (febe-ci) older than 14 days («pulizia» workflow, every
# Monday and by hand)
# pulizia-docker.sh <modo> --prova lists what it would remove and removes nothing: only commands that read
# (on the registry only GET)
#
# All the arguments are checked before touching Docker: an option other than --prova (--dry-run, -n, --Prova) or an
# extra argument (prova without dashes) stops everything with code 2, instead of starting the real cleanup in place
# of the dry run.
#
# Never docker system prune, container prune, volume prune or network prune; never image prune -a or builder prune -a
# without the 24-hour filter; never a container, a volume or a network that does not belong to the CI. The images are
# removed by Docker itself (image prune), which never removes an image used by a container, not even a stopped one;
# with -a, though, it removes their extra names, and the script writes them out (in the dry run it estimates them,
# depending on the store). On the registry never main, latest or an X.Y.Z version: only the sha-<hexadecimal> tags of
# the verification and the <x.y.z>-ci.<n> and <x.y.z>-rilascio.<n> artifacts of the generic febe-ci package.
#
# In the «residui», «settimanale» and «completa» modes a test container is removed only if it is stopped. One still
# running after 90 minutes (its job was killed right during the container test) stays where it is: it is reported,
# with the command to remove it by hand. The builders are the exception: they are always running and their cache goes
# away only by removing the container; they are recognised by the exact name and the buildkit image, never by a label.
#
# An object already gone is not an error: the cleanup can be repeated. In the «esecuzione», «penzolanti» and «residui»
# modes a problem becomes a warning (a green job does not turn red because of the cleanup, which the Monday workflow
# repeats); in the «settimanale» and «completa» modes it fails the job, so that someone looks at it. The registry is
# the exception: a refusal by its API is only a warning, and the following Monday it is tried again.
#
# Variables for the registry («completa» mode): REGISTRY_TOKEN (token with «package: read and write», never printed),
# GITEA_API (the server's API, for example https://gitea.example/api/v1) and PROPRIETARIO (the owner of the febe
# package). The choice of the versions to remove lives in versioni-registro.sh, next to this script.
set -uo pipefail
uso() {
[[ -z "${1:-}" ]] || echo "$1" >&2
echo "Uso: $0 esecuzione <id> | penzolanti | residui [minuti] | settimanale | completa [--prova]" >&2
exit 2
}
prova=0
argomenti=()
for argomento in "$@"; do
case "$argomento" in
--prova) prova=1 ;;
-*) uso "Opzione sconosciuta: «$argomento». L'unica è --prova." ;;
*) argomenti+=("$argomento") ;;
esac
done
modo="${argomenti[0]:-}"
case "$modo" in
esecuzione) ((${#argomenti[@]} == 2)) || uso "Il modo esecuzione vuole il numero dell'esecuzione e nient'altro." ;;
residui) ((${#argomenti[@]} <= 2)) || uso "Il modo residui vuole al più i minuti." ;;
penzolanti | settimanale | completa) ((${#argomenti[@]} == 1)) || uso "Il modo $modo non vuole altri argomenti: «${argomenti[1]}»." ;;
*) uso ;;
esac
cartella_script="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
problemi=0
# In a dry run: the containers (id and name) and the image names the real cleanup would remove, so that the lists
# that follow treat them as already removed (a volume used only by a container that would go away, for example,
# would go away too).
previsti=()
nomi_previsti=()
# For the summary: how many objects per kind, in the order they appear, and the space reclaimed by Docker.
declare -A conteggi=()
tipi=()
note=()
# The build cache that is pruned is the one of the daemon's builder, «default». docker builder is an alias of docker
# buildx when the plugin is there, and buildx works on the current builder: if someone had made the run's builder
# current (costruisci-immagine.sh builder does not), the «esecuzione» mode would have just removed it. The other
# buildx commands of this script name the builder explicitly.
export BUILDX_BUILDER=default
avviso() {
echo "::warning::$*"
problemi=$((problemi + 1))
}
# A warning that does not turn the job red: for the registry.
segnala() {
echo "::warning::$*"
}
conta() {
[[ -n "${conteggi[$1]+x}" ]] || tipi+=("$1")
conteggi[$1]=$((${conteggi[$1]:-0} + 1))
}
# True if the first word is among the ones that follow.
fra() {
local cercata="$1" voce
shift
for voce in "$@"; do
[[ "$voce" == "$cercata" ]] && return 0
done
return 1
}
# Minutes elapsed since an RFC 3339 instant as Docker writes it (Created of a container or an image, CreatedAt of a
# volume, {{json .Created}} of a network, in quotes), with or without fractions of a second, with «Z» or with the
# offset from universal time (+02:00). If it cannot be read, 0: when in doubt the object is young and stays.
eta_minuti() {
local creato="${1:-}" secondi
creato="${creato//\"/}"
[[ "$creato" =~ ^([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2})(\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})$ ]] \
|| { echo 0; return; }
secondi=$(date -u -d "${BASH_REMATCH[1]}${BASH_REMATCH[3]}" +%s 2> /dev/null) || { echo 0; return; }
echo $((($(date -u +%s) - secondi) / 60))
}
durata() {
local minuti="$1"
if ((minuti >= 2 * 1440)); then
echo "$((minuti / 1440)) giorni"
elif ((minuti >= 120)); then
echo "$((minuti / 60)) ore"
else
echo "$minuti minuti"
fi
}
# Among the given containers (ids, one per line), those that remain after this cleanup: in a dry run without the ones
# the real cleanup would remove.
restanti() {
local id
while read -r id; do
[[ -n "$id" ]] || continue
fra "$id" "${previsti[@]}" || echo "$id"
done <<< "${1:-}"
}
# The CI test containers, one per line «id name»: the label febe.ci.prova (of the given run, or of any run if the
# first argument is empty) and the exact name febe-prova-<label value>. The states that follow narrow the choice
# (Docker joins them with OR). Exits with 1 if Docker does not answer.
contenitori_di_prova() {
local run="$1"
shift
local stati=() stato elenco id nome valore
for stato in "$@"; do stati+=(--filter "status=$stato"); done
elenco=$(docker ps -a --no-trunc --filter "label=febe.ci.prova${run:+=$run}" "${stati[@]}" \
--format '{{.ID}} {{.Names}} {{.Label "febe.ci.prova"}}') || return 1
while read -r id nome valore; do
[[ -n "${id:-}" && "${valore:-}" =~ ^[0-9]+$ && "${nome:-}" == "febe-prova-$valore" ]] || continue
[[ -z "$run" || "$valore" == "$run" ]] || continue
echo "$id $nome"
done <<< "$elenco"
}
# Removes a container with its anonymous volumes (in a dry run it only lists it). With «forza» even if it is running:
# only for those of the run itself and for the builders. Exits with 0 if the container goes away (or would).
togli_contenitore() {
local id="$1" nome="$2" opzioni=(-v)
[[ "${3:-}" == forza ]] && opzioni=(-f -v)
if ((prova)); then
echo " toglierei il contenitore $nome"
previsti+=("$id" "$nome")
return 0
fi
if docker rm "${opzioni[@]}" "$id" > /dev/null 2>&1; then
echo " contenitore $nome tolto"
return 0
fi
docker container inspect "$id" > /dev/null 2>&1 && avviso "Non riesco a togliere il contenitore $nome."
return 1
}
# Removes the local name febe-ci:<esecuzione> (or febe:ci), never the image by id and never with -f: if the image also
# has another name (a registry one, for example) that one stays; if a container uses it, everything stays.
togli_immagine() {
local riferimento="$1" nomi
[[ "$riferimento" =~ ^febe-ci:[0-9]+$ ]] || [[ "$riferimento" == febe:ci ]] \
|| { avviso "Nome di immagine inatteso: «$riferimento»."; return 1; }
nomi=$(docker image inspect -f '{{len .RepoTags}}' "$riferimento" 2> /dev/null) || return 1
if [[ "$nomi" == 1 && -n "$(restanti "$(docker ps -a -q --no-trunc --filter "ancestor=$riferimento")")" ]]; then
echo " immagine $riferimento in uso da un contenitore: resta"
return 1
fi
if ((prova)); then
echo " toglierei l'immagine $riferimento"
nomi_previsti+=("$riferimento")
return 0
fi
if docker image rm "$riferimento" > /dev/null 2>&1; then
echo " immagine $riferimento tolta"
return 0
fi
avviso "Non riesco a togliere l'immagine $riferimento."
return 1
}
# A CI buildx builder: first with buildx (if this client knows it), then container and volume by name, because a job
# other than the one that created it does not have its configuration. The container is removed only if it runs the
# buildkit image, and the volume only when the container is gone.
togli_builder() {
local builder="$1"
[[ "$builder" =~ ^febe-ci-[0-9]+$ ]] || { avviso "Nome di builder inatteso: «$builder»."; return 1; }
local contenitore="buildx_buildkit_${builder}0" volume="buildx_buildkit_${builder}0_state" immagine esito=1
if ((!prova)) && docker buildx rm -f "$builder" > /dev/null 2>&1; then
echo " builder $builder tolto"
esito=0
fi
if immagine=$(docker container inspect -f '{{.Config.Image}}' "$contenitore" 2> /dev/null); then
if [[ "$immagine" != *moby/buildkit* ]]; then
avviso "Il contenitore $contenitore non è un builder buildx (immagine «$immagine»): resta."
return 1
fi
togli_contenitore "$contenitore" "$contenitore" forza && esito=0
if ((!prova)) && docker container inspect "$contenitore" > /dev/null 2>&1; then
return 1
fi
fi
if docker volume inspect "$volume" > /dev/null 2>&1; then
if ((prova)); then
echo " toglierei il volume $volume"
esito=0
elif docker volume rm -f "$volume" > /dev/null 2>&1; then
echo " volume $volume tolto"
esito=0
else
avviso "Non riesco a togliere il volume $volume."
fi
fi
return "$esito"
}
# A volume or a network of act_runner. Docker itself does not remove a volume a container uses, nor a network with a
# running container attached.
togli_volume() {
local nome="$1"
if ((prova)); then
echo " toglierei il volume $nome"
return 0
fi
if docker volume rm "$nome" > /dev/null 2>&1; then
echo " volume $nome tolto"
return 0
fi
docker volume inspect "$nome" > /dev/null 2>&1 && avviso "Non riesco a togliere il volume $nome."
return 1
}
togli_rete() {
local id="$1" nome="$2"
if ((prova)); then
echo " toglierei la rete $nome"
return 0
fi
if docker network rm "$id" > /dev/null 2>&1; then
echo " rete $nome tolta"
return 0
fi
docker network inspect "$id" > /dev/null 2>&1 && avviso "Non riesco a togliere la rete $nome."
return 1
}
# True if no container, running or stopped, uses the volume or the network (in a dry run: none that the real cleanup
# would leave). When in doubt (Docker does not answer) false: it stays.
nessuno_usa() {
local tipo="$1" nome="$2" utenti
if [[ "$tipo" == volume ]]; then
utenti=$(docker ps -a -q --no-trunc --filter "volume=$nome") || return 1
else
utenti=$(docker ps -a -q --no-trunc --filter "network=$nome") || return 1
fi
[[ -z "$(restanti "$utenti")" ]]
}
esecuzione() {
local run="${1:-}"
[[ "$run" =~ ^[0-9]+$ ]] || { echo "Indica il numero dell'esecuzione (gitea.run_id), non «$run»." >&2; exit 2; }
echo "== Pulizia dell'esecuzione $run"
local elenco id nome
if elenco=$(contenitori_di_prova "$run"); then
while read -r id nome; do
[[ -n "${id:-}" ]] && togli_contenitore "$id" "$nome" forza
done <<< "$elenco"
else
avviso "Non riesco a elencare i contenitori di prova dell'esecuzione $run."
fi
togli_immagine "febe-ci:$run"
togli_builder "febe-ci-$run"
}
residui() {
local minuti="${1:-90}"
[[ "$minuti" =~ ^[0-9]+$ ]] || { echo "I minuti devono essere un numero, non «$minuti»." >&2; exit 2; }
echo "== Resti di esecuzioni interrotte della CI di Febe, più vecchi di $minuti minuti"
local elenco id nome eta riferimento builder
# Stopped test containers: they are removed. Without -f: if one started again in the meantime, Docker leaves it alone.
if elenco=$(contenitori_di_prova "" exited created dead); then
while read -r id nome; do
[[ -n "${id:-}" ]] || continue
eta=$(eta_minuti "$(docker container inspect -f '{{.Created}}' "$id" 2> /dev/null)")
((eta >= minuti)) && togli_contenitore "$id" "$nome" && conta "contenitori di prova della CI di Febe"
done <<< "$elenco"
else
avviso "Non riesco a elencare i contenitori di prova fermi."
fi
# Test containers still running: they are not touched, they are reported.
if elenco=$(contenitori_di_prova "" running restarting paused); then
while read -r id nome; do
[[ -n "${id:-}" ]] || continue
eta=$(eta_minuti "$(docker container inspect -f '{{.Created}}' "$id" 2> /dev/null)")
if ((eta >= minuti)); then
avviso "Il contenitore di prova $nome è acceso da $eta minuti: il suo lavoro si è interrotto durante la prova. La pulizia non toglie contenitori accesi; se nessuna esecuzione lo usa più, toglilo a mano: docker rm -f -v $nome"
fi
done <<< "$elenco"
else
avviso "Non riesco a elencare i contenitori di prova accesi."
fi
# Tested images: only the febe-ci:<esecuzione> names.
if elenco=$(docker image ls --filter "reference=febe-ci" --format '{{.Repository}}:{{.Tag}}'); then
while read -r riferimento; do
[[ "${riferimento:-}" =~ ^febe-ci:[0-9]+$ ]] || continue
eta=$(eta_minuti "$(docker image inspect -f '{{.Created}}' "$riferimento" 2> /dev/null)")
((eta >= minuti)) && togli_immagine "$riferimento" && conta "immagini febe-ci"
done <<< "$elenco"
else
avviso "Non riesco a elencare le immagini febe-ci."
fi
# buildx builders. Docker's name filter matches part of the name: the exact name is checked here.
if elenco=$(docker ps -a --no-trunc --filter "name=buildx_buildkit_febe-ci-" --format '{{.ID}} {{.Names}}'); then
while read -r id nome; do
[[ -n "${id:-}" ]] || continue
nome="${nome#/}"
[[ "$nome" =~ ^buildx_buildkit_(febe-ci-[0-9]+)0$ ]] || continue
builder="${BASH_REMATCH[1]}"
eta=$(eta_minuti "$(docker container inspect -f '{{.Created}}' "$id" 2> /dev/null)")
((eta >= minuti)) && togli_builder "$builder" && conta "builder buildx della CI di Febe"
done <<< "$elenco"
else
avviso "Non riesco a elencare i builder buildx."
fi
}
# The leftovers of the Febe CI and the febe:ci image of the old workflow («settimanale» and «completa» modes).
resti_della_ci() {
residui 90
echo "== Immagine febe:ci del vecchio flusso di verifica"
if docker image inspect febe:ci > /dev/null 2>&1; then
togli_immagine febe:ci && conta "immagini febe-ci"
fi
}
# act_runner names its objects GITEA-ACTIONS-TASK-<task number>, followed by «_WORKFLOW-…» or, in older versions, by
# «-WORKFLOW-…» with a hash at the end.
nome_act='^GITEA-ACTIONS-TASK-[0-9]+[-_]'
resti_di_act_runner() {
local minuti="$1" elenco id nome eta
echo "== Resti di act_runner (GITEA-ACTIONS-TASK-…) più vecchi di $minuti minuti: contenitori fermi, volumi e reti che nessun contenitore usa"
# Stopped containers. Docker's name filter matches part of the name: the exact start is checked here. Without -f:
# Docker does not remove a running container.
if elenco=$(docker ps -a --no-trunc --filter "name=GITEA-ACTIONS-TASK-" --filter "status=exited" \
--filter "status=created" --filter "status=dead" --format '{{.ID}} {{.Names}}'); then
while read -r id nome; do
[[ -n "${id:-}" ]] || continue
nome="${nome#/}"
[[ "$nome" =~ $nome_act ]] || continue
eta=$(eta_minuti "$(docker container inspect -f '{{.Created}}' "$id" 2> /dev/null)")
((eta >= minuti)) && togli_contenitore "$id" "$nome" && conta "contenitori fermi di act_runner"
done <<< "$elenco"
else
avviso "Non riesco a elencare i contenitori di act_runner."
fi
# Volumes no container uses, not even a stopped one.
if elenco=$(docker volume ls -q --filter "name=GITEA-ACTIONS-TASK-"); then
while read -r nome; do
[[ -n "${nome:-}" && "$nome" =~ $nome_act ]] || continue
eta=$(eta_minuti "$(docker volume inspect -f '{{.CreatedAt}}' "$nome" 2> /dev/null)")
((eta >= minuti)) || continue
nessuno_usa volume "$nome" && togli_volume "$nome" && conta "volumi di act_runner"
done <<< "$elenco"
else
avviso "Non riesco a elencare i volumi di act_runner."
fi
# Networks no container is attached to, not even a stopped one. Created of a network is a Go time, which the template
# prints as «2026-10-21 06:17:03 +0200 CEST»: in JSON it is RFC 3339.
if elenco=$(docker network ls --no-trunc --filter "name=GITEA-ACTIONS-TASK-" --format '{{.ID}} {{.Name}}'); then
while read -r id nome; do
[[ -n "${id:-}" && "${nome:-}" =~ $nome_act ]] || continue
eta=$(eta_minuti "$(docker network inspect -f '{{json .Created}}' "$id" 2> /dev/null)")
((eta >= minuti)) || continue
nessuno_usa network "$nome" && togli_rete "$id" "$nome" && conta "reti di act_runner"
done <<< "$elenco"
else
avviso "Non riesco a elencare le reti di act_runner."
fi
}
# The images of the containers, running or stopped, except those the cleanup would remove: «id image» one per line,
# the image as it was given to docker run (a name or an id). Read only: it serves the dry-run listing.
immagini_in_uso() {
local elenco id nome
elenco=$(docker ps -a --no-trunc --format '{{.ID}} {{.Names}}') || return 1
while read -r id nome; do
[[ -n "${id:-}" ]] || continue
fra "$id" "${previsti[@]}" && continue
fra "${nome#/}" "${previsti[@]}" && continue
docker container inspect -f '{{.Image}} {{.Config.Image}}' "$id" 2> /dev/null
done <<< "$elenco"
return 0
}
# The full name of an image name, as Docker sorts it: docker.io/library/ or docker.io/ in front of Docker Hub names
# written without a domain, :latest if the tag is missing.
nome_completo() {
local nome="$1" primo
[[ "${nome##*/}" == *:* ]] || nome="$nome:latest"
if [[ "$nome" != */* ]]; then
echo "docker.io/library/$nome"
return
fi
primo="${nome%%/*}"
if [[ "$primo" == *.* || "$primo" == *:* || "$primo" == localhost ]]; then
echo "$nome"
else
echo "docker.io/$nome"
fi
}
# In a dry run: the names «image prune -a» would remove from an image a container uses (the names and the images of
# the containers, as docker image ls and docker container inspect write them), one per line. The image stays, but the
# extra names do not (moby). With the classic store Docker removes the names in alphabetical order of the full name
# and stops at the last one, the only one it refuses to remove because a container uses the image
# (daemon/images/image_prune.go and image_delete.go, isSingleReference): even the name the container was created from
# may go. With containerd the names the containers were created from stay and, if one uses it by id and no name would
# stay, the last one in alphabetical order (daemon/containerd/image_prune.go).
nomi_che_perde() {
local id="$1" nomi="$2" configurazioni="$3" nome completo configurazione resto per_id=0 ordinati quanti
local -A protetti=()
local -a lista=() via=()
ordinati=$(while read -r nome; do
[[ -n "$nome" ]] && printf '%s %s\n' "$(nome_completo "$nome")" "$nome"
done <<< "$nomi" | LC_ALL=C sort)
quanti=$(grep -c . <<< "$ordinati")
((quanti > 1)) || return 0
if [[ "$store" != containerd ]]; then
sed '$d' <<< "$ordinati" | cut -d' ' -f2-
return 0
fi
read -r -a lista <<< "$configurazioni"
for configurazione in "${lista[@]}"; do
if [[ "$id" == "$configurazione"* || "$id" == "sha256:$configurazione"* ]]; then
per_id=1
elif [[ "$configurazione" == *@* ]]; then
[[ "${configurazione#*@}" == "$id" ]] && per_id=1
resto="${configurazione%%@*}"
[[ "${resto##*/}" == *:* ]] && protetti[$(nome_completo "$resto")]=1
else
protetti[$(nome_completo "$configurazione")]=1
fi
done
while read -r completo nome; do
[[ -n "${protetti[$completo]:-}" ]] || via+=("$nome")
done <<< "$ordinati"
if ((per_id && ${#via[@]} == quanti)); then
unset "via[$((quanti - 1))]"
fi
((${#via[@]} == 0)) || printf '%s\n' "${via[@]}"
return 0
}
# In a dry run: the images the pruning would remove, with size and age. No container uses them (apart from those this
# cleanup would remove) and they were created more than N minutes ago; with «senza-nome» only the unnamed ones. With
# «tutte», for an image a container uses, the extra names Docker would remove from it. It is an estimate made here: in
# the real cleanup Docker decides (image prune).
elenca_immagini() {
local minimo="$1" quali="$2" usate elenco id nome breve dimensione eta quante=0 configurazione
local -A nomi=() elenco_nomi=() dimensioni=() aveva_nomi=() usata_da=()
local ordine=()
if ! usate=$(immagini_in_uso) \
|| ! elenco=$(docker image ls --no-trunc --format '{{.ID}}|{{.Repository}}:{{.Tag}}|{{.Size}}'); then
avviso "Non riesco a elencare le immagini."
return 0
fi
if [[ "$store" != classico ]] && ((minimo > 0)); then
echo " (l'età qui è quella dell'immagine, dalla costruzione; con lo store di containerd la pulizia vera conta da quando il nome è arrivato sul demone, e un nome riscaricato tiene la data di prima: l'elenco è solo indicativo)"
fi
while read -r id configurazione; do
[[ -n "${id:-}" ]] || continue
usata_da[$id]="${usata_da[$id]:+${usata_da[$id]} }$configurazione"
done <<< "$usate"
while IFS='|' read -r id nome dimensione; do
[[ -n "${id:-}" ]] || continue
if [[ -z "${dimensioni[$id]+x}" ]]; then
ordine+=("$id")
dimensioni[$id]="${dimensione:-?}"
nomi[$id]=""
elenco_nomi[$id]=""
fi
[[ "$nome" == "<none>:<none>" ]] && continue
aveva_nomi[$id]=1
fra "$nome" "${nomi_previsti[@]}" && continue
nomi[$id]="${nomi[$id]:+${nomi[$id]}, }$nome"
[[ "$nome" == *":<none>" ]] || elenco_nomi[$id]+="$nome"$'\n'
done <<< "$elenco"
for id in "${ordine[@]}"; do
# An image whose names the cleanup removes above already goes away with the last one.
[[ -n "${aveva_nomi[$id]:-}" && -z "${nomi[$id]}" ]] && continue
breve="${id#sha256:}"
if [[ -n "${usata_da[$id]+x}" ]]; then
# A container uses it: it stays. With -a, though, Docker removes its extra names.
[[ "$quali" == tutte && -n "${elenco_nomi[$id]}" ]] || continue
eta=$(eta_minuti "$(docker image inspect -f '{{.Created}}' "$id" 2> /dev/null)")
((eta >= minimo)) || continue
while read -r nome; do
[[ -n "$nome" ]] || continue
echo " toglierei il nome $nome; l'immagine ${breve:0:12} resta, perché la usa un contenitore"
quante=$((quante + 1))
conta "nomi tolti a immagini che restano"
done < <(nomi_che_perde "$id" "${elenco_nomi[$id]}" "${usata_da[$id]}")
continue
fi
[[ "$quali" == senza-nome && -n "${aveva_nomi[$id]:-}" ]] && continue
eta=$(eta_minuti "$(docker image inspect -f '{{.Created}}' "$id" 2> /dev/null)")
((eta >= minimo)) || continue
nome="${nomi[$id]}"
[[ -n "$nome" ]] || nome="un'immagine senza nome"
echo " toglierei $nome (${breve:0:12}) · ${dimensioni[$id]} · creata $(durata "$eta") fa"
quante=$((quante + 1))
if [[ "$quali" == senza-nome ]]; then
conta "immagini senza nome"
else
conta "immagini che nessun contenitore usa"
fi
done
((quante > 0)) || echo " nessuna"
}
# In a dry run: how much build cache the daemon has. How much of it the pruning would remove Docker does not say
# without removing it: at most the part nobody is using («RECLAIMABLE» of docker system df).
elenca_cache() {
local riga tipo dimensione recuperabile
riga=$(docker system df --format '{{.Type}}|{{.Size}}|{{.Reclaimable}}' 2> /dev/null | grep '^Build Cache|')
if [[ -z "$riga" ]]; then
echo " docker system df non dice quanta cache di costruzione c'è"
return 0
fi
IFS='|' read -r tipo dimensione recuperabile <<< "$riga"
echo " la cache di costruzione del demone occupa $dimensione; ne toglierei al più $recuperabile, la parte che nessuno sta usando"
note+=("cache di costruzione: $dimensione in tutto, al più $recuperabile da togliere")
}
# The daemon's image store: «containerd» (io.containerd.snapshotter.v1, the default in new Docker Engine installations
# since 29) or «classico» (overlay2 and the other earlier drivers). It decides from when the 24 hours of image prune
# --filter until count: with the classic store from the image build (Created of the configuration), with containerd
# from when the name arrived on the daemon (CreatedAt of its record, which a new pull of the same name does not
# change).
store=""
rileva_store() {
local stato
if ! stato=$(docker info --format '{{json .DriverStatus}}' 2> /dev/null); then
store=sconosciuto
elif [[ "$stato" == *io.containerd.snapshotter* ]]; then
store=containerd
else
store=classico
fi
case "$store" in
containerd) echo "== Store delle immagini del demone: containerd (le 24 ore contano da quando un nome è arrivato sul demone)" ;;
classico) echo "== Store delle immagini del demone: classico (le 24 ore contano dalla costruzione dell'immagine)" ;;
*) echo "== Store delle immagini del demone: non lo so, docker info non risponde" ;;
esac
}
# Every image with each of its names, «id name» one per line (<none>:<none> if it has none).
immagini_e_nomi() {
docker image ls --no-trunc --format '{{.ID}} {{.Repository}}:{{.Tag}}' 2> /dev/null
}
# The space reclaimed according to Docker: «Total reclaimed space: 1.2GB» (docker) or «Total: 1.2GB» (buildx).
spazio_recuperato() {
local riga
riga=$(grep -E '^Total' <<< "$1" | tail -n 1 | sed -E 's/^Total( reclaimed space)?:[[:space:]]*//')
echo "${riga:-0B}"
}
# A Docker image pruning: the names removed, how many images and how much space. An error is a warning. The names are
# compared before and after: with -a Docker also removes the extra names of an image a container uses and that stays,
# and the job log says so.
pota_immagini() {
local cosa="$1" uscita prima dopo recuperato prima_nomi dopo_nomi dopo_id id nome breve
shift
prima_nomi=$(immagini_e_nomi)
prima=$(cut -d' ' -f1 <<< "$prima_nomi" | sort -u | grep -c .)
if ! uscita=$("$@" 2>&1); then
avviso "Non riesco a togliere le $cosa: $(tail -n 1 <<< "$uscita")"
return 0
fi
dopo_nomi=$(immagini_e_nomi)
dopo_id=$(cut -d' ' -f1 <<< "$dopo_nomi" | sort -u)
dopo=$(grep -c . <<< "$dopo_id")
while read -r id nome; do
[[ -n "${nome:-}" && "$nome" != *":<none>" ]] || continue
grep -qxF -- "$id $nome" <<< "$dopo_nomi" && continue
if grep -qxF -- "$id" <<< "$dopo_id"; then
breve="${id#sha256:}"
echo " tolto il nome $nome; l'immagine ${breve:0:12} resta"
conta "nomi tolti a immagini che restano"
else
echo " tolta $nome"
fi
done <<< "$prima_nomi"
recuperato=$(spazio_recuperato "$uscita")
if [[ "$prima" =~ ^[0-9]+$ && "$dopo" =~ ^[0-9]+$ ]]; then
echo " $cosa: $((prima - dopo)) tolte, $recuperato recuperati"
note+=("$cosa: $((prima - dopo)) tolte ($prima prima, $dopo dopo), $recuperato recuperati")
else
echo " $cosa: $recuperato recuperati"
note+=("$cosa: $recuperato recuperati")
fi
}
# A build cache pruning: how much space. An error is a warning.
pota_cache() {
local cosa="$1" uscita recuperato
shift
if ! uscita=$("$@" 2>&1); then
avviso "Non riesco a togliere la $cosa: $(tail -n 1 <<< "$uscita")"
return 0
fi
recuperato=$(spazio_recuperato "$uscita")
echo " $cosa: $recuperato recuperati"
note+=("$cosa: $recuperato recuperati")
}
# A call to the Gitea API with the registry token, which is only in the curl header and never in the job log. Prints
# the HTTP code: 000 if Gitea does not answer.
chiedi() {
local metodo="$1" indirizzo="$2" uscita="$3" codice
codice=$(curl -sS --max-time 30 -X "$metodo" -H "Authorization: token $REGISTRY_TOKEN" -H "Accept: application/json" \
-o "$uscita" -w '%{http_code}' "$indirizzo") || true
echo "${codice:-000}"
}
spiega() {
case "$1" in
000) echo "niente (Gitea non risponde)" ;;
401) echo "401: il token non vale" ;;
403) echo "403: il token non ha il permesso «package: read and write»" ;;
*) echo "$1" ;;
esac
}
# The sha- tags of the febe package beyond the 10 most recent, with the package API of Gitea 28:
# GET /api/v1/packages/{proprietario}/container/febe?page=N&limit=50 the versions, one page at a time until an
# empty one arrives (the server may give
# fewer than 50 per page)
# DELETE /api/v1/packages/{proprietario}/container/febe/{versione} one version (answers 204)
# Which ones to remove is chosen by versioni-registro.sh (POSIX awk with json.awk: no Node, no jq); here the
# sha-<hexadecimal> form is checked again before every DELETE. Every refusal by the API is a warning that does not
# turn the job red, and after a refusal the registry is not touched any more (the token is the same). The sha256:…
# versions without a tag (the child manifests of an index, with the layers) are never touched: the API does not say
# whether a tag still uses them. Only their number is reported; the CI publishes plain manifests
# (costruisci-immagine.sh), so there should be none, and those no tag uses are removed by a Gitea cleanup rule
# (docs/processo.md, «Registro dei container»).
# Then the CI artifacts (artefatti.sh): the versions of the generic febe-ci package created more than 14 days ago,
# GET /api/v1/packages/{proprietario}/generic/febe-ci?page=N&limit=50
# DELETE /api/v1/packages/{proprietario}/generic/febe-ci/{versione} the version with its files (204)
# only with the form <x.y.z>-ci.<n> or <x.y.z>-rilascio.<n>, checked again before every DELETE.
registro() {
local tenere=10
echo "== Registro: le etichette sha- del pacchetto febe oltre le $tenere più recenti"
if [[ -z "${REGISTRY_TOKEN:-}" ]]; then
echo " Manca il segreto REGISTRY_TOKEN: il registro non si tocca."
return 0
fi
if [[ -z "${GITEA_API:-}" || -z "${PROPRIETARIO:-}" ]]; then
segnala "Mancano GITEA_API o PROPRIETARIO: il registro non si tocca."
return 0
fi
local programma
for programma in curl awk sort; do
command -v "$programma" > /dev/null || { segnala "Manca $programma: il registro non si tocca."; return 0; }
done
local base="${GITEA_API%/}/packages/$PROPRIETARIO/container/febe" cartella codice scelte esito
cartella=$(mktemp -d) || { segnala "Non riesco a creare una cartella temporanea: il registro non si tocca."; return 0; }
esito=0
pagine "$base" "$cartella" febe || esito=$?
if ((esito == 2)); then
rm -rf "$cartella"
return 0
fi
if ((esito == 1)); then
echo " Il pacchetto febe non è ancora sul registro: niente da togliere."
else
contenitore "$base" "$cartella"
fi
rm -rf "$cartella"
artefatti_della_ci
}
# The pages of the versions of a package in the folder, pagina-<n>.json, up to the first empty one (the server may give
# fewer than 50 per page). Exits with 0 if it read them, 1 if the package is not there (404 on the first page), 2 if
# the API refuses (and reports it).
pagine() {
local base="$1" cartella="$2" nome="$3" pagina codice
for ((pagina = 1; ; pagina++)); do
if ((pagina > 200)); then
segnala "Più di 200 pagine di versioni di $nome sul registro: il registro non si tocca."
return 2
fi
codice=$(chiedi GET "$base?page=$pagina&limit=50" "$cartella/pagina-$pagina.json")
if [[ "$codice" == 404 && "$pagina" == 1 ]]; then
return 1
fi
if [[ "$codice" != 200 ]]; then
segnala "L'API dei pacchetti di Gitea risponde $(spiega "$codice") alla pagina $pagina delle versioni di $nome: il registro non si tocca."
return 2
fi
case "$(tr -d '[:space:]' < "$cartella/pagina-$pagina.json")" in
"[]" | null) return 0 ;;
esac
done
}
# The sha- tags of the febe container, from the pages already read.
contenitore() {
local base="$1" cartella="$2" scelte senza_etichetta quante codice
if ! scelte=$(bash "$cartella_script/versioni-registro.sh" "$tenere" "$cartella"/pagina-*.json) \
|| ! senza_etichetta=$(bash "$cartella_script/versioni-registro.sh" senza-etichetta "$cartella"/pagina-*.json); then
segnala "Non riesco a leggere le versioni del pacchetto febe: il registro non si tocca."
return 0
fi
quante=$(grep -c . <<< "$senza_etichetta")
if ((quante > 0)); then
echo " $quante versioni senza etichetta (sha256:…, i manifest di un indice con i loro strati): restano, questa pulizia non le tocca mai (docs/processo.md, «Registro dei container»)"
note+=("registro: $quante versioni sha256:… senza etichetta, che restano")
fi
if [[ -z "$scelte" ]]; then
echo " niente da togliere"
return 0
fi
local versione creata
while IFS=$'\t' read -r versione creata; do
[[ -n "${versione:-}" ]] || continue
if [[ ! "$versione" =~ ^sha-[0-9a-f]{7,40}$ ]]; then
segnala "Versione inattesa «$versione» fra quelle da togliere: resta."
continue
fi
if ((prova)); then
echo " toglierei $versione (pubblicata il $creata)"
conta "etichette sha- sul registro"
continue
fi
codice=$(chiedi DELETE "$base/$versione" /dev/null)
if [[ "$codice" == 204 ]]; then
echo " $versione tolta (pubblicata il $creata)"
conta "etichette sha- sul registro"
else
segnala "Non riesco a togliere $versione dal registro: l'API risponde $(spiega "$codice")."
fi
done <<< "$scelte"
}
# The CI artifacts (artefatti.sh): the versions of the generic febe-ci package created more than 14 days ago, like the
# artifact expiry of the old days.
artefatti_della_ci() {
local giorni=14 base="${GITEA_API%/}/packages/$PROPRIETARIO/generic/febe-ci" cartella esito scelte versione creata codice
echo "== Registro: gli artefatti della CI (pacchetto febe-ci) creati più di $giorni giorni fa"
cartella=$(mktemp -d) || { segnala "Non riesco a creare una cartella temporanea: gli artefatti restano."; return 0; }
esito=0
pagine "$base" "$cartella" febe-ci || esito=$?
if ((esito == 1)); then
echo " Il pacchetto febe-ci non è ancora sul registro: niente da togliere."
elif ((esito == 0)) && ! scelte=$(bash "$cartella_script/versioni-registro.sh" scadute "$giorni" "$(date +%s)" "$cartella"/pagina-*.json); then
segnala "Non riesco a leggere le versioni del pacchetto febe-ci: gli artefatti restano."
esito=3
fi
rm -rf "$cartella"
((esito == 0)) || return 0
if [[ -z "${scelte:-}" ]]; then
echo " niente da togliere"
return 0
fi
while IFS=$'\t' read -r versione creata; do
[[ -n "${versione:-}" ]] || continue
if [[ ! "$versione" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?-(ci|rilascio)\.[0-9]+$ ]]; then
segnala "Versione inattesa «$versione» fra gli artefatti da togliere: resta."
continue
fi
if ((prova)); then
echo " toglierei febe-ci $versione (caricata il $creata)"
conta "artefatti della CI sul registro"
continue
fi
codice=$(chiedi DELETE "$base/$versione" /dev/null)
if [[ "$codice" == 204 ]]; then
echo " febe-ci $versione tolta (caricata il $creata)"
conta "artefatti della CI sul registro"
else
segnala "Non riesco a togliere febe-ci $versione dal registro: l'API risponde $(spiega "$codice")."
fi
done <<< "$scelte"
}
# The cache with the same limit as on Monday: without it, every push of every branch would remove the intermediate
# layers and the mounted caches (RUN --mount=type=cache) that the builds of the other projects have just used.
penzolanti() {
echo "== Immagini senza nome che nessun contenitore usa e cache di costruzione penzolante non usata da 24 ore, di tutti i progetti"
if ((prova)); then
elenca_immagini 0 senza-nome
elenca_cache
return 0
fi
pota_immagini "immagini senza nome" docker image prune -f
pota_cache "cache di costruzione penzolante" docker builder prune -f --filter "until=24h"
}
settimanale() {
resti_della_ci
echo "== Immagini senza nome più vecchie di 72 ore che nessun contenitore usa"
if ((prova)); then
elenca_immagini 4320 senza-nome
else
pota_immagini "immagini senza nome" docker image prune -f --filter "until=72h"
fi
}
# Everything «settimanale» does (the unnamed images older than 72 hours are among those no container uses created
# more than 24 hours ago) plus the act_runner leftovers, everyone's images and cache, and the registry. Containers
# first, so that their images, volumes and networks are left with nobody using them.
completa() {
resti_della_ci
resti_di_act_runner 90
echo "== Immagini che nessun contenitore usa, create più di 24 ore fa, di tutti i progetti"
if ((prova)); then
elenca_immagini 1440 tutte
else
pota_immagini "immagini che nessun contenitore usa" docker image prune -a -f --filter "until=24h"
fi
echo "== Cache di costruzione del demone non usata da più di 24 ore"
if ((prova)); then
elenca_cache
else
pota_cache "cache di costruzione" docker builder prune -a -f --filter "until=24h"
fi
registro
}
riepilogo() {
local tipo riga
if ((prova)); then
echo "== Riepilogo della prova (che cosa toglierei; non è stato tolto nulla)"
else
echo "== Riepilogo"
fi
for tipo in "${tipi[@]}"; do
echo " $tipo: ${conteggi[$tipo]}"
done
for riga in "${note[@]}"; do
echo " $riga"
done
((${#tipi[@]} + ${#note[@]} > 0)) || echo " niente"
}
command -v docker > /dev/null || { echo "Manca il client Docker: niente da pulire." >&2; exit 2; }
((prova)) && echo "Prova: elenco che cosa toglierei, senza togliere nulla."
case "$modo" in
esecuzione) esecuzione "${argomenti[1]:-}" ;;
penzolanti) penzolanti ;;
residui) residui "${argomenti[1]:-90}" ;;
settimanale | completa)
rileva_store
docker system df || true
if [[ "$modo" == settimanale ]]; then settimanale; else completa; fi
docker system df || true
riepilogo
;;
*) uso ;;
esac
if ((problemi > 0)); then
echo "Pulizia finita con $problemi avvisi."
[[ "$modo" == settimanale || "$modo" == completa ]] && exit 1
fi
exit 0