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

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

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

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

No files matched your search

+2 -227
View File
@@ -1,4 +1,3 @@
using System.Diagnostics;
using System.Text.RegularExpressions;
using Febe.Tests.Desktop.Support;
using Febe.Tests.Support;
@@ -10,8 +9,8 @@ namespace Febe.Tests.Packaging;
/// text: the rules that must survive later edits. Every push of every branch is verified and nothing else triggers
/// it twice; the tests run only through tests/Febe.Tests, with the browser, and again with the seed of the run; the
/// image is published only from main and never as :latest; credentials are never printed; the external tools are
/// pinned and checked; the cleanup touches only what the CI of Febe made, never a real Febe on the same daemon; the
/// tried container never has a network.
/// pinned and checked; the tried container never has a network. The cleanup, which runs against fake docker and curl
/// clients, is in PipelineTests.Pulizia.cs.
/// </summary>
[TestClass]
public sealed partial class PipelineTests
@@ -163,41 +162,6 @@ public sealed partial class PipelineTests
StringAssert.Contains(scan, "--exit-code 1");
}
[TestMethod]
public void TheCleanupTouchesOnlyWhatTheCiOfFebeMade()
{
var cleanup = Code(Script("pulizia-docker.sh"));
foreach (var forbidden in new[] { "system prune", "builder prune", "volume prune", "container prune", "image prune -a", "prune --all", "image prune -f -a" })
{
Assert.DoesNotContain(forbidden, cleanup, "the daemon is shared with Alberto's other projects");
}
Assert.HasCount(1, ImagePrune().Matches(cleanup), "only dangling images, older than three days");
StringAssert.Contains(cleanup, "docker image prune -f --filter \"until=72h\"");
StringAssert.Contains(cleanup, "^buildx_buildkit_(febe-ci-[0-9]+)0$");
// The febe.ci.* labels of the image are in every container made from a published image, a real Febe too: they
// never choose what goes. Containers are chosen by febe.ci.prova (and their exact name), the builders by name,
// and an image only by its local name febe-ci:<run>, never by id and never forced.
Assert.IsFalse(ProvenanceLabelFilter().IsMatch(cleanup), "the cleanup filters on febe.ci.prova only");
foreach (var line in cleanup.Split('\n').Where(l => l.Contains("docker ps", StringComparison.Ordinal)))
{
Assert.IsTrue(
line.Contains("--filter \"label=febe.ci.prova", StringComparison.Ordinal) || line.Contains("--filter \"name=buildx_buildkit_febe-ci-\"", StringComparison.Ordinal) || line.Contains("--filter \"ancestor=", StringComparison.Ordinal),
$"«{line.Trim()}» lists containers without the mark of the tried container");
}
StringAssert.Contains(cleanup, "\"febe-prova-$valore\"", "the name must match the mark");
StringAssert.Contains(cleanup, "contenitori_di_prova \"\" exited created dead", "the sweeps take only stopped tried containers");
Assert.IsFalse(ForcedImageRemoval().IsMatch(cleanup), "an image is never removed by force");
StringAssert.Contains(cleanup, "[[ \"$riferimento\" =~ ^febe-ci:[0-9]+$ ]]");
var weekly = Workflow("pulizia.yml");
StringAssert.Contains(weekly, "schedule:");
StringAssert.Contains(weekly, "workflow_dispatch:");
StringAssert.Contains(weekly, "bash .gitea/scripts/pulizia-docker.sh settimanale");
}
[TestMethod]
public void TheTriedContainerNeverHasANetworkAndAlwaysCarriesTheMarkNoImageHas()
{
@@ -218,186 +182,6 @@ public sealed partial class PipelineTests
Assert.DoesNotContain("febe.ci.prova", Code(Read(Repository.PathOf("docker", "Dockerfile"))));
}
[TestMethod]
[Timeout(180_000, CooperativeCancellation = true)]
public async Task OnADaemonSharedWithARealFebeTheCleanupTakesOnlyWhatTheCiMade()
{
var script = CiPath("scripts", "pulizia-docker.sh");
var bash = BashForScripts();
if (bash is null)
{
Assert.Inconclusive("Manca bash (su Windows serve Git Bash): la prova della pulizia su un demone finto si salta.");
}
Assert.IsTrue(File.Exists(script));
// At the start or the end of a run (a release run again keeps its id, so the published image has the same
// febe.ci.run as the run): only the tried container, the local name and the builder of that run.
var run = await RunCleanupAsync(bash, FakeDaemon.Full, "esecuzione", "777");
Assert.AreEqual(0, run.Code, run.Report);
Assert.DoesNotContain("::warning::", run.Output, run.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Full).Except(["c-prova-777", "b-777"]).ToList(), run.Containers, run.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777(), run.Images, run.Report);
CollectionAssert.AreEquivalent(FakeDaemon.Volumes.Except(["buildx_buildkit_febe-ci-7770_state"]).ToList(), run.Volumes, run.Report);
// Leftovers of interrupted runs: stopped tried containers, febe-ci images and builders older than 90 minutes.
var leftovers = await RunCleanupAsync(bash, FakeDaemon.Full, "residui", "90");
Assert.AreEqual(0, leftovers.Code, leftovers.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Full).Except(["c-prova-555", "b-vecchio"]).ToList(), leftovers.Containers, leftovers.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777("img-ci555"), leftovers.Images, leftovers.Report);
CollectionAssert.AreEquivalent(FakeDaemon.Volumes.Except(["buildx_buildkit_febe-ci-4560_state"]).ToList(), leftovers.Volumes, leftovers.Report);
StringAssert.Contains(leftovers.Output, "::warning::Il contenitore di prova febe-prova-556 è acceso", "a running tried container is reported, not removed");
StringAssert.Contains(leftovers.Output, "::warning::Il contenitore buildx_buildkit_febe-ci-4570 non è un builder buildx", leftovers.Report);
// Every week, on a daemon without anything odd: the same, the old febe:ci and the dangling images older than
// 72 hours that no container uses. Green.
var weekly = await RunCleanupAsync(bash, FakeDaemon.Clean, "settimanale");
Assert.AreEqual(0, weekly.Code, weekly.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Clean).Except(["c-prova-555", "b-vecchio"]).ToList(), weekly.Containers, weekly.Report);
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777("img-ci555", "img-ci556", "img-legacy", "img-penzolante-vecchia"), weekly.Images, weekly.Report);
// With something left for a person to look at, the weekly cleanup goes red.
var noticed = await RunCleanupAsync(bash, FakeDaemon.Full, "settimanale");
Assert.AreEqual(1, noticed.Code, noticed.Report);
CollectionAssert.Contains(noticed.Containers, "c-prova-556");
CollectionAssert.Contains(noticed.Containers, "c-febe-vero");
}
/// <summary>
/// The daemon the cleanup runs against in <see cref="OnADaemonSharedWithARealFebeTheCleanupTakesOnlyWhatTheCiMade"/>
/// (format in fake-docker.sh). A real Febe started from :latest and one from :main carry the febe.ci.* labels of
/// their images, as Docker gives them; the image of the release also has the local name of run 777.
/// </summary>
private static class FakeDaemon
{
public static readonly string[] Full =
[
"c-febe-vero|febe|running|43200|192.168.30.23:3000/alby96/febe:latest|img-rilascio|febe.ci.workflow=rilascio,febe.ci.run=777,febe.ci.ref=v0.1.0",
"c-febe-fermo|febe-main|exited|43200|192.168.30.23:3000/alby96/febe:main|img-main|febe.ci.workflow=verifica,febe.ci.run=888",
"c-febe-antico|febe-antico|exited|20000|img-penzolante-in-uso|img-penzolante-in-uso|febe.ci.run=111",
"c-prova-777|febe-prova-777|running|5|febe-ci:777|img-rilascio|febe.ci.workflow=rilascio,febe.ci.run=777,febe.ci.prova=777",
"c-prova-555|febe-prova-555|exited|300|febe-ci:555|img-ci555|febe.ci.run=555,febe.ci.prova=555",
"c-prova-556|febe-prova-556|running|300|febe-ci:556|img-ci556|febe.ci.run=556,febe.ci.prova=556",
"c-prova-557|febe-prova-557|exited|10|febe-ci:557|img-ci557|febe.ci.run=557,febe.ci.prova=557",
"c-nome-strano|febe-prova-558-bis|exited|300|encelado:latest|img-encelado|febe.ci.prova=558",
"c-segno-diverso|febe-prova-559|exited|300|encelado:latest|img-encelado|febe.ci.prova=560",
"c-senza-segno|febe-prova-561|exited|300|encelado:latest|img-encelado|",
"c-encelado|encelado|exited|5000|encelado:latest|img-encelado|",
"b-vecchio|buildx_buildkit_febe-ci-4560|running|300|moby/buildkit:buildx-stable-1|img-buildkit|",
"b-finto|buildx_buildkit_febe-ci-4570|running|300|encelado:latest|img-encelado|",
"b-giovane|buildx_buildkit_febe-ci-7890|running|10|moby/buildkit:buildx-stable-1|img-buildkit|",
"b-altro|altro_buildx_buildkit_febe-ci-10|running|300|moby/buildkit:buildx-stable-1|img-buildkit|",
"b-777|buildx_buildkit_febe-ci-7770|running|20|moby/buildkit:buildx-stable-1|img-buildkit|",
];
/// <summary>The same daemon without the running tried container and the builder that is not one.</summary>
public static readonly string[] Clean = [.. Full.Where(c => !c.StartsWith("c-prova-556|", StringComparison.Ordinal) && !c.StartsWith("b-finto|", StringComparison.Ordinal))];
public static readonly string[] Images =
[
"img-rilascio|192.168.30.23:3000/alby96/febe:latest,192.168.30.23:3000/alby96/febe:0.1.0,febe-ci:777|43200|febe.ci.run=777",
"img-main|192.168.30.23:3000/alby96/febe:main|43200|febe.ci.run=888",
"img-ci555|febe-ci:555|300|febe.ci.run=555",
"img-ci556|febe-ci:556|300|febe.ci.run=556",
"img-ci557|febe-ci:557|10|febe.ci.run=557",
"img-penzolante-febe||300|febe.ci.run=999",
"img-penzolante-vecchia||6000|",
"img-penzolante-in-uso||20000|febe.ci.run=111",
"img-encelado|encelado:latest|5000|",
"img-buildkit|moby/buildkit:buildx-stable-1|50000|",
"img-legacy|febe:ci|6000|",
];
public static readonly string[] Volumes =
[
"buildx_buildkit_febe-ci-4560_state",
"buildx_buildkit_febe-ci-4570_state",
"buildx_buildkit_febe-ci-7890_state",
"buildx_buildkit_febe-ci-7770_state",
"encelado-dati",
];
public static List<string> ContainersOf(string[] world) => [.. world.Select(c => c[..c.IndexOf('|', StringComparison.Ordinal)])];
/// <summary>
/// «id|names» of each image once febe-ci:777 is gone (the image of the release keeps its registry names), without
/// the images given.
/// </summary>
public static List<string> ImagesWithout777(params string[] gone) =>
[
.. Images
.Select(i => string.Join('|', i.Split('|')[..2]).Replace(",febe-ci:777", string.Empty, StringComparison.Ordinal))
.Where(i => !gone.Contains(i[..i.IndexOf('|', StringComparison.Ordinal)])),
];
}
private sealed record CleanupRun(int Code, string Output, string Errors, List<string> Containers, List<string> Images, List<string> Volumes)
{
public string Report => $"codice {Code}\n{Output}\n{Errors}";
}
/// <summary>
/// pulizia-docker.sh against the fake daemon. DOCKER_HOST points nowhere: even if a real docker client came first on
/// the PATH it could not reach a daemon, and the test fails because the fake recorded no call.
/// </summary>
private async Task<CleanupRun> RunCleanupAsync(string bash, string[] containers, params string[] arguments)
{
using var world = new TempFolder("febe-pulizia");
var bin = world.Combine("bin");
Directory.CreateDirectory(bin);
var docker = Path.Combine(bin, "docker");
File.Copy(Repository.PathOf("tests", "Febe.Tests", "Packaging", "fake-docker.sh"), docker);
if (!OperatingSystem.IsWindows())
{
File.SetUnixFileMode(docker, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
}
await WriteLinesAsync(world.Combine("containers"), containers);
await WriteLinesAsync(world.Combine("images"), FakeDaemon.Images);
await WriteLinesAsync(world.Combine("volumes"), FakeDaemon.Volumes);
var start = new ProcessStartInfo(bash)
{
WorkingDirectory = Repository.Root()!,
RedirectStandardOutput = true,
RedirectStandardError = true,
StandardOutputEncoding = System.Text.Encoding.UTF8,
StandardErrorEncoding = System.Text.Encoding.UTF8,
};
start.ArgumentList.Add(".gitea/scripts/pulizia-docker.sh");
foreach (var argument in arguments)
{
start.ArgumentList.Add(argument);
}
start.Environment["PATH"] = bin + Path.PathSeparator + Environment.GetEnvironmentVariable("PATH");
start.Environment["FAKE_DOCKER_WORLD"] = world.Path.Replace('\\', '/');
start.Environment["DOCKER_HOST"] = OperatingSystem.IsWindows() ? "npipe:////./pipe/febe-nessun-demone" : "unix:///nonexistent/febe-nessun-demone.sock";
start.Environment.Remove("DOCKER_CONTEXT");
using var process = Process.Start(start)!;
var output = process.StandardOutput.ReadToEndAsync(TestContext.CancellationToken);
var errors = process.StandardError.ReadToEndAsync(TestContext.CancellationToken);
await process.WaitForExitAsync(TestContext.CancellationToken);
var result = new CleanupRun(
process.ExitCode,
(await output).Replace("\r\n", "\n", StringComparison.Ordinal),
await errors,
FakeDaemon.ContainersOf([.. await ReadLinesAsync(world.Combine("containers"))]),
[.. (await ReadLinesAsync(world.Combine("images"))).Select(i => string.Join('|', i.Split('|')[..2]))],
await ReadLinesAsync(world.Combine("volumes")));
var calls = world.Combine("calls");
Assert.IsTrue(File.Exists(calls) && (await File.ReadAllTextAsync(calls, TestContext.CancellationToken)).Contains("docker ps", StringComparison.Ordinal), $"the fake docker client was not the one called\n{result.Report}");
Assert.DoesNotContain("unexpected call", result.Errors, result.Report);
return result;
}
private async Task WriteLinesAsync(string path, IEnumerable<string> lines) =>
await File.WriteAllTextAsync(path, string.Concat(lines.Select(line => line + "\n")), TestContext.CancellationToken);
private async Task<List<string>> ReadLinesAsync(string path) =>
[.. (await File.ReadAllTextAsync(path, TestContext.CancellationToken)).Split('\n', StringSplitOptions.RemoveEmptyEntries)];
/// <summary>bash for the scripts of the CI: the system one on Linux, Git Bash on Windows (not the one of WSL).</summary>
private static string? BashForScripts()
{
@@ -473,15 +257,6 @@ public sealed partial class PipelineTests
[GeneratedRegex(@"\b[0-9a-f]{64}\b")]
private static partial Regex Sha256();
[GeneratedRegex(@"docker (?:image|container|volume|builder|system) prune")]
private static partial Regex ImagePrune();
[GeneratedRegex(@"docker run\b(?:[^\n]*\\\n)*[^\n]*")]
private static partial Regex DockerRun();
[GeneratedRegex(@"label=febe\.ci\.(?!prova\b)")]
private static partial Regex ProvenanceLabelFilter();
[GeneratedRegex(@"docker (?:image rm|rmi)\s+(?:-\w+\s+)*-\w*f")]
private static partial Regex ForcedImageRemoval();
}