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(); }