diff --git a/.gitea/scripts/controlli.sh b/.gitea/scripts/controlli.sh index 47c6c7f..023a0de 100755 --- a/.gitea/scripts/controlli.sh +++ b/.gitea/scripts/controlli.sh @@ -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 diff --git a/.gitea/scripts/costruisci-immagine.sh b/.gitea/scripts/costruisci-immagine.sh index a4cff5d..9a5e9b1 100755 --- a/.gitea/scripts/costruisci-immagine.sh +++ b/.gitea/scripts/costruisci-immagine.sh @@ -8,6 +8,11 @@ # già nella configurazione del client, il demone non # parla mai con il registro (proverebbe HTTPS) # +# L'immagine è un manifest semplice, senza attestazioni (--provenance=false --sbom=false). Con le attestazioni, che +# buildx aggiunge da sé, sarebbe un indice: Gitea tiene ogni manifest figlio come una versione a sé, sha256:… senza +# etichetta, con la configurazione e gli strati, e togliere dal registro un'etichetta :sha- toglierebbe solo l'indice. +# Con un manifest semplice gli strati stanno nella versione dell'etichetta, e la pulizia del registro li libera davvero. +# # Variabili richieste: BUILDER, VERSIONE, GIT_COMMIT, FLUSSO (verifica o rilascio), ESECUZIONE (gitea.run_id). # Le etichette febe.ci.* dicono quale flusso, esecuzione, ramo e commit hanno costruito l'immagine. Non servono alla # pulizia: stanno anche nelle immagini pubblicate e Docker le copia in ogni contenitore creato da quelle, anche in un @@ -19,7 +24,7 @@ modo="${1:?Indica il modo: archivio o pubblica.}" shift cd "$(git rev-parse --show-toplevel)" -comuni=(--builder "${BUILDER:?}" -f docker/Dockerfile +comuni=(--builder "${BUILDER:?}" -f docker/Dockerfile --provenance=false --sbom=false --build-arg "VERSION=${VERSIONE:?}" --build-arg "GIT_COMMIT=${GIT_COMMIT:?}" --label "febe.ci.workflow=${FLUSSO:?}" --label "febe.ci.run=${ESECUZIONE:?}" --label "febe.ci.ref=${GITHUB_REF_NAME:-}" --label "febe.ci.commit=${GITHUB_SHA:-}") diff --git a/.gitea/scripts/pulizia-docker.sh b/.gitea/scripts/pulizia-docker.sh index 9081122..8f20e85 100755 --- a/.gitea/scripts/pulizia-docker.sh +++ b/.gitea/scripts/pulizia-docker.sh @@ -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=, che mette solo prova-immagine.sh con # «docker run --label» e che nessuna immagine porta (lo controlla PipelineTests), E il nome esatto # febe-prova- (gli altri contenitori della prova, senza nome, girano con --rm e Docker li @@ -16,41 +18,154 @@ # - builder buildx: il contenitore buildx_buildkit_febe-ci-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-… (il contenitore del lavoro, i suoi volumi e -env, la sua rete +# --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 tutto ciò che ha creato l'esecuzione (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) non usata da +# 24 ore, 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 --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. +# Gli argomenti si controllano tutti prima di toccare Docker: un'opzione diversa da --prova (--dry-run, -n, --Prova) o +# un argomento in più (prova senza trattini) fermano tutto con codice 2, invece di far partire la pulizia vera al posto +# della prova. # -# 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. +# 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 toglie mai un'immagine usata da un contenitore, nemmeno fermo; con -a, però, le toglie i +# nomi in più, e lo script li scrive (nella prova li stima, secondo lo store). Sul registro mai main, latest o una +# versione X.Y.Z: solo le etichette sha- della verifica. +# +# 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:-}" +uso() { + [[ -z "${1:-}" ]] || echo "$1" >&2 + echo "Uso: $0 esecuzione | penzolanti | residui [minuti] | settimanale | completa [--prova]" >&2 + exit 2 +} + +prova=0 +argomenti=() +for argomento in "$@"; do + case "$argomento" in + --prova) prova=1 ;; + -*) uso "Opzione sconosciuta: «$argomento». L'unica è --prova." ;; + *) argomenti+=("$argomento") ;; + esac +done +modo="${argomenti[0]:-}" +case "$modo" in + esecuzione) ((${#argomenti[@]} == 2)) || uso "Il modo esecuzione vuole il numero dell'esecuzione e nient'altro." ;; + residui) ((${#argomenti[@]} <= 2)) || uso "Il modo residui vuole al più i minuti." ;; + penzolanti | settimanale | completa) ((${#argomenti[@]} == 1)) || uso "Il modo $modo non vuole altri argomenti: «${argomenti[1]}»." ;; + *) uso ;; +esac +cartella_script="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" problemi=0 +# In 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-. Gli stati che seguono # restringono la scelta (Docker li unisce in OR). Esce con 1 se Docker non risponde. @@ -68,33 +183,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:, 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: (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 +230,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 +321,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 +339,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 +352,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 +365,494 @@ 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-, 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 dei contenitori, accesi o fermi, tranne quelli che la pulizia toglierebbe: «identificativo immagine» una +# per riga, l'immagine come la si è data a docker run (un nome o un identificativo). 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}} {{.Config.Image}}' "$id" 2> /dev/null + done <<< "$elenco" + return 0 +} + +# Il nome completo di un nome d'immagine, come lo ordina Docker: docker.io/library/ o docker.io/ davanti ai nomi di +# Docker Hub scritti senza dominio, :latest se manca l'etichetta. +nome_completo() { + local nome="$1" primo + [[ "${nome##*/}" == *:* ]] || nome="$nome:latest" + if [[ "$nome" != */* ]]; then + echo "docker.io/library/$nome" + return + fi + primo="${nome%%/*}" + if [[ "$primo" == *.* || "$primo" == *:* || "$primo" == localhost ]]; then + echo "$nome" + else + echo "docker.io/$nome" + fi +} + +# In prova: i nomi che «image prune -a» toglierebbe a un'immagine che un contenitore usa (i nomi e le immagini dei +# contenitori, come li scrivono docker image ls e docker container inspect), uno per riga. L'immagine resta, ma i nomi +# in più no (moby). Con lo store classico Docker toglie i nomi in ordine alfabetico del nome completo e si ferma +# all'ultimo, l'unico che rifiuta di togliere perché un contenitore usa l'immagine (daemon/images/image_prune.go e +# image_delete.go, isSingleReference): può andarsene anche il nome da cui il contenitore è stato creato. Con containerd +# restano i nomi da cui i contenitori sono stati creati e, se uno la usa per identificativo e nessun nome resterebbe, +# l'ultimo in ordine alfabetico (daemon/containerd/image_prune.go). +nomi_che_perde() { + local id="$1" nomi="$2" configurazioni="$3" nome completo configurazione resto per_id=0 ordinati quanti + local -A protetti=() + local -a lista=() via=() + ordinati=$(while read -r nome; do + [[ -n "$nome" ]] && printf '%s %s\n' "$(nome_completo "$nome")" "$nome" + done <<< "$nomi" | LC_ALL=C sort) + quanti=$(grep -c . <<< "$ordinati") + ((quanti > 1)) || return 0 + if [[ "$store" != containerd ]]; then + sed '$d' <<< "$ordinati" | cut -d' ' -f2- + return 0 + fi + read -r -a lista <<< "$configurazioni" + for configurazione in "${lista[@]}"; do + if [[ "$id" == "$configurazione"* || "$id" == "sha256:$configurazione"* ]]; then + per_id=1 + elif [[ "$configurazione" == *@* ]]; then + [[ "${configurazione#*@}" == "$id" ]] && per_id=1 + resto="${configurazione%%@*}" + [[ "${resto##*/}" == *:* ]] && protetti[$(nome_completo "$resto")]=1 + else + protetti[$(nome_completo "$configurazione")]=1 + fi + done + while read -r completo nome; do + [[ -n "${protetti[$completo]:-}" ]] || via+=("$nome") + done <<< "$ordinati" + if ((per_id && ${#via[@]} == quanti)); then + unset "via[$((quanti - 1))]" + fi + ((${#via[@]} == 0)) || printf '%s\n' "${via[@]}" + return 0 +} + +# In 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. Con +# «tutte», di un'immagine che un contenitore usa, i nomi in più che Docker le toglierebbe. È 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 configurazione + local -A nomi=() elenco_nomi=() dimensioni=() aveva_nomi=() usata_da=() + local ordine=() + if ! usate=$(immagini_in_uso) \ + || ! elenco=$(docker image ls --no-trunc --format '{{.ID}}|{{.Repository}}:{{.Tag}}|{{.Size}}'); then + avviso "Non riesco a elencare le immagini." + return 0 + fi + if [[ "$store" != classico ]] && ((minimo > 0)); then + echo " (l'età qui è quella dell'immagine, dalla costruzione; con lo store di containerd la pulizia vera conta da quando il nome è arrivato sul demone, e un nome riscaricato tiene la data di prima: l'elenco è solo indicativo)" + fi + while read -r id configurazione; do + [[ -n "${id:-}" ]] || continue + usata_da[$id]="${usata_da[$id]:+${usata_da[$id]} }$configurazione" + done <<< "$usate" + while IFS='|' read -r id nome dimensione; do + [[ -n "${id:-}" ]] || continue + if [[ -z "${dimensioni[$id]+x}" ]]; then + ordine+=("$id") + dimensioni[$id]="${dimensione:-?}" + nomi[$id]="" + elenco_nomi[$id]="" + fi + [[ "$nome" == ":" ]] && continue + aveva_nomi[$id]=1 + fra "$nome" "${nomi_previsti[@]}" && continue + nomi[$id]="${nomi[$id]:+${nomi[$id]}, }$nome" + [[ "$nome" == *":" ]] || elenco_nomi[$id]+="$nome"$'\n' + 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 + breve="${id#sha256:}" + if [[ -n "${usata_da[$id]+x}" ]]; then + # Un contenitore la usa: resta. Con -a, però, Docker le toglie i nomi in più. + [[ "$quali" == tutte && -n "${elenco_nomi[$id]}" ]] || continue + eta=$(eta_minuti "$(docker image inspect -f '{{.Created}}' "$id" 2> /dev/null)") + ((eta >= minimo)) || continue + while read -r nome; do + [[ -n "$nome" ]] || continue + echo " toglierei il nome $nome; l'immagine ${breve:0:12} resta, perché la usa un contenitore" + quante=$((quante + 1)) + conta "nomi tolti a immagini che restano" + done < <(nomi_che_perde "$id" "${elenco_nomi[$id]}" "${usata_da[$id]}") + continue + fi + [[ "$quali" == senza-nome && -n "${aveva_nomi[$id]:-}" ]] && continue + eta=$(eta_minuti "$(docker image inspect -f '{{.Created}}' "$id" 2> /dev/null)") + ((eta >= minimo)) || continue + nome="${nomi[$id]}" + [[ -n "$nome" ]] || nome="un'immagine senza nome" + echo " toglierei $nome (${breve:0:12}) · ${dimensioni[$id]} · creata $(durata "$eta") fa" + quante=$((quante + 1)) + if [[ "$quali" == senza-nome ]]; then + conta "immagini senza nome" + else + conta "immagini che nessun contenitore usa" + fi + done + ((quante > 0)) || echo " nessuna" +} + +# In 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") +} + +# Lo store delle immagini del demone: «containerd» (io.containerd.snapshotter.v1, predefinito nelle installazioni nuove +# di Docker Engine dalla 29) o «classico» (overlay2 e gli altri driver di prima). Ne dipende da quando contano le 24 ore +# di image prune --filter until: con lo store classico dalla costruzione dell'immagine (Created della configurazione), +# con containerd da quando il nome è arrivato sul demone (CreatedAt del suo record, che un nuovo pull dello stesso nome +# non cambia). +store="" +rileva_store() { + local stato + if ! stato=$(docker info --format '{{json .DriverStatus}}' 2> /dev/null); then + store=sconosciuto + elif [[ "$stato" == *io.containerd.snapshotter* ]]; then + store=containerd + else + store=classico + fi + case "$store" in + containerd) echo "== Store delle immagini del demone: containerd (le 24 ore contano da quando un nome è arrivato sul demone)" ;; + classico) echo "== Store delle immagini del demone: classico (le 24 ore contano dalla costruzione dell'immagine)" ;; + *) echo "== Store delle immagini del demone: non lo so, docker info non risponde" ;; + esac +} + +# Ogni immagine con ciascuno dei suoi nomi, «identificativo nome» una per riga (: se non ne ha). +immagini_e_nomi() { + docker image ls --no-trunc --format '{{.ID}} {{.Repository}}:{{.Tag}}' 2> /dev/null +} + +# 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. I nomi si +# confrontano prima e dopo: con -a Docker toglie anche i nomi in più di un'immagine che un contenitore usa e che resta, +# e il registro del lavoro lo dice. +pota_immagini() { + local cosa="$1" uscita prima dopo recuperato prima_nomi dopo_nomi dopo_id id nome breve + shift + prima_nomi=$(immagini_e_nomi) + prima=$(cut -d' ' -f1 <<< "$prima_nomi" | sort -u | grep -c .) + if ! uscita=$("$@" 2>&1); then + avviso "Non riesco a togliere le $cosa: $(tail -n 1 <<< "$uscita")" + return 0 + fi + dopo_nomi=$(immagini_e_nomi) + dopo_id=$(cut -d' ' -f1 <<< "$dopo_nomi" | sort -u) + dopo=$(grep -c . <<< "$dopo_id") + while read -r id nome; do + [[ -n "${nome:-}" && "$nome" != *":" ]] || continue + grep -qxF -- "$id $nome" <<< "$dopo_nomi" && continue + if grep -qxF -- "$id" <<< "$dopo_id"; then + breve="${id#sha256:}" + echo " tolto il nome $nome; l'immagine ${breve:0:12} resta" + conta "nomi tolti a immagini che restano" + else + echo " tolta $nome" + fi + done <<< "$prima_nomi" + recuperato=$(spazio_recuperato "$uscita") + if [[ "$prima" =~ ^[0-9]+$ && "$dopo" =~ ^[0-9]+$ ]]; then + echo " $cosa: $((prima - dopo)) tolte, $recuperato recuperati" + note+=("$cosa: $((prima - dopo)) tolte ($prima prima, $dopo dopo), $recuperato recuperati") + else + echo " $cosa: $recuperato recuperati" + note+=("$cosa: $recuperato recuperati") + fi +} + +# 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- prima di ogni DELETE. +# Ogni rifiuto dell'API è un avviso che non fa diventare rosso il lavoro. Le versioni sha256:… senza etichetta (i +# manifest figli di un indice, con gli strati) non si toccano mai: l'API non dice se un'etichetta le usa ancora. Si +# dice solo quante sono; la CI pubblica manifest semplici (costruisci-immagine.sh), quindi non dovrebbero essercene, e +# quelle che nessuna etichetta usa le toglie una regola di pulizia di Gitea (docs/processo.md, «Registro dei container»). +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 + local senza_etichetta quante + if ! scelte=$(node "$cartella_script/versioni-registro.js" "$tenere" "$cartella"/pagina-*.json) \ + || ! senza_etichetta=$(node "$cartella_script/versioni-registro.js" senza-etichetta "$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" + quante=$(grep -c . <<< "$senza_etichetta") + if ((quante > 0)); then + echo " $quante versioni senza etichetta (sha256:…, i manifest di un indice con i loro strati): restano, questa pulizia non le tocca mai (docs/processo.md, «Registro dei container»)" + note+=("registro: $quante versioni sha256:… senza etichetta, che restano") + fi + if [[ -z "$scelte" ]]; then + echo " niente da togliere" + return 0 + fi + local versione creata + while IFS=$'\t' read -r versione creata; do + [[ -n "${versione:-}" ]] || continue + if [[ ! "$versione" =~ ^sha-[0-9a-f]{7,40}$ ]]; then + segnala "Versione inattesa «$versione» fra quelle da togliere: resta." + continue + fi + if ((prova)); then + echo " toglierei $versione (pubblicata il $creata)" + conta "etichette sha- sul registro" + continue + fi + codice=$(chiedi DELETE "$base/$versione" /dev/null) + if [[ "$codice" == 204 ]]; then + echo " $versione tolta (pubblicata il $creata)" + conta "etichette sha- sul registro" + else + segnala "Non riesco a togliere $versione dal registro: l'API risponde $(spiega "$codice")." + fi + done <<< "$scelte" +} + +# La cache con lo stesso limite del lunedì: senza, a ogni push di ogni ramo se ne andrebbero gli strati intermedi e le +# cache montate (RUN --mount=type=cache) che le costruzioni degli altri progetti hanno appena usato. +penzolanti() { + echo "== Immagini senza nome che nessun contenitore usa e cache di costruzione penzolante non usata da 24 ore, di tutti i progetti" + if ((prova)); then + elenca_immagini 0 senza-nome + elenca_cache + return 0 + fi + pota_immagini "immagini senza nome" docker image prune -f + pota_cache "cache di costruzione penzolante" docker builder prune -f --filter "until=24h" +} + +settimanale() { + resti_della_ci + echo "== Immagini senza nome più vecchie di 72 ore che nessun contenitore usa" + if ((prova)); then + elenca_immagini 4320 senza-nome + else + pota_immagini "immagini senza nome" docker image prune -f --filter "until=72h" + fi +} + +# 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) + rileva_store docker system df || true - settimanale + if [[ "$modo" == settimanale ]]; then settimanale; else completa; fi docker system df || true + riepilogo ;; - *) - echo "Uso: $0 esecuzione | residui [minuti] | settimanale" >&2 - exit 2 - ;; + *) uso ;; esac if ((problemi > 0)); then echo "Pulizia finita con $problemi avvisi." - [[ "$modo" == settimanale ]] && exit 1 + [[ "$modo" == settimanale || "$modo" == completa ]] && exit 1 fi exit 0 diff --git a/.gitea/scripts/versioni-registro.js b/.gitea/scripts/versioni-registro.js new file mode 100644 index 0000000..d50c651 --- /dev/null +++ b/.gitea/scripts/versioni-registro.js @@ -0,0 +1,82 @@ +"use strict"; +// Chooses the tags to remove from Gitea's container registry (pulizia-docker.sh, mode «completa»). It only reads the +// files it is given: no network, no writes, so it is tested with a JSON file. +// +// node versioni-registro.js ... +// node versioni-registro.js senza-etichetta ... +// +// Each file is a page of the answer of GET /api/v1/packages/{owner}/container/febe of Gitea 28: a list of versions with +// «type», «name», «version» and «created_at» (an empty page may be «[]» or «null»). Only the versions of the container +// package «febe» count, and a version found in two pages counts once. Both forms print, oldest first and one per line, +// «versioncreated». +// +// With a number N: the sha-<7 to 40 hex digits> tags beyond the N newest by creation date. Everything else always +// stays: main, latest, the X.Y.Z releases (X.Y.Z-rc.N too), the digests (sha256:…), any other tag and a sha- tag +// without a date that can be read. +// +// With «senza-etichetta»: the untagged versions, sha256:<64 hex digits>. They are the manifests of an image index, +// which Gitea keeps as versions of their own with the configuration and the layers; nothing here removes them (Gitea +// cannot be asked through this API whether a tag still uses one), the cleanup only says how many there are. +// +// If a file is not a JSON list it exits with 2 and prints nothing: when in doubt nothing is removed. +// Messages are in Italian, like every message of the CI. +const fs = require("fs"); + +const [mode, ...pages] = process.argv.slice(2); +const untagged = mode === "senza-etichetta"; +if (!(untagged || /^[0-9]+$/.test(mode || "")) || pages.length === 0) { + console.error("Uso: node versioni-registro.js | senza-etichetta ..."); + process.exit(2); +} + +const shaTag = /^sha-[0-9a-f]{7,40}$/; +const digest = /^sha256:[0-9a-f]{64}$/; +const versions = new Map(); +for (const file of pages) { + let page; + try { + page = JSON.parse(fs.readFileSync(file, "utf8").replace(/^/, "")); + } catch (error) { + console.error(`${file}: ${error.message}`); + process.exit(2); + } + if (page === null) { + continue; + } + if (!Array.isArray(page)) { + console.error(`${file}: non è un elenco di versioni`); + process.exit(2); + } + for (const version of page) { + if (version && version.type === "container" && version.name === "febe" && typeof version.version === "string") { + versions.set(version.version, version); + } + } +} + +const dated = (version) => ({ + name: version.version, + created: String(version.created_at), + time: Date.parse(version.created_at), + id: Number(version.id) || 0, +}); + +let chosen; +if (untagged) { + chosen = [...versions.values()] + .filter((version) => digest.test(version.version)) + .map(dated) + .sort((a, b) => (Number.isFinite(a.time) ? a.time : 0) - (Number.isFinite(b.time) ? b.time : 0) || a.id - b.id); +} else { + chosen = [...versions.values()] + .filter((version) => shaTag.test(version.version)) + .map(dated) + .filter((version) => Number.isFinite(version.time)) + .sort((a, b) => b.time - a.time || b.id - a.id) + .slice(Number(mode)) + .reverse(); +} + +for (const version of chosen) { + process.stdout.write(`${version.name}\t${version.created}\n`); +} diff --git a/.gitea/workflows/pulizia.yml b/.gitea/workflows/pulizia.yml index aaa8de7..47a2ebf 100644 --- a/.gitea/workflows/pulizia.yml +++ b/.gitea/workflows/pulizia.yml @@ -1,19 +1,33 @@ -# Pulizia settimanale (il lunedì alle 4:17, ora del server di Gitea) e a mano (Actions ▸ pulizia ▸ Esegui) del demone -# Docker del runner. -# Ogni esecuzione di verifica e di rilascio toglie già ciò che crea; qui si toglie ciò che resta di esecuzioni -# interrotte (annullate o scadute) e ciò che invecchia. Il demone è lo stesso di Encelado, Mimante e degli altri -# progetti di Alberto, e ci può girare un Febe vero: si toccano solo i contenitori di prova fermi (etichetta -# febe.ci.prova e nome febe-prova-, mai le etichette febe.ci.* che un Febe vero eredita dall'immagine), i -# nomi locali febe-ci:, i builder febe-ci- e le immagini senza nome più vecchie di 72 ore. Mai -# le immagini degli altri progetti, mai la cache di costruzione del demone, mai i volumi con un nome. Un contenitore di -# prova ancora acceso si segnala e il lavoro diventa rosso. Dettagli in .gitea/scripts/pulizia-docker.sh e in -# docs/processo.md, «Pulizia». +# Pulizia del lunedì (alle 4:17, ora del server di Gitea) e a mano (Actions ▸ pulizia ▸ Esegui) del demone Docker del +# runner e del registro dei container. A mano, con «Solo prova» spuntato, elenca che cosa toglierebbe e non toglie +# nulla: da lanciare prima della prima pulizia vera e dopo ogni cambio dello script. +# Ogni esecuzione di verifica e di rilascio toglie già ciò che crea e, per tutti, le immagini senza nome e la cache di +# costruzione penzolante non usata da 24 ore. Qui, dal 21 ottobre 2026 (decisione di Alberto: eliminare tutto ciò che +# non serve più), si toglie anche ciò che non serve più a nessuno, di qualunque progetto (pulizia-docker.sh completa): +# - i resti della CI di Febe: contenitori di prova fermi (etichetta febe.ci.prova e nome febe-prova-, mai +# le etichette febe.ci.* che un Febe vero eredita dall'immagine), nomi locali febe-ci:, builder +# febe-ci-, l'immagine febe:ci del vecchio flusso; +# - i resti di act_runner: contenitori fermi, volumi e reti GITEA-ACTIONS-TASK-… che nessun contenitore usa, più +# vecchi di 90 minuti; +# - le immagini che nessun contenitore usa, né acceso né fermo, create più di 24 ore fa (di un'immagine in uso Docker +# toglie i nomi in più), e la cache di costruzione del demone non usata da 24 ore. Le immagini di base +# (node:24-trixie, moby/buildkit, …) si riscaricano alla prima esecuzione che le chiede; +# - con il segreto REGISTRY_TOKEN, le etichette sha- del registro oltre le 10 più recenti; mai main, latest o X.Y.Z. +# Mai system prune, container prune, volume prune o network prune; mai un contenitore, un volume o una rete che non sia +# della CI. Un contenitore di prova ancora acceso si segnala e il lavoro diventa rosso; un rifiuto dell'API del +# registro è solo un avviso. Dettagli in .gitea/scripts/pulizia-docker.sh e in docs/processo.md, «Pulizia». name: pulizia on: schedule: - cron: "17 4 * * 1" workflow_dispatch: + inputs: + prova: + description: "Solo prova: elenca che cosa toglierebbe e non toglie nulla" + type: boolean + required: false + default: false permissions: contents: read @@ -29,9 +43,26 @@ defaults: jobs: docker: runs-on: ubuntu-latest - timeout-minutes: 20 + timeout-minutes: 30 steps: - uses: actions/checkout@v4 - - name: Resti della CI di Febe e immagini senza nome - run: bash .gitea/scripts/pulizia-docker.sh settimanale + # Gitea 28 mette nell'evento la casella «prova» come testo, "true" o "false"; il lunedì l'evento non ha input e + # la pulizia è quella vera. Un avvio con l'API passa il valore così com'è: qualunque altro («True», «1») ferma il + # lavoro senza toccare nulla. Il token del registro va solo nell'ambiente di questo passo e non si stampa mai. + - name: Pulizia completa del demone Docker e del registro + env: + PROVA: ${{ gitea.event.inputs.prova }} + REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }} + GITEA_API: ${{ gitea.server_url }}/api/v1 + PROPRIETARIO: ${{ gitea.repository_owner }} + run: | + case "${PROVA:-}" in + true) bash .gitea/scripts/pulizia-docker.sh completa --prova ;; + "" | false) bash .gitea/scripts/pulizia-docker.sh completa ;; + *) + VALORE=$(printf '%s' "$PROVA" | tr -c 'A-Za-z0-9' '_' | cut -c 1-20) + echo "::error::La casella «prova» vale true o false, non «$VALORE»: non tolgo nulla." + exit 2 + ;; + esac diff --git a/.gitea/workflows/rilascio.yml b/.gitea/workflows/rilascio.yml index 3497b4b..017551d 100644 --- a/.gitea/workflows/rilascio.yml +++ b/.gitea/workflows/rilascio.yml @@ -7,7 +7,8 @@ # scansionata con Trivy come nella verifica (una CRITICAL con correzione ferma tutto), poi pubblicata sul registro # dei container di Gitea come //febe:X.Y.Z e :latest (solo per le versioni senza # trattino). Il lavoro dice se l'ha pubblicata, e alla fine toglie sempre immagini, contenitori, cache e builder -# dell'esecuzione; +# dell'esecuzione, poi le immagini senza nome e la cache di costruzione penzolante non usata da 24 ore di tutti i +# progetti del demone; # 4. release: solo dopo le prove, l'installatore e l'immagine. Crea la release (o la completa, se esiste già) con # installatore, zip portabile, modello Unraid e l'archivio per Docker Compose (compose.yml con il profilo seccomp # accanto); le note dicono dove sta l'immagine, o che non è stata pubblicata. @@ -211,6 +212,9 @@ jobs: run: | if [ -n "${ARCHIVIO:-}" ]; then rm -f "$ARCHIVIO"; fi bash .gitea/scripts/pulizia-docker.sh esecuzione "$ESECUZIONE" + # Poi, per tutti i progetti del demone, ciò che nessuno usa: immagini senza nome e cache di costruzione + # penzolante non usata da 24 ore. Non fa mai fallire il lavoro. + bash .gitea/scripts/pulizia-docker.sh penzolanti || echo "::warning::La pulizia di ciò che nessuno usa non è riuscita." release: runs-on: ubuntu-latest diff --git a/.gitea/workflows/verifica.yml b/.gitea/workflows/verifica.yml index 5c76c53..23cd7d6 100644 --- a/.gitea/workflows/verifica.yml +++ b/.gitea/workflows/verifica.yml @@ -11,7 +11,8 @@ # immagine dopo l'installatore: l'immagine Docker costruita con buildx, provata senza rete (parte, salute, # Chromium, it_IT) e scansionata con Trivy (si ferma per una CRITICAL con correzione); solo dopo un push # su main la pubblica come :main e :sha-<7 caratteri> (:latest resta al rilascio). Alla fine, sempre, -# toglie immagini, contenitori, cache e builder di questa esecuzione. +# toglie immagini, contenitori, cache e builder di questa esecuzione, poi le immagini senza nome e la +# cache di costruzione penzolante non usata da 24 ore di tutti i progetti del demone. # # Niente «pull_request»: in Gitea una richiesta di unione mostra lo stato del suo ultimo commit, che il push del ramo # ha già verificato; pull_request rifarebbe tutto sullo stesso commit (refs/pull/N/head) sull'unico runner. @@ -308,3 +309,6 @@ jobs: fi if [ -n "${ARCHIVIO:-}" ]; then rm -f "$ARCHIVIO"; fi bash .gitea/scripts/pulizia-docker.sh esecuzione "$ESECUZIONE" + # Poi, per tutti i progetti del demone, ciò che nessuno usa: immagini senza nome e cache di costruzione + # penzolante non usata da 24 ore. Non fa mai fallire il lavoro. + bash .gitea/scripts/pulizia-docker.sh penzolanti || echo "::warning::La pulizia di ciò che nessuno usa non è riuscita." diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f9fc79..e5f6a97 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,14 @@ Sviluppo e qualità: - Prove dell'interfaccia senza attese a tempo fisso (#8): le risposte in ritardo si trattengono finché la prova non le rilascia, e ciò che non deve succedere si controlla quando la pagina ha finito le sue richieste. Restano verdi anche con Chrome rallentato 20 volte. +- **Pulizia della CI**: oltre a ciò che crea, la CI toglie ciò che non serve più a nessuno sul demone Docker del runner. + Dopo ogni lavoro «immagine» se ne vanno le immagini senza nome e la cache di costruzione che nessuno usa da 24 ore. + Ogni lunedì se ne vanno le immagini che nessun contenitore usa e la cache più vecchie di 24 ore, i resti dei lavori di + act_runner e, con `REGISTRY_TOKEN`, le `:sha-` del registro oltre le 10 più recenti (mai `:main`, `:latest` o una + versione). Non tocca mai un contenitore, un volume o una rete che non sia della CI. A mano, «Solo prova» elenca che + cosa toglierebbe senza togliere nulla (`docs/processo.md`, «Pulizia»). +- Immagine Docker: si pubblica come manifest semplice, senza attestazioni, così togliere un'etichetta dal registro ne + libera davvero gli strati. ## 0.1.1 diff --git a/CLAUDE.md b/CLAUDE.md index cba71bc..c5f2acf 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -43,7 +43,7 @@ Conserva: tappa in corso, file modificati, controlli ancora da eseguire, domande - CI in `.gitea/workflows/`, script comuni in `.gitea/scripts/`: - `verifica.yml` a ogni push su qualunque ramo (non sui tag) e a mano, niente pull_request: controlli e gitleaks; compilazione di tutta la soluzione e tutte le prove di `tests/Febe.Tests` con Chromium, Xvfb, ffmpeg e NSIS veri in Debian, nessuna saltata, anche con il seme dell'esecuzione (`FEBE_SEME_PROVA`); installatore e zip `-ci.`; immagine provata senza rete e scansionata con Trivy. Dopo un push su main pubblica `:main` e `:sha-` (con il segreto `REGISTRY_TOKEN`; senza, un avviso). - `rilascio.yml` a ogni tag `vX.Y.Z`: immagine `:X.Y.Z` (e `:latest`) sul registro di Gitea, installatore Windows e release. - - `pulizia.yml` ogni lunedì: solo i resti della CI di Febe sul demone Docker condiviso. + - `pulizia.yml` ogni lunedì e a mano (con «Solo prova» elenca e non toglie nulla): resti della CI di Febe e di act_runner, immagini che nessun contenitore usa e cache di costruzione più vecchie di 24 ore, di tutti i progetti; con `REGISTRY_TOKEN` le `:sha-` oltre le 10 più recenti, mai `main`, `latest` o `X.Y.Z`. Mai contenitori, volumi o reti che non siano della CI, mai `system prune`. Ogni lavoro «immagine» toglie alla fine anche le immagini senza nome e la cache penzolante non usata da 24 ore. - Le prove nella CI passano solo da `tests/Febe.Tests`, mai `dotnet test` sulla soluzione intera. - La versione sta solo in `Directory.Build.props` (``); il tag deve coincidere. - Guida per l'uso: wiki del repository (sorgenti in `docs/guida/`). diff --git a/docs/decisioni.md b/docs/decisioni.md index 366b70c..000ae3d 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -284,3 +284,12 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-10-21 | La prova dei tasti della vista remota li manda quando il WebSocket della pagina è aperto (`__sockets` di `UiBrowser.Requests`), non 300 ms dopo che il server ha aperto la vista; la prova del mouse scrive meta e fotogramma senza pausa | Il server apre la vista prima di rispondere al socket (`RemoteViewSocket.HandleAsync`) e la pagina scarta i messaggi finché il socket non è aperto: su una macchina più lenta di 300 ms i tasti andavano persi e la prova falliva dopo 30 s. Ciò che il server scrive resta nella vista finché il socket non è aperto e la pagina ascolta da subito, quindi la pausa del mouse non serviva: il primo fotogramma sullo schermo dice già che il socket è aperto | | 2026-10-21 | I ridisegni rimandati di una pagina (`later`: 150 ms in «In evidenza») le prove li aspettano come timer: `PageTimers` dice quali timeout erano in sospeso in un dato momento e quando sono finiti; dopo un cambio di dimensione si aspetta un ResizeObserver della prova, chiamato dopo quelli della pagina, e i timer che quelli hanno lasciato. Il trascinamento della maniglia della fascia aspetta ogni passo nel campo dell'ora prima del successivo; l'intestazione dell'account non ha più una pausa fra un'azione e l'altra | Con pause di 500 e 600 ms il ridisegno sbagliato poteva arrivare dopo il controllo. Con 60 ms fra un passo e l'altro una macchina lenta può consegnare più passi come un solo movimento: la prova vedeva solo l'ultimo e non provava più che la maniglia segua tutto il trascinamento. La pausa dell'intestazione non proteggeva nulla: ogni giro aspetta già il menu ridisegnato. Con copie rotte apposta (ridisegno non annullato, osservatore non staccato, tessere tardive disegnate, trascinamento che finisce al primo passo) le prove falliscono in ogni giro provato, anche a 20x; il ridisegno non annullato si vede quando è ancora in sospeso al cambio di filtro, come prima (in tutti i giri provati lo era) | | 2026-10-21 | `APageLeftWhileLoadingLeavesNothingBehind` controlla che Attività, lasciata mentre carica, non lasci né il timer di un minuto, né l'ascolto della libreria, né avvisi sulla Libreria; e che, aperta, a una modifica della libreria si ricarichi. La modifica la prova la manda alla pagina come la manda il flusso degli eventi (un evento «libreria» sul suo `EventSource`, che chiama subito chi ascolta) e ne ha conferma quando la Libreria richiede i suoi giorni; gli avvisi li registra un MutationObserver, anche quelli già spariti | Rilievo della revisione: il controllo «niente di Attività sulla Libreria» guardava solo `main`, dove Attività non disegna (la sua cornice ne esce prima ancora che il modulo si carichi), e poteva fallire solo per un nodo messo lì direttamente. Con copie rotte apposta la prova di prima passava con l'ascolto della libreria rimasto e con l'errore delle richieste annullate mostrato sulla Libreria; ora le trova entrambe, a velocità normale e con Chrome rallentato 20 volte. Una modifica pubblicata sul server non darebbe lo stesso ordine: il flusso si iscrive alle modifiche in un `Task.Run`, senza dire quando, e le raccoglie per 300 ms | +| 2026-10-21 | La pulizia toglie anche ciò che non serve più a nessuno, di qualunque progetto, e non più solo ciò che è della CI di Febe. Alla fine di ogni lavoro «immagine» (verifica e rilascio), dopo la pulizia dell'esecuzione, `pulizia-docker.sh penzolanti`: `docker image prune -f` e `docker builder prune -f --filter until=24h` (senza `-a`), che non fa mai fallire il lavoro. Ogni lunedì e a mano `pulizia-docker.sh completa`: i resti della CI di Febe come prima, i resti di act_runner, `docker image prune -a -f --filter until=24h`, `docker builder prune -a -f --filter until=24h`, con `REGISTRY_TOKEN` le `:sha-` del registro oltre le 10 più recenti, `docker system df` prima e dopo e un riepilogo. Mai `system prune`, `container prune`, `volume prune`, `network prune`, né un contenitore, un volume o una rete che non sia della CI. Per ciò che nessuno usa sostituisce il «mai le immagini degli altri progetti, mai la cache di costruzione del demone, mai le immagini col nome del registro» del 20 ottobre | Decisione di Alberto del 21 ottobre: «aggiungi il prune delle immagini non più utilizzate nel workflow di Actions, in modo da eliminare tutto quello che non serve più». Docker stesso non toglie mai un'immagine usata da un contenitore, acceso o fermo, quindi le applicazioni di Unraid e un Febe vero tengono le loro; le 24 ore lasciano stare ciò che un'altra costruzione ha appena prodotto (per la cache contano dall'ultimo uso; per le immagini dipende dallo store, riga sullo store più sotto). Il prezzo è scritto in `docs/processo.md` («Pulizia»): le immagini di base si riscaricano, le costruzioni ritrovano meno cache, un'immagine costruita a mano e tenuta senza contenitore va ricostruita. `docker builder prune` senza `-a` toglie ciò che nessuna immagine condivide: BuildKit salta solo i record interni, del frontend e condivisi (`cache/manager.go`), quindi senza un limite d'età a ogni push di ogni ramo se ne andrebbero anche gli strati intermedi e le cache montate che le costruzioni degli altri progetti hanno appena usato, e la finestra di 24 ore del lunedì non servirebbe. Per questo anche dopo ogni esecuzione `until=24h`, che BuildKit confronta con l'ultimo uso (rilievo della revisione: il compito chiedeva il comando senza filtro, che non è innocuo per gli altri progetti; se Alberto lo preferisce, basta togliere il filtro) | +| 2026-10-21 | Resti di act_runner: contenitori fermi (`exited`, `created`, `dead`), volumi e reti il cui nome comincia con `GITEA-ACTIONS-TASK-` seguito da `_` o `-`, più vecchi di 90 minuti; volumi e reti solo se nessun contenitore, nemmeno fermo, li usa (`docker ps -a --filter volume=…` e `network=…`). Contenitori e volumi senza `-f`; il volume `act-toolcache` resta | act_runner dà a tutto ciò che crea per un lavoro il prefisso `GITEA-ACTIONS-TASK-` (`internal/app/run/runner.go`); act chiama il contenitore `_WORKFLOW-_JOB-` (`createSimpleContainerName`; le versioni più vecchie `-WORKFLOW-…-JOB-…-`), i volumi `` e `-env`, la rete `--network`, e monta `act-toolcache`, la cache degli strumenti di tutti i lavori (`pkg/runner/run_context.go`; controllato su gitea.com il 21 ottobre). Un lavoro vivo ha il contenitore acceso e usa volumi e rete; i 90 minuti, come per i resti della CI di Febe, coprono l'istante in cui un lavoro che parte li ha creati e non ancora usati, se un giorno il runner farà più lavori insieme. Il `Created` di una rete si legge con `{{json .Created}}`: senza, il modello lo stampa nel formato di Go e non in RFC 3339 | +| 2026-10-21 | Registro: con `REGISTRY_TOKEN` la pulizia del lunedì toglie le etichette `sha-` del pacchetto container `febe` oltre le 10 più recenti per data di creazione, con l'API dei pacchetti di Gitea 28: `GET /api/v1/packages/{proprietario}/container/febe?page=N&limit=50` fino alla prima pagina vuota e `DELETE /api/v1/packages/{proprietario}/container/febe/{versione}` (risponde 204). Sceglie `.gitea/scripts/versioni-registro.js` (Node, senza rete, provato con `tests/Febe.Tests/Packaging/versioni-registro.json`); lo script ricontrolla la forma prima di ogni DELETE. Mai `main`, `latest`, `X.Y.Z` (anche `-rc.N`), i digest o altro; un rifiuto dell'API è un avviso, non un lavoro rosso; il token sta solo nell'intestazione di curl e non si stampa | Percorsi controllati sul codice di Gitea `release/v28` (`routers/api/v1/api.go`: `ListPackageVersions` e `DeletePackageVersion` nel gruppo `/packages/{username}`, con token e ambito «package»; `routers/api/v1/packages/package.go`: `page` e `limit`, versioni interne escluse, DELETE con 204) e su docs.gitea.com («List package versions», «Delete a package version»). In Gitea ogni etichetta di un contenitore è una versione del pacchetto con i suoi file: togliere `sha-…` non tocca `main` o una versione che puntano allo stesso manifest, e i blob rimasti senza riferimenti li toglie la pulizia dei pacchetti di Gitea (`[cron.cleanup_packages]`), purché l'immagine sia un manifest semplice e non un indice (riga seguente sulle attestazioni). Le versioni `sha256:…` senza etichetta non si toccano mai: si contano soltanto. Node e non jq: Node c'è in ogni contenitore dei lavori (lo usano le azioni) e nelle prove, jq non c'è in `node:24-trixie` né in Git Bash. Prende il posto della regola di pulizia dei pacchetti suggerita il 20 ottobre | +| 2026-10-21 | L'immagine di Febe si costruisce e si pubblica senza attestazioni: `--provenance=false --sbom=false` fra gli argomenti comuni di `.gitea/scripts/costruisci-immagine.sh` (l'archivio provato e la spinta sul registro), così sul registro ogni etichetta è un manifest semplice | Con il builder `docker-container` buildx aggiunge da sé l'attestazione di provenienza (`mode=min`; docs.docker.com, «Build attestations») e l'immagine spinta diventa un indice con due figli spinti per digest, l'immagine e l'attestazione. Gitea tiene ogni figlio come una versione a sé, `sha256:…` senza etichetta, a cui sono legati configurazione e strati (release/v28, `routers/api/packages/container/manifest.go`: `processOciImageManifest` lega i blob alla versione del manifest stesso con `createFileFromBlobReference`, `processOciImageIndex` salva solo l'indice e le proprietà `container.manifest.reference`), e togliere un'etichetta toglie solo i file di quella versione: gli strati sarebbero rimasti per sempre (rilievo della revisione). Con un manifest semplice gli strati stanno nella versione dell'etichetta, e quando nessuna versione li usa più li cancella `[cron.cleanup_packages]` (attiva per impostazione predefinita, `@midnight`, `OLDER_THAN = 24h`: `custom/conf/app.example.ini`). Si perde l'attestazione di provenienza, che nessuno legge: da dove viene l'immagine lo dicono le etichette `febe.ci.*` e quelle OCI. Le versioni `sha256:…` (spinte a mano, o con più piattaforme; la CI non ha ancora pubblicato nulla, perché manca `REGISTRY_TOKEN`) lo script non le tocca, perché l'API dei pacchetti non dice se un indice le rimanda ancora, e ne scrive il numero; se servisse, le toglie una regola di pulizia di Gitea con schema `sha256:.+` e 7 giorni, che salta quelle rimandate e sempre `latest` (`services/packages/container/cleanup.go`, `ShouldBeSkipped`; schema confrontato con tutta la versione, `(?i)\A…\z`) | +| 2026-10-21 | Prova della pulizia: `pulizia.yml` ha l'input `prova` (`type: boolean`, `default: false`, «Solo prova») e il passo passa `gitea.event.inputs.prova` allo script, che con `--prova` elenca che cosa toglierebbe (immagini con dimensione ed età, cache di costruzione, resti della CI di Febe e di act_runner, etichette del registro) con soli comandi che leggono e, sul registro, soli GET. Nella pulizia vera le immagini le sceglie Docker; nella prova le stima lo script con la stessa regola, contando come già tolti i contenitori che la pulizia toglierebbe prima | Gitea 28 mostra un input booleano come una casella (`templates/repo/actions/workflow_dispatch_inputs.tmpl`) e nell'evento lo scrive come testo, «true» o «false» (`routers/web/repo/actions/view.go`, `Run`: `strconv.FormatBool(ctx.FormBool(name))`); il lunedì l'evento non ha input, e la stringa vuota vuol dire pulizia vera. Il passo accetta solo «true» (la prova) e «false» o niente (la pulizia vera): un avvio con l'API passa il valore così com'è (`routers/api/v1/repo/action.go`, `ActionsDispatchWorkflow`: `inputs[name] = value`, senza conversione), e qualunque altro valore («True», «1») ferma il lavoro con un errore senza toccare nulla. Allo stesso modo lo script, prima di chiamare Docker, rifiuta con codice 2 ogni opzione diversa da `--prova` e ogni argomento in più: una prova scritta in un altro modo (`--dry-run`, `-n`, `prova`) prima faceva partire la pulizia vera con codice 0 (rilievo della revisione) | +| 2026-10-21 | `pulizia-docker.sh` gira con `BUILDX_BUILDER=default`: la cache che pota è quella del builder del demone | Con il plugin buildx `docker builder` diventa `docker buildx` (`cmd/docker/builder.go` del client Docker), che lavora sul builder corrente: nel lavoro «immagine» è quello dell'esecuzione, che `setup-buildx-action` crea con `--use` (`src/context.ts`) e che il modo «esecuzione» ha già tolto. I comandi buildx che toccano i builder di Febe li indicano per nome | +| 2026-10-21 | Il lavoro «controlli» legge anche gli script Node della CI (`node --check .gitea/scripts/*.js`) | Come `bash -n` per gli script di shell: un errore di sintassi in `versioni-registro.js` si vede in pochi secondi, non alla pulizia del lunedì | +| 2026-10-21 | Nei modi «settimanale» e «completa» la pulizia legge lo store delle immagini del demone (`docker info --format '{{json .DriverStatus}}'`: con `io.containerd.snapshotter.v1` è quello di containerd, altrimenti il classico) e lo scrive all'inizio; con containerd, o se non lo sa, la prova avverte che le età che elenca sono solo indicative | Da quando contano le 24 ore di `image prune --filter until` dipende dallo store (rilievo della revisione). Con quello classico Docker confronta il `Created` della configurazione, cioè la costruzione (moby, `daemon/images/image_prune.go`: `img.Created.After(until)`); con quello di containerd il `CreatedAt` del record dell'immagine sul demone (`daemon/containerd/image_list.go`: `image.CreatedAt.Before(until)`), che containerd conserva quando lo stesso nome viene riscaricato. Nessun comando mostra quel `CreatedAt` (`docker image ls` dà il `Created` della configurazione anche con containerd), quindi la prova resta sull'età dalla costruzione e lo dice. Lo store di containerd è il predefinito nelle installazioni nuove di Docker Engine dalla 29; su Unraid è più probabile quello classico. `docker info` solo legge | +| 2026-10-21 | Della pulizia del lunedì si dice anche che cosa `image prune -a` toglie alle immagini che un contenitore usa: i nomi in più. La pulizia vera confronta i nomi prima e dopo e scrive, nome per nome, quelli tolti a un'immagine che resta; la prova li stima secondo lo store (classico: tutti tranne l'ultimo in ordine alfabetico del nome completo, `docker.io/library/…` per Docker Hub; containerd: tutti tranne quelli da cui i contenitori sono stati creati, e l'ultimo se un contenitore la usa per identificativo). Il comando resta quello chiesto | Rilievo della revisione: la prova saltava ogni immagine in uso, e i documenti dicevano che un'immagine usata da un contenitore non si tocca. Docker non toglie l'immagine, ma con lo store classico `ImagesPrune` non guarda i contenitori e chiama `ImageDelete` senza forza su ogni riferimento, in ordine alfabetico (`daemon/images/image_prune.go`, uguale in moby v24.0.9, v27.5.1 e master; `reference/store.go`, `lexicalRefs`); `ImageDelete` rifiuta solo l'ultimo riferimento di un'immagine in uso (`image_delete.go`, `isSingleReference`), quindi può sparire proprio il nome da cui il contenitore è stato creato (un'applicazione di Unraid creata da `app:1.2` che si chiama anche `app:latest`). Con containerd `filterImagesUsedByContainers` protegge solo il nome di `Config.Image` e, se il contenitore usa l'immagine per identificativo o digest, l'ultimo nome (`daemon/containerd/image_prune.go`). Il demone finto delle prove fa lo stesso con l'uno e con l'altro store | diff --git a/docs/docker.md b/docs/docker.md index 37a82e4..9fd57cd 100644 --- a/docs/docker.md +++ b/docs/docker.md @@ -34,13 +34,17 @@ Sul registro di Gitea, `192.168.30.23:3000/alby96/febe`: | `:latest` | l'ultima versione rilasciata senza trattino: quella del modello di Unraid e di `compose.yml` | a ogni rilascio stabile | | `:X.Y.Z` | una versione rilasciata (anche `X.Y.Z-rc.N` per un'anteprima) | mai: serve per tornare a una versione precisa | | `:main` | l'ultimo commit di `main` che ha passato la verifica | a ogni unione in `main`: per provare, non per l'archivio vero | -| `:sha-<7 caratteri>` | un commit di `main` preciso | mai | +| `:sha-<7 caratteri>` | un commit di `main` preciso | mai; sul registro restano le 10 più recenti | Ogni immagine costruita dalla CI dice da dove viene, nelle etichette Docker `febe.ci.workflow`, `febe.ci.run`, `febe.ci.ref` e `febe.ci.commit` e in `org.opencontainers.image.version` e `.revision`: `docker inspect --format '{{json .Config.Labels}}' `. Docker copia queste etichette anche nel contenitore di Febe: la pulizia della CI non le usa per scegliere che cosa togliere, quindi un Febe sullo stesso Docker del runner -della CI non viene mai toccato. +della CI non viene mai toccato, né la sua immagine, anche a contenitore fermo. Su quel Docker, però, la pulizia del +lunedì toglie le immagini che nessun contenitore usa e che sono state create più di 24 ore fa: un'immagine di Febe +tenuta senza contenitore (una versione precedente, per tornare indietro) se ne va, e si riscarica dal registro, dove +`:X.Y.Z` resta. E se l'immagine del Febe vero ha più nomi (`:latest` e `:0.1.0`, per esempio), resta, ma con uno solo: +gli altri la pulizia li toglie (`docs/processo.md`, «Pulizia»). ## Volumi diff --git a/docs/guida/Sviluppo.md b/docs/guida/Sviluppo.md index f69ffa8..1b32ac5 100644 --- a/docs/guida/Sviluppo.md +++ b/docs/guida/Sviluppo.md @@ -196,10 +196,14 @@ richieste di unione, protezione di `main`, rilievi di sicurezza, rilasci, correz - `installatore`: `Febe-Setup--ci..exe` e lo zip portabile, fra gli artefatti per 14 giorni; - `immagine`, dopo l'installatore: l'immagine Docker, provata senza rete (parte, diventa «healthy», si ferma) e scansionata con Trivy; dopo un push su `main` va sul registro come `:main` e `:sha-`. Alla fine si toglie - tutto ciò che l'esecuzione ha creato sul demone Docker, che è condiviso con gli altri progetti; + tutto ciò che l'esecuzione ha creato sul demone Docker, che è condiviso con gli altri progetti, e poi, di tutti, le + immagini senza nome e la cache di costruzione che nessuno usa da 24 ore; - `rilascio.yml`, a ogni tag `vX.Y.Z`: prove, installatore e zip, immagine provata e scansionata, pubblicata come `:X.Y.Z` e `:latest` (solo per le versioni senza trattino), poi la release; -- `pulizia.yml`, ogni lunedì e a mano: i resti delle esecuzioni interrotte e le immagini senza nome vecchie. +- `pulizia.yml`, ogni lunedì e a mano: i resti delle esecuzioni interrotte e dei lavori di act_runner, le immagini che + nessun contenitore usa e la cache di costruzione più vecchie di 24 ore, di tutti i progetti, e sul registro le + `:sha-` oltre le 10 più recenti; mai un contenitore, un volume o una rete che non sia della CI. A mano, con «Solo + prova», elenca che cosa toglierebbe e non toglie nulla (`docs/processo.md`, «Pulizia»). Nella CI le prove del sito di prova (categoria `SitoDiProva`) girano due volte: con il seme 13 e con un seme diverso a ogni esecuzione, scritto nel registro del lavoro. Per rifare un errore con quel seme: diff --git a/docs/processo.md b/docs/processo.md index 00fbd3d..0000c2b 100644 --- a/docs/processo.md +++ b/docs/processo.md @@ -96,7 +96,7 @@ ramo un push nuovo annulla l'esecuzione in corso; su `main` ogni unione arriva f annulla mai quella di un push (l'evento fa parte del gruppo di concorrenza): solo il push scrive gli stati del commit che servono per unire, e un lavoro annullato lascerebbe lo stato «failure». -Altri flussi: `rilascio.yml` a ogni tag (vedi «Rilasci») e `pulizia.yml` ogni lunedì (vedi «Pulizia»). +Altri flussi: `rilascio.yml` a ogni tag (vedi «Rilasci») e `pulizia.yml` ogni lunedì e a mano (vedi «Pulizia»). ### Il mondo sintetico e il suo seme @@ -129,20 +129,39 @@ Sul registro di Gitea, `192.168.30.23:3000/alby96/febe`: | `:latest` | `rilascio`, solo versioni senza trattino | a ogni rilascio stabile | Unraid e Docker Compose | | `:X.Y.Z` | `rilascio` (anche `X.Y.Z-rc.1` per un'anteprima) | mai | una versione precisa, per tornare indietro | | `:main` | `verifica`, dopo ogni unione in `main` | a ogni unione (mai all'indietro) | provare `main` su un server di prova; non per l'archivio vero | -| `:sha-<7 caratteri>` | `verifica`, dopo ogni unione in `main` | mai | un commit preciso di `main` | +| `:sha-<7 caratteri>` | `verifica`, dopo ogni unione in `main` | mai; restano le 10 più recenti | un commit preciso di `main` | Ogni immagine della CI porta le etichette Docker `febe.ci.workflow`, `febe.ci.run`, `febe.ci.ref` e `febe.ci.commit`, oltre a quelle OCI del Dockerfile: da un'immagine si risale all'esecuzione e al commit. Docker le copia in ogni contenitore creato dall'immagine, anche in un Febe vero: per questo la pulizia non le usa mai per scegliere che cosa -togliere (vedi «Pulizia»). Le `:sha-` si accumulano: una -regola di pulizia dei pacchetti (Impostazioni ▸ Pacchetti ▸ Regole di pulizia) può tenere sempre `latest`, `main` e -le versioni e togliere le `sha-.*` più vecchie di 30 giorni. +togliere (vedi «Pulizia»). Le `:sha-` non si accumulano: con il segreto `REGISTRY_TOKEN`, la pulizia del lunedì tiene le +10 più recenti e toglie le altre; `:main`, `:latest` e le versioni restano sempre. + +Perché togliere un'etichetta liberi davvero spazio, l'immagine si pubblica come un manifest semplice, senza attestazioni +(`--provenance=false --sbom=false` in `.gitea/scripts/costruisci-immagine.sh`): in Gitea ogni etichetta è una versione +del pacchetto che tiene la configurazione e gli strati, e i blob che nessuna versione usa più li cancella la pulizia dei +pacchetti di Gitea stessa, ogni notte, quando hanno più di 24 ore (`[cron.cleanup_packages]`, attiva per impostazione +predefinita). Con le attestazioni, che buildx aggiunge da sé, l'immagine sarebbe un indice: Gitea terrebbe ogni manifest +figlio come una versione a sé, `sha256:…` senza etichetta, con gli strati, e togliere l'etichetta toglierebbe solo +l'indice. La pulizia del lunedì non tocca mai le versioni `sha256:…` (l'API dei pacchetti non dice se un'etichetta le usa +ancora) e scrive quante sono. Se ce ne sono (un'immagine spinta a mano, o con più piattaforme), quelle che nessuna +etichetta usa più le toglie una regola di pulizia di Gitea, da impostare una volta sul proprietario del pacchetto +(Impostazioni ▸ Pacchetti ▸ regole di pulizia): tipo container, attiva, schema delle versioni da rimuovere `sha256:.+`, +più vecchie di 7 giorni (il valore più basso dopo lo zero, che toglierebbe anche un figlio appena spinto e non ancora +rimandato dal suo indice), nessun numero da tenere. Gitea confronta lo schema con tutta la versione, salta da sé +le versioni `sha256:` che un indice ancora rimanda e sempre `latest`, e applica la regola ogni notte; una regola non deve +mai toccare `main` e le versioni. ## Pulizia -Il demone Docker è condiviso con gli altri progetti, e ci può girare anche un Febe vero, avviato da un'immagine che la -CI ha pubblicato e che quindi porta le sue etichette `febe.ci.*`. La CI di Febe toglie solo ciò che può provare suo -(`.gitea/scripts/pulizia-docker.sh`): +Il demone Docker è condiviso con gli altri progetti di Alberto e, molto probabilmente, con le applicazioni di Unraid; ci +può girare anche un Febe vero, avviato da un'immagine che la CI ha pubblicato e che quindi porta le sue etichette +`febe.ci.*`. Dal 21 ottobre 2026, per decisione di Alberto, la pulizia (`.gitea/scripts/pulizia-docker.sh`) toglie due +cose: ciò che la CI di Febe può provare suo e ciò che non serve più a nessuno, di qualunque progetto. Mai un +contenitore, un volume o una rete che non sia della CI. + +Ciò che è della CI di Febe si riconosce da segni che nessuna immagine porta (le etichette `febe.ci.*` no: Docker le +copia in ogni contenitore creato dall'immagine, anche in un Febe vero): - contenitori di prova: l'etichetta `febe.ci.prova=`, che mette solo `prova-immagine.sh` con `docker run --label` e che nessuna immagine porta (lo controlla `PipelineTests`), e insieme il nome esatto @@ -150,18 +169,71 @@ CI ha pubblicato e che quindi porta le sue etichette `febe.ci.*`. La CI di Febe - immagini provate: il nome locale `febe-ci:`, tolto per nome, mai per identificativo e mai con `-f`. Se la stessa immagine ha anche un nome del registro, quello resta; se un contenitore la usa, resta tutto; - builder buildx: il contenitore `buildx_buildkit_febe-ci-0` con l'immagine `moby/buildkit` e il suo volume - `…_state`; -- più le immagini senza nome più vecchie di 72 ore che nessun contenitore usa. + `…_state`. -`PipelineTests` fa girare la pulizia contro un demone finto (`tests/Febe.Tests/Packaging/fake-docker.sh`) con un Febe -vero acceso e uno fermo che portano le etichette delle loro immagini: non li deve toccare. +Ciò che resta dei lavori di act_runner si riconosce dal nome che act_runner dà a tutto ciò che crea per un lavoro, +`GITEA-ACTIONS-TASK-…`: il contenitore del lavoro, i suoi volumi `` e `-env`, la sua +rete `--network`. Se ne vanno i contenitori fermi e i volumi e le reti che nessun contenitore usa, più +vecchi di 90 minuti. Il volume `act-toolcache`, la cache degli strumenti condivisa fra i lavori, resta. + +Ciò che non serve più a nessuno lo toglie Docker stesso (`docker image prune`, `docker builder prune`), che non toglie +mai un'immagine usata da un contenitore, acceso o fermo: un'applicazione di Unraid ferma tiene la sua immagine. Se però +quell'immagine ha più nomi, `image prune -a` le toglie quelli in più (vedi «Che cosa costa»). | Quando | Che cosa si toglie | |---|---| -| alla fine di ogni lavoro «immagine», sempre | il contenitore di prova con i suoi volumi anonimi, l'immagine provata, il builder buildx dell'esecuzione con la sua cache, l'archivio dell'immagine, le credenziali del registro | +| alla fine di ogni lavoro «immagine» (verifica e rilascio), sempre | il contenitore di prova con i suoi volumi anonimi, l'immagine provata, il builder buildx dell'esecuzione con la sua cache, l'archivio dell'immagine, le credenziali del registro; poi, di tutti i progetti, le immagini senza nome che nessun contenitore usa e la cache di costruzione penzolante del demone, cioè quella che nessuna immagine condivide, non usata da 24 ore (`pulizia-docker.sh penzolanti`). Un errore qui è solo un avviso: il lavoro non diventa rosso | | all'inizio di ogni lavoro «immagine» | i resti di esecuzioni interrotte più vecchi di 90 minuti (un lavoro dura al massimo 60 minuti): contenitori di prova **fermi**, immagini `febe-ci:`, builder; e ciò che ha lasciato un tentativo precedente della stessa esecuzione | -| ogni lunedì e a mano (`pulizia.yml`) | gli stessi resti, l'immagine `febe:ci` del vecchio flusso se nessuno la usa, le immagini senza nome più vecchie di 72 ore | -| mai | immagini, contenitori e volumi degli altri progetti; un contenitore Febe che non sia di prova, anche se porta le etichette `febe.ci.*`; un contenitore di prova ancora acceso di un'altra esecuzione (si segnala con un avviso e il comando per toglierlo: il flusso settimanale diventa rosso); la cache di costruzione del demone; i volumi con un nome; le immagini col nome del registro | +| ogni lunedì alle 4:17 e a mano (`pulizia.yml`, `pulizia-docker.sh completa`) | gli stessi resti e l'immagine `febe:ci` del vecchio flusso; i resti di act_runner; **le immagini che nessun contenitore usa create più di 24 ore fa**, di tutti i progetti, anche col nome del registro; la cache di costruzione del demone non usata da più di 24 ore; con il segreto `REGISTRY_TOKEN`, sul registro le `:sha-` oltre le 10 più recenti. Prima e dopo `docker system df`, alla fine un riepilogo di che cosa è andato via | +| mai | `docker system prune`, `container prune`, `volume prune`, `network prune`; un contenitore, un volume o una rete che non sia della CI: un Febe vero, anche se porta le etichette `febe.ci.*`, le applicazioni di Unraid, i volumi con i dati, `act-toolcache`; un contenitore di prova ancora acceso di un'altra esecuzione (si segnala con un avviso e il comando per toglierlo: il flusso del lunedì diventa rosso); un'immagine usata da un contenitore, anche fermo (i suoi nomi in più sì: vedi sotto); `image prune -a` e `builder prune -a` senza il filtro delle 24 ore; sul registro `:main`, `:latest` e le versioni `X.Y.Z` | + +Che cosa costa: + +- le immagini di base che fra un lavoro e l'altro nessun contenitore usa (`node:24-trixie` del lavoro «prove», + `moby/buildkit` dei builder, quelle dei lavori degli altri progetti) si riscaricano alla prima esecuzione che le + chiede dopo il lunedì: qualche minuto e qualche centinaio di MB in più, una volta. L'immagine dei lavori + (`ubuntu-latest`) resta, perché durante la pulizia la usa il lavoro stesso; +- da quando contano le 24 ore delle immagini dipende dallo store delle immagini del demone, che la pulizia scrive + all'inizio. Con lo store classico (il più probabile su Unraid) contano dalla costruzione dell'immagine: una + scaricata ieri ma costruita un mese fa se ne va, e una costruita con una data fissa (costruzioni riproducibili, + `SOURCE_DATE_EPOCH`) non è mai protetta dalla finestra. Con lo store di containerd (predefinito nelle installazioni + nuove di Docker Engine dalla 29) contano da quando il nome è arrivato sul demone, e un nome riscaricato tiene la data di + prima: un'immagine appena riscaricata con un nome che c'era già, e non ancora usata da un contenitore, se ne va. Con + tutti e due, un'immagine scaricata e non ancora usata non è al sicuro. La prova dà sempre l'età dalla costruzione, e + con containerd lo dice: lì il suo elenco è solo indicativo; +- un'immagine costruita a mano e tenuta senza contenitore (per esempio quella di `docker build -t febe .`) se ne va e va + ricostruita; una versione di Febe tenuta per tornare indietro si riscarica dal registro, dove `:X.Y.Z` resta; +- un'immagine che un contenitore usa resta, ma se ha più nomi `image prune -a` le toglie quelli in più. Con lo store + classico resta solo l'ultimo in ordine alfabetico del nome completo, anche quando il contenitore è stato creato da un + altro: un'applicazione di Unraid creata da `app:1.2`, se la stessa immagine si chiama anche `app:latest`, continua a + girare, ma in locale `app:1.2` non c'è più, e Unraid la mostra da aggiornare o la riscarica. Con lo store di + containerd restano i nomi da cui i contenitori sono stati creati. Un Febe vero avviato da `:latest`, se la stessa + immagine si chiama anche `:0.1.0`, perde `:0.1.0` e resta `:latest`. La prova elenca questi nomi e la pulizia vera li + scrive uno per uno; +- la cache di costruzione del builder del demone, con cui costruiscono gli altri progetti: resta quella usata nelle + ultime 24 ore. Dopo ogni esecuzione di Febe se ne va quella che nessuna immagine condivide (strati intermedi, cache + montate con `RUN --mount=type=cache`) e che nessuno usa da un giorno; il lunedì anche quella condivisa e quella + interna di BuildKit, con lo stesso limite. Una costruzione che si ripete almeno una volta al giorno ritrova la sua + cache; una più rara la rifà. + +**Prova senza togliere nulla.** Actions ▸ pulizia ▸ Esegui, con «Solo prova» spuntato: il registro del lavoro elenca +che cosa toglierebbe (le immagini con dimensione ed età, i nomi in più delle immagini in uso, la cache di costruzione, i +resti della CI di Febe e di act_runner, le `:sha-` del registro) e non toglie nulla: solo comandi che leggono, e sul +registro solo GET. Si lancia prima della prima pulizia vera e dopo ogni cambio dello script. Dal server, nella cartella +del repository: +`bash .gitea/scripts/pulizia-docker.sh completa --prova` (il registro solo con `REGISTRY_TOKEN`, `GITEA_API` e +`PROPRIETARIO` nell'ambiente). Una prova scritta in un altro modo non diventa la pulizia vera: un'opzione diversa da +`--prova` (`--dry-run`, `-n`, `--Prova`) o una parola in più (`prova` senza trattini) fermano lo script con codice 2 +prima che tocchi Docker, e il flusso accetta per «prova» solo `true` e `false` (un avvio con l'API che passa un altro +valore, «True» o «1», si ferma con un errore). Le immagini, nella pulizia vera, le sceglie Docker; nella prova le stima +lo script con la stessa regola. + +`PipelineTests` fa girare la pulizia contro un demone finto (`tests/Febe.Tests/Packaging/fake-docker.sh`), con lo store +classico e con quello di containerd, con un Febe vero acceso e uno fermo, applicazioni di Unraid accese e ferme (una con +due nomi), il lavoro della pulizia stessa, resti veri e finti di act_runner, e contro un'API dei pacchetti finta +(`fake-curl.sh`): controlla che cosa resta, che nessun comando vietato parta, che la prova non tocchi nulla e dica ciò +che la pulizia vera poi toglie, che una prova scritta male si fermi, e che il token non finisca mai nel registro del +lavoro. ## Rilievi di sicurezza @@ -211,4 +283,13 @@ di ogni blocco `run`), gli script con un client Docker finto. Restano da vedere `node:24-trixie` con le azioni dentro; le prove con il browser nel contenitore (nessuna saltata); `upload-artifact@v3` con `retention-days`; la concorrenza; il builder buildx con il nome dell'esecuzione; la prova del contenitore senza rete fino a «healthy»; il download e la scansione di Trivy (e se trova CRITICAL da correggere); gitleaks sulla storia; -la pubblicazione su `main` con il segreto; la pulizia settimanale sul demone vero. +la pubblicazione su `main` con il segreto. + +Della pulizia del 21 ottobre 2026 (script e API provati con un client Docker e un curl finti) restano da vedere: la +casella «Solo prova» di Gitea che arriva al lavoro come «true»; i nomi che questo act_runner dà ai suoi contenitori, +volumi e reti; che cosa la prova dice di togliere sul demone vero, da leggere prima della prima pulizia vera; poi la +pulizia vera: `docker builder prune` passato a buildx con `BUILDX_BUILDER=default`, il tempo e lo spazio recuperato, +le immagini riscaricate dopo; con il segreto, l'API dei pacchetti con `REGISTRY_TOKEN` (elenco a pagine e DELETE delle +`:sha-`), e che dopo la prima pubblicazione con `--provenance=false --sbom=false` il pacchetto non abbia versioni +`sha256:…` (la riga del registro nel lavoro della pulizia, o la pagina del pacchetto su Gitea); la pulizia di ogni +esecuzione alla fine del lavoro «immagine». diff --git a/tests/Febe.Tests/Packaging/PipelineTests.Pulizia.cs b/tests/Febe.Tests/Packaging/PipelineTests.Pulizia.cs new file mode 100644 index 0000000..74caeaf --- /dev/null +++ b/tests/Febe.Tests/Packaging/PipelineTests.Pulizia.cs @@ -0,0 +1,977 @@ +using System.Diagnostics; +using System.Text.Json; +using System.Text.RegularExpressions; +using Febe.Tests.Desktop.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Packaging; + +/// +/// 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. +/// +public sealed partial class PipelineTests +{ + private const string RegistryApi = "http://gitea.invalid/api/v1"; + + private const string WeeklyStep = "Pulizia completa del demone Docker e del registro"; + + // 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"; + + /// The tags versioni-registro.json leaves to the cleanup once the ten newest sha- are kept, oldest first. + private static readonly string[] OldShaTags = ["sha-0a1b2c3", "sha-1b2c3d4", "sha-2c3d4e5", "sha-4e5f6a7"]; + + /// The untagged versions of the container febe in versioni-registro.json (manifests of an index), oldest first. + private static readonly string[] UntaggedDigests = + [ + "sha256:4f3c2b1a0e9d8c7b6a5f4e3d2c1b0a9f8e7d6c5b4a3f2e1d0c9b8a7f6e5d4c3b", + "sha256:7c39e42c6e919ae17c7dfa17bd5fcf8cd38fa29c02be97e2b0134947b4674f3c", + "sha256:d0e666bf0a465af6218c1825f3fd72143e2f9ddfc038a8cda19b0504656e0647", + ]; + + [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. The cache always with the filter of 24 hours, after every run + // too: other projects build with the daemon's builder, and what they used today stays. + string[] allowed = + [ + "image prune -f", + "image prune -f --filter \"until=72h\"", + "image prune -a -f --filter \"until=24h\"", + "builder prune -f --filter \"until=24h\"", + "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] + public void EveryImageJobEndsByPruningWhatNobodyUsesAndThatNeverFailsTheJob() + { + foreach (var name in new[] { "verifica.yml", "rilascio.yml" }) + { + var cleanup = Step(Job(Workflow(name), "immagine"), "Pulizia (sempre)"); + StringAssert.Contains(cleanup, "if: always()", name); + var own = cleanup.IndexOf("bash .gitea/scripts/pulizia-docker.sh esecuzione \"$ESECUZIONE\"", StringComparison.Ordinal); + var everyone = cleanup.IndexOf("bash .gitea/scripts/pulizia-docker.sh penzolanti || echo \"::warning::", StringComparison.Ordinal); + Assert.IsTrue(own >= 0 && everyone > own, $"{name}: after the cleanup of the run, and a failure is only a warning"); + } + } + + [TestMethod] + public void TheWeeklyCleanupIsCompleteAndCanBeTriedFirstWithoutRemovingAnything() + { + var weekly = Workflow("pulizia.yml"); + StringAssert.Contains(weekly, "schedule:\n - cron: \"17 4 * * 1\""); + StringAssert.Contains(weekly, " workflow_dispatch:\n inputs:\n prova:\n"); + var input = weekly[weekly.IndexOf(" prova:\n", StringComparison.Ordinal)..weekly.IndexOf("\npermissions:", StringComparison.Ordinal)]; + StringAssert.Contains(input, "type: boolean", "Gitea 28 shows a checkbox and puts \"true\" or \"false\" in the event"); + StringAssert.Contains(input, "default: false", "by hand the cleanup is real unless the box is ticked"); + + var step = Step(Job(weekly, "docker"), WeeklyStep); + StringAssert.Contains(step, "PROVA: ${{ gitea.event.inputs.prova }}"); + StringAssert.Contains(step, "REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}"); + StringAssert.Contains(step, "GITEA_API: ${{ gitea.server_url }}/api/v1"); + StringAssert.Contains(step, "PROPRIETARIO: ${{ gitea.repository_owner }}"); + Assert.DoesNotContain("settimanale", Code(weekly), "the weekly cleanup is the complete one"); + } + + [TestMethod] + [Timeout(120_000, CooperativeCancellation = true)] + public async Task TheWeeklyStepTriesOnlyForTrueCleansForFalseOrNothingAndStopsOnAnyOtherValue() + { + // The run block of the step, as the runner executes it, with a cleanup script that only records how it is + // called. The box of the form gives "true" or "false" and Monday no value at all; a dispatch through the API + // passes any text as it is, and anything else must not become the real cleanup. + var bash = RequireBash(); + var block = RunBlock(Step(Job(Workflow("pulizia.yml"), "docker"), WeeklyStep)); + using var folder = new TempFolder("febe-passo-pulizia"); + Directory.CreateDirectory(folder.Combine(".gitea", "scripts")); + await File.WriteAllTextAsync(folder.Combine(".gitea", "scripts", "pulizia-docker.sh"), "printf '%s\\n' \"$*\" >> chiamate\n", TestContext.CancellationToken); + await File.WriteAllTextAsync(folder.Combine("passo.sh"), block, TestContext.CancellationToken); + (string? Value, string? Called)[] cases = + [ + ("true", "completa --prova"), + ("false", "completa"), + (string.Empty, "completa"), + (null, "completa"), + ("True", null), + ("1", null), + ("yes", null), + ("true ", null), + ("x\n::add-mask::y", null), + ]; + foreach (var (value, called) in cases) + { + File.Delete(folder.Combine("chiamate")); + var step = await RunProcessAsync(bash, ["--noprofile", "--norc", "-eo", "pipefail", "passo.sh"], start => + { + start.WorkingDirectory = folder.Path; + start.Environment.Remove("PROVA"); + if (value is not null) + { + start.Environment["PROVA"] = value; + } + }); + var calls = await ReadLinesAsync(folder.Combine("chiamate")); + var report = $"PROVA=«{value}»: codice {step.Code}\n{step.Output}\n{step.Errors}"; + if (called is not null) + { + Assert.AreEqual(0, step.Code, report); + CollectionAssert.AreEqual(new[] { called }, calls, report); + } + else + { + Assert.AreEqual(2, step.Code, report); + Assert.IsEmpty(calls, report); + StringAssert.StartsWith(step.Output, "::error::", report); + Assert.HasCount(1, Lines(step.Output), "a value cannot add a workflow command of its own"); + } + } + } + + [TestMethod] + [Timeout(120_000, CooperativeCancellation = true)] + public async Task AWrongOptionOrAWordTooManyStopsTheCleanupBeforeItTouchesDocker() + { + // By hand on the server a dry run spelt another way must not become the real cleanup. + var bash = RequireBash(); + string[][] wrong = + [ + ["completa", "--dry-run"], + ["completa", "--Prova"], + ["completa", "-n"], + ["completa", "prova"], + ["--prova"], + [], + ["penzolanti", "--forza"], + ["settimanale", "-f"], + ["esecuzione", "777", "778"], + ["residui", "90", "10"], + ]; + foreach (var arguments in wrong) + { + var run = await RunCleanupAsync(bash, SharedDaemon.World, touchesDocker: false, arguments); + var report = $"«{string.Join(' ', arguments)}»\n{run.Report}"; + Assert.AreEqual(2, run.Code, report); + Assert.IsEmpty(run.Calls, report); + StringAssert.Contains(run.Errors, "Uso: ", report); + Assert.IsEmpty(run.Output, report); + } + } + + [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 --filter until=24h", "the dangling cache of the daemon's builder, without -a, unused for a day"); + + // 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); + + // An image a container uses stays, but «image prune -a» takes its extra names: with the classic store all but + // the last in the order of their full names, even the one the container was made from (Jellyfin, from :10.9). + // The log says so, name by name. + StringAssert.Contains(run.Output, "== Store delle immagini del demone: classico", run.Report); + CollectionAssert.Contains(run.Images, "img-rilascio|192.168.30.23:3000/alby96/febe:latest", run.Report); + CollectionAssert.Contains(run.Images, "img-jellyfin|jellyfin/jellyfin:latest", run.Report); + StringAssert.Contains(run.Output, " tolto il nome jellyfin/jellyfin:10.9; l'immagine img-jellyfin resta\n", run.Report); + StringAssert.Contains(run.Output, " tolto il nome 192.168.30.23:3000/alby96/febe:0.1.0; l'immagine img-rilascio resta\n", run.Report); + Assert.AreEqual("2", SummaryCount(run.Output, "nomi tolti a immagini che restano"), 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. + Assert.DoesNotContain("solo indicativo", tried.Output, "with the classic store the ages are those «until» uses"); + foreach (var expected in new[] + { + "Prova: elenco che cosa toglierei, senza togliere nulla.", + "== Store delle immagini del demone: classico (le 24 ore contano dalla costruzione dell'immagine)\n", + " 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", + " toglierei il nome 192.168.30.23:3000/alby96/febe:0.1.0; l'immagine img-rilascio resta, perché la usa un contenitore\n", + " toglierei il nome jellyfin/jellyfin:10.9; l'immagine img-jellyfin resta, perché la usa un contenitore\n", + "la cache di costruzione del demone occupa 5.3GB", + " toglierei sha-4e5f6a7 (pubblicata il 2026-10-05T01:00:00+02:00)\n", + $" {UntaggedDigests.Length} versioni senza etichetta (sha256:…", + "== 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", "jellyfin/jellyfin: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", "nomi tolti a immagini che restano", "etichette sha- sul registro" }) + { + Assert.AreEqual(SummaryCount(real.Output, kind), SummaryCount(tried.Output, kind), $"{kind}\n{tried.Report}\n{real.Report}"); + } + } + + [TestMethod] + [Timeout(300_000, CooperativeCancellation = true)] + public async Task OnTheContainerdStoreTheCleanupSaysSoAndTheAgesOfTheDryRunAreOnlyIndicative() + { + // With the containerd image store «until» counts from when a name reached the daemon, which no command shows; + // the dry run can only give the age of the image and must say so. + var bash = RequireBash(); + var world = SharedDaemon.World with { Store = "containerd" }; + var tried = await RunCleanupAsync(bash, world, "completa", "--prova"); + Assert.AreEqual(0, tried.Code, tried.Report); + StringAssert.Contains(tried.Output, "== Store delle immagini del demone: containerd (le 24 ore contano da quando un nome è arrivato sul demone)\n", tried.Report); + StringAssert.Contains(tried.Output, "l'elenco è solo indicativo)", tried.Report); + CollectionAssert.Contains(tried.Calls, "BUILDX_BUILDER=default docker info --format {{json .DriverStatus}}", "the store is read, never changed"); + + // Of an image a container uses, containerd keeps the names the containers were made from and takes the others: + // Jellyfin keeps :10.9 and loses :latest, the other way round from the classic store. The dry run says so, and + // the real cleanup does it. + StringAssert.Contains(tried.Output, " toglierei il nome jellyfin/jellyfin:latest; l'immagine img-jellyfin resta, perché la usa un contenitore\n", tried.Report); + StringAssert.Contains(tried.Output, " toglierei il nome 192.168.30.23:3000/alby96/febe:0.1.0; l'immagine img-rilascio resta, perché la usa un contenitore\n", tried.Report); + Assert.DoesNotContain("jellyfin/jellyfin:10.9", tried.Output, tried.Report); + var real = await RunCleanupAsync(bash, world, "completa"); + Assert.AreEqual(0, real.Code, real.Report); + CollectionAssert.AreEquivalent(SharedDaemon.ImagesLeft, real.ImageIds, real.Report); + CollectionAssert.Contains(real.Images, "img-jellyfin|jellyfin/jellyfin:10.9", real.Report); + CollectionAssert.Contains(real.Images, "img-rilascio|192.168.30.23:3000/alby96/febe:latest", real.Report); + foreach (var kind in new[] { "immagini che nessun contenitore usa", "nomi tolti a immagini che restano" }) + { + Assert.AreEqual(SummaryCount(real.Output, kind), SummaryCount(tried.Output, kind), $"{kind}\n{tried.Report}\n{real.Report}"); + } + } + + [TestMethod] + public void TheImageIsAPlainManifestSoRemovingATagFromTheRegistryFreesItsLayers() + { + // With attestations, which buildx adds by itself, the image is an index: Gitea keeps each child manifest as an + // untagged sha256: version holding the configuration and the layers, and deleting the tag deletes only the + // index. Both builds (the tried archive and the push) share these arguments, so they stay the same image. + var build = Code(Script("costruisci-immagine.sh")); + var start = build.IndexOf("comuni=(", StringComparison.Ordinal); + Assert.IsGreaterThanOrEqualTo(0, start, "costruisci-immagine.sh has no common arguments"); + var common = build[start..build.IndexOf(')', start)]; + StringAssert.Contains(common, "--provenance=false"); + StringAssert.Contains(common, "--sbom=false"); + Assert.AreEqual(2, Regex.Count(build, @"docker buildx build ""\$\{comuni\[@\]\}"""), "every build uses the common arguments"); + Assert.DoesNotContain("--platform", build, "more platforms would make an index again"); + Assert.DoesNotContain("--attest", build); + } + + [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); + } + + // The untagged versions, the manifests of an index with their layers: listed only to be counted, oldest first, + // those of the container febe and no other package. + var untagged = await RunProcessAsync(node, [script, "senza-etichetta", .. pages]); + Assert.AreEqual(0, untagged.Code, untagged.Errors); + CollectionAssert.AreEqual(UntaggedDigests, Lines(untagged.Output).Select(l => l.Split('\t')[0]).ToList(), untagged.Output); + + // 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 untagged versions stay, and the log says how many there are: their layers are freed only by a cleanup + // rule of Gitea, which knows whether a tag still uses them. + Assert.IsFalse(run.RegistryCalls.Any(c => c.Contains("sha256:", StringComparison.Ordinal)), run.Report); + StringAssert.Contains(run.Output, $" {UntaggedDigests.Length} versioni senza etichetta (sha256:…, i manifest di un indice con i loro strati): restano", 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); + } + } + + /// + /// The daemon of (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. + /// + 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", + ]; + + /// The same daemon without the running tried container and the builder that is not one. + 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 ContainersOf(string[] world) => [.. world.Select(c => c[..c.IndexOf('|', StringComparison.Ordinal)])]; + + /// + /// «id|names» of each image once febe-ci:777 is gone (the image of the release keeps its registry names), without + /// the images given. + /// + public static List 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)])), + ]; + } + + /// + /// 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. The images of the + /// real Febe and of Jellyfin have two names each, and Jellyfin was created from the one that is not the last. + /// + 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-jellyfin|jellyfin|running|90000|jellyfin/jellyfin:10.9|img-jellyfin||", + "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-jellyfin|jellyfin/jellyfin:10.9,jellyfin/jellyfin:latest|100000||900MB", + "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 ImageIds = [.. Images.Select(First)]; + + public static readonly List VolumeNames = [.. Volumes.Select(First)]; + + public static readonly List NetworkNames = [.. Networks.Select(n => n.Split('|')[1])]; + + /// + /// 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). + /// + 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 ContainersLeft = [.. FakeDaemon.ContainersOf(Containers).Except(Removed)]; + + public static readonly List ImagesLeft = [.. ImageIds.Except(Removed)]; + + public static readonly List VolumesLeft = [.. VolumeNames.Except(Removed)]; + + public static readonly List NetworksLeft = [.. Networks.Where(n => !Removed.Contains(First(n))).Select(n => n.Split('|')[1])]; + + private static string First(string line) => line.Split('|')[0]; + } + + /// A fake daemon (format in fake-docker.sh) and, for the registry, a fake Gitea (fake-curl.sh). + private sealed record World(string[] Containers, string[] Images, string[] Volumes, string[] Networks) + { + /// Docker commands that fail as if the daemon refused them («image prune», «builder prune»). + public string[] Broken { get; init; } = []; + + /// The registry; without it the cleanup runs with no REGISTRY_TOKEN. + public FakeRegistry? Registry { get; init; } + + /// «containerd» for the containerd image store; null for the classic one. + public string? Store { get; init; } + } + + /// + /// 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. + /// + private sealed record FakeRegistry(string Token, bool Refuse = false, string? Sent = null); + + private sealed record CleanupRun(int Code, string Output, string Errors) + { + /// The ids of the containers left. + public List Containers { get; init; } = []; + + /// «id|names» of the images left. + public List Images { get; init; } = []; + + public List Volumes { get; init; } = []; + + public List Networks { get; init; } = []; + + /// Every docker call, as fake-docker.sh writes it. + public List Calls { get; init; } = []; + + /// Every call to the API of the registry, «METHOD URL». + public List RegistryCalls { get; init; } = []; + + /// The versions deleted from the registry. + public List Deleted { get; init; } = []; + + public List ImageIds => [.. Images.Select(i => i.Split('|')[0])]; + + public string Report => $"codice {Code}\n{Output}\n{Errors}"; + } + + /// + /// 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. + /// + private Task RunCleanupAsync(string bash, World world, params string[] arguments) => + RunCleanupAsync(bash, world, touchesDocker: true, arguments); + + /// + /// As ; with false the run + /// may call no docker at all (wrong arguments stop before it). + /// + private async Task RunCleanupAsync(string bash, World world, bool touchesDocker, 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.Store is { } store) + { + await WriteLinesAsync(folder.Combine("store"), [store]); + } + + 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")), + }; + if (touchesDocker) + { + 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; + } + + /// A program with its arguments, from the root of the repository; its output with Unix lines. + private async Task<(int Code, string Output, string Errors)> RunProcessAsync(string program, IEnumerable arguments, Action? 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)); + } + + /// The pages of versioni-registro.json as Gitea would answer them, one file each. + private async Task> 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(); + 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 lines) => + await File.WriteAllTextAsync(path, string.Concat(lines.Select(line => line + "\n")), TestContext.CancellationToken); + + private async Task> ReadLinesAsync(string path) => + File.Exists(path) ? Lines(await File.ReadAllTextAsync(path, TestContext.CancellationToken)) : []; + + private static List Lines(string text) => [.. text.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n', StringSplitOptions.RemoveEmptyEntries)]; + + /// The number the summary of the cleanup gives for a kind of object, or null when it does not list it. + private static string? SummaryCount(string output, string kind) + { + var match = Regex.Match(output, $@"^ {Regex.Escape(kind)}: (?[0-9]+)", RegexOptions.Multiline); + return match.Success ? match.Groups["count"].Value : null; + } + + /// The «run: |» block of a step without its indentation, as the runner writes it to a script. + private static string RunBlock(string step) + { + const string start = "run: |\n"; + var at = step.IndexOf(start, StringComparison.Ordinal); + Assert.IsGreaterThanOrEqualTo(0, at, $"the step has no «{start.Trim()}» block"); + var lines = step[(at + start.Length)..].Split('\n'); + var indent = new string(' ', lines.First(l => l.Trim().Length > 0).TakeWhile(c => c == ' ').Count()); + var body = lines.TakeWhile(l => l.Trim().Length == 0 || l.StartsWith(indent, StringComparison.Ordinal)); + return string.Concat(body.Select(l => (l.Length >= indent.Length ? l[indent.Length..] : string.Empty) + "\n")); + } + + /// The body of a shell function of a script, from «name() {» to the closing brace at the start of a line. + private static string Function(string script, string name) + { + var match = Regex.Match(script, $@"^{Regex.Escape(name)}\(\) \{{\n(?.*?)^\}}", 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; + } + + /// node from the PATH: the registry part of the cleanup reads JSON with it, in the CI as here. + 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 (?[a-z]+) prune(?[^\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]+)* (?\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(); +} diff --git a/tests/Febe.Tests/Packaging/PipelineTests.cs b/tests/Febe.Tests/Packaging/PipelineTests.cs index 445f880..e4e4b87 100644 --- a/tests/Febe.Tests/Packaging/PipelineTests.cs +++ b/tests/Febe.Tests/Packaging/PipelineTests.cs @@ -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. /// [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:, 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"); - } - - /// - /// The daemon the cleanup runs against in - /// (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. - /// - 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|", - ]; - - /// The same daemon without the running tried container and the builder that is not one. - 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 ContainersOf(string[] world) => [.. world.Select(c => c[..c.IndexOf('|', StringComparison.Ordinal)])]; - - /// - /// «id|names» of each image once febe-ci:777 is gone (the image of the release keeps its registry names), without - /// the images given. - /// - public static List 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 Containers, List Images, List Volumes) - { - public string Report => $"codice {Code}\n{Output}\n{Errors}"; - } - - /// - /// 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. - /// - private async Task 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 lines) => - await File.WriteAllTextAsync(path, string.Concat(lines.Select(line => line + "\n")), TestContext.CancellationToken); - - private async Task> ReadLinesAsync(string path) => - [.. (await File.ReadAllTextAsync(path, TestContext.CancellationToken)).Split('\n', StringSplitOptions.RemoveEmptyEntries)]; - /// bash for the scripts of the CI: the system one on Linux, Git Bash on Windows (not the one of WSL). 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(); } diff --git a/tests/Febe.Tests/Packaging/fake-curl.sh b/tests/Febe.Tests/Packaging/fake-curl.sh new file mode 100644 index 0000000..292b69a --- /dev/null +++ b/tests/Febe.Tests/Packaging/fake-curl.sh @@ -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 ?page=&limit=50 the page $FAKE_CURL_WORLD/page-.json, or [] after the last one (200) +# DELETE / 204, and the version is written to $FAKE_CURL_WORLD/deleted +# where is the content of $FAKE_CURL_WORLD/base (…/api/v1/packages//container/febe). Without the header +# «Authorization: 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 diff --git a/tests/Febe.Tests/Packaging/fake-docker.sh b/tests/Febe.Tests/Packaging/fake-docker.sh index dd0d23c..7a7986b 100644 --- a/tests/Febe.Tests/Packaging/fake-docker.sh +++ b/tests/Febe.Tests/Packaging/fake-docker.sh @@ -3,32 +3,53 @@ # 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 » 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. With -a an image a container uses stays but loses +# its extra names, as moby does it with the classic store or, with $FAKE_DOCKER_WORLD/store, with containerd; +# - «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 [-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/store optional: «containerd» for the containerd image store (what «docker info» says); +# otherwise the classic store of overlay2 +# $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= 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 ). label_value() { local labels=",$1," key="$2" rest @@ -48,8 +69,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 +79,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 +112,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 +147,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 +170,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 +184,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 +193,28 @@ 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 "" ;; - *) 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" ;; + "{{.Image}} {{.Config.Image}}") echo "$image_id $config" ;; + "{{.Name}}") echo "/$name" ;; + '{{index .Config.Labels "febe.ci.prova"}}') label_value "$labels" febe.ci.prova "" ;; + *) unexpected "container inspect -f $format" ;; + esac + done + return "$status" } rm_command() { @@ -192,19 +242,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=(":") + 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 +275,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 @@ -256,18 +315,232 @@ image_rm() { echo "Deleted: $id" } +# The full name of an image name, the way Docker sorts references: docker.io/library/ or docker.io/ before the names +# of Docker Hub written without a domain, :latest when the tag is missing. +full_name() { + local name="$1" first + [[ "${name##*/}" == *:* ]] || name="$name:latest" + if [[ "$name" != */* ]]; then + echo "docker.io/library/$name" + return + fi + first="${name%%/*}" + if [[ "$first" == *.* || "$first" == *:* || "$first" == localhost ]]; then echo "$name"; else echo "docker.io/$name"; fi +} + +# The names «image prune -a» leaves to an image a container uses, comma separated, the way moby does it. With the +# classic store it removes the references in lexical order of their full names and only the last one is refused +# (ImageDelete keeps the single reference of an image in use); with containerd it keeps the names the containers were +# created from and, when a container uses the image by id and no name would be left, the last one in lexical order. +names_kept() { + local image="$1" names="$2" sorted name full cid cname state age config image_id rest by_id=0 + local -A from=() + local kept=() + sorted=$(IFS=','; for name in $names; do printf '%s %s\n' "$(full_name "$name")" "$name"; done | LC_ALL=C sort) + if [[ "$(store)" == classic ]]; then + tail -n 1 <<< "$sorted" | cut -d' ' -f2- + return + fi + while IFS='|' read -r cid cname state age config image_id rest; do + [[ -n "$cid" && "$image_id" == "$image" ]] || continue + if [[ "$config" == "$image" ]]; then by_id=1; else from[$(full_name "$config")]=1; fi + done < "$world/containers" + while read -r full name; do + [[ -n "${from[$full]:-}" ]] && kept+=("$name") + done <<< "$sorted" + ((${#kept[@]} > 0 || !by_id)) || kept=("$(tail -n 1 <<< "$sorted" | cut -d' ' -f2-)") + (IFS=','; echo "${kept[*]}") +} + 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 - used_by "$id" any || gone+=("$id") + 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=() untag=() tag left + while IFS='|' read -r id names age labels size; do + [[ -n "$id" ]] || continue + ((all)) || [[ -z "$names" ]] || continue + ((age >= hours * 60)) || continue + if used_by "$id" any; then + [[ "$names" == *,* ]] && untag+=("$id") + else + gone+=("$id") + fi done < "$world/images" - for id in "${gone[@]}"; do + ((${#gone[@]} + ${#untag[@]} == 0)) || echo "Deleted Images:" + for id in "${untag[@]}"; do + IFS='|' read -r id names age labels size <<< "$(image_line "$id")" + left=$(names_kept "$id" "$names") + IFS=',' read -r -a tags <<< "$names" + for tag in "${tags[@]}"; do + [[ ",$left," == *",$tag,"* ]] || echo "untagged: $tag" + done drop "$world/images" "$id" - echo "deleted: $id" + printf '%s|%s|%s|%s|%s\n' "$id" "$left" "$age" "$labels" "$size" >> "$world/images" done - echo "Total reclaimed space: 0B" + 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: sha256:$id" + done + echo + if ((${#gone[@]} > 0)); then + echo "Total reclaimed space: ${#gone[@]}00MB" + else + echo "Total reclaimed space: 0B" + fi +} + +builder_prune() { + case "$*" in + "-f --filter until=24h" | "-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" +} + +store() { + if [[ "$(cat "$world/store" 2> /dev/null)" == containerd ]]; then echo containerd; else echo classic; fi +} + +# The DriverStatus of «docker info» as Docker prints it: with the containerd image store the snapshotter, with the +# classic one the details of overlay2. +info_command() { + [[ "$*" == "--format {{json .DriverStatus}}" ]] || unexpected "info $*" + if [[ "$(store)" == containerd ]]; then + echo '[["driver-type","io.containerd.snapshotter.v1"]]' + else + echo '[["Backing Filesystem","extfs"],["Supports d_type","true"],["Using metacopy","false"],["Native Overlay Diff","true"],["userxattr","false"]]' + fi +} + +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 +558,29 @@ 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 "$@" ;; + info) shift; info_command "$@" ;; *) unexpected "$*" ;; esac diff --git a/tests/Febe.Tests/Packaging/versioni-registro.json b/tests/Febe.Tests/Packaging/versioni-registro.json new file mode 100644 index 0000000..03d7e2f --- /dev/null +++ b/tests/Febe.Tests/Packaging/versioni-registro.json @@ -0,0 +1,36 @@ +[ + [ + {"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": 142, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha256:d0e666bf0a465af6218c1825f3fd72143e2f9ddfc038a8cda19b0504656e0647", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha256:d0e666bf0a465af6218c1825f3fd72143e2f9ddfc038a8cda19b0504656e0647", "created_at": "2026-10-20T19:42:09+02:00"}, + {"id": 141, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha256:7c39e42c6e919ae17c7dfa17bd5fcf8cd38fa29c02be97e2b0134947b4674f3c", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha256:7c39e42c6e919ae17c7dfa17bd5fcf8cd38fa29c02be97e2b0134947b4674f3c", "created_at": "2026-10-20T19:42:09+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": 91, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe-strumenti", "version": "sha256:48f76e113cd23ae3e60a2657cf0f84618fce331ef675e8ea39527ba0937b34d0", "html_url": "https://gitea.example/Alby96/-/packages/container/febe-strumenti/sha256:48f76e113cd23ae3e60a2657cf0f84618fce331ef675e8ea39527ba0937b34d0", "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"} + ] +]