CI: la pulizia sceglie solo per segni che nessuna immagine porta e non tocca mai un Febe vero

Le etichette febe.ci.* stanno anche nelle immagini pubblicate (:main, :sha-, :X.Y.Z, :latest) e Docker le copia in
ogni contenitore creato da quelle: un Febe vero avviato sullo stesso demone del runner le portava, e la pulizia lo
toglieva con docker rm -f -v insieme ai suoi volumi anonimi. Con un rilascio rilanciato, che ha lo stesso numero di
esecuzione dell'immagine pubblicata, succedeva subito, e l'immagine col nome del registro spariva con docker image rm -f.

Ora le etichette dell'immagine dicono solo da dove viene. I contenitori di prova portano febe.ci.prova=<esecuzione>,
che mette solo prova-immagine.sh con docker run --label e che nessuna immagine porta, e devono chiamarsi
febe-prova-<esecuzione>; nei giri di pulizia (residui, settimanale) si tolgono solo se fermi, uno ancora acceso si
segnala con il comando per toglierlo. Le immagini si tolgono solo per il nome locale febe-ci:<esecuzione>, mai per
identificativo né con -f: un nome del registro sulla stessa immagine resta, un'immagine in uso resta. I builder si
tolgono solo se il contenitore gira l'immagine di buildkit. Le immagini senza nome restano alla pulizia oltre 72 ore.

PipelineTests fa girare la pulizia contro un client Docker finto (tests/Febe.Tests/Packaging/fake-docker.sh) con un
Febe vero acceso e uno fermo che portano le etichette delle loro immagini, e vieta i filtri sulle etichette di
provenienza e la rimozione forzata delle immagini. Rilievo bloccante della revisione (pulizia-contenitori-non-ci).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-10-20 12:04:32 +02:00
1 parent 5397d31e13
commit 1bff405384
9 files changed
+707 -65

No files matched your search

+228 -3
View File
@@ -1,3 +1,4 @@
using System.Diagnostics;
using System.Text.RegularExpressions;
using Febe.Tests.Desktop.Support;
using Febe.Tests.Support;
@@ -9,13 +10,16 @@ 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; the tried container never has a network.
/// 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.
/// </summary>
[TestClass]
public sealed partial class PipelineTests
{
private static readonly string[] Jobs = ["controlli", "prove", "installatore", "immagine"];
public TestContext TestContext { get; set; } = null!;
[TestMethod]
public void EveryPushOfEveryBranchIsVerifiedOnceAndTagsAreLeftToTheRelease()
{
@@ -166,9 +170,24 @@ public sealed partial class PipelineTests
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, "--filter \"label=febe.ci.run=$run\"");
StringAssert.Contains(cleanup, "^buildx_buildkit_(febe-ci-[0-9]+)0$");
// The febe.ci.* labels of the image are in every container made from a published image, a real Febe too: they
// never choose what goes. Containers are chosen by febe.ci.prova (and their exact name), the builders by name,
// and an image only by its local name febe-ci:<run>, never by id and never forced.
Assert.IsFalse(ProvenanceLabelFilter().IsMatch(cleanup), "the cleanup filters on febe.ci.prova only");
foreach (var line in cleanup.Split('\n').Where(l => l.Contains("docker ps", StringComparison.Ordinal)))
{
Assert.IsTrue(
line.Contains("--filter \"label=febe.ci.prova", StringComparison.Ordinal) || line.Contains("--filter \"name=buildx_buildkit_febe-ci-\"", StringComparison.Ordinal) || line.Contains("--filter \"ancestor=", StringComparison.Ordinal),
$"«{line.Trim()}» lists containers without the mark of the tried container");
}
StringAssert.Contains(cleanup, "\"febe-prova-$valore\"", "the name must match the mark");
StringAssert.Contains(cleanup, "contenitori_di_prova \"\" exited created dead", "the sweeps take only stopped tried containers");
Assert.IsFalse(ForcedImageRemoval().IsMatch(cleanup), "an image is never removed by force");
StringAssert.Contains(cleanup, "[[ \"$riferimento\" =~ ^febe-ci:[0-9]+$ ]]");
var weekly = Workflow("pulizia.yml");
StringAssert.Contains(weekly, "schedule:");
StringAssert.Contains(weekly, "workflow_dispatch:");
@@ -176,7 +195,7 @@ public sealed partial class PipelineTests
}
[TestMethod]
public void TheTriedContainerNeverHasANetwork()
public void TheTriedContainerNeverHasANetworkAndAlwaysCarriesTheMarkNoImageHas()
{
var smoke = Code(Script("prova-immagine.sh"));
var runs = DockerRun().Matches(smoke);
@@ -184,7 +203,207 @@ public sealed partial class PipelineTests
foreach (Match run in runs)
{
StringAssert.Contains(run.Value, "--network none", "rule 1: the image under test cannot reach any site");
StringAssert.Contains(run.Value, "\"${etichette[@]}\"", "every tried container carries the mark the cleanup looks for");
}
StringAssert.Contains(smoke, "etichette=(--label \"febe.ci.prova=$esecuzione\")");
StringAssert.Contains(smoke, "nome=\"febe-prova-$esecuzione\"");
// Docker copies the labels of an image into every container made from it: the mark must never be in an image.
Assert.DoesNotContain("febe.ci.prova", Code(Script("costruisci-immagine.sh")));
Assert.DoesNotContain("febe.ci.prova", Code(Read(Repository.PathOf("docker", "Dockerfile"))));
}
[TestMethod]
[Timeout(180_000, CooperativeCancellation = true)]
public async Task OnADaemonSharedWithARealFebeTheCleanupTakesOnlyWhatTheCiMade()
{
var script = CiPath("scripts", "pulizia-docker.sh");
var bash = BashForScripts();
if (bash is null)
{
Assert.Inconclusive("Manca bash (su Windows serve Git Bash): la prova della pulizia su un demone finto si salta.");
}
Assert.IsTrue(File.Exists(script));
// At the start or the end of a run (a release run again keeps its id, so the published image has the same
// febe.ci.run as the run): only the tried container, the local name and the builder of that run.
var run = await RunCleanupAsync(bash, FakeDaemon.Full, "esecuzione", "777");
Assert.AreEqual(0, run.Code, run.Report);
Assert.DoesNotContain("::warning::", run.Output, run.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Full).Except(["c-prova-777", "b-777"]).ToList(), run.Containers, run.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777(), run.Images, run.Report);
CollectionAssert.AreEquivalent(FakeDaemon.Volumes.Except(["buildx_buildkit_febe-ci-7770_state"]).ToList(), run.Volumes, run.Report);
// Leftovers of interrupted runs: stopped tried containers, febe-ci images and builders older than 90 minutes.
var leftovers = await RunCleanupAsync(bash, FakeDaemon.Full, "residui", "90");
Assert.AreEqual(0, leftovers.Code, leftovers.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Full).Except(["c-prova-555", "b-vecchio"]).ToList(), leftovers.Containers, leftovers.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777("img-ci555"), leftovers.Images, leftovers.Report);
CollectionAssert.AreEquivalent(FakeDaemon.Volumes.Except(["buildx_buildkit_febe-ci-4560_state"]).ToList(), leftovers.Volumes, leftovers.Report);
StringAssert.Contains(leftovers.Output, "::warning::Il contenitore di prova febe-prova-556 è acceso", "a running tried container is reported, not removed");
StringAssert.Contains(leftovers.Output, "::warning::Il contenitore buildx_buildkit_febe-ci-4570 non è un builder buildx", leftovers.Report);
// Every week, on a daemon without anything odd: the same, the old febe:ci and the dangling images older than
// 72 hours that no container uses. Green.
var weekly = await RunCleanupAsync(bash, FakeDaemon.Clean, "settimanale");
Assert.AreEqual(0, weekly.Code, weekly.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Clean).Except(["c-prova-555", "b-vecchio"]).ToList(), weekly.Containers, weekly.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777("img-ci555", "img-ci556", "img-legacy", "img-penzolante-vecchia"), weekly.Images, weekly.Report);
// With something left for a person to look at, the weekly cleanup goes red.
var noticed = await RunCleanupAsync(bash, FakeDaemon.Full, "settimanale");
Assert.AreEqual(1, noticed.Code, noticed.Report);
CollectionAssert.Contains(noticed.Containers, "c-prova-556");
CollectionAssert.Contains(noticed.Containers, "c-febe-vero");
}
/// <summary>
/// The daemon the cleanup runs against in <see cref="OnADaemonSharedWithARealFebeTheCleanupTakesOnlyWhatTheCiMade"/>
/// (format in fake-docker.sh). A real Febe started from :latest and one from :main carry the febe.ci.* labels of
/// their images, as Docker gives them; the image of the release also has the local name of run 777.
/// </summary>
private static class FakeDaemon
{
public static readonly string[] Full =
[
"c-febe-vero|febe|running|43200|192.168.30.23:3000/alby96/febe:latest|img-rilascio|febe.ci.workflow=rilascio,febe.ci.run=777,febe.ci.ref=v0.1.0",
"c-febe-fermo|febe-main|exited|43200|192.168.30.23:3000/alby96/febe:main|img-main|febe.ci.workflow=verifica,febe.ci.run=888",
"c-febe-antico|febe-antico|exited|20000|img-penzolante-in-uso|img-penzolante-in-uso|febe.ci.run=111",
"c-prova-777|febe-prova-777|running|5|febe-ci:777|img-rilascio|febe.ci.workflow=rilascio,febe.ci.run=777,febe.ci.prova=777",
"c-prova-555|febe-prova-555|exited|300|febe-ci:555|img-ci555|febe.ci.run=555,febe.ci.prova=555",
"c-prova-556|febe-prova-556|running|300|febe-ci:556|img-ci556|febe.ci.run=556,febe.ci.prova=556",
"c-prova-557|febe-prova-557|exited|10|febe-ci:557|img-ci557|febe.ci.run=557,febe.ci.prova=557",
"c-nome-strano|febe-prova-558-bis|exited|300|encelado:latest|img-encelado|febe.ci.prova=558",
"c-segno-diverso|febe-prova-559|exited|300|encelado:latest|img-encelado|febe.ci.prova=560",
"c-senza-segno|febe-prova-561|exited|300|encelado:latest|img-encelado|",
"c-encelado|encelado|exited|5000|encelado:latest|img-encelado|",
"b-vecchio|buildx_buildkit_febe-ci-4560|running|300|moby/buildkit:buildx-stable-1|img-buildkit|",
"b-finto|buildx_buildkit_febe-ci-4570|running|300|encelado:latest|img-encelado|",
"b-giovane|buildx_buildkit_febe-ci-7890|running|10|moby/buildkit:buildx-stable-1|img-buildkit|",
"b-altro|altro_buildx_buildkit_febe-ci-10|running|300|moby/buildkit:buildx-stable-1|img-buildkit|",
"b-777|buildx_buildkit_febe-ci-7770|running|20|moby/buildkit:buildx-stable-1|img-buildkit|",
];
/// <summary>The same daemon without the running tried container and the builder that is not one.</summary>
public static readonly string[] Clean = [.. Full.Where(c => !c.StartsWith("c-prova-556|", StringComparison.Ordinal) && !c.StartsWith("b-finto|", StringComparison.Ordinal))];
public static readonly string[] Images =
[
"img-rilascio|192.168.30.23:3000/alby96/febe:latest,192.168.30.23:3000/alby96/febe:0.1.0,febe-ci:777|43200|febe.ci.run=777",
"img-main|192.168.30.23:3000/alby96/febe:main|43200|febe.ci.run=888",
"img-ci555|febe-ci:555|300|febe.ci.run=555",
"img-ci556|febe-ci:556|300|febe.ci.run=556",
"img-ci557|febe-ci:557|10|febe.ci.run=557",
"img-penzolante-febe||300|febe.ci.run=999",
"img-penzolante-vecchia||6000|",
"img-penzolante-in-uso||20000|febe.ci.run=111",
"img-encelado|encelado:latest|5000|",
"img-buildkit|moby/buildkit:buildx-stable-1|50000|",
"img-legacy|febe:ci|6000|",
];
public static readonly string[] Volumes =
[
"buildx_buildkit_febe-ci-4560_state",
"buildx_buildkit_febe-ci-4570_state",
"buildx_buildkit_febe-ci-7890_state",
"buildx_buildkit_febe-ci-7770_state",
"encelado-dati",
];
public static List<string> ContainersOf(string[] world) => [.. world.Select(c => c[..c.IndexOf('|', StringComparison.Ordinal)])];
/// <summary>
/// «id|names» of each image once febe-ci:777 is gone (the image of the release keeps its registry names), without
/// the images given.
/// </summary>
public static List<string> ImagesWithout777(params string[] gone) =>
[
.. Images
.Select(i => string.Join('|', i.Split('|')[..2]).Replace(",febe-ci:777", string.Empty, StringComparison.Ordinal))
.Where(i => !gone.Contains(i[..i.IndexOf('|', StringComparison.Ordinal)])),
];
}
private sealed record CleanupRun(int Code, string Output, string Errors, List<string> Containers, List<string> Images, List<string> Volumes)
{
public string Report => $"codice {Code}\n{Output}\n{Errors}";
}
/// <summary>
/// pulizia-docker.sh against the fake daemon. DOCKER_HOST points nowhere: even if a real docker client came first on
/// the PATH it could not reach a daemon, and the test fails because the fake recorded no call.
/// </summary>
private async Task<CleanupRun> RunCleanupAsync(string bash, string[] containers, params string[] arguments)
{
using var world = new TempFolder("febe-pulizia");
var bin = world.Combine("bin");
Directory.CreateDirectory(bin);
var docker = Path.Combine(bin, "docker");
File.Copy(Repository.PathOf("tests", "Febe.Tests", "Packaging", "fake-docker.sh"), docker);
if (!OperatingSystem.IsWindows())
{
File.SetUnixFileMode(docker, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
}
await WriteLinesAsync(world.Combine("containers"), containers);
await WriteLinesAsync(world.Combine("images"), FakeDaemon.Images);
await WriteLinesAsync(world.Combine("volumes"), FakeDaemon.Volumes);
var start = new ProcessStartInfo(bash)
{
WorkingDirectory = Repository.Root()!,
RedirectStandardOutput = true,
RedirectStandardError = true,
StandardOutputEncoding = System.Text.Encoding.UTF8,
StandardErrorEncoding = System.Text.Encoding.UTF8,
};
start.ArgumentList.Add(".gitea/scripts/pulizia-docker.sh");
foreach (var argument in arguments)
{
start.ArgumentList.Add(argument);
}
start.Environment["PATH"] = bin + Path.PathSeparator + Environment.GetEnvironmentVariable("PATH");
start.Environment["FAKE_DOCKER_WORLD"] = world.Path.Replace('\\', '/');
start.Environment["DOCKER_HOST"] = OperatingSystem.IsWindows() ? "npipe:////./pipe/febe-nessun-demone" : "unix:///nonexistent/febe-nessun-demone.sock";
start.Environment.Remove("DOCKER_CONTEXT");
using var process = Process.Start(start)!;
var output = process.StandardOutput.ReadToEndAsync(TestContext.CancellationToken);
var errors = process.StandardError.ReadToEndAsync(TestContext.CancellationToken);
await process.WaitForExitAsync(TestContext.CancellationToken);
var result = new CleanupRun(
process.ExitCode,
(await output).Replace("\r\n", "\n", StringComparison.Ordinal),
await errors,
FakeDaemon.ContainersOf([.. await ReadLinesAsync(world.Combine("containers"))]),
[.. (await ReadLinesAsync(world.Combine("images"))).Select(i => string.Join('|', i.Split('|')[..2]))],
await ReadLinesAsync(world.Combine("volumes")));
var calls = world.Combine("calls");
Assert.IsTrue(File.Exists(calls) && (await File.ReadAllTextAsync(calls, TestContext.CancellationToken)).Contains("docker ps", StringComparison.Ordinal), $"the fake docker client was not the one called\n{result.Report}");
Assert.DoesNotContain("unexpected call", result.Errors, result.Report);
return result;
}
private async Task WriteLinesAsync(string path, IEnumerable<string> lines) =>
await File.WriteAllTextAsync(path, string.Concat(lines.Select(line => line + "\n")), TestContext.CancellationToken);
private async Task<List<string>> ReadLinesAsync(string path) =>
[.. (await File.ReadAllTextAsync(path, TestContext.CancellationToken)).Split('\n', StringSplitOptions.RemoveEmptyEntries)];
/// <summary>bash for the scripts of the CI: the system one on Linux, Git Bash on Windows (not the one of WSL).</summary>
private static string? BashForScripts()
{
if (OperatingSystem.IsWindows())
{
var git = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Git", "bin", "bash.exe");
return File.Exists(git) ? git : null;
}
return new[] { "/bin/bash", "/usr/bin/bash" }.FirstOrDefault(File.Exists);
}
/// <summary>The workflows and the scripts of the CI, by name.</summary>
@@ -255,4 +474,10 @@ public sealed partial class PipelineTests
[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();
}
+302
View File
@@ -0,0 +1,302 @@
#!/usr/bin/env bash
# A fake docker client for PipelineTests: .gitea/scripts/pulizia-docker.sh runs against a small daemon written in text
# 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);
# - «rm» refuses a running container without -f;
# - «image rm <name>» only untags when the image has other names, and refuses an image a container uses (always if the
# container runs, without -f if it is stopped);
# - «image prune --filter until=72h» takes only images without a name, older than 72 hours, used by no container.
# Any other call is an error (exit 3), so the test sees every command the cleanup starts to use.
#
# $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)
set -uo pipefail
world="${FAKE_DOCKER_WORLD:?}"
printf 'docker %s\n' "$*" >> "$world/calls"
now=$(date -u +%s)
touch "$world/containers" "$world/images" "$world/volumes"
unexpected() {
echo "fake docker: unexpected call: $*" >&2
exit 3
}
created() { date -u -d "@$((now - $1 * 60))" +%Y-%m-%dT%H:%M:%S.123456789Z; }
# The value of a label, or $3 when it is missing («docker ps» prints nothing, «inspect» prints <no value>).
label_value() {
local labels=",$1," key="$2" rest
[[ "$labels" == *",$key="* ]] || { echo "${3:-}"; return; }
rest="${labels#*,"$key"=}"
echo "${rest%%,*}"
}
has_label() {
local labels=",$1," want="$2"
if [[ "$want" == *=* ]]; then
[[ "$labels" == *",$want,"* ]]
else
[[ "$labels" == *",$want="* ]]
fi
}
# 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
[[ -n "$id" ]] || continue
if [[ "$id" == "$ref" || ",$names," == *",$ref,"* ]]; then
echo "$id"
return
fi
done < "$world/images"
}
# The image line for an id; empty when there is none.
image_line() {
local line
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
echo "$line"
return
fi
done < "$world/containers"
}
# Rewrites a world file without the lines whose first field is $2.
drop() {
local file="$1" id="$2" line
: > "$file.new"
while IFS= read -r line; do
[[ "${line%%|*}" == "$id" ]] || printf '%s\n' "$line" >> "$file.new"
done < "$file"
mv "$file.new" "$file"
}
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
[[ -n "$id" && "$image_id" == "$image" ]] || 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 -A seen=() ok=()
local filter key value
for filter in "$@"; do
key="${filter%%=*}"
value="${filter#*=}"
case "$key" in
label) has_label "$labels" "$value" || return 1 ;;
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 ;;
*) unexpected "filter $filter" ;;
esac
done
for key in "${!seen[@]}"; do
[[ -n "${ok[$key]:-}" ]] || return 1
done
return 0
}
ps_command() {
local quiet=0 format='{{.ID}} {{.Names}}' filters=()
while (($#)); do
case "$1" in
-a | --no-trunc) ;;
-q) quiet=1 ;;
--filter) filters+=("$2"); shift ;;
--format) format="$2"; shift ;;
*) unexpected "ps $1" ;;
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
[[ -n "$id" ]] || continue
matches "$name" "$state" "$image_id" "$labels" "${filters[@]}" || continue
if ((quiet)); then
echo "$id"
continue
fi
out="${format//"{{.ID}}"/$id}"
out="${out//"{{.Names}}"/$name}"
while [[ "$out" =~ \{\{\.Label\ \"([^\"]+)\"\}\} ]]; do
key="${BASH_REMATCH[1]}"
out="${out/"${BASH_REMATCH[0]}"/$(label_value "$labels" "$key" "")}"
done
printf '%s\n' "$out"
done < "$world/containers"
return 0
}
container_inspect() {
local format=""
[[ "${1:-}" == -f ]] && { format="$2"; shift 2; }
local line id name state age config image_id labels
line=$(find_container "${1:?}")
[[ -n "$line" ]] || { echo "Error: No such container: $1" >&2; exit 1; }
IFS='|' read -r id name state age config image_id labels <<< "$line"
case "$format" in
"") echo "[{\"Id\": \"$id\"}]" ;;
"{{.Created}}") created "$age" ;;
"{{.Config.Image}}") echo "$config" ;;
"{{.Name}}") echo "/$name" ;;
'{{index .Config.Labels "febe.ci.prova"}}') label_value "$labels" febe.ci.prova "<no value>" ;;
*) unexpected "container inspect -f $format" ;;
esac
}
rm_command() {
local force=0
while [[ "${1:-}" == -* ]]; do
case "$1" in
-f) force=1 ;;
-v) ;;
*) unexpected "rm $1" ;;
esac
shift
done
local line id name state rest
line=$(find_container "${1:?}")
[[ -n "$line" ]] || { echo "Error: No such container: $1" >&2; exit 1; }
IFS='|' read -r id name state rest <<< "$line"
if [[ "$state" == running && "$force" == 0 ]]; then
echo "Error: cannot remove container \"/$name\": container is running: stop the container before removing or force remove" >&2
exit 1
fi
drop "$world/containers" "$id"
}
image_ls() {
local format="" reference=""
while (($#)); do
case "$1" in
--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 "$id" ]] || continue
IFS=',' read -r -a tags <<< "$names"
for tag in "${tags[@]}"; do
[[ -z "$reference" || "${tag%:*}" == "$reference" || "$tag" == "$reference" ]] && echo "$tag"
done
done < "$world/images"
return 0
}
image_inspect() {
local format=""
[[ "${1:-}" == -f ]] && { format="$2"; shift 2; }
local wanted id names age labels
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"
}
image_rm() {
local force=0
[[ "${1:-}" == -f ]] && { force=1; shift; }
local ref="${1:?}" wanted id names age labels 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")"
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"
echo "Untagged: $ref"
return 0
fi
if [[ "$ref" == "$id" && ${#tags[@]} -gt 1 && "$force" == 0 ]]; then
echo "Error: conflict: unable to delete $id (must be forced) - image is referenced in multiple repositories" >&2
exit 1
fi
if used_by "$id" running || { [[ "$force" == 0 ]] && used_by "$id" any; }; then
echo "Error: conflict: unable to remove repository reference \"$ref\" - container is using its referenced image" >&2
exit 1
fi
drop "$world/images" "$id"
echo "Deleted: $id"
}
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")
done < "$world/images"
for id in "${gone[@]}"; do
drop "$world/images" "$id"
echo "deleted: $id"
done
echo "Total reclaimed space: 0B"
}
case "${1:-}" in
ps) shift; ps_command "$@" ;;
container) [[ "${2:-}" == inspect ]] || unexpected "$*"; shift 2; container_inspect "$@" ;;
rm) shift; rm_command "$@" ;;
image)
sub="${2:-}"
shift 2
case "$sub" in
ls) image_ls "$@" ;;
inspect) image_inspect "$@" ;;
rm) image_rm "$@" ;;
prune) image_prune "$@" ;;
*) unexpected "image $sub" ;;
esac
;;
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 "$*" ;;
esac
;;
system) [[ "${2:-}" == df ]] || unexpected "$*"; echo "TYPE TOTAL ACTIVE SIZE RECLAIMABLE" ;;
*) unexpected "$*" ;;
esac