CI: la pulizia toglie anche ciò che non serve più a nessuno

Alberto, 21/10: la pulizia della CI deve eliminare tutto quello che non
serve più, non solo ciò che la CI di Febe ha creato. pulizia-docker.sh ha
due modi nuovi. «penzolanti»: le immagini senza nome e la cache di
costruzione che nessuna immagine condivide, di tutti i progetti; un errore
è solo un avviso. «completa»: i resti della CI di Febe come prima, i resti
di act_runner (contenitori fermi, volumi e reti GITEA-ACTIONS-TASK-… che
nessuno usa), le immagini che nessun contenitore usa e la cache più
vecchie di 24 ore, e con REGISTRY_TOKEN le etichette sha- del registro
oltre le 10 più recenti. Mai system, container, volume o network prune,
mai un contenitore, un volume o una rete che non sia della CI. Con
--prova ogni modo elenca che cosa toglierebbe e non tocca nulla.

Le etichette del registro le sceglie versioni-registro.js, che si prova
con un JSON e senza rete; controlli.sh ne controlla la sintassi. Le prove
girano contro un docker e un curl finti, su un demone come quello del
runner: applicazioni di Unraid ferme, un Febe vero, il lavoro della
pulizia stessa, resti veri e finti di act_runner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-10-21 10:36:59 +02:00
1 parent 7a70b464f3
commit 0f11fc5220
8 files changed
+1753 -371

No files matched your search

+14 -1
View File
@@ -4,7 +4,8 @@
#
# bash .gitea/scripts/controlli.sh
#
# 1. ogni script di shell del repository è sintassi valida (bash -n; sh -n per quelli in sh) e ha le righe Unix;
# 1. ogni script di shell del repository è sintassi valida (bash -n; sh -n per quelli in sh) e ha le righe Unix; gli
# script Node della CI (.gitea/scripts/*.js) sono JavaScript valido (node --check);
# 2. i flussi della CI non hanno tabulazioni (YAML non le accetta come rientro);
# 3. nessun file contiene segni di conflitto rimasti da un'unione;
# 4. la versione di Directory.Build.props è nella forma x.y.z[-qualcosa], quella che installer/costruisci.sh accetta;
@@ -35,6 +36,18 @@ while IFS= read -r -d '' script; do
done < <(git ls-files -z -- '*.sh')
echo " $quanti script controllati"
echo "== Script Node della CI"
if command -v node > /dev/null; then
quanti=0
while IFS= read -r -d '' script; do
quanti=$((quanti + 1))
node --check "$script" || errore "$script: JavaScript non valido."
done < <(git ls-files -z -- '.gitea/scripts/*.js')
echo " $quanti script controllati"
else
errore "manca node: gli script Node della CI non si possono controllare."
fi
echo "== Flussi della CI"
while IFS= read -r -d '' flusso; do
if grep -n $'\t' "$flusso" > /dev/null; then
+547 -64
View File
@@ -1,12 +1,14 @@
#!/usr/bin/env bash
# Pulizia di ciò che la CI di Febe lascia sul demone Docker del runner. È lo stesso demone che costruisce Encelado,
# Mimante e gli altri progetti di Alberto, e ci può girare anche un Febe vero: si tocca solo ciò che si può provare
# creato dalla CI, più le immagini senza nome («dangling») più vecchie di tre giorni. Mai altro, e mai la cache di
# costruzione del demone (è condivisa).
# Pulizia del demone Docker del runner e del registro dei container. Il demone è lo stesso che costruisce Encelado,
# Mimante e gli altri progetti di Alberto (e molto probabilmente quello delle applicazioni di Unraid), e ci può girare
# anche un Febe vero. Dal 21 ottobre 2026 (decisione di Alberto) la pulizia toglie anche ciò che non serve più a
# nessuno, di qualunque progetto: le immagini che nessun contenitore usa, la cache di costruzione, i resti di
# act_runner. Mai un contenitore, un volume o una rete che non sia della CI.
#
# Le etichette febe.ci.workflow, febe.ci.run, febe.ci.ref e febe.ci.commit dicono da dove viene un'immagine, ma NON
# scelgono che cosa togliere: stanno anche nelle immagini pubblicate (:main, :sha-, :X.Y.Z, :latest), e Docker le copia
# in ogni contenitore creato da quelle immagini, quindi le porta anche un Febe vero. Ciò che si toglie si riconosce così:
# Della CI di Febe si toglie ciò che si può provare suo. Le etichette febe.ci.workflow, febe.ci.run, febe.ci.ref e
# febe.ci.commit dicono da dove viene un'immagine, ma NON scelgono che cosa togliere: stanno anche nelle immagini
# pubblicate (:main, :sha-, :X.Y.Z, :latest), e Docker le copia in ogni contenitore creato da quelle, quindi le porta
# anche un Febe vero. Ciò che si toglie si riconosce così:
# - contenitori di prova: l'etichetta febe.ci.prova=<esecuzione>, che mette solo prova-immagine.sh con
# «docker run --label» e che nessuna immagine porta (lo controlla PipelineTests), E il nome esatto
# febe-prova-<la stessa esecuzione> (gli altri contenitori della prova, senza nome, girano con --rm e Docker li
@@ -16,41 +18,135 @@
# - builder buildx: il contenitore buildx_buildkit_febe-ci-<esecuzione>0, con l'immagine moby/buildkit, e il suo
# volume …_state, che contengono la cache di costruzione di quell'esecuzione;
# - l'immagine febe:ci lasciata dal vecchio flusso di verifica (prima del 20 ottobre 2026), se nessuno la usa.
# Di act_runner si tolgono i resti dei lavori: act_runner chiama tutto ciò che crea per un lavoro
# GITEA-ACTIONS-TASK-<numero del compito>… (il contenitore del lavoro, i suoi volumi <nome> e <nome>-env, la sua rete
# <nome>-<lavoro>-network). Solo i contenitori fermi e i volumi e le reti che nessun contenitore usa, più vecchi di 90
# minuti: un lavoro che parte li crea e li usa subito. Il volume act-toolcache (la cache degli strumenti, condivisa fra
# i lavori) resta.
#
# pulizia-docker.sh esecuzione <id> tutto ciò che ha creato l'esecuzione <id> (all'inizio e alla fine del suo
# lavoro «immagine», sempre)
# pulizia-docker.sh penzolanti le immagini senza nome che nessun contenitore usa e la cache di costruzione
# penzolante del demone (quella che nessuna immagine condivide), di tutti i
# progetti (alla fine di ogni lavoro «immagine», dopo «esecuzione»)
# pulizia-docker.sh residui [minuti] i resti di esecuzioni interrotte, più vecchi di N minuti (predefinito 90: un
# lavoro dura al massimo 60 minuti, quindi nessuno di essi è ancora vivo)
# pulizia-docker.sh settimanale residui, febe:ci, immagini senza nome più vecchie di 72 ore (flusso «pulizia»)
# pulizia-docker.sh settimanale residui, febe:ci, immagini senza nome più vecchie di 72 ore: la pulizia
# stretta di prima del 21 ottobre 2026, ora solo a mano
# pulizia-docker.sh completa residui, febe:ci, resti di act_runner, le immagini che nessun contenitore
# usa create più di 24 ore fa, la cache di costruzione non usata da 24 ore e,
# con REGISTRY_TOKEN, le etichette sha- del registro oltre le 10 più recenti
# (flusso «pulizia», ogni lunedì e a mano)
# pulizia-docker.sh <modo> --prova elenca che cosa toglierebbe e non toglie nulla: solo comandi che leggono
# (sul registro solo GET)
#
# Nei modi «residui» e «settimanale» un contenitore di prova si toglie solo se è fermo. Uno ancora acceso dopo 90 minuti
# (il suo lavoro è stato ucciso proprio durante la prova del contenitore) resta dov'è: lo si segnala, con il comando per
# toglierlo a mano. I builder sono l'eccezione: sono sempre accesi e la loro cache se ne va solo togliendo il
# contenitore; si riconoscono dal nome esatto e dall'immagine di buildkit, mai da un'etichetta.
# Mai docker system prune, container prune, volume prune o network prune; mai image prune -a o builder prune -a senza
# il filtro delle 24 ore; mai un contenitore, un volume o una rete che non sia della CI. Le immagini le toglie Docker
# stesso (image prune), che non tocca mai un'immagine usata da un contenitore, nemmeno fermo. Sul registro mai main,
# latest o una versione X.Y.Z: solo le etichette sha-<esadecimale> della verifica.
#
# Un oggetto già sparito non è un errore: la pulizia si può ripetere. Nei modi «esecuzione» e «residui» un problema
# diventa un avviso (un lavoro verde non diventa rosso per la pulizia, che il flusso settimanale ripete); nel modo
# «settimanale» fa fallire il lavoro, perché qualcuno lo guardi.
# Nei modi «residui», «settimanale» e «completa» un contenitore di prova si toglie solo se è fermo. Uno ancora acceso
# dopo 90 minuti (il suo lavoro è stato ucciso proprio durante la prova del contenitore) resta dov'è: lo si segnala, con
# il comando per toglierlo a mano. I builder sono l'eccezione: sono sempre accesi e la loro cache se ne va solo
# togliendo il contenitore; si riconoscono dal nome esatto e dall'immagine di buildkit, mai da un'etichetta.
#
# Un oggetto già sparito non è un errore: la pulizia si può ripetere. Nei modi «esecuzione», «penzolanti» e «residui»
# un problema diventa un avviso (un lavoro verde non diventa rosso per la pulizia, che il flusso del lunedì ripete); nei
# modi «settimanale» e «completa» fa fallire il lavoro, perché qualcuno lo guardi. Il registro è l'eccezione: un
# rifiuto della sua API è solo un avviso, e il lunedì dopo si riprova.
#
# Variabili per il registro (modo «completa»): REGISTRY_TOKEN (token con «package: read and write», mai stampato),
# GITEA_API (l'API del server, per esempio https://gitea.example/api/v1) e PROPRIETARIO (il proprietario del pacchetto
# febe). La scelta delle versioni da togliere sta in versioni-registro.js, accanto a questo script.
set -uo pipefail
modo="${1:-}"
prova=0
argomenti=()
for argomento in "$@"; do
case "$argomento" in
--prova) prova=1 ;;
*) argomenti+=("$argomento") ;;
esac
done
modo="${argomenti[0]:-}"
cartella_script="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
problemi=0
# In prova: i contenitori (identificativo e nome) e i nomi di immagine che la pulizia vera toglierebbe, perché gli
# elenchi che seguono li trattino come già tolti (un volume usato solo da un contenitore che se ne andrebbe, per
# esempio, se ne andrebbe anche lui).
previsti=()
nomi_previsti=()
# Per il riepilogo: quanti oggetti per tipo, nell'ordine in cui compaiono, e lo spazio recuperato da Docker.
declare -A conteggi=()
tipi=()
note=()
# La cache di costruzione che si pota è quella del builder del demone, «default». docker builder è un alias di docker
# buildx quando c'è il plugin, e buildx lavora sul builder corrente: nel lavoro «immagine» è quello dell'esecuzione
# (setup-buildx-action lo crea con --use), che il modo «esecuzione» ha appena tolto. Gli altri comandi buildx di questo
# script indicano il builder per nome.
export BUILDX_BUILDER=default
avviso() {
echo "::warning::$*"
problemi=$((problemi + 1))
}
# Minuti trascorsi da un istante RFC 3339 (il campo Created di docker inspect). Se non si legge, 0: nel dubbio
# l'oggetto è giovane e resta.
# Un avviso che non fa diventare rosso il lavoro: per il registro.
segnala() {
echo "::warning::$*"
}
conta() {
[[ -n "${conteggi[$1]+x}" ]] || tipi+=("$1")
conteggi[$1]=$((${conteggi[$1]:-0} + 1))
}
# Vero se la prima parola è fra quelle che seguono.
fra() {
local cercata="$1" voce
shift
for voce in "$@"; do
[[ "$voce" == "$cercata" ]] && return 0
done
return 1
}
# Minuti trascorsi da un istante RFC 3339 come lo scrive Docker (Created di un contenitore o di un'immagine, CreatedAt
# di un volume, {{json .Created}} di una rete, fra virgolette), con o senza frazioni di secondo, con «Z» o con lo scarto
# dall'ora universale (+02:00). Se non si legge, 0: nel dubbio l'oggetto è giovane e resta.
eta_minuti() {
local creato="${1%%.*}"
creato="${creato%Z}"
local secondi
secondi=$(date -u -d "${creato}Z" +%s 2>/dev/null) || { echo 0; return; }
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
}
# Fra i contenitori dati (identificativi, uno per riga), quelli che restano dopo questa pulizia: in prova senza quelli
# che la pulizia vera toglierebbe.
restanti() {
local id
while read -r id; do
[[ -n "$id" ]] || continue
fra "$id" "${previsti[@]}" || echo "$id"
done <<< "${1:-}"
}
# I contenitori di prova della CI, uno per riga «id nome»: l'etichetta febe.ci.prova (dell'esecuzione indicata, o di
# qualunque se il primo argomento è vuoto) e il nome esatto febe-prova-<valore dell'etichetta>. Gli stati che seguono
# restringono la scelta (Docker li unisce in OR). Esce con 1 se Docker non risponde.
@@ -68,33 +164,46 @@ contenitori_di_prova() {
done <<< "$elenco"
}
# Toglie un contenitore con i suoi volumi anonimi. Con «forza» anche se è acceso: solo per quelli dell'esecuzione
# stessa e per i builder.
# Toglie un contenitore con i suoi volumi anonimi (in prova lo elenca soltanto). Con «forza» anche se è acceso: solo
# per quelli dell'esecuzione stessa e per i builder. Esce con 0 se il contenitore se ne va (o se ne andrebbe).
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"
elif docker container inspect "$id" > /dev/null 2>&1; then
avviso "Non riesco a togliere il contenitore $nome."
return 0
fi
docker container inspect "$id" > /dev/null 2>&1 && avviso "Non riesco a togliere il contenitore $nome."
return 1
}
# Toglie il nome locale febe-ci:<esecuzione>, mai l'immagine per identificativo e mai con -f: se l'immagine ha anche un
# altro nome (del registro, per esempio) quello resta; se un contenitore la usa, resta tutto.
# Toglie il nome locale febe-ci:<esecuzione> (o febe:ci), mai l'immagine per identificativo e mai con -f: se l'immagine
# ha anche un altro nome (del registro, per esempio) quello resta; se un contenitore la usa, resta tutto.
togli_immagine() {
local riferimento="$1" nomi
[[ "$riferimento" =~ ^febe-ci:[0-9]+$ ]] || { avviso "Nome di immagine inatteso: «$riferimento»."; return 0; }
nomi=$(docker image inspect -f '{{len .RepoTags}}' "$riferimento" 2>/dev/null) || return 0
if [[ "$nomi" == 1 && -n "$(docker ps -a -q --filter "ancestor=$riferimento")" ]]; then
[[ "$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"
else
avviso "Non riesco a togliere l'immagine $riferimento."
return 0
fi
avviso "Non riesco a togliere l'immagine $riferimento."
return 1
}
# Un builder buildx della CI: prima con buildx (se questo client lo conosce), poi contenitore e volume per nome, perché
@@ -102,24 +211,76 @@ togli_immagine() {
# l'immagine di buildkit, e il volume solo quando il contenitore non c'è più.
togli_builder() {
local builder="$1"
[[ "$builder" =~ ^febe-ci-[0-9]+$ ]] || { avviso "Nome di builder inatteso: «$builder»."; return 0; }
docker buildx rm -f "$builder" > /dev/null 2>&1 && echo " builder $builder tolto"
local contenitore="buildx_buildkit_${builder}0" immagine
if immagine=$(docker container inspect -f '{{.Config.Image}}' "$contenitore" 2>/dev/null); then
[[ "$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 0
return 1
fi
togli_contenitore "$contenitore" "$contenitore" forza && esito=0
if ((!prova)) && docker container inspect "$contenitore" > /dev/null 2>&1; then
return 1
fi
togli_contenitore "$contenitore" "$contenitore" forza
docker container inspect "$contenitore" > /dev/null 2>&1 && return 0
fi
if docker volume inspect "${contenitore}_state" > /dev/null 2>&1; then
if docker volume rm -f "${contenitore}_state" > /dev/null 2>&1; then
echo " volume ${contenitore}_state tolto"
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 ${contenitore}_state."
avviso "Non riesco a togliere il volume $volume."
fi
fi
return "$esito"
}
# Un volume o una rete di act_runner. Docker stesso non toglie un volume che un contenitore usa, né una rete con un
# contenitore acceso collegato.
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
}
# Vero se nessun contenitore, acceso o fermo, usa il volume o la rete (in prova: nessuno che la pulizia vera
# lascerebbe). Nel dubbio (Docker non risponde) falso: resta.
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() {
@@ -141,15 +302,15 @@ esecuzione() {
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, più vecchi di $minuti minuti"
local elenco id nome eta riferimento
echo "== Resti di esecuzioni interrotte della CI di Febe, più vecchi di $minuti minuti"
local elenco id nome eta riferimento builder
# Contenitori di prova fermi: si tolgono. Senza -f: se nel frattempo uno ripartisse, Docker lo lascia stare.
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"
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."
@@ -159,7 +320,7 @@ residui() {
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)")
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
@@ -172,8 +333,8 @@ residui() {
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"
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."
@@ -185,42 +346,364 @@ residui() {
[[ -n "${id:-}" ]] || continue
nome="${nome#/}"
[[ "$nome" =~ ^buildx_buildkit_(febe-ci-[0-9]+)0$ ]] || continue
eta=$(eta_minuti "$(docker container inspect -f '{{.Created}}' "$id" 2>/dev/null)")
((eta >= minuti)) && togli_builder "${BASH_REMATCH[1]}"
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
}
settimanale() {
# I resti della CI di Febe e l'immagine febe:ci del vecchio flusso (modi «settimanale» e «completa»).
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
# Senza -f: se un contenitore la usa resta dov'è.
docker image rm febe:ci > /dev/null 2>&1 && echo " febe:ci tolta" || echo " febe:ci è in uso: resta"
togli_immagine febe:ci && conta "immagini febe-ci"
fi
echo "== Immagini senza nome più vecchie di 72 ore"
docker image prune -f --filter "until=72h" || avviso "La pulizia delle immagini senza nome non è riuscita."
}
# act_runner chiama i suoi oggetti GITEA-ACTIONS-TASK-<numero del compito>, seguito da «_WORKFLOW-…» o, nelle versioni
# più vecchie, da «-WORKFLOW-…» con un'impronta in fondo.
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"
# Contenitori fermi. Il filtro per nome di Docker cerca una parte del nome: l'inizio esatto si controlla qui. Senza
# -f: Docker non toglie un contenitore acceso.
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
# Volumi che nessun contenitore usa, nemmeno fermo.
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
# Reti a cui nessun contenitore è collegato, nemmeno fermo. Created di una rete è un istante di Go, che il modello
# stampa come «2026-10-21 06:17:03 +0200 CEST»: in JSON è 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
}
# Le immagini (identificativo) dei contenitori, accesi o fermi, tranne quelli che la pulizia toglierebbe. Solo
# lettura: serve all'elenco della prova.
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}}' "$id" 2> /dev/null
done <<< "$elenco"
return 0
}
# In prova: le immagini che la potatura toglierebbe, con dimensione ed età. Nessun contenitore le usa (a parte quelli
# che questa pulizia toglierebbe) e sono state create più di N minuti fa; con «senza-nome» solo quelle senza nome. È
# una stima fatta qui: nella pulizia vera decide Docker (image prune).
elenca_immagini() {
local minimo="$1" quali="$2" usate elenco id nome breve dimensione eta quante=0
local -A nomi=() dimensioni=() aveva_nomi=()
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
while IFS='|' read -r id nome dimensione; do
[[ -n "${id:-}" ]] || continue
if [[ -z "${dimensioni[$id]+x}" ]]; then
ordine+=("$id")
dimensioni[$id]="${dimensione:-?}"
nomi[$id]=""
fi
[[ "$nome" == "<none>:<none>" ]] && continue
aveva_nomi[$id]=1
fra "$nome" "${nomi_previsti[@]}" && continue
nomi[$id]="${nomi[$id]:+${nomi[$id]}, }$nome"
done <<< "$elenco"
for id in "${ordine[@]}"; do
# Un'immagine i cui nomi la pulizia toglie qui sopra se ne va già con l'ultimo.
[[ -n "${aveva_nomi[$id]:-}" && -z "${nomi[$id]}" ]] && continue
[[ "$quali" == senza-nome && -n "${aveva_nomi[$id]:-}" ]] && continue
grep -qxF -- "$id" <<< "$usate" && 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"
breve="${id#sha256:}"
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 prova: quanta cache di costruzione ha il demone. Quanta ne toglierebbe la potatura Docker non lo dice senza
# toglierla: al più quella che nessuno sta usando («RECLAIMABLE» di 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")
}
numero_immagini() {
docker image ls --no-trunc --format '{{.ID}}' 2> /dev/null | sort -u | grep -c .
}
# Lo spazio recuperato secondo Docker: «Total reclaimed space: 1.2GB» (docker) o «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}"
}
# Una potatura di immagini di Docker: i nomi tolti, quante immagini e quanto spazio. Un errore è un avviso.
pota_immagini() {
local cosa="$1" uscita prima dopo recuperato
shift
prima=$(numero_immagini)
if ! uscita=$("$@" 2>&1); then
avviso "Non riesco a togliere le $cosa: $(tail -n 1 <<< "$uscita")"
return 0
fi
grep '^untagged: ' <<< "$uscita" | grep -v '@sha256:' | sed 's/^untagged: / tolta /'
dopo=$(numero_immagini)
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
}
# Una potatura della cache di costruzione: quanto spazio. Un errore è un avviso.
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")
}
# Una chiamata all'API di Gitea con il token del registro, che sta solo nell'intestazione di curl e mai nel registro
# del lavoro. Stampa il codice HTTP: 000 se Gitea non risponde.
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
}
# Le etichette sha- del pacchetto febe oltre le 10 più recenti, con l'API dei pacchetti di Gitea 28:
# GET /api/v1/packages/{proprietario}/container/febe?page=N&limit=50 le versioni, una pagina alla volta finché
# ne arriva una vuota (il server può darne
# meno di 50 per pagina)
# DELETE /api/v1/packages/{proprietario}/container/febe/{versione} una versione (risponde 204)
# Quali togliere lo sceglie versioni-registro.js; qui si ricontrolla la forma sha-<esadecimale> prima di ogni DELETE.
# Ogni rifiuto dell'API è un avviso che non fa diventare rosso il lavoro.
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 node; 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 pagina codice scelte
cartella=$(mktemp -d) || { segnala "Non riesco a creare una cartella temporanea: il registro non si tocca."; return 0; }
for ((pagina = 1; ; pagina++)); do
if ((pagina > 200)); then
segnala "Più di 200 pagine di versioni sul registro: il registro non si tocca."
rm -rf "$cartella"
return 0
fi
codice=$(chiedi GET "$base?page=$pagina&limit=50" "$cartella/pagina-$pagina.json")
if [[ "$codice" == 404 && "$pagina" == 1 ]]; then
echo " Il pacchetto febe non è ancora sul registro: niente da togliere."
rm -rf "$cartella"
return 0
fi
if [[ "$codice" != 200 ]]; then
segnala "L'API dei pacchetti di Gitea risponde $(spiega "$codice") alla pagina $pagina delle versioni: il registro non si tocca."
rm -rf "$cartella"
return 0
fi
case "$(tr -d '[:space:]' < "$cartella/pagina-$pagina.json")" in
"[]" | null) break ;;
esac
done
if ! scelte=$(node "$cartella_script/versioni-registro.js" "$tenere" "$cartella"/pagina-*.json); then
segnala "Non riesco a leggere le versioni del pacchetto febe: il registro non si tocca."
rm -rf "$cartella"
return 0
fi
rm -rf "$cartella"
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"
}
penzolanti() {
echo "== Immagini senza nome che nessun contenitore usa e cache di costruzione penzolante, 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
}
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
}
# Tutto ciò che fa «settimanale» (le immagini senza nome più vecchie di 72 ore sono fra quelle che nessun contenitore
# usa create più di 24 ore fa) e in più i resti di act_runner, le immagini e la cache di tutti e il registro. Prima i
# contenitori, così le loro immagini, i loro volumi e le loro reti restano senza nessuno che li usi.
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 "${2:-}" ;;
residui) residui "${2:-90}" ;;
settimanale)
esecuzione) esecuzione "${argomenti[1]:-}" ;;
penzolanti) penzolanti ;;
residui) residui "${argomenti[1]:-90}" ;;
settimanale | completa)
docker system df || true
settimanale
if [[ "$modo" == settimanale ]]; then settimanale; else completa; fi
docker system df || true
riepilogo
;;
*)
echo "Uso: $0 esecuzione <id> | residui [minuti] | settimanale" >&2
echo "Uso: $0 esecuzione <id> | penzolanti | residui [minuti] | settimanale | completa [--prova]" >&2
exit 2
;;
esac
if ((problemi > 0)); then
echo "Pulizia finita con $problemi avvisi."
[[ "$modo" == settimanale ]] && exit 1
[[ "$modo" == settimanale || "$modo" == completa ]] && exit 1
fi
exit 0
+59
View File
@@ -0,0 +1,59 @@
"use strict";
// Scelta delle etichette da togliere dal registro dei container di Gitea (pulizia-docker.sh, modo «completa»). Legge,
// non scrive e non chiama nessuno: si prova con un file JSON, senza rete.
//
// node versioni-registro.js <quante tenere> <pagina.json>...
//
// Ogni file è una pagina della risposta di GET /api/v1/packages/{proprietario}/container/febe di Gitea 28: un elenco di
// versioni con «type», «name», «version» e «created_at» (una pagina vuota può essere «[]» o «null»). Stampa, dalla più
// vecchia e una per riga, «versione<TAB>creata» delle sole etichette sha-<da 7 a 40 cifre esadecimali> del pacchetto
// container «febe» oltre le N più recenti per data di creazione. Tutto il resto resta sempre: main, latest, le
// versioni X.Y.Z (anche X.Y.Z-rc.N), i digest (sha256:…), qualunque altra etichetta e una sha- senza una data che si
// legga. Una versione che compare in due pagine conta una volta. Se un file non è un elenco JSON esce con 2 e non
// stampa nulla: nel dubbio non si toglie niente.
const fs = require("fs");
const [tenere, ...pagine] = process.argv.slice(2);
if (!/^[0-9]+$/.test(tenere || "") || pagine.length === 0) {
console.error("Uso: node versioni-registro.js <quante tenere> <pagina.json>...");
process.exit(2);
}
const etichettaSha = /^sha-[0-9a-f]{7,40}$/;
const versioni = new Map();
for (const file of pagine) {
let pagina;
try {
pagina = JSON.parse(fs.readFileSync(file, "utf8").replace(/^/, ""));
} catch (errore) {
console.error(`${file}: ${errore.message}`);
process.exit(2);
}
if (pagina === null) {
continue;
}
if (!Array.isArray(pagina)) {
console.error(`${file}: non è un elenco di versioni`);
process.exit(2);
}
for (const versione of pagina) {
if (versione && versione.type === "container" && versione.name === "febe" && typeof versione.version === "string") {
versioni.set(versione.version, versione);
}
}
}
const candidate = [...versioni.values()]
.filter((versione) => etichettaSha.test(versione.version))
.map((versione) => ({
nome: versione.version,
creata: String(versione.created_at),
quando: Date.parse(versione.created_at),
id: Number(versione.id) || 0,
}))
.filter((versione) => Number.isFinite(versione.quando))
.sort((a, b) => b.quando - a.quando || b.id - a.id);
for (const versione of candidate.slice(Number(tenere)).reverse()) {
process.stdout.write(`${versione.nome}\t${versione.creata}\n`);
}
@@ -0,0 +1,743 @@
using System.Diagnostics;
using System.Text.Json;
using System.Text.RegularExpressions;
using Febe.Tests.Desktop.Support;
using Febe.Tests.Support;
namespace Febe.Tests.Packaging;
/// <summary>
/// The cleanup of the CI: .gitea/scripts/pulizia-docker.sh, its choice of registry tags (versioni-registro.js) and the
/// steps that run it. The Docker daemon is shared with Alberto's other projects, very likely with his Unraid apps, and
/// may run a real Febe. Since 21 October 2026 the cleanup removes what the CI of Febe made and what nothing uses any
/// more, of any project; never a container, a volume or a network that is not the CI's, never main, latest or a
/// release on the registry, never the token in the log; with --prova it removes nothing at all. The script runs against
/// a fake docker client (fake-docker.sh) and a fake curl (fake-curl.sh): no daemon, no network.
/// </summary>
public sealed partial class PipelineTests
{
private const string RegistryApi = "http://gitea.invalid/api/v1";
// Low entropy on purpose: gitleaks reads every commit, and a fake value shaped like a token would look like one.
private const string RegistryToken = "gettone-finto-gettone-finto";
/// <summary>The tags versioni-registro.json leaves to the cleanup once the ten newest sha- are kept, oldest first.</summary>
private static readonly string[] OldShaTags = ["sha-0a1b2c3", "sha-1b2c3d4", "sha-2c3d4e5", "sha-4e5f6a7"];
[TestMethod]
public void TheCleanupNeverPrunesBlindlyAndChoosesOnlyByTheMarksOfTheCiOrByUse()
{
var cleanup = Code(Script("pulizia-docker.sh"));
foreach (var forbidden in new[] { "system prune", "container prune", "volume prune", "network prune", "prune --all", "image prune -f -a", "builder prune -f -a" })
{
Assert.DoesNotContain(forbidden, cleanup, "the daemon is shared with Alberto's other projects and his Unraid apps");
}
// Only these prunes: what nothing uses after every run, the narrow weekly of before, and in the complete
// cleanup every unused image and all the cache, but only with the filter of 24 hours.
string[] allowed =
[
"image prune -f",
"image prune -f --filter \"until=72h\"",
"image prune -a -f --filter \"until=24h\"",
"builder prune -f",
"builder prune -a -f --filter \"until=24h\"",
];
CollectionAssert.AreEquivalent(allowed, Prune().Matches(cleanup).Select(m => $"{m.Groups["what"].Value} prune{m.Groups["args"].Value.TrimEnd()}").Distinct().ToList());
StringAssert.Contains(cleanup, "export BUILDX_BUILDER=default", "the cache pruned is the daemon's, not the builder of the run, which is gone by then");
// The febe.ci.* labels of the image are in every container made from a published image, a real Febe too: they
// never choose what goes. Containers are listed for removal only by a mark of the CI (the label of the tried
// containers with their exact name, the name of Febe's builders, the name act_runner gives its jobs); who uses
// an image, a volume or a network is asked only to keep it; the one listing of every container reads.
Assert.IsFalse(ProvenanceLabelFilter().IsMatch(cleanup), "the cleanup filters on febe.ci.prova only");
var readsOnly = Function(cleanup, "immagini_in_uso");
Assert.IsFalse(Removal().IsMatch(readsOnly), "immagini_in_uso only reads");
foreach (var line in cleanup.Split('\n').Where(l => l.Contains("docker ps", StringComparison.Ordinal)))
{
var marked = new[] { "--filter \"label=febe.ci.prova", "--filter \"name=buildx_buildkit_febe-ci-\"", "--filter \"name=GITEA-ACTIONS-TASK-\"", "--filter \"ancestor=", "--filter \"volume=", "--filter \"network=" }
.Any(filter => line.Contains(filter, StringComparison.Ordinal));
Assert.IsTrue(marked || readsOnly.Contains(line, StringComparison.Ordinal), $"«{line.Trim()}» lists containers without a mark of the CI");
}
StringAssert.Contains(cleanup, "\"febe-prova-$valore\"", "the name must match the mark");
StringAssert.Contains(cleanup, "contenitori_di_prova \"\" exited created dead", "the sweeps take only stopped tried containers");
StringAssert.Contains(cleanup, "^buildx_buildkit_(febe-ci-[0-9]+)0$");
StringAssert.Contains(cleanup, "nome_act='^GITEA-ACTIONS-TASK-[0-9]+[-_]'", "act_runner's objects start with the task");
StringAssert.Contains(cleanup, "togli_contenitore \"$id\" \"$nome\" && conta \"contenitori fermi di act_runner\"", "act_runner's containers go without -f: Docker keeps a running one");
StringAssert.Contains(cleanup, "docker volume rm \"$nome\"", "act_runner's volumes go without -f");
Assert.IsFalse(ForcedImageRemoval().IsMatch(cleanup), "an image is never removed by force");
StringAssert.Contains(cleanup, "[[ \"$riferimento\" =~ ^febe-ci:[0-9]+$ ]]");
// On the registry only the shape of a sha- tag of the verification, checked again before every DELETE.
StringAssert.Contains(cleanup, "[[ ! \"$versione\" =~ ^sha-[0-9a-f]{7,40}$ ]]");
StringAssert.Contains(Script("versioni-registro.js"), "/^sha-[0-9a-f]{7,40}$/");
}
[TestMethod]
[Timeout(300_000, CooperativeCancellation = true)]
public async Task OnADaemonSharedWithARealFebeTheCleanupOfTheCiTakesOnlyWhatTheCiMade()
{
var bash = RequireBash();
// At the start or the end of a run (a release run again keeps its id, so the published image has the same
// febe.ci.run as the run): only the tried container, the local name and the builder of that run.
var run = await RunCleanupAsync(bash, FakeDaemon.WorldOf(FakeDaemon.Full), "esecuzione", "777");
Assert.AreEqual(0, run.Code, run.Report);
Assert.DoesNotContain("::warning::", run.Output, run.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Full).Except(["c-prova-777", "b-777"]).ToList(), run.Containers, run.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777(), run.Images, run.Report);
CollectionAssert.AreEquivalent(FakeDaemon.Volumes.Except(["buildx_buildkit_febe-ci-7770_state"]).ToList(), run.Volumes, run.Report);
// Leftovers of interrupted runs: stopped tried containers, febe-ci images and builders older than 90 minutes.
var leftovers = await RunCleanupAsync(bash, FakeDaemon.WorldOf(FakeDaemon.Full), "residui", "90");
Assert.AreEqual(0, leftovers.Code, leftovers.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Full).Except(["c-prova-555", "b-vecchio"]).ToList(), leftovers.Containers, leftovers.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777("img-ci555"), leftovers.Images, leftovers.Report);
CollectionAssert.AreEquivalent(FakeDaemon.Volumes.Except(["buildx_buildkit_febe-ci-4560_state"]).ToList(), leftovers.Volumes, leftovers.Report);
StringAssert.Contains(leftovers.Output, "::warning::Il contenitore di prova febe-prova-556 è acceso", "a running tried container is reported, not removed");
StringAssert.Contains(leftovers.Output, "::warning::Il contenitore buildx_buildkit_febe-ci-4570 non è un builder buildx", leftovers.Report);
// The narrow weekly cleanup of before, on a daemon without anything odd: the same, the old febe:ci and the
// dangling images older than 72 hours that no container uses. Green.
var weekly = await RunCleanupAsync(bash, FakeDaemon.WorldOf(FakeDaemon.Clean), "settimanale");
Assert.AreEqual(0, weekly.Code, weekly.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Clean).Except(["c-prova-555", "b-vecchio"]).ToList(), weekly.Containers, weekly.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777("img-ci555", "img-ci556", "img-legacy", "img-penzolante-vecchia"), weekly.Images, weekly.Report);
// With something left for a person to look at, the weekly cleanup goes red.
var noticed = await RunCleanupAsync(bash, FakeDaemon.WorldOf(FakeDaemon.Full), "settimanale");
Assert.AreEqual(1, noticed.Code, noticed.Report);
CollectionAssert.Contains(noticed.Containers, "c-prova-556");
CollectionAssert.Contains(noticed.Containers, "c-febe-vero");
}
[TestMethod]
[Timeout(300_000, CooperativeCancellation = true)]
public async Task AfterEveryRunOnlyWhatNobodyUsesGoesAndADaemonThatRefusesIsOnlyAWarning()
{
var bash = RequireBash();
var run = await RunCleanupAsync(bash, SharedDaemon.World, "penzolanti");
Assert.AreEqual(0, run.Code, run.Report);
Assert.DoesNotContain("::warning::", run.Output, run.Report);
// Images without a name that no container uses, of any age; never one with a name, never one a stopped
// container uses. Containers, volumes and networks stay as they are.
CollectionAssert.AreEquivalent(SharedDaemon.ImageIds.Except(["img-plex-precedente", "img-penzolante-giovane"]).ToList(), run.ImageIds, run.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(SharedDaemon.Containers), run.Containers, run.Report);
CollectionAssert.AreEquivalent(SharedDaemon.VolumeNames, run.Volumes, run.Report);
CollectionAssert.AreEquivalent(SharedDaemon.NetworkNames, run.Networks, run.Report);
CollectionAssert.Contains(run.Calls, "BUILDX_BUILDER=default docker image prune -f");
CollectionAssert.Contains(run.Calls, "BUILDX_BUILDER=default docker builder prune -f", "the dangling cache of the daemon's builder, without -a");
// A daemon that refuses: two warnings, and the job of the run stays green.
var refused = await RunCleanupAsync(bash, SharedDaemon.World with { Broken = ["image prune", "builder prune"] }, "penzolanti");
Assert.AreEqual(0, refused.Code, refused.Report);
Assert.HasCount(2, WarningLine().Matches(refused.Output), refused.Report);
CollectionAssert.AreEquivalent(SharedDaemon.ImageIds, refused.ImageIds, refused.Report);
}
[TestMethod]
[Timeout(300_000, CooperativeCancellation = true)]
public async Task TheCompleteCleanupTakesWhatNobodyUsesAndNeverAContainerVolumeOrNetworkOfAnotherProject()
{
var bash = RequireBash();
var run = await RunCleanupAsync(bash, SharedDaemon.World, "completa");
Assert.AreEqual(0, run.Code, run.Report);
Assert.DoesNotContain("::warning::", run.Output, run.Report);
CollectionAssert.AreEquivalent(SharedDaemon.ContainersLeft, run.Containers, run.Report);
CollectionAssert.AreEquivalent(SharedDaemon.ImagesLeft, run.ImageIds, run.Report);
CollectionAssert.AreEquivalent(SharedDaemon.VolumesLeft, run.Volumes, run.Report);
CollectionAssert.AreEquivalent(SharedDaemon.NetworksLeft, run.Networks, run.Report);
// Not even an attempt on what is not the CI's (Docker would refuse some of it: the script must not ask), and
// the prunes of everyone only with their filter, once.
foreach (var call in run.Calls)
{
var target = RemovalTarget().Match(call);
if (target.Success)
{
CollectionAssert.Contains(SharedDaemon.Removed, target.Groups["target"].Value, call);
}
}
Assert.HasCount(1, run.Calls.Where(c => c == "BUILDX_BUILDER=default docker image prune -a -f --filter until=24h"), run.Report);
Assert.HasCount(1, run.Calls.Where(c => c == "BUILDX_BUILDER=default docker builder prune -a -f --filter until=24h"), run.Report);
Assert.HasCount(2, run.Calls.Where(c => c.EndsWith("docker system df", StringComparison.Ordinal)), "before and after");
// Without the secret the registry is not touched, and the summary says what went.
StringAssert.Contains(run.Output, " Manca il segreto REGISTRY_TOKEN: il registro non si tocca.");
Assert.IsEmpty(run.RegistryCalls, run.Report);
StringAssert.Contains(run.Output, "== Riepilogo\n");
Assert.AreEqual("2", SummaryCount(run.Output, "contenitori fermi di act_runner"), run.Report);
Assert.AreEqual("4", SummaryCount(run.Output, "volumi di act_runner"), run.Report);
Assert.AreEqual("2", SummaryCount(run.Output, "reti di act_runner"), run.Report);
Assert.AreEqual("4", SummaryCount(run.Output, "immagini che nessun contenitore usa"), run.Report);
// Something left for a person to look at (a tried container still running) turns it red, as before.
var noticed = await RunCleanupAsync(bash, SharedDaemon.World with { Containers = [.. SharedDaemon.Containers, "c-prova-556|febe-prova-556|running|300|febe-ci:556|img-rilascio|febe.ci.prova=556"] }, "completa");
Assert.AreEqual(1, noticed.Code, noticed.Report);
CollectionAssert.Contains(noticed.Containers, "c-prova-556");
}
[TestMethod]
[Timeout(300_000, CooperativeCancellation = true)]
public async Task TheDryRunListsWhatTheCleanupWouldTakeAndTouchesNothing()
{
var bash = RequireBash();
RequireNode();
var world = SharedDaemon.World with { Registry = new FakeRegistry(RegistryToken) };
var tried = await RunCleanupAsync(bash, world, "completa", "--prova");
Assert.AreEqual(0, tried.Code, tried.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(SharedDaemon.Containers), tried.Containers, tried.Report);
CollectionAssert.AreEquivalent(SharedDaemon.ImageIds, tried.ImageIds, tried.Report);
CollectionAssert.AreEquivalent(SharedDaemon.VolumeNames, tried.Volumes, tried.Report);
CollectionAssert.AreEquivalent(SharedDaemon.NetworkNames, tried.Networks, tried.Report);
foreach (var call in tried.Calls)
{
Assert.IsFalse(Destructive().IsMatch(call), $"the dry run called «{call}»");
}
Assert.IsTrue(tried.RegistryCalls.Count > 0 && tried.RegistryCalls.All(c => c.StartsWith("GET ", StringComparison.Ordinal)), tried.Report);
Assert.IsEmpty(tried.Deleted, tried.Report);
Assert.DoesNotContain(RegistryToken, tried.Output + tried.Errors, "the token never reaches the log");
// What it lists, with size and age: also what becomes unused once the leftovers it lists are gone.
foreach (var expected in new[]
{
"Prova: elenco che cosa toglierei, senza togliere nulla.",
" toglierei il contenitore febe-prova-555\n",
" toglierei il contenitore GITEA-ACTIONS-TASK-53_WORKFLOW-verifica_JOB-prove\n",
" toglierei il volume GITEA-ACTIONS-TASK-53_WORKFLOW-verifica_JOB-prove-env\n",
" toglierei la rete GITEA-ACTIONS-TASK-53_WORKFLOW-verifica_JOB-prove-prove-network\n",
" toglierei 192.168.30.23:3000/alby96/febe:0.0.9 (img-febe-vec) · 400MB · creata 34 giorni fa\n",
" toglierei node:24-trixie (img-node) · 410MB · creata 13 giorni fa\n",
" toglierei un'immagine senza nome (img-plex-pre) · 300MB · creata 69 giorni fa\n",
"la cache di costruzione del demone occupa 5.3GB",
" toglierei sha-4e5f6a7 (pubblicata il 2026-10-05T01:00:00+02:00)\n",
"== Riepilogo della prova",
})
{
StringAssert.Contains(tried.Output, expected, tried.Report);
}
foreach (var kept in new[] { "plexinc/pms-docker", "encelado:latest", "mimante:latest", "runner-images", "moby/buildkit", "act-toolcache", "encelado-dati", "febe:latest", "toglierei main", "toglierei latest", "toglierei 0.1.", "GITEA-ACTIONS-TASK-90", "GITEA-ACTIONS-TASK-60", "GITEA-ACTIONS-TASK-88", "GITEA-ACTIONS-TASK-89", "GITEA-ACTIONS-TASK-77" })
{
Assert.DoesNotContain(kept, tried.Output, tried.Report);
}
// And it counts what the real cleanup then takes.
var real = await RunCleanupAsync(bash, world, "completa");
Assert.AreEqual(0, real.Code, real.Report);
foreach (var kind in new[] { "contenitori di prova della CI di Febe", "immagini febe-ci", "builder buildx della CI di Febe", "contenitori fermi di act_runner", "volumi di act_runner", "reti di act_runner", "immagini che nessun contenitore usa", "etichette sha- sul registro" })
{
Assert.AreEqual(SummaryCount(real.Output, kind), SummaryCount(tried.Output, kind), $"{kind}\n{tried.Report}\n{real.Report}");
}
}
[TestMethod]
[Timeout(60_000, CooperativeCancellation = true)]
public async Task TheRegistryKeepsMainLatestTheReleasesAndTheTenNewestShaTags()
{
var node = RequireNode();
var script = CiPath("scripts", "versioni-registro.js");
using var folder = new TempFolder("febe-registro");
var pages = await WriteRegistryPagesAsync(folder.Path);
// Of fourteen sha- tags the four oldest go. sha-3d4e5f6 (23:30 UTC) is newer than sha-4e5f6a7 (01:00 in Italy,
// 23:00 UTC): dates, not text. main, latest, the releases, digests, malformed sha- tags, one without a date and
// other packages stay, though they are older; a tag in two pages counts once.
var chosen = await RunProcessAsync(node, [script, "10", .. pages]);
Assert.AreEqual(0, chosen.Code, chosen.Errors);
CollectionAssert.AreEqual(OldShaTags, Lines(chosen.Output).Select(l => l.Split('\t')[0]).ToList(), chosen.Output);
StringAssert.Contains(chosen.Output, "sha-2c3d4e5\t2026-10-03T07:00:00Z\n");
// Keeping none: every well formed sha- tag of the container febe, and nothing else.
var all = await RunProcessAsync(node, [script, "0", .. pages]);
Assert.HasCount(14, Lines(all.Output), all.Output);
foreach (var line in Lines(all.Output))
{
Assert.IsTrue(ShaTagLine().IsMatch(line), line);
}
// Keeping more than there are: nothing. An empty page of Gitea is fine; a page that is not a list stops
// everything, so in doubt nothing goes.
var empty = Path.Combine(folder.Path, "vuota.json");
await File.WriteAllTextAsync(empty, "null", TestContext.CancellationToken);
Assert.IsEmpty((await RunProcessAsync(node, [script, "20", .. pages, empty])).Output);
var broken = Path.Combine(folder.Path, "rotta.json");
await File.WriteAllTextAsync(broken, "{\"message\":\"internal error\"}", TestContext.CancellationToken);
var refused = await RunProcessAsync(node, [script, "10", .. pages, broken]);
Assert.AreEqual(2, refused.Code, refused.Errors);
Assert.IsEmpty(refused.Output);
}
[TestMethod]
[Timeout(300_000, CooperativeCancellation = true)]
public async Task TheRegistryCleanupDeletesOnlyTheChosenTagsNeverPrintsTheTokenAndARefusalIsOnlyAWarning()
{
var bash = RequireBash();
RequireNode();
// A daemon with almost nothing on it: here only the registry counts.
var quiet = new World(["c-encelado|encelado|exited|5000|encelado:latest|img-encelado|"], ["img-encelado|encelado:latest|5000||250MB"], [], []);
var run = await RunCleanupAsync(bash, quiet with { Registry = new FakeRegistry(RegistryToken) }, "completa");
Assert.AreEqual(0, run.Code, run.Report);
CollectionAssert.AreEqual(OldShaTags, run.Deleted, run.Report);
var package = $"{RegistryApi}/packages/Alby96/container/febe";
CollectionAssert.AreEqual(
new[] { $"GET {package}?page=1&limit=50", $"GET {package}?page=2&limit=50", $"GET {package}?page=3&limit=50" }
.Concat(OldShaTags.Select(tag => $"DELETE {package}/{tag}")).ToList(),
run.RegistryCalls,
run.Report);
Assert.DoesNotContain(RegistryToken, run.Output + run.Errors, "the token never reaches the log");
Assert.AreEqual("4", SummaryCount(run.Output, "etichette sha- sul registro"), run.Report);
// The API refuses (a token without the permission) or does not know the token: a warning, nothing deleted,
// and the weekly job stays green.
foreach (var registry in new[] { new FakeRegistry(RegistryToken, Refuse: true), new FakeRegistry(RegistryToken, Sent: "un-altro-gettone-finto") })
{
var refused = await RunCleanupAsync(bash, quiet with { Registry = registry }, "completa");
Assert.AreEqual(0, refused.Code, refused.Report);
StringAssert.Contains(refused.Output, "::warning::L'API dei pacchetti di Gitea risponde 40", refused.Report);
Assert.IsEmpty(refused.Deleted, refused.Report);
Assert.HasCount(1, refused.RegistryCalls, refused.Report);
Assert.DoesNotContain(RegistryToken, refused.Output + refused.Errors);
Assert.DoesNotContain("un-altro-gettone-finto", refused.Output + refused.Errors);
}
}
/// <summary>
/// The daemon of <see cref="OnADaemonSharedWithARealFebeTheCleanupOfTheCiTakesOnlyWhatTheCiMade"/> (format in
/// fake-docker.sh). A real Febe started from :latest and one from :main carry the febe.ci.* labels of their images,
/// as Docker gives them; the image of the release also has the local name of run 777.
/// </summary>
private static class FakeDaemon
{
public static readonly string[] Full =
[
"c-febe-vero|febe|running|43200|192.168.30.23:3000/alby96/febe:latest|img-rilascio|febe.ci.workflow=rilascio,febe.ci.run=777,febe.ci.ref=v0.1.0",
"c-febe-fermo|febe-main|exited|43200|192.168.30.23:3000/alby96/febe:main|img-main|febe.ci.workflow=verifica,febe.ci.run=888",
"c-febe-antico|febe-antico|exited|20000|img-penzolante-in-uso|img-penzolante-in-uso|febe.ci.run=111",
"c-prova-777|febe-prova-777|running|5|febe-ci:777|img-rilascio|febe.ci.workflow=rilascio,febe.ci.run=777,febe.ci.prova=777",
"c-prova-555|febe-prova-555|exited|300|febe-ci:555|img-ci555|febe.ci.run=555,febe.ci.prova=555",
"c-prova-556|febe-prova-556|running|300|febe-ci:556|img-ci556|febe.ci.run=556,febe.ci.prova=556",
"c-prova-557|febe-prova-557|exited|10|febe-ci:557|img-ci557|febe.ci.run=557,febe.ci.prova=557",
"c-nome-strano|febe-prova-558-bis|exited|300|encelado:latest|img-encelado|febe.ci.prova=558",
"c-segno-diverso|febe-prova-559|exited|300|encelado:latest|img-encelado|febe.ci.prova=560",
"c-senza-segno|febe-prova-561|exited|300|encelado:latest|img-encelado|",
"c-encelado|encelado|exited|5000|encelado:latest|img-encelado|",
"b-vecchio|buildx_buildkit_febe-ci-4560|running|300|moby/buildkit:buildx-stable-1|img-buildkit||buildx_buildkit_febe-ci-4560_state",
"b-finto|buildx_buildkit_febe-ci-4570|running|300|encelado:latest|img-encelado||buildx_buildkit_febe-ci-4570_state",
"b-giovane|buildx_buildkit_febe-ci-7890|running|10|moby/buildkit:buildx-stable-1|img-buildkit||buildx_buildkit_febe-ci-7890_state",
"b-altro|altro_buildx_buildkit_febe-ci-10|running|300|moby/buildkit:buildx-stable-1|img-buildkit|",
"b-777|buildx_buildkit_febe-ci-7770|running|20|moby/buildkit:buildx-stable-1|img-buildkit||buildx_buildkit_febe-ci-7770_state",
];
/// <summary>The same daemon without the running tried container and the builder that is not one.</summary>
public static readonly string[] Clean = [.. Full.Where(c => !c.StartsWith("c-prova-556|", StringComparison.Ordinal) && !c.StartsWith("b-finto|", StringComparison.Ordinal))];
public static readonly string[] Images =
[
"img-rilascio|192.168.30.23:3000/alby96/febe:latest,192.168.30.23:3000/alby96/febe:0.1.0,febe-ci:777|43200|febe.ci.run=777",
"img-main|192.168.30.23:3000/alby96/febe:main|43200|febe.ci.run=888",
"img-ci555|febe-ci:555|300|febe.ci.run=555",
"img-ci556|febe-ci:556|300|febe.ci.run=556",
"img-ci557|febe-ci:557|10|febe.ci.run=557",
"img-penzolante-febe||300|febe.ci.run=999",
"img-penzolante-vecchia||6000|",
"img-penzolante-in-uso||20000|febe.ci.run=111",
"img-encelado|encelado:latest|5000|",
"img-buildkit|moby/buildkit:buildx-stable-1|50000|",
"img-legacy|febe:ci|6000|",
];
public static readonly string[] Volumes =
[
"buildx_buildkit_febe-ci-4560_state",
"buildx_buildkit_febe-ci-4570_state",
"buildx_buildkit_febe-ci-7890_state",
"buildx_buildkit_febe-ci-7770_state",
"encelado-dati",
];
public static World WorldOf(string[] containers) => new(containers, Images, Volumes, []);
public static List<string> ContainersOf(string[] world) => [.. world.Select(c => c[..c.IndexOf('|', StringComparison.Ordinal)])];
/// <summary>
/// «id|names» of each image once febe-ci:777 is gone (the image of the release keeps its registry names), without
/// the images given.
/// </summary>
public static List<string> ImagesWithout777(params string[] gone) =>
[
.. Images
.Select(i => string.Join('|', i.Split('|')[..2]).Replace(",febe-ci:777", string.Empty, StringComparison.Ordinal))
.Where(i => !gone.Contains(i[..i.IndexOf('|', StringComparison.Ordinal)])),
];
}
/// <summary>
/// A daemon as the runner's is likely to be (format in fake-docker.sh): a real Febe and Unraid apps, running and
/// stopped; the job container of the cleanup itself; leftovers of act_runner, with the names of today's act_runner
/// («_WORKFLOW-…») and of older ones («-WORKFLOW-…» with a hash), and look-alikes; leftovers of the CI of Febe;
/// images used and unused, named and dangling, old and young; volumes and networks of every kind.
/// </summary>
private static class SharedDaemon
{
private const string Job53 = "GITEA-ACTIONS-TASK-53_WORKFLOW-verifica_JOB-prove";
private const string Job41 = "GITEA-ACTIONS-TASK-41-WORKFLOW-verifica-JOB-prove-9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08";
private const string Job90 = "GITEA-ACTIONS-TASK-90_WORKFLOW-pulizia_JOB-docker";
public static readonly string[] Containers =
[
"c-febe-vero|febe|running|43200|192.168.30.23:3000/alby96/febe:latest|img-rilascio|febe.ci.workflow=rilascio,febe.ci.run=777,febe.ci.ref=v0.1.0|febe-dati|bridge",
"c-plex|plex|exited|90000|plexinc/pms-docker:latest|img-plex||plex-config|br0",
"c-encelado|encelado|exited|5000|encelado:latest|img-encelado|||encelado_default",
$"c-lavoro|{Job90}|running|5|docker.gitea.com/runner-images:ubuntu-latest|img-runner||{Job90},{Job90}-env,act-toolcache|{Job90}-docker-network",
$"c-act-fermo|{Job53}|exited|3000|node:24-trixie|img-node||{Job53},{Job53}-env,act-toolcache|{Job53}-prove-network",
$"c-act-antico|{Job41}|dead|20000|node:24-trixie|img-node||{Job41}-env|",
"c-act-giovane|GITEA-ACTIONS-TASK-89_WORKFLOW-verifica_JOB-controlli|exited|30|docker.gitea.com/runner-images:ubuntu-latest|img-runner||GITEA-ACTIONS-TASK-89_WORKFLOW-verifica_JOB-controlli|",
"c-act-acceso|GITEA-ACTIONS-TASK-60_WORKFLOW-encelado_JOB-build|running|3000|docker.gitea.com/runner-images:ubuntu-latest|img-runner||GITEA-ACTIONS-TASK-60_WORKFLOW-encelado_JOB-build|GITEA-ACTIONS-TASK-60_WORKFLOW-encelado_JOB-build-build-network",
"c-quasi-act|mio-GITEA-ACTIONS-TASK-7_WORKFLOW-x|exited|3000|encelado:latest|img-encelado||GITEA-ACTIONS-TASK-77_WORKFLOW-y_JOB-z|",
"c-senza-numero|GITEA-ACTIONS-TASK-x_WORKFLOW-y|exited|3000|encelado:latest|img-encelado|",
"c-prova-555|febe-prova-555|exited|300|febe-ci:555|img-ci555|febe.ci.run=555,febe.ci.prova=555",
"c-febe-antico|febe-antico|exited|20000|img-penzolante-in-uso|img-penzolante-in-uso|febe.ci.run=111",
"b-vecchio|buildx_buildkit_febe-ci-4560|running|300|moby/buildkit:buildx-stable-1|img-buildkit||buildx_buildkit_febe-ci-4560_state|",
"b-altro|buildx_buildkit_encelado0|running|3000|moby/buildkit:buildx-stable-1|img-buildkit||buildx_buildkit_encelado0_state|",
];
public static readonly string[] Images =
[
"img-rilascio|192.168.30.23:3000/alby96/febe:latest,192.168.30.23:3000/alby96/febe:0.1.0|43200|febe.ci.run=777|412MB",
"img-febe-vecchia|192.168.30.23:3000/alby96/febe:0.0.9|50000||400MB",
"img-plex|plexinc/pms-docker:latest|100000||300MB",
"img-plex-precedente||100000||300MB",
"img-encelado|encelado:latest|5000||250MB",
"img-encelado-dev|encelado:dev|3000||250MB",
"img-mimante-nuova|mimante:latest|60||180MB",
"img-runner|docker.gitea.com/runner-images:ubuntu-latest|20000||1.2GB",
"img-node|node:24-trixie|20000||410MB",
"img-buildkit|moby/buildkit:buildx-stable-1|50000||210MB",
"img-penzolante-giovane||30||40MB",
"img-penzolante-in-uso||20000|febe.ci.run=111|400MB",
"img-ci555|febe-ci:555|300|febe.ci.run=555|412MB",
"img-legacy|febe:ci|6000||400MB",
];
public static readonly string[] Volumes =
[
$"{Job53}|3000",
$"{Job53}-env|3000",
$"{Job41}-env|20000",
$"{Job90}|5",
$"{Job90}-env|5",
"GITEA-ACTIONS-TASK-89_WORKFLOW-verifica_JOB-controlli|30",
"GITEA-ACTIONS-TASK-60_WORKFLOW-encelado_JOB-build|3000",
"GITEA-ACTIONS-TASK-12_WORKFLOW-vecchio_JOB-x|50000",
"GITEA-ACTIONS-TASK-88_WORKFLOW-nuovo_JOB-y|30",
"GITEA-ACTIONS-TASK-77_WORKFLOW-y_JOB-z|50000",
"act-toolcache|50000",
"encelado-dati|50000",
"febe-dati|43200",
"plex-config|100000",
"3f9a2b7c1d0e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a|50000",
"mio-GITEA-ACTIONS-TASK-3_WORKFLOW-x|50000",
"buildx_buildkit_febe-ci-4560_state",
"buildx_buildkit_encelado0_state",
];
public static readonly string[] Networks =
[
"net-bridge|bridge|100000",
"net-host|host|100000",
"net-none|none|100000",
"net-br0|br0|100000",
"net-encelado|encelado_default|5000",
$"net-act-53|{Job53}-prove-network|3000",
$"net-act-90|{Job90}-docker-network|5",
"net-act-60|GITEA-ACTIONS-TASK-60_WORKFLOW-encelado_JOB-build-build-network|3000",
"net-act-12|GITEA-ACTIONS-TASK-12_WORKFLOW-vecchio_JOB-x-x-network|50000",
"net-act-88|GITEA-ACTIONS-TASK-88_WORKFLOW-nuovo_JOB-y-y-network|30",
"net-quasi|altro-GITEA-ACTIONS-TASK-5_WORKFLOW-x-network|50000",
];
public static readonly World World = new(Containers, Images, Volumes, Networks);
public static readonly List<string> ImageIds = [.. Images.Select(First)];
public static readonly List<string> VolumeNames = [.. Volumes.Select(First)];
public static readonly List<string> NetworkNames = [.. Networks.Select(n => n.Split('|')[1])];
/// <summary>
/// What the complete cleanup takes: stopped act_runner containers older than 90 minutes, a stopped tried
/// container and a builder of Febe; the volumes and networks of act_runner nothing else uses; the images no
/// container uses created more than a day ago (node:24-trixie only once its stopped containers are gone).
/// </summary>
public static readonly string[] Removed =
[
"c-act-fermo", "c-act-antico", "c-prova-555", "b-vecchio",
"img-febe-vecchia", "img-plex-precedente", "img-encelado-dev", "img-node", "img-ci555", "img-legacy",
$"{Job53}", $"{Job53}-env", $"{Job41}-env", "GITEA-ACTIONS-TASK-12_WORKFLOW-vecchio_JOB-x", "buildx_buildkit_febe-ci-4560_state",
"net-act-53", "net-act-12",
// How the cleanup names what it removes: by id or by name, and the local names of the images.
"buildx_buildkit_febe-ci-4560", "febe-ci:555", "febe:ci", "febe-ci-4560",
];
public static readonly List<string> ContainersLeft = [.. FakeDaemon.ContainersOf(Containers).Except(Removed)];
public static readonly List<string> ImagesLeft = [.. ImageIds.Except(Removed)];
public static readonly List<string> VolumesLeft = [.. VolumeNames.Except(Removed)];
public static readonly List<string> NetworksLeft = [.. Networks.Where(n => !Removed.Contains(First(n))).Select(n => n.Split('|')[1])];
private static string First(string line) => line.Split('|')[0];
}
/// <summary>A fake daemon (format in fake-docker.sh) and, for the registry, a fake Gitea (fake-curl.sh).</summary>
private sealed record World(string[] Containers, string[] Images, string[] Volumes, string[] Networks)
{
/// <summary>Docker commands that fail as if the daemon refused them («image prune», «builder prune»).</summary>
public string[] Broken { get; init; } = [];
/// <summary>The registry; without it the cleanup runs with no REGISTRY_TOKEN.</summary>
public FakeRegistry? Registry { get; init; }
}
/// <summary>
/// The packages API of Gitea with the pages of versioni-registro.json, for the token given. Sent is the token the
/// cleanup gets (the same, if null); Refuse answers 403 to everything.
/// </summary>
private sealed record FakeRegistry(string Token, bool Refuse = false, string? Sent = null);
private sealed record CleanupRun(int Code, string Output, string Errors)
{
/// <summary>The ids of the containers left.</summary>
public List<string> Containers { get; init; } = [];
/// <summary>«id|names» of the images left.</summary>
public List<string> Images { get; init; } = [];
public List<string> Volumes { get; init; } = [];
public List<string> Networks { get; init; } = [];
/// <summary>Every docker call, as fake-docker.sh writes it.</summary>
public List<string> Calls { get; init; } = [];
/// <summary>Every call to the API of the registry, «METHOD URL».</summary>
public List<string> RegistryCalls { get; init; } = [];
/// <summary>The versions deleted from the registry.</summary>
public List<string> Deleted { get; init; } = [];
public List<string> ImageIds => [.. Images.Select(i => i.Split('|')[0])];
public string Report => $"codice {Code}\n{Output}\n{Errors}";
}
/// <summary>
/// pulizia-docker.sh against the fake daemon and, with a registry, the fake curl. DOCKER_HOST points nowhere and the
/// API is on a domain that cannot exist (.invalid): even if a real docker or curl came first on the PATH they could
/// reach nothing, and the test fails because the fakes recorded no call or curl complained on stderr.
/// </summary>
private async Task<CleanupRun> RunCleanupAsync(string bash, World world, params string[] arguments)
{
using var folder = new TempFolder("febe-pulizia");
var bin = folder.Combine("bin");
var registry = folder.Combine("registro");
var temporary = folder.Combine("tmp");
foreach (var directory in new[] { bin, registry, temporary })
{
Directory.CreateDirectory(directory);
}
InstallFake("fake-docker.sh", Path.Combine(bin, "docker"));
await WriteLinesAsync(folder.Combine("containers"), world.Containers);
await WriteLinesAsync(folder.Combine("images"), world.Images);
await WriteLinesAsync(folder.Combine("volumes"), world.Volumes);
await WriteLinesAsync(folder.Combine("networks"), world.Networks);
if (world.Broken.Length > 0)
{
await WriteLinesAsync(folder.Combine("broken"), world.Broken);
}
if (world.Registry is { } fake)
{
InstallFake("fake-curl.sh", Path.Combine(bin, "curl"));
await File.WriteAllTextAsync(Path.Combine(registry, "token"), fake.Token, TestContext.CancellationToken);
await File.WriteAllTextAsync(Path.Combine(registry, "base"), $"{RegistryApi}/packages/Alby96/container/febe", TestContext.CancellationToken);
if (fake.Refuse)
{
await File.WriteAllTextAsync(Path.Combine(registry, "refuse"), string.Empty, TestContext.CancellationToken);
}
await WriteRegistryPagesAsync(registry);
}
// The fakes go first on the PATH from inside bash: Git Bash puts its own folders (with a real curl) before the
// PATH it is given.
string[] script = ["-c", "bin=\"$FAKE_BIN\"; if command -v cygpath > /dev/null; then bin=\"$(cygpath -u \"$bin\")\"; fi; PATH=\"$bin:$PATH\"; exec bash \"$@\"", "bash", ".gitea/scripts/pulizia-docker.sh"];
var result = await RunProcessAsync(bash, [.. script, .. arguments], start =>
{
start.Environment["FAKE_BIN"] = bin;
start.Environment["FAKE_DOCKER_WORLD"] = folder.Path.Replace('\\', '/');
start.Environment["FAKE_CURL_WORLD"] = registry.Replace('\\', '/');
start.Environment["TMPDIR"] = temporary.Replace('\\', '/');
start.Environment["DOCKER_HOST"] = OperatingSystem.IsWindows() ? "npipe:////./pipe/febe-nessun-demone" : "unix:///nonexistent/febe-nessun-demone.sock";
start.Environment.Remove("DOCKER_CONTEXT");
start.Environment.Remove("BUILDX_BUILDER");
start.Environment.Remove("REGISTRY_TOKEN");
start.Environment["GITEA_API"] = RegistryApi;
start.Environment["PROPRIETARIO"] = "Alby96";
if (world.Registry is { } sent)
{
start.Environment["REGISTRY_TOKEN"] = sent.Sent ?? sent.Token;
}
});
var run = new CleanupRun(result.Code, result.Output, result.Errors)
{
Containers = FakeDaemon.ContainersOf([.. await ReadLinesAsync(folder.Combine("containers"))]),
Images = [.. (await ReadLinesAsync(folder.Combine("images"))).Select(i => string.Join('|', i.Split('|')[..2]))],
Volumes = [.. (await ReadLinesAsync(folder.Combine("volumes"))).Select(v => v.Split('|')[0])],
Networks = [.. (await ReadLinesAsync(folder.Combine("networks"))).Select(n => n.Split('|')[1])],
Calls = await ReadLinesAsync(folder.Combine("calls")),
RegistryCalls = await ReadLinesAsync(Path.Combine(registry, "calls")),
Deleted = await ReadLinesAsync(Path.Combine(registry, "deleted")),
};
Assert.IsNotEmpty(run.Calls, $"the fake docker client was not the one called\n{run.Report}");
Assert.DoesNotContain("unexpected call", run.Errors, run.Report);
Assert.DoesNotContain("fake curl:", run.Errors, run.Report);
Assert.DoesNotContain("curl: (", run.Errors, $"a real curl was called\n{run.Report}");
Assert.IsEmpty(Directory.EnumerateFileSystemEntries(temporary), $"the cleanup leaves no temporary files\n{run.Report}");
return run;
}
/// <summary>A program with its arguments, from the root of the repository; its output with Unix lines.</summary>
private async Task<(int Code, string Output, string Errors)> RunProcessAsync(string program, IEnumerable<string> arguments, Action<ProcessStartInfo>? configure = null)
{
var start = new ProcessStartInfo(program)
{
WorkingDirectory = Repository.Root()!,
RedirectStandardOutput = true,
RedirectStandardError = true,
StandardOutputEncoding = System.Text.Encoding.UTF8,
StandardErrorEncoding = System.Text.Encoding.UTF8,
};
foreach (var argument in arguments)
{
start.ArgumentList.Add(argument);
}
configure?.Invoke(start);
using var process = Process.Start(start)!;
var output = process.StandardOutput.ReadToEndAsync(TestContext.CancellationToken);
var errors = process.StandardError.ReadToEndAsync(TestContext.CancellationToken);
await process.WaitForExitAsync(TestContext.CancellationToken);
return (process.ExitCode, (await output).Replace("\r\n", "\n", StringComparison.Ordinal), (await errors).Replace("\r\n", "\n", StringComparison.Ordinal));
}
/// <summary>The pages of versioni-registro.json as Gitea would answer them, one file each.</summary>
private async Task<List<string>> WriteRegistryPagesAsync(string folder)
{
var fixture = await File.ReadAllTextAsync(Repository.PathOf("tests", "Febe.Tests", "Packaging", "versioni-registro.json"), TestContext.CancellationToken);
using var pages = JsonDocument.Parse(fixture);
var files = new List<string>();
foreach (var page in pages.RootElement.EnumerateArray())
{
var file = Path.Combine(folder, $"page-{files.Count + 1}.json");
await File.WriteAllTextAsync(file, page.GetRawText(), TestContext.CancellationToken);
files.Add(file);
}
return files;
}
private static void InstallFake(string name, string path)
{
File.Copy(Repository.PathOf("tests", "Febe.Tests", "Packaging", name), path);
if (!OperatingSystem.IsWindows())
{
File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
}
}
private async Task WriteLinesAsync(string path, IEnumerable<string> lines) =>
await File.WriteAllTextAsync(path, string.Concat(lines.Select(line => line + "\n")), TestContext.CancellationToken);
private async Task<List<string>> ReadLinesAsync(string path) =>
File.Exists(path) ? Lines(await File.ReadAllTextAsync(path, TestContext.CancellationToken)) : [];
private static List<string> Lines(string text) => [.. text.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n', StringSplitOptions.RemoveEmptyEntries)];
/// <summary>The number the summary of the cleanup gives for a kind of object, or null when it does not list it.</summary>
private static string? SummaryCount(string output, string kind)
{
var match = Regex.Match(output, $@"^ {Regex.Escape(kind)}: (?<count>[0-9]+)", RegexOptions.Multiline);
return match.Success ? match.Groups["count"].Value : null;
}
/// <summary>The body of a shell function of a script, from «name() {» to the closing brace at the start of a line.</summary>
private static string Function(string script, string name)
{
var match = Regex.Match(script, $@"^{Regex.Escape(name)}\(\) \{{\n(?<body>.*?)^\}}", RegexOptions.Multiline | RegexOptions.Singleline);
Assert.IsTrue(match.Success, $"manca la funzione {name}");
return match.Groups["body"].Value;
}
private static string RequireBash()
{
var bash = BashForScripts();
if (bash is null)
{
Assert.Inconclusive("Manca bash (su Windows serve Git Bash): la prova della pulizia su un demone finto si salta.");
}
Assert.IsTrue(File.Exists(CiPath("scripts", "pulizia-docker.sh")));
return bash;
}
/// <summary>node from the PATH: the registry part of the cleanup reads JSON with it, in the CI as here.</summary>
private static string RequireNode()
{
var names = OperatingSystem.IsWindows() ? new[] { "node.exe" } : ["node"];
var node = (Environment.GetEnvironmentVariable("PATH") ?? string.Empty)
.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)
.SelectMany(folder => names.Select(name => Path.Combine(folder.Trim('"'), name)))
.FirstOrDefault(File.Exists);
if (node is null)
{
Assert.Inconclusive("Manca node: la prova della scelta delle versioni del registro si salta.");
}
return node;
}
[GeneratedRegex(@"docker (?<what>[a-z]+) prune(?<args>[^\n]*)")]
private static partial Regex Prune();
[GeneratedRegex(@"label=febe\.ci\.(?!prova\b)")]
private static partial Regex ProvenanceLabelFilter();
[GeneratedRegex(@"docker (?:image rm|rmi)\s+(?:-\w+\s+)*-\w*f")]
private static partial Regex ForcedImageRemoval();
[GeneratedRegex(@"docker (?:rm|image rm|volume rm|network rm|buildx rm)\b|prune")]
private static partial Regex Removal();
[GeneratedRegex(@"docker (?:rm|image rm|volume rm|network rm)(?: -[a-z]+)* (?<target>\S+)$")]
private static partial Regex RemovalTarget();
[GeneratedRegex(@"docker (?:rm|kill|stop|image rm|rmi|image prune|builder prune|buildx rm|buildx prune|volume rm|volume prune|network rm|network prune|container prune|system prune)\b")]
private static partial Regex Destructive();
[GeneratedRegex(@"^::warning::", RegexOptions.Multiline)]
private static partial Regex WarningLine();
[GeneratedRegex(@"^sha-[0-9a-f]{7,40}\t")]
private static partial Regex ShaTagLine();
}
+2 -227
View File
@@ -1,4 +1,3 @@
using System.Diagnostics;
using System.Text.RegularExpressions;
using Febe.Tests.Desktop.Support;
using Febe.Tests.Support;
@@ -10,8 +9,8 @@ namespace Febe.Tests.Packaging;
/// text: the rules that must survive later edits. Every push of every branch is verified and nothing else triggers
/// it twice; the tests run only through tests/Febe.Tests, with the browser, and again with the seed of the run; the
/// image is published only from main and never as :latest; credentials are never printed; the external tools are
/// pinned and checked; the cleanup touches only what the CI of Febe made, never a real Febe on the same daemon; the
/// tried container never has a network.
/// pinned and checked; the tried container never has a network. The cleanup, which runs against fake docker and curl
/// clients, is in PipelineTests.Pulizia.cs.
/// </summary>
[TestClass]
public sealed partial class PipelineTests
@@ -163,41 +162,6 @@ public sealed partial class PipelineTests
StringAssert.Contains(scan, "--exit-code 1");
}
[TestMethod]
public void TheCleanupTouchesOnlyWhatTheCiOfFebeMade()
{
var cleanup = Code(Script("pulizia-docker.sh"));
foreach (var forbidden in new[] { "system prune", "builder prune", "volume prune", "container prune", "image prune -a", "prune --all", "image prune -f -a" })
{
Assert.DoesNotContain(forbidden, cleanup, "the daemon is shared with Alberto's other projects");
}
Assert.HasCount(1, ImagePrune().Matches(cleanup), "only dangling images, older than three days");
StringAssert.Contains(cleanup, "docker image prune -f --filter \"until=72h\"");
StringAssert.Contains(cleanup, "^buildx_buildkit_(febe-ci-[0-9]+)0$");
// The febe.ci.* labels of the image are in every container made from a published image, a real Febe too: they
// never choose what goes. Containers are chosen by febe.ci.prova (and their exact name), the builders by name,
// and an image only by its local name febe-ci:<run>, never by id and never forced.
Assert.IsFalse(ProvenanceLabelFilter().IsMatch(cleanup), "the cleanup filters on febe.ci.prova only");
foreach (var line in cleanup.Split('\n').Where(l => l.Contains("docker ps", StringComparison.Ordinal)))
{
Assert.IsTrue(
line.Contains("--filter \"label=febe.ci.prova", StringComparison.Ordinal) || line.Contains("--filter \"name=buildx_buildkit_febe-ci-\"", StringComparison.Ordinal) || line.Contains("--filter \"ancestor=", StringComparison.Ordinal),
$"«{line.Trim()}» lists containers without the mark of the tried container");
}
StringAssert.Contains(cleanup, "\"febe-prova-$valore\"", "the name must match the mark");
StringAssert.Contains(cleanup, "contenitori_di_prova \"\" exited created dead", "the sweeps take only stopped tried containers");
Assert.IsFalse(ForcedImageRemoval().IsMatch(cleanup), "an image is never removed by force");
StringAssert.Contains(cleanup, "[[ \"$riferimento\" =~ ^febe-ci:[0-9]+$ ]]");
var weekly = Workflow("pulizia.yml");
StringAssert.Contains(weekly, "schedule:");
StringAssert.Contains(weekly, "workflow_dispatch:");
StringAssert.Contains(weekly, "bash .gitea/scripts/pulizia-docker.sh settimanale");
}
[TestMethod]
public void TheTriedContainerNeverHasANetworkAndAlwaysCarriesTheMarkNoImageHas()
{
@@ -218,186 +182,6 @@ public sealed partial class PipelineTests
Assert.DoesNotContain("febe.ci.prova", Code(Read(Repository.PathOf("docker", "Dockerfile"))));
}
[TestMethod]
[Timeout(180_000, CooperativeCancellation = true)]
public async Task OnADaemonSharedWithARealFebeTheCleanupTakesOnlyWhatTheCiMade()
{
var script = CiPath("scripts", "pulizia-docker.sh");
var bash = BashForScripts();
if (bash is null)
{
Assert.Inconclusive("Manca bash (su Windows serve Git Bash): la prova della pulizia su un demone finto si salta.");
}
Assert.IsTrue(File.Exists(script));
// At the start or the end of a run (a release run again keeps its id, so the published image has the same
// febe.ci.run as the run): only the tried container, the local name and the builder of that run.
var run = await RunCleanupAsync(bash, FakeDaemon.Full, "esecuzione", "777");
Assert.AreEqual(0, run.Code, run.Report);
Assert.DoesNotContain("::warning::", run.Output, run.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Full).Except(["c-prova-777", "b-777"]).ToList(), run.Containers, run.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777(), run.Images, run.Report);
CollectionAssert.AreEquivalent(FakeDaemon.Volumes.Except(["buildx_buildkit_febe-ci-7770_state"]).ToList(), run.Volumes, run.Report);
// Leftovers of interrupted runs: stopped tried containers, febe-ci images and builders older than 90 minutes.
var leftovers = await RunCleanupAsync(bash, FakeDaemon.Full, "residui", "90");
Assert.AreEqual(0, leftovers.Code, leftovers.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Full).Except(["c-prova-555", "b-vecchio"]).ToList(), leftovers.Containers, leftovers.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777("img-ci555"), leftovers.Images, leftovers.Report);
CollectionAssert.AreEquivalent(FakeDaemon.Volumes.Except(["buildx_buildkit_febe-ci-4560_state"]).ToList(), leftovers.Volumes, leftovers.Report);
StringAssert.Contains(leftovers.Output, "::warning::Il contenitore di prova febe-prova-556 è acceso", "a running tried container is reported, not removed");
StringAssert.Contains(leftovers.Output, "::warning::Il contenitore buildx_buildkit_febe-ci-4570 non è un builder buildx", leftovers.Report);
// Every week, on a daemon without anything odd: the same, the old febe:ci and the dangling images older than
// 72 hours that no container uses. Green.
var weekly = await RunCleanupAsync(bash, FakeDaemon.Clean, "settimanale");
Assert.AreEqual(0, weekly.Code, weekly.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Clean).Except(["c-prova-555", "b-vecchio"]).ToList(), weekly.Containers, weekly.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777("img-ci555", "img-ci556", "img-legacy", "img-penzolante-vecchia"), weekly.Images, weekly.Report);
// With something left for a person to look at, the weekly cleanup goes red.
var noticed = await RunCleanupAsync(bash, FakeDaemon.Full, "settimanale");
Assert.AreEqual(1, noticed.Code, noticed.Report);
CollectionAssert.Contains(noticed.Containers, "c-prova-556");
CollectionAssert.Contains(noticed.Containers, "c-febe-vero");
}
/// <summary>
/// The daemon the cleanup runs against in <see cref="OnADaemonSharedWithARealFebeTheCleanupTakesOnlyWhatTheCiMade"/>
/// (format in fake-docker.sh). A real Febe started from :latest and one from :main carry the febe.ci.* labels of
/// their images, as Docker gives them; the image of the release also has the local name of run 777.
/// </summary>
private static class FakeDaemon
{
public static readonly string[] Full =
[
"c-febe-vero|febe|running|43200|192.168.30.23:3000/alby96/febe:latest|img-rilascio|febe.ci.workflow=rilascio,febe.ci.run=777,febe.ci.ref=v0.1.0",
"c-febe-fermo|febe-main|exited|43200|192.168.30.23:3000/alby96/febe:main|img-main|febe.ci.workflow=verifica,febe.ci.run=888",
"c-febe-antico|febe-antico|exited|20000|img-penzolante-in-uso|img-penzolante-in-uso|febe.ci.run=111",
"c-prova-777|febe-prova-777|running|5|febe-ci:777|img-rilascio|febe.ci.workflow=rilascio,febe.ci.run=777,febe.ci.prova=777",
"c-prova-555|febe-prova-555|exited|300|febe-ci:555|img-ci555|febe.ci.run=555,febe.ci.prova=555",
"c-prova-556|febe-prova-556|running|300|febe-ci:556|img-ci556|febe.ci.run=556,febe.ci.prova=556",
"c-prova-557|febe-prova-557|exited|10|febe-ci:557|img-ci557|febe.ci.run=557,febe.ci.prova=557",
"c-nome-strano|febe-prova-558-bis|exited|300|encelado:latest|img-encelado|febe.ci.prova=558",
"c-segno-diverso|febe-prova-559|exited|300|encelado:latest|img-encelado|febe.ci.prova=560",
"c-senza-segno|febe-prova-561|exited|300|encelado:latest|img-encelado|",
"c-encelado|encelado|exited|5000|encelado:latest|img-encelado|",
"b-vecchio|buildx_buildkit_febe-ci-4560|running|300|moby/buildkit:buildx-stable-1|img-buildkit|",
"b-finto|buildx_buildkit_febe-ci-4570|running|300|encelado:latest|img-encelado|",
"b-giovane|buildx_buildkit_febe-ci-7890|running|10|moby/buildkit:buildx-stable-1|img-buildkit|",
"b-altro|altro_buildx_buildkit_febe-ci-10|running|300|moby/buildkit:buildx-stable-1|img-buildkit|",
"b-777|buildx_buildkit_febe-ci-7770|running|20|moby/buildkit:buildx-stable-1|img-buildkit|",
];
/// <summary>The same daemon without the running tried container and the builder that is not one.</summary>
public static readonly string[] Clean = [.. Full.Where(c => !c.StartsWith("c-prova-556|", StringComparison.Ordinal) && !c.StartsWith("b-finto|", StringComparison.Ordinal))];
public static readonly string[] Images =
[
"img-rilascio|192.168.30.23:3000/alby96/febe:latest,192.168.30.23:3000/alby96/febe:0.1.0,febe-ci:777|43200|febe.ci.run=777",
"img-main|192.168.30.23:3000/alby96/febe:main|43200|febe.ci.run=888",
"img-ci555|febe-ci:555|300|febe.ci.run=555",
"img-ci556|febe-ci:556|300|febe.ci.run=556",
"img-ci557|febe-ci:557|10|febe.ci.run=557",
"img-penzolante-febe||300|febe.ci.run=999",
"img-penzolante-vecchia||6000|",
"img-penzolante-in-uso||20000|febe.ci.run=111",
"img-encelado|encelado:latest|5000|",
"img-buildkit|moby/buildkit:buildx-stable-1|50000|",
"img-legacy|febe:ci|6000|",
];
public static readonly string[] Volumes =
[
"buildx_buildkit_febe-ci-4560_state",
"buildx_buildkit_febe-ci-4570_state",
"buildx_buildkit_febe-ci-7890_state",
"buildx_buildkit_febe-ci-7770_state",
"encelado-dati",
];
public static List<string> ContainersOf(string[] world) => [.. world.Select(c => c[..c.IndexOf('|', StringComparison.Ordinal)])];
/// <summary>
/// «id|names» of each image once febe-ci:777 is gone (the image of the release keeps its registry names), without
/// the images given.
/// </summary>
public static List<string> ImagesWithout777(params string[] gone) =>
[
.. Images
.Select(i => string.Join('|', i.Split('|')[..2]).Replace(",febe-ci:777", string.Empty, StringComparison.Ordinal))
.Where(i => !gone.Contains(i[..i.IndexOf('|', StringComparison.Ordinal)])),
];
}
private sealed record CleanupRun(int Code, string Output, string Errors, List<string> Containers, List<string> Images, List<string> Volumes)
{
public string Report => $"codice {Code}\n{Output}\n{Errors}";
}
/// <summary>
/// pulizia-docker.sh against the fake daemon. DOCKER_HOST points nowhere: even if a real docker client came first on
/// the PATH it could not reach a daemon, and the test fails because the fake recorded no call.
/// </summary>
private async Task<CleanupRun> RunCleanupAsync(string bash, string[] containers, params string[] arguments)
{
using var world = new TempFolder("febe-pulizia");
var bin = world.Combine("bin");
Directory.CreateDirectory(bin);
var docker = Path.Combine(bin, "docker");
File.Copy(Repository.PathOf("tests", "Febe.Tests", "Packaging", "fake-docker.sh"), docker);
if (!OperatingSystem.IsWindows())
{
File.SetUnixFileMode(docker, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
}
await WriteLinesAsync(world.Combine("containers"), containers);
await WriteLinesAsync(world.Combine("images"), FakeDaemon.Images);
await WriteLinesAsync(world.Combine("volumes"), FakeDaemon.Volumes);
var start = new ProcessStartInfo(bash)
{
WorkingDirectory = Repository.Root()!,
RedirectStandardOutput = true,
RedirectStandardError = true,
StandardOutputEncoding = System.Text.Encoding.UTF8,
StandardErrorEncoding = System.Text.Encoding.UTF8,
};
start.ArgumentList.Add(".gitea/scripts/pulizia-docker.sh");
foreach (var argument in arguments)
{
start.ArgumentList.Add(argument);
}
start.Environment["PATH"] = bin + Path.PathSeparator + Environment.GetEnvironmentVariable("PATH");
start.Environment["FAKE_DOCKER_WORLD"] = world.Path.Replace('\\', '/');
start.Environment["DOCKER_HOST"] = OperatingSystem.IsWindows() ? "npipe:////./pipe/febe-nessun-demone" : "unix:///nonexistent/febe-nessun-demone.sock";
start.Environment.Remove("DOCKER_CONTEXT");
using var process = Process.Start(start)!;
var output = process.StandardOutput.ReadToEndAsync(TestContext.CancellationToken);
var errors = process.StandardError.ReadToEndAsync(TestContext.CancellationToken);
await process.WaitForExitAsync(TestContext.CancellationToken);
var result = new CleanupRun(
process.ExitCode,
(await output).Replace("\r\n", "\n", StringComparison.Ordinal),
await errors,
FakeDaemon.ContainersOf([.. await ReadLinesAsync(world.Combine("containers"))]),
[.. (await ReadLinesAsync(world.Combine("images"))).Select(i => string.Join('|', i.Split('|')[..2]))],
await ReadLinesAsync(world.Combine("volumes")));
var calls = world.Combine("calls");
Assert.IsTrue(File.Exists(calls) && (await File.ReadAllTextAsync(calls, TestContext.CancellationToken)).Contains("docker ps", StringComparison.Ordinal), $"the fake docker client was not the one called\n{result.Report}");
Assert.DoesNotContain("unexpected call", result.Errors, result.Report);
return result;
}
private async Task WriteLinesAsync(string path, IEnumerable<string> lines) =>
await File.WriteAllTextAsync(path, string.Concat(lines.Select(line => line + "\n")), TestContext.CancellationToken);
private async Task<List<string>> ReadLinesAsync(string path) =>
[.. (await File.ReadAllTextAsync(path, TestContext.CancellationToken)).Split('\n', StringSplitOptions.RemoveEmptyEntries)];
/// <summary>bash for the scripts of the CI: the system one on Linux, Git Bash on Windows (not the one of WSL).</summary>
private static string? BashForScripts()
{
@@ -473,15 +257,6 @@ public sealed partial class PipelineTests
[GeneratedRegex(@"\b[0-9a-f]{64}\b")]
private static partial Regex Sha256();
[GeneratedRegex(@"docker (?:image|container|volume|builder|system) prune")]
private static partial Regex ImagePrune();
[GeneratedRegex(@"docker run\b(?:[^\n]*\\\n)*[^\n]*")]
private static partial Regex DockerRun();
[GeneratedRegex(@"label=febe\.ci\.(?!prova\b)")]
private static partial Regex ProvenanceLabelFilter();
[GeneratedRegex(@"docker (?:image rm|rmi)\s+(?:-\w+\s+)*-\w*f")]
private static partial Regex ForcedImageRemoval();
}
+63
View File
@@ -0,0 +1,63 @@
#!/usr/bin/env bash
# A fake curl for PipelineTests: the registry part of .gitea/scripts/pulizia-docker.sh talks to the packages API of
# Gitea 28 through it. No network. It knows only the options the cleanup uses and answers like Gitea:
# GET <base>?page=<n>&limit=50 the page $FAKE_CURL_WORLD/page-<n>.json, or [] after the last one (200)
# DELETE <base>/<version> 204, and the version is written to $FAKE_CURL_WORLD/deleted
# where <base> is the content of $FAKE_CURL_WORLD/base (…/api/v1/packages/<owner>/container/febe). Without the header
# «Authorization: token <content of $FAKE_CURL_WORLD/token>» it answers 401; with $FAKE_CURL_WORLD/refuse it answers
# 403 to every call; any other address is 404. Every call goes to $FAKE_CURL_WORLD/calls as «METHOD URL», never with
# its headers. Any other option is an error (exit 3).
set -uo pipefail
world="${FAKE_CURL_WORLD:?}"
token="$(cat "$world/token" 2> /dev/null)"
method=GET output="" write="" url="" authorized=0
while (($#)); do
case "$1" in
-s | -S | -sS) ;;
--max-time) shift ;;
-X) method="$2"; shift ;;
-H) [[ -n "$token" && "$2" == "Authorization: token $token" ]] && authorized=1; shift ;;
-o) output="$2"; shift ;;
-w) write="$2"; shift ;;
-*) echo "fake curl: unexpected option $1" >&2; exit 3 ;;
*)
[[ -z "$url" ]] || { echo "fake curl: a second address $1" >&2; exit 3; }
url="$1"
;;
esac
shift
done
printf '%s %s\n' "$method" "$url" >> "$world/calls"
[[ -z "$write" || "$write" == '%{http_code}' ]] || { echo "fake curl: unexpected -w $write" >&2; exit 3; }
answer() {
local code="$1" body="${2:-}"
if [[ -n "$output" ]]; then
printf '%s' "$body" > "$output"
else
printf '%s' "$body"
fi
[[ -z "$write" ]] || printf '%s' "$code"
exit 0
}
[[ -f "$world/refuse" ]] && answer 403 '{"message":"token does not have at least one of required scope(s): [write:package]"}'
((authorized)) || answer 401 '{"message":"token is required"}'
base="$(cat "$world/base")"
case "$method $url" in
"GET $base?page="*"&limit=50")
page="${url#"$base?page="}"
page="${page%%&*}"
if [[ -f "$world/page-$page.json" ]]; then
answer 200 "$(cat "$world/page-$page.json")"
fi
answer 200 "[]"
;;
"DELETE $base/"*)
echo "${url#"$base/"}" >> "$world/deleted"
answer 204
;;
*) answer 404 '{"message":"The target couldn'"'"'t be found."}' ;;
esac
+292 -79
View File
@@ -3,32 +3,50 @@
# files, and the test reads what is left. No daemon, no network. It models only what the cleanup relies on, the way
# Docker does it:
# - filters of «ps»: label filters must all match, the values of any other key are alternatives (status, name as a
# regular expression, ancestor by name or id);
# regular expression, ancestor by name or id, volume and network by name; stopped containers too);
# - «rm» refuses a running container without -f;
# - «image rm <name>» only untags when the image has other names, and refuses an image a container uses (always if the
# container runs, without -f if it is stopped);
# - «image prune --filter until=72h» takes only images without a name, older than 72 hours, used by no container.
# Any other call is an error (exit 3), so the test sees every command the cleanup starts to use.
# - «image prune» takes only images no container uses, running or stopped: without -a only those without a name, with
# -a any; «until» keeps those created in the last 72 or 24 hours;
# - «builder prune» only answers (the cache is not modelled);
# - «volume rm» refuses a volume a container mounts, running or stopped, even with -f;
# - «network rm» refuses the predefined networks and a network a running container is attached to;
# - creation times: containers and images in UTC with nanoseconds, volumes and networks two hours ahead with the
# offset (+02:00), as a daemon in Italy writes them; the Created of a network is a time of Go, which the template
# prints as «2026-10-21 06:17:03.123456789 +0200 CEST» and {{json .Created}} as RFC 3339 between quotes.
# Any other call is an error (exit 3), so the test sees every command the cleanup starts to use. That includes any prune
# other than those the cleanup may run: image prune -f [--filter until=72h], image prune -a -f --filter until=24h,
# builder prune -f and builder prune -a -f --filter until=24h.
#
# $FAKE_DOCKER_WORLD/containers id|name|state|minutes ago|image as given to «docker run»|image id|labels
# (labels as Docker gives them to the container: those of the image plus those of «run»)
# $FAKE_DOCKER_WORLD/images id|names (comma separated; empty: dangling)|minutes ago|labels
# $FAKE_DOCKER_WORLD/volumes one name per line
# $FAKE_DOCKER_WORLD/calls every call, one per line (written here)
# $FAKE_DOCKER_WORLD/containers id|name|state|minutes ago|image as given to «docker run»|image id|labels|volumes|networks
# (labels as Docker gives them to the container: those of the image plus those of «run»;
# volumes and networks by name, comma separated; the last fields may be missing)
# $FAKE_DOCKER_WORLD/images id|names (comma separated; empty: dangling)|minutes ago|labels|size
# $FAKE_DOCKER_WORLD/volumes name|minutes ago (missing: just created)
# $FAKE_DOCKER_WORLD/networks id|name|minutes ago
# $FAKE_DOCKER_WORLD/broken optional: commands («image prune», «builder prune») that fail as if the daemon refused
# $FAKE_DOCKER_WORLD/calls every call, one per line (written here), after BUILDX_BUILDER=<value> when it is set
set -uo pipefail
world="${FAKE_DOCKER_WORLD:?}"
printf 'docker %s\n' "$*" >> "$world/calls"
printf '%sdocker %s\n' "${BUILDX_BUILDER:+BUILDX_BUILDER=$BUILDX_BUILDER }" "$*" >> "$world/calls"
now=$(date -u +%s)
touch "$world/containers" "$world/images" "$world/volumes"
touch "$world/containers" "$world/images" "$world/volumes" "$world/networks"
unexpected() {
echo "fake docker: unexpected call: $*" >&2
exit 3
}
broken() {
[[ -f "$world/broken" ]] && grep -qxF -- "$1" "$world/broken"
}
created() { date -u -d "@$((now - $1 * 60))" +%Y-%m-%dT%H:%M:%S.123456789Z; }
created_in_italy() { date -u -d "@$((now - ${1:-0} * 60 + 7200))" "+%Y-%m-%dT%H:%M:%S${2:-}+02:00"; }
# The value of a label, or $3 when it is missing («docker ps» prints nothing, «inspect» prints <no value>).
label_value() {
local labels=",$1," key="$2" rest
@@ -48,8 +66,8 @@ has_label() {
# Image id for a name or an id; empty when there is none.
resolve_image() {
local ref="$1" id names age labels
while IFS='|' read -r id names age labels; do
local ref="$1" id names rest
while IFS='|' read -r id names rest; do
[[ -n "$id" ]] || continue
if [[ "$id" == "$ref" || ",$names," == *",$ref,"* ]]; then
echo "$id"
@@ -58,26 +76,29 @@ resolve_image() {
done < "$world/images"
}
# The image line for an id; empty when there is none.
image_line() {
local line
# The line of a world file whose first field (or, with $3, whose field number $3) is $2; empty when there is none.
line_of() {
local file="$1" wanted="$2" field="${3:-1}" line fields
while IFS= read -r line; do
[[ -n "$line" && "${line%%|*}" == "$1" ]] && { echo "$line"; return; }
done < "$world/images"
}
# The container line for an id or a name; empty when there is none.
find_container() {
local ref="$1" line id name rest
while IFS= read -r line; do
IFS='|' read -r id name rest <<< "$line"
if [[ -n "$id" && ("$id" == "$ref" || "$name" == "$ref") ]]; then
[[ -n "$line" ]] || continue
IFS='|' read -r -a fields <<< "$line"
if [[ "${fields[0]}" == "$wanted" || "${fields[field - 1]:-}" == "$wanted" ]]; then
echo "$line"
return
fi
done < "$world/containers"
done < "$file"
}
image_line() { line_of "$world/images" "$1"; }
# The container line for an id or a name; empty when there is none.
find_container() { line_of "$world/containers" "$1" 2; }
volume_line() { line_of "$world/volumes" "$1"; }
# The network line for an id or a name; empty when there is none.
network_line() { line_of "$world/networks" "$1" 2; }
# Rewrites a world file without the lines whose first field is $2.
drop() {
local file="$1" id="$2" line
@@ -88,18 +109,31 @@ drop() {
mv "$file.new" "$file"
}
# True when a container uses the image (any: in any state; running: only a running one).
used_by() {
local image="$1" want="$2" id name state age config image_id labels
while IFS='|' read -r id name state age config image_id labels; do
local image="$1" want="$2" id name state age config image_id labels volumes networks
while IFS='|' read -r id name state age config image_id labels volumes networks; do
[[ -n "$id" && "$image_id" == "$image" ]] || continue
[[ "$want" == any || "$state" == running ]] && return 0
done < "$world/containers"
return 1
}
# True when a container (any: in any state; running: only a running one) has the volume or the network.
uses() {
local field="$1" wanted="$2" want="$3" id name state age config image_id labels volumes networks list
while IFS='|' read -r id name state age config image_id labels volumes networks; do
[[ -n "$id" ]] || continue
if [[ "$field" == volume ]]; then list="$volumes"; else list="$networks"; fi
[[ ",$list," == *",$wanted,"* ]] || continue
[[ "$want" == any || "$state" == running ]] && return 0
done < "$world/containers"
return 1
}
matches() {
local name="$1" state="$2" image_id="$3" labels="$4"
shift 4
local name="$1" state="$2" image_id="$3" labels="$4" volumes="$5" networks="$6"
shift 6
local -A seen=() ok=()
local filter key value
for filter in "$@"; do
@@ -110,6 +144,8 @@ matches() {
status) seen[$key]=1; [[ "$state" == "$value" ]] && ok[$key]=1 ;;
name) seen[$key]=1; [[ "$name" =~ $value ]] && ok[$key]=1 ;;
ancestor) seen[$key]=1; [[ -n "$image_id" && "$(resolve_image "$value")" == "$image_id" ]] && ok[$key]=1 ;;
volume) seen[$key]=1; [[ ",$volumes," == *",$value,"* ]] && ok[$key]=1 ;;
network) seen[$key]=1; [[ ",$networks," == *",$value,"* ]] && ok[$key]=1 ;;
*) unexpected "filter $filter" ;;
esac
done
@@ -131,10 +167,10 @@ ps_command() {
esac
shift
done
local id name state age config image_id labels out key
while IFS='|' read -r id name state age config image_id labels; do
local id name state age config image_id labels volumes networks out key
while IFS='|' read -r id name state age config image_id labels volumes networks; do
[[ -n "$id" ]] || continue
matches "$name" "$state" "$image_id" "$labels" "${filters[@]}" || continue
matches "$name" "$state" "$image_id" "$labels" "$volumes" "$networks" "${filters[@]}" || continue
if ((quiet)); then
echo "$id"
continue
@@ -145,6 +181,7 @@ ps_command() {
key="${BASH_REMATCH[1]}"
out="${out/"${BASH_REMATCH[0]}"/$(label_value "$labels" "$key" "")}"
done
[[ "$out" == *"{{"* ]] && unexpected "ps --format $format"
printf '%s\n' "$out"
done < "$world/containers"
return 0
@@ -153,18 +190,27 @@ ps_command() {
container_inspect() {
local format=""
[[ "${1:-}" == -f ]] && { format="$2"; shift 2; }
local line id name state age config image_id labels
line=$(find_container "${1:?}")
[[ -n "$line" ]] || { echo "Error: No such container: $1" >&2; exit 1; }
IFS='|' read -r id name state age config image_id labels <<< "$line"
case "$format" in
"") echo "[{\"Id\": \"$id\"}]" ;;
"{{.Created}}") created "$age" ;;
"{{.Config.Image}}") echo "$config" ;;
"{{.Name}}") echo "/$name" ;;
'{{index .Config.Labels "febe.ci.prova"}}') label_value "$labels" febe.ci.prova "<no value>" ;;
*) unexpected "container inspect -f $format" ;;
esac
(($#)) || unexpected "container inspect without a container"
local ref line id name state age config image_id labels volumes networks status=0
for ref in "$@"; do
line=$(find_container "$ref")
if [[ -z "$line" ]]; then
echo "Error: No such container: $ref" >&2
status=1
continue
fi
IFS='|' read -r id name state age config image_id labels volumes networks <<< "$line"
case "$format" in
"") echo "[{\"Id\": \"$id\"}]" ;;
"{{.Created}}") created "$age" ;;
"{{.Config.Image}}") echo "$config" ;;
"{{.Image}}") echo "$image_id" ;;
"{{.Name}}") echo "/$name" ;;
'{{index .Config.Labels "febe.ci.prova"}}') label_value "$labels" febe.ci.prova "<no value>" ;;
*) unexpected "container inspect -f $format" ;;
esac
done
return "$status"
}
rm_command() {
@@ -192,19 +238,31 @@ image_ls() {
local format="" reference=""
while (($#)); do
case "$1" in
--no-trunc) ;;
--filter) [[ "$2" == reference=* ]] || unexpected "image ls --filter $2"; reference="${2#reference=}"; shift ;;
--format) format="$2"; shift ;;
*) unexpected "image ls $1" ;;
esac
shift
done
[[ "$format" == "{{.Repository}}:{{.Tag}}" ]] || unexpected "image ls --format $format"
local id names age labels tag
while IFS='|' read -r id names age labels; do
[[ -n "$format" ]] || unexpected "image ls without --format"
local id names age labels size tag out
while IFS='|' read -r id names age labels size; do
[[ -n "$id" ]] || continue
IFS=',' read -r -a tags <<< "$names"
tags=()
[[ -z "$names" ]] || IFS=',' read -r -a tags <<< "$names"
if ((${#tags[@]} == 0)); then
[[ -z "$reference" ]] || continue
tags=("<none>:<none>")
fi
for tag in "${tags[@]}"; do
[[ -z "$reference" || "${tag%:*}" == "$reference" || "$tag" == "$reference" ]] && echo "$tag"
[[ -z "$reference" || "${tag%:*}" == "$reference" || "$tag" == "$reference" ]] || continue
out="${format//"{{.ID}}"/$id}"
out="${out//"{{.Repository}}"/${tag%:*}}"
out="${out//"{{.Tag}}"/${tag##*:}}"
out="${out//"{{.Size}}"/${size:-100MB}}"
[[ "$out" == *"{{"* ]] && unexpected "image ls --format $format"
printf '%s\n' "$out"
done
done < "$world/images"
return 0
@@ -213,34 +271,31 @@ image_ls() {
image_inspect() {
local format=""
[[ "${1:-}" == -f ]] && { format="$2"; shift 2; }
local wanted id names age labels
local wanted id names age labels size
wanted=$(resolve_image "${1:?}")
[[ -n "$wanted" ]] || { echo "Error: No such image: $1" >&2; exit 1; }
while IFS='|' read -r id names age labels; do
[[ "$id" == "$wanted" ]] || continue
case "$format" in
"") echo "[{\"Id\": \"$id\"}]" ;;
"{{.Created}}") created "$age" ;;
"{{len .RepoTags}}") if [[ -z "$names" ]]; then echo 0; else IFS=',' read -r -a tags <<< "$names"; echo "${#tags[@]}"; fi ;;
*) unexpected "image inspect -f $format" ;;
esac
done < "$world/images"
IFS='|' read -r id names age labels size <<< "$(image_line "$wanted")"
case "$format" in
"") echo "[{\"Id\": \"$id\"}]" ;;
"{{.Created}}") created "$age" ;;
"{{len .RepoTags}}") if [[ -z "$names" ]]; then echo 0; else IFS=',' read -r -a tags <<< "$names"; echo "${#tags[@]}"; fi ;;
*) unexpected "image inspect -f $format" ;;
esac
}
image_rm() {
local force=0
[[ "${1:-}" == -f ]] && { force=1; shift; }
local ref="${1:?}" wanted id names age labels left="" tag
local ref="${1:?}" wanted id names age labels size left="" tag
wanted=$(resolve_image "$ref")
[[ -n "$wanted" ]] || { echo "Error: No such image: $ref" >&2; exit 1; }
IFS='|' read -r id names age labels <<< "$(image_line "$wanted")"
IFS='|' read -r id names age labels size <<< "$(image_line "$wanted")"
tags=()
[[ -z "$names" ]] || IFS=',' read -r -a tags <<< "$names"
if [[ "$ref" != "$id" && ${#tags[@]} -gt 1 ]]; then
for tag in "${tags[@]}"; do [[ "$tag" == "$ref" ]] || left="${left:+$left,}$tag"; done
drop "$world/images" "$id"
printf '%s|%s|%s|%s
' "$id" "$left" "$age" "$labels" >> "$world/images"
printf '%s|%s|%s|%s|%s\n' "$id" "$left" "$age" "$labels" "$size" >> "$world/images"
echo "Untagged: $ref"
return 0
fi
@@ -257,17 +312,165 @@ image_rm() {
}
image_prune() {
[[ "$*" == "-f --filter until=72h" ]] || unexpected "image prune $*"
local id names age labels gone=()
while IFS='|' read -r id names age labels; do
[[ -n "$id" && -z "$names" && "$age" -ge $((72 * 60)) ]] || continue
local all=0 hours=0
case "$*" in
"-f") ;;
"-f --filter until=72h") hours=72 ;;
"-a -f --filter until=24h") all=1; hours=24 ;;
*) unexpected "image prune $*" ;;
esac
broken "image prune" && { echo "Error response from daemon: a prune operation is already running" >&2; exit 1; }
local id names age labels size gone=() tag
while IFS='|' read -r id names age labels size; do
[[ -n "$id" ]] || continue
((all)) || [[ -z "$names" ]] || continue
((age >= hours * 60)) || continue
used_by "$id" any || gone+=("$id")
done < "$world/images"
((${#gone[@]} == 0)) || echo "Deleted Images:"
for id in "${gone[@]}"; do
IFS='|' read -r id names age labels size <<< "$(image_line "$id")"
tags=()
[[ -z "$names" ]] || IFS=',' read -r -a tags <<< "$names"
for tag in "${tags[@]}"; do
echo "untagged: $tag"
echo "untagged: ${tag%:*}@sha256:0123456789abcdef"
done
drop "$world/images" "$id"
echo "deleted: $id"
echo "deleted: sha256:$id"
done
echo "Total reclaimed space: 0B"
echo
if ((${#gone[@]} > 0)); then
echo "Total reclaimed space: ${#gone[@]}00MB"
else
echo "Total reclaimed space: 0B"
fi
}
builder_prune() {
case "$*" in
"-f" | "-a -f --filter until=24h") ;;
*) unexpected "builder prune $*" ;;
esac
broken "builder prune" && { echo "ERROR: failed to prune build cache: a prune operation is already running" >&2; exit 1; }
printf 'Total:\t1.5GB\n'
}
volume_ls() {
local filters=() format='{{.Name}}' filter name age
while (($#)); do
case "$1" in
-q) ;;
--filter) filters+=("$2"); shift ;;
--format) format="$2"; shift ;;
*) unexpected "volume ls $1" ;;
esac
shift
done
[[ "$format" == '{{.Name}}' ]] || unexpected "volume ls --format $format"
while IFS='|' read -r name age; do
[[ -n "$name" ]] || continue
for filter in "${filters[@]}"; do
case "$filter" in
name=*) [[ "$name" =~ ${filter#name=} ]] || continue 2 ;;
dangling=true) uses volume "$name" any && continue 2 ;;
*) unexpected "volume ls --filter $filter" ;;
esac
done
echo "$name"
done < "$world/volumes"
return 0
}
volume_inspect() {
local format=""
[[ "${1:-}" == -f ]] && { format="$2"; shift 2; }
local line name age
line=$(volume_line "${1:?}")
[[ -n "$line" ]] || { echo "Error response from daemon: get $1: no such volume" >&2; exit 1; }
IFS='|' read -r name age <<< "$line"
case "$format" in
"") echo "[{\"Name\": \"$name\"}]" ;;
"{{.CreatedAt}}") created_in_italy "$age" ;;
*) unexpected "volume inspect -f $format" ;;
esac
}
volume_rm() {
[[ "${1:-}" == -f ]] && shift
local name="${1:?}"
[[ -n "$(volume_line "$name")" ]] || { echo "Error response from daemon: get $name: no such volume" >&2; exit 1; }
if uses volume "$name" any; then
echo "Error response from daemon: remove $name: volume is in use" >&2
exit 1
fi
drop "$world/volumes" "$name"
}
network_ls() {
local filters=() format='{{.ID}} {{.Name}}' filter id name age
while (($#)); do
case "$1" in
--no-trunc) ;;
--filter) filters+=("$2"); shift ;;
--format) format="$2"; shift ;;
*) unexpected "network ls $1" ;;
esac
shift
done
[[ "$format" == '{{.ID}} {{.Name}}' ]] || unexpected "network ls --format $format"
while IFS='|' read -r id name age; do
[[ -n "$id" ]] || continue
for filter in "${filters[@]}"; do
case "$filter" in
name=*) [[ "$name" =~ ${filter#name=} ]] || continue 2 ;;
*) unexpected "network ls --filter $filter" ;;
esac
done
echo "$id $name"
done < "$world/networks"
return 0
}
network_inspect() {
local format=""
[[ "${1:-}" == -f ]] && { format="$2"; shift 2; }
local line id name age
line=$(network_line "${1:?}")
[[ -n "$line" ]] || { echo "Error response from daemon: network $1 not found" >&2; exit 1; }
IFS='|' read -r id name age <<< "$line"
case "$format" in
"") echo "[{\"Id\": \"$id\", \"Name\": \"$name\"}]" ;;
"{{json .Created}}") echo "\"$(created_in_italy "$age" .123456789)\"" ;;
# Created of a network is a time.Time: the template prints it the way Go does, not as RFC 3339.
"{{.Created}}") date -u -d "@$((now - ${age:-0} * 60 + 7200))" "+%Y-%m-%d %H:%M:%S.123456789 +0200 CEST" ;;
*) unexpected "network inspect -f $format" ;;
esac
}
network_rm() {
local line id name age
line=$(network_line "${1:?}")
[[ -n "$line" ]] || { echo "Error response from daemon: network $1 not found" >&2; exit 1; }
IFS='|' read -r id name age <<< "$line"
case "$name" in
bridge | host | none) echo "Error response from daemon: $name is a pre-defined network and cannot be removed" >&2; exit 1 ;;
esac
if uses network "$name" running; then
echo "Error response from daemon: error while removing network: network $name id $id has active endpoints" >&2
exit 1
fi
drop "$world/networks" "$id"
}
system_df() {
case "$*" in
"") echo "TYPE TOTAL ACTIVE SIZE RECLAIMABLE" ;;
"--format {{.Type}}|{{.Size}}|{{.Reclaimable}}")
printf '%s\n' "Images|9.1GB|6.2GB (68%)" "Containers|120MB|80MB (66%)" "Local Volumes|3.4GB|1.1GB (32%)" "Build Cache|5.3GB|4.8GB"
;;
*) unexpected "system df $*" ;;
esac
}
case "${1:-}" in
@@ -285,18 +488,28 @@ case "${1:-}" in
*) unexpected "image $sub" ;;
esac
;;
builder) [[ "${2:-}" == prune ]] || unexpected "$*"; shift 2; builder_prune "$@" ;;
buildx) [[ "${2:-}" == rm ]] || unexpected "$*"; echo "ERROR: no builder \"${4:-}\" found" >&2; exit 1 ;;
volume)
case "${2:-}" in
inspect) grep -qxF -- "${3:?}" "$world/volumes" || { echo "Error: no such volume: $3" >&2; exit 1; } ;;
rm)
[[ "${3:-}" == -f ]] || unexpected "$*"
grep -vxF -- "${4:?}" "$world/volumes" > "$world/volumes.new"
mv "$world/volumes.new" "$world/volumes"
;;
*) unexpected "$*" ;;
sub="${2:-}"
shift 2
case "$sub" in
ls) volume_ls "$@" ;;
inspect) volume_inspect "$@" ;;
rm) volume_rm "$@" ;;
*) unexpected "volume $sub" ;;
esac
;;
system) [[ "${2:-}" == df ]] || unexpected "$*"; echo "TYPE TOTAL ACTIVE SIZE RECLAIMABLE" ;;
network)
sub="${2:-}"
shift 2
case "$sub" in
ls) network_ls "$@" ;;
inspect) network_inspect "$@" ;;
rm) network_rm "$@" ;;
*) unexpected "network $sub" ;;
esac
;;
system) [[ "${2:-}" == df ]] || unexpected "$*"; shift 2; system_df "$@" ;;
*) unexpected "$*" ;;
esac
@@ -0,0 +1,33 @@
[
[
{"id": 140, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "main", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/main", "created_at": "2026-10-20T19:42:15+02:00"},
{"id": 139, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-d0a3b4c5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-d0a3b4c5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1", "created_at": "2026-10-20T19:42:11+02:00"},
{"id": 138, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "0.1.1", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/0.1.1", "created_at": "2026-10-20T18:05:00+02:00"},
{"id": 137, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "latest", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/latest", "created_at": "2026-10-14T10:00:00+02:00"},
{"id": 136, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "0.1.0", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/0.1.0", "created_at": "2026-10-14T10:00:00+02:00"},
{"id": 113, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-cf2a3b4", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-cf2a3b4", "created_at": "2026-10-13T09:00:00+02:00"},
{"id": 101, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-0a1b2c3", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-0a1b2c3", "created_at": "2026-10-01T09:00:00+02:00"},
{"id": 112, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-be1f2a3", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-be1f2a3", "created_at": "2026-10-12T09:00:00+02:00"},
{"id": 111, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-ad0e1f2", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-ad0e1f2", "created_at": "2026-10-11T09:00:00+02:00"},
{"id": 110, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-9d0e1f2", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-9d0e1f2", "created_at": "2026-10-10T09:00:00+02:00"},
{"id": 99, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha256:4f3c2b1a0e9d8c7b6a5f4e3d2c1b0a9f8e7d6c5b4a3f2e1d0c9b8a7f6e5d4c3b", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha256:4f3c2b1a0e9d8c7b6a5f4e3d2c1b0a9f8e7d6c5b4a3f2e1d0c9b8a7f6e5d4c3b", "created_at": "2026-09-20T09:00:00+02:00"},
{"id": 109, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-8c9d0e1", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-8c9d0e1", "created_at": "2026-10-09T09:00:00+02:00"}
],
[
{"id": 113, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-cf2a3b4", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-cf2a3b4", "created_at": "2026-10-13T09:00:00+02:00"},
{"id": 108, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-7b8c9d0", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-7b8c9d0", "created_at": "2026-10-08T09:00:00+02:00"},
{"id": 107, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-6a7b8c9", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-6a7b8c9", "created_at": "2026-10-07T09:00:00+02:00"},
{"id": 106, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-5f6a7b8", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-5f6a7b8", "created_at": "2026-10-06T09:00:00+02:00"},
{"id": 105, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-4e5f6a7", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-4e5f6a7", "created_at": "2026-10-05T01:00:00+02:00"},
{"id": 104, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-3d4e5f6", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-3d4e5f6", "created_at": "2026-10-04T23:30:00Z"},
{"id": 103, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-2c3d4e5", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-2c3d4e5", "created_at": "2026-10-03T07:00:00Z"},
{"id": 102, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-1b2c3d4", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-1b2c3d4", "created_at": "2026-10-02T09:00:00+02:00"},
{"id": 100, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "0.2.0-rc.1", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/0.2.0-rc.1", "created_at": "2026-09-01T09:00:00+02:00"},
{"id": 97, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-zzzzzzz", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-zzzzzzz", "created_at": "2026-09-01T09:00:00+02:00"},
{"id": 96, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-1a2b3c", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-1a2b3c", "created_at": "2026-09-01T09:00:00+02:00"},
{"id": 95, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-ABCDEF0", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-ABCDEF0", "created_at": "2026-09-01T09:00:00+02:00"},
{"id": 94, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-e1f2a3b4", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-e1f2a3b4"},
{"id": 93, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe-strumenti", "version": "sha-0000000", "html_url": "https://gitea.example/Alby96/-/packages/container/febe-strumenti/sha-0000000", "created_at": "2026-08-01T09:00:00+02:00"},
{"id": 92, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "generic", "name": "febe", "version": "sha-1111111", "html_url": "https://gitea.example/Alby96/-/packages/generic/febe/sha-1111111", "created_at": "2026-08-01T09:00:00+02:00"}
]
]