Alla fine di ogni lavoro «immagine» di verifica e rilascio, dopo la pulizia dell'esecuzione, gira pulizia-docker.sh penzolanti: le immagini senza nome e la cache penzolante del demone se ne vanno subito invece di aspettare il lunedì, e un errore resta un avviso, così il lavoro non diventa rosso per la pulizia. pulizia.yml passa al modo «completa» e, a mano, ha la casella «Solo prova» (input booleano: Gitea 28 lo mette nell'evento come «true» o «false»), con cui elenca che cosa toglierebbe e non tocca nulla: da lanciare prima della prima pulizia vera. Il passo riceve REGISTRY_TOKEN, l'indirizzo dell'API e il proprietario per le etichette del registro. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
776 lines
47 KiB
C#
776 lines
47 KiB
C#
using System.Diagnostics;
|
|
using System.Text.Json;
|
|
using System.Text.RegularExpressions;
|
|
using Febe.Tests.Desktop.Support;
|
|
using Febe.Tests.Support;
|
|
|
|
namespace Febe.Tests.Packaging;
|
|
|
|
/// <summary>
|
|
/// The cleanup of the CI: .gitea/scripts/pulizia-docker.sh, its choice of registry tags (versioni-registro.js) and the
|
|
/// steps that run it. The Docker daemon is shared with Alberto's other projects, very likely with his Unraid apps, and
|
|
/// may run a real Febe. Since 21 October 2026 the cleanup removes what the CI of Febe made and what nothing uses any
|
|
/// more, of any project; never a container, a volume or a network that is not the CI's, never main, latest or a
|
|
/// release on the registry, never the token in the log; with --prova it removes nothing at all. The script runs against
|
|
/// a fake docker client (fake-docker.sh) and a fake curl (fake-curl.sh): no daemon, no network.
|
|
/// </summary>
|
|
public sealed partial class PipelineTests
|
|
{
|
|
private const string RegistryApi = "http://gitea.invalid/api/v1";
|
|
|
|
// Low entropy on purpose: gitleaks reads every commit, and a fake value shaped like a token would look like one.
|
|
private const string RegistryToken = "gettone-finto-gettone-finto";
|
|
|
|
/// <summary>The tags versioni-registro.json leaves to the cleanup once the ten newest sha- are kept, oldest first.</summary>
|
|
private static readonly string[] OldShaTags = ["sha-0a1b2c3", "sha-1b2c3d4", "sha-2c3d4e5", "sha-4e5f6a7"];
|
|
|
|
[TestMethod]
|
|
public void TheCleanupNeverPrunesBlindlyAndChoosesOnlyByTheMarksOfTheCiOrByUse()
|
|
{
|
|
var cleanup = Code(Script("pulizia-docker.sh"));
|
|
foreach (var forbidden in new[] { "system prune", "container prune", "volume prune", "network prune", "prune --all", "image prune -f -a", "builder prune -f -a" })
|
|
{
|
|
Assert.DoesNotContain(forbidden, cleanup, "the daemon is shared with Alberto's other projects and his Unraid apps");
|
|
}
|
|
|
|
// Only these prunes: what nothing uses after every run, the narrow weekly of before, and in the complete
|
|
// cleanup every unused image and all the cache, but only with the filter of 24 hours.
|
|
string[] allowed =
|
|
[
|
|
"image prune -f",
|
|
"image prune -f --filter \"until=72h\"",
|
|
"image prune -a -f --filter \"until=24h\"",
|
|
"builder prune -f",
|
|
"builder prune -a -f --filter \"until=24h\"",
|
|
];
|
|
CollectionAssert.AreEquivalent(allowed, Prune().Matches(cleanup).Select(m => $"{m.Groups["what"].Value} prune{m.Groups["args"].Value.TrimEnd()}").Distinct().ToList());
|
|
StringAssert.Contains(cleanup, "export BUILDX_BUILDER=default", "the cache pruned is the daemon's, not the builder of the run, which is gone by then");
|
|
|
|
// The febe.ci.* labels of the image are in every container made from a published image, a real Febe too: they
|
|
// never choose what goes. Containers are listed for removal only by a mark of the CI (the label of the tried
|
|
// containers with their exact name, the name of Febe's builders, the name act_runner gives its jobs); who uses
|
|
// an image, a volume or a network is asked only to keep it; the one listing of every container reads.
|
|
Assert.IsFalse(ProvenanceLabelFilter().IsMatch(cleanup), "the cleanup filters on febe.ci.prova only");
|
|
var readsOnly = Function(cleanup, "immagini_in_uso");
|
|
Assert.IsFalse(Removal().IsMatch(readsOnly), "immagini_in_uso only reads");
|
|
foreach (var line in cleanup.Split('\n').Where(l => l.Contains("docker ps", StringComparison.Ordinal)))
|
|
{
|
|
var marked = new[] { "--filter \"label=febe.ci.prova", "--filter \"name=buildx_buildkit_febe-ci-\"", "--filter \"name=GITEA-ACTIONS-TASK-\"", "--filter \"ancestor=", "--filter \"volume=", "--filter \"network=" }
|
|
.Any(filter => line.Contains(filter, StringComparison.Ordinal));
|
|
Assert.IsTrue(marked || readsOnly.Contains(line, StringComparison.Ordinal), $"«{line.Trim()}» lists containers without a mark of the CI");
|
|
}
|
|
|
|
StringAssert.Contains(cleanup, "\"febe-prova-$valore\"", "the name must match the mark");
|
|
StringAssert.Contains(cleanup, "contenitori_di_prova \"\" exited created dead", "the sweeps take only stopped tried containers");
|
|
StringAssert.Contains(cleanup, "^buildx_buildkit_(febe-ci-[0-9]+)0$");
|
|
StringAssert.Contains(cleanup, "nome_act='^GITEA-ACTIONS-TASK-[0-9]+[-_]'", "act_runner's objects start with the task");
|
|
StringAssert.Contains(cleanup, "togli_contenitore \"$id\" \"$nome\" && conta \"contenitori fermi di act_runner\"", "act_runner's containers go without -f: Docker keeps a running one");
|
|
StringAssert.Contains(cleanup, "docker volume rm \"$nome\"", "act_runner's volumes go without -f");
|
|
Assert.IsFalse(ForcedImageRemoval().IsMatch(cleanup), "an image is never removed by force");
|
|
StringAssert.Contains(cleanup, "[[ \"$riferimento\" =~ ^febe-ci:[0-9]+$ ]]");
|
|
|
|
// On the registry only the shape of a sha- tag of the verification, checked again before every DELETE.
|
|
StringAssert.Contains(cleanup, "[[ ! \"$versione\" =~ ^sha-[0-9a-f]{7,40}$ ]]");
|
|
StringAssert.Contains(Script("versioni-registro.js"), "/^sha-[0-9a-f]{7,40}$/");
|
|
}
|
|
|
|
[TestMethod]
|
|
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"), "Pulizia completa del demone Docker e del registro");
|
|
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 }}");
|
|
StringAssert.Contains(step, "if [ \"${PROVA:-}\" = true ]; then\n bash .gitea/scripts/pulizia-docker.sh completa --prova\n else\n bash .gitea/scripts/pulizia-docker.sh completa\n");
|
|
Assert.DoesNotContain("settimanale", Code(weekly), "the weekly cleanup is the complete one");
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(300_000, CooperativeCancellation = true)]
|
|
public async Task OnADaemonSharedWithARealFebeTheCleanupOfTheCiTakesOnlyWhatTheCiMade()
|
|
{
|
|
var bash = RequireBash();
|
|
|
|
// At the start or the end of a run (a release run again keeps its id, so the published image has the same
|
|
// febe.ci.run as the run): only the tried container, the local name and the builder of that run.
|
|
var run = await RunCleanupAsync(bash, FakeDaemon.WorldOf(FakeDaemon.Full), "esecuzione", "777");
|
|
Assert.AreEqual(0, run.Code, run.Report);
|
|
Assert.DoesNotContain("::warning::", run.Output, run.Report);
|
|
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Full).Except(["c-prova-777", "b-777"]).ToList(), run.Containers, run.Report);
|
|
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777(), run.Images, run.Report);
|
|
CollectionAssert.AreEquivalent(FakeDaemon.Volumes.Except(["buildx_buildkit_febe-ci-7770_state"]).ToList(), run.Volumes, run.Report);
|
|
|
|
// Leftovers of interrupted runs: stopped tried containers, febe-ci images and builders older than 90 minutes.
|
|
var leftovers = await RunCleanupAsync(bash, FakeDaemon.WorldOf(FakeDaemon.Full), "residui", "90");
|
|
Assert.AreEqual(0, leftovers.Code, leftovers.Report);
|
|
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Full).Except(["c-prova-555", "b-vecchio"]).ToList(), leftovers.Containers, leftovers.Report);
|
|
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777("img-ci555"), leftovers.Images, leftovers.Report);
|
|
CollectionAssert.AreEquivalent(FakeDaemon.Volumes.Except(["buildx_buildkit_febe-ci-4560_state"]).ToList(), leftovers.Volumes, leftovers.Report);
|
|
StringAssert.Contains(leftovers.Output, "::warning::Il contenitore di prova febe-prova-556 è acceso", "a running tried container is reported, not removed");
|
|
StringAssert.Contains(leftovers.Output, "::warning::Il contenitore buildx_buildkit_febe-ci-4570 non è un builder buildx", leftovers.Report);
|
|
|
|
// The narrow weekly cleanup of before, on a daemon without anything odd: the same, the old febe:ci and the
|
|
// dangling images older than 72 hours that no container uses. Green.
|
|
var weekly = await RunCleanupAsync(bash, FakeDaemon.WorldOf(FakeDaemon.Clean), "settimanale");
|
|
Assert.AreEqual(0, weekly.Code, weekly.Report);
|
|
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Clean).Except(["c-prova-555", "b-vecchio"]).ToList(), weekly.Containers, weekly.Report);
|
|
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777("img-ci555", "img-ci556", "img-legacy", "img-penzolante-vecchia"), weekly.Images, weekly.Report);
|
|
|
|
// With something left for a person to look at, the weekly cleanup goes red.
|
|
var noticed = await RunCleanupAsync(bash, FakeDaemon.WorldOf(FakeDaemon.Full), "settimanale");
|
|
Assert.AreEqual(1, noticed.Code, noticed.Report);
|
|
CollectionAssert.Contains(noticed.Containers, "c-prova-556");
|
|
CollectionAssert.Contains(noticed.Containers, "c-febe-vero");
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(300_000, CooperativeCancellation = true)]
|
|
public async Task AfterEveryRunOnlyWhatNobodyUsesGoesAndADaemonThatRefusesIsOnlyAWarning()
|
|
{
|
|
var bash = RequireBash();
|
|
var run = await RunCleanupAsync(bash, SharedDaemon.World, "penzolanti");
|
|
Assert.AreEqual(0, run.Code, run.Report);
|
|
Assert.DoesNotContain("::warning::", run.Output, run.Report);
|
|
|
|
// Images without a name that no container uses, of any age; never one with a name, never one a stopped
|
|
// container uses. Containers, volumes and networks stay as they are.
|
|
CollectionAssert.AreEquivalent(SharedDaemon.ImageIds.Except(["img-plex-precedente", "img-penzolante-giovane"]).ToList(), run.ImageIds, run.Report);
|
|
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(SharedDaemon.Containers), run.Containers, run.Report);
|
|
CollectionAssert.AreEquivalent(SharedDaemon.VolumeNames, run.Volumes, run.Report);
|
|
CollectionAssert.AreEquivalent(SharedDaemon.NetworkNames, run.Networks, run.Report);
|
|
CollectionAssert.Contains(run.Calls, "BUILDX_BUILDER=default docker image prune -f");
|
|
CollectionAssert.Contains(run.Calls, "BUILDX_BUILDER=default docker builder prune -f", "the dangling cache of the daemon's builder, without -a");
|
|
|
|
// A daemon that refuses: two warnings, and the job of the run stays green.
|
|
var refused = await RunCleanupAsync(bash, SharedDaemon.World with { Broken = ["image prune", "builder prune"] }, "penzolanti");
|
|
Assert.AreEqual(0, refused.Code, refused.Report);
|
|
Assert.HasCount(2, WarningLine().Matches(refused.Output), refused.Report);
|
|
CollectionAssert.AreEquivalent(SharedDaemon.ImageIds, refused.ImageIds, refused.Report);
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(300_000, CooperativeCancellation = true)]
|
|
public async Task TheCompleteCleanupTakesWhatNobodyUsesAndNeverAContainerVolumeOrNetworkOfAnotherProject()
|
|
{
|
|
var bash = RequireBash();
|
|
var run = await RunCleanupAsync(bash, SharedDaemon.World, "completa");
|
|
Assert.AreEqual(0, run.Code, run.Report);
|
|
Assert.DoesNotContain("::warning::", run.Output, run.Report);
|
|
CollectionAssert.AreEquivalent(SharedDaemon.ContainersLeft, run.Containers, run.Report);
|
|
CollectionAssert.AreEquivalent(SharedDaemon.ImagesLeft, run.ImageIds, run.Report);
|
|
CollectionAssert.AreEquivalent(SharedDaemon.VolumesLeft, run.Volumes, run.Report);
|
|
CollectionAssert.AreEquivalent(SharedDaemon.NetworksLeft, run.Networks, run.Report);
|
|
|
|
// Not even an attempt on what is not the CI's (Docker would refuse some of it: the script must not ask), and
|
|
// the prunes of everyone only with their filter, once.
|
|
foreach (var call in run.Calls)
|
|
{
|
|
var target = RemovalTarget().Match(call);
|
|
if (target.Success)
|
|
{
|
|
CollectionAssert.Contains(SharedDaemon.Removed, target.Groups["target"].Value, call);
|
|
}
|
|
}
|
|
|
|
Assert.HasCount(1, run.Calls.Where(c => c == "BUILDX_BUILDER=default docker image prune -a -f --filter until=24h"), run.Report);
|
|
Assert.HasCount(1, run.Calls.Where(c => c == "BUILDX_BUILDER=default docker builder prune -a -f --filter until=24h"), run.Report);
|
|
Assert.HasCount(2, run.Calls.Where(c => c.EndsWith("docker system df", StringComparison.Ordinal)), "before and after");
|
|
|
|
// Without the secret the registry is not touched, and the summary says what went.
|
|
StringAssert.Contains(run.Output, " Manca il segreto REGISTRY_TOKEN: il registro non si tocca.");
|
|
Assert.IsEmpty(run.RegistryCalls, run.Report);
|
|
StringAssert.Contains(run.Output, "== Riepilogo\n");
|
|
Assert.AreEqual("2", SummaryCount(run.Output, "contenitori fermi di act_runner"), run.Report);
|
|
Assert.AreEqual("4", SummaryCount(run.Output, "volumi di act_runner"), run.Report);
|
|
Assert.AreEqual("2", SummaryCount(run.Output, "reti di act_runner"), run.Report);
|
|
Assert.AreEqual("4", SummaryCount(run.Output, "immagini che nessun contenitore usa"), run.Report);
|
|
|
|
// Something left for a person to look at (a tried container still running) turns it red, as before.
|
|
var noticed = await RunCleanupAsync(bash, SharedDaemon.World with { Containers = [.. SharedDaemon.Containers, "c-prova-556|febe-prova-556|running|300|febe-ci:556|img-rilascio|febe.ci.prova=556"] }, "completa");
|
|
Assert.AreEqual(1, noticed.Code, noticed.Report);
|
|
CollectionAssert.Contains(noticed.Containers, "c-prova-556");
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(300_000, CooperativeCancellation = true)]
|
|
public async Task TheDryRunListsWhatTheCleanupWouldTakeAndTouchesNothing()
|
|
{
|
|
var bash = RequireBash();
|
|
RequireNode();
|
|
var world = SharedDaemon.World with { Registry = new FakeRegistry(RegistryToken) };
|
|
var tried = await RunCleanupAsync(bash, world, "completa", "--prova");
|
|
Assert.AreEqual(0, tried.Code, tried.Report);
|
|
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(SharedDaemon.Containers), tried.Containers, tried.Report);
|
|
CollectionAssert.AreEquivalent(SharedDaemon.ImageIds, tried.ImageIds, tried.Report);
|
|
CollectionAssert.AreEquivalent(SharedDaemon.VolumeNames, tried.Volumes, tried.Report);
|
|
CollectionAssert.AreEquivalent(SharedDaemon.NetworkNames, tried.Networks, tried.Report);
|
|
foreach (var call in tried.Calls)
|
|
{
|
|
Assert.IsFalse(Destructive().IsMatch(call), $"the dry run called «{call}»");
|
|
}
|
|
|
|
Assert.IsTrue(tried.RegistryCalls.Count > 0 && tried.RegistryCalls.All(c => c.StartsWith("GET ", StringComparison.Ordinal)), tried.Report);
|
|
Assert.IsEmpty(tried.Deleted, tried.Report);
|
|
Assert.DoesNotContain(RegistryToken, tried.Output + tried.Errors, "the token never reaches the log");
|
|
|
|
// What it lists, with size and age: also what becomes unused once the leftovers it lists are gone.
|
|
foreach (var expected in new[]
|
|
{
|
|
"Prova: elenco che cosa toglierei, senza togliere nulla.",
|
|
" toglierei il contenitore febe-prova-555\n",
|
|
" toglierei il contenitore GITEA-ACTIONS-TASK-53_WORKFLOW-verifica_JOB-prove\n",
|
|
" toglierei il volume GITEA-ACTIONS-TASK-53_WORKFLOW-verifica_JOB-prove-env\n",
|
|
" toglierei la rete GITEA-ACTIONS-TASK-53_WORKFLOW-verifica_JOB-prove-prove-network\n",
|
|
" toglierei 192.168.30.23:3000/alby96/febe:0.0.9 (img-febe-vec) · 400MB · creata 34 giorni fa\n",
|
|
" toglierei node:24-trixie (img-node) · 410MB · creata 13 giorni fa\n",
|
|
" toglierei un'immagine senza nome (img-plex-pre) · 300MB · creata 69 giorni fa\n",
|
|
"la cache di costruzione del demone occupa 5.3GB",
|
|
" toglierei sha-4e5f6a7 (pubblicata il 2026-10-05T01:00:00+02:00)\n",
|
|
"== Riepilogo della prova",
|
|
})
|
|
{
|
|
StringAssert.Contains(tried.Output, expected, tried.Report);
|
|
}
|
|
|
|
foreach (var kept in new[] { "plexinc/pms-docker", "encelado:latest", "mimante:latest", "runner-images", "moby/buildkit", "act-toolcache", "encelado-dati", "febe:latest", "toglierei main", "toglierei latest", "toglierei 0.1.", "GITEA-ACTIONS-TASK-90", "GITEA-ACTIONS-TASK-60", "GITEA-ACTIONS-TASK-88", "GITEA-ACTIONS-TASK-89", "GITEA-ACTIONS-TASK-77" })
|
|
{
|
|
Assert.DoesNotContain(kept, tried.Output, tried.Report);
|
|
}
|
|
|
|
// And it counts what the real cleanup then takes.
|
|
var real = await RunCleanupAsync(bash, world, "completa");
|
|
Assert.AreEqual(0, real.Code, real.Report);
|
|
foreach (var kind in new[] { "contenitori di prova della CI di Febe", "immagini febe-ci", "builder buildx della CI di Febe", "contenitori fermi di act_runner", "volumi di act_runner", "reti di act_runner", "immagini che nessun contenitore usa", "etichette sha- sul registro" })
|
|
{
|
|
Assert.AreEqual(SummaryCount(real.Output, kind), SummaryCount(tried.Output, kind), $"{kind}\n{tried.Report}\n{real.Report}");
|
|
}
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(60_000, CooperativeCancellation = true)]
|
|
public async Task TheRegistryKeepsMainLatestTheReleasesAndTheTenNewestShaTags()
|
|
{
|
|
var node = RequireNode();
|
|
var script = CiPath("scripts", "versioni-registro.js");
|
|
using var folder = new TempFolder("febe-registro");
|
|
var pages = await WriteRegistryPagesAsync(folder.Path);
|
|
|
|
// Of fourteen sha- tags the four oldest go. sha-3d4e5f6 (23:30 UTC) is newer than sha-4e5f6a7 (01:00 in Italy,
|
|
// 23:00 UTC): dates, not text. main, latest, the releases, digests, malformed sha- tags, one without a date and
|
|
// other packages stay, though they are older; a tag in two pages counts once.
|
|
var chosen = await RunProcessAsync(node, [script, "10", .. pages]);
|
|
Assert.AreEqual(0, chosen.Code, chosen.Errors);
|
|
CollectionAssert.AreEqual(OldShaTags, Lines(chosen.Output).Select(l => l.Split('\t')[0]).ToList(), chosen.Output);
|
|
StringAssert.Contains(chosen.Output, "sha-2c3d4e5\t2026-10-03T07:00:00Z\n");
|
|
|
|
// Keeping none: every well formed sha- tag of the container febe, and nothing else.
|
|
var all = await RunProcessAsync(node, [script, "0", .. pages]);
|
|
Assert.HasCount(14, Lines(all.Output), all.Output);
|
|
foreach (var line in Lines(all.Output))
|
|
{
|
|
Assert.IsTrue(ShaTagLine().IsMatch(line), line);
|
|
}
|
|
|
|
// Keeping more than there are: nothing. An empty page of Gitea is fine; a page that is not a list stops
|
|
// everything, so in doubt nothing goes.
|
|
var empty = Path.Combine(folder.Path, "vuota.json");
|
|
await File.WriteAllTextAsync(empty, "null", TestContext.CancellationToken);
|
|
Assert.IsEmpty((await RunProcessAsync(node, [script, "20", .. pages, empty])).Output);
|
|
var broken = Path.Combine(folder.Path, "rotta.json");
|
|
await File.WriteAllTextAsync(broken, "{\"message\":\"internal error\"}", TestContext.CancellationToken);
|
|
var refused = await RunProcessAsync(node, [script, "10", .. pages, broken]);
|
|
Assert.AreEqual(2, refused.Code, refused.Errors);
|
|
Assert.IsEmpty(refused.Output);
|
|
}
|
|
|
|
[TestMethod]
|
|
[Timeout(300_000, CooperativeCancellation = true)]
|
|
public async Task TheRegistryCleanupDeletesOnlyTheChosenTagsNeverPrintsTheTokenAndARefusalIsOnlyAWarning()
|
|
{
|
|
var bash = RequireBash();
|
|
RequireNode();
|
|
|
|
// A daemon with almost nothing on it: here only the registry counts.
|
|
var quiet = new World(["c-encelado|encelado|exited|5000|encelado:latest|img-encelado|"], ["img-encelado|encelado:latest|5000||250MB"], [], []);
|
|
var run = await RunCleanupAsync(bash, quiet with { Registry = new FakeRegistry(RegistryToken) }, "completa");
|
|
Assert.AreEqual(0, run.Code, run.Report);
|
|
CollectionAssert.AreEqual(OldShaTags, run.Deleted, run.Report);
|
|
var package = $"{RegistryApi}/packages/Alby96/container/febe";
|
|
CollectionAssert.AreEqual(
|
|
new[] { $"GET {package}?page=1&limit=50", $"GET {package}?page=2&limit=50", $"GET {package}?page=3&limit=50" }
|
|
.Concat(OldShaTags.Select(tag => $"DELETE {package}/{tag}")).ToList(),
|
|
run.RegistryCalls,
|
|
run.Report);
|
|
Assert.DoesNotContain(RegistryToken, run.Output + run.Errors, "the token never reaches the log");
|
|
Assert.AreEqual("4", SummaryCount(run.Output, "etichette sha- sul registro"), run.Report);
|
|
|
|
// The API refuses (a token without the permission) or does not know the token: a warning, nothing deleted,
|
|
// and the weekly job stays green.
|
|
foreach (var registry in new[] { new FakeRegistry(RegistryToken, Refuse: true), new FakeRegistry(RegistryToken, Sent: "un-altro-gettone-finto") })
|
|
{
|
|
var refused = await RunCleanupAsync(bash, quiet with { Registry = registry }, "completa");
|
|
Assert.AreEqual(0, refused.Code, refused.Report);
|
|
StringAssert.Contains(refused.Output, "::warning::L'API dei pacchetti di Gitea risponde 40", refused.Report);
|
|
Assert.IsEmpty(refused.Deleted, refused.Report);
|
|
Assert.HasCount(1, refused.RegistryCalls, refused.Report);
|
|
Assert.DoesNotContain(RegistryToken, refused.Output + refused.Errors);
|
|
Assert.DoesNotContain("un-altro-gettone-finto", refused.Output + refused.Errors);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The daemon of <see cref="OnADaemonSharedWithARealFebeTheCleanupOfTheCiTakesOnlyWhatTheCiMade"/> (format in
|
|
/// fake-docker.sh). A real Febe started from :latest and one from :main carry the febe.ci.* labels of their images,
|
|
/// as Docker gives them; the image of the release also has the local name of run 777.
|
|
/// </summary>
|
|
private static class FakeDaemon
|
|
{
|
|
public static readonly string[] Full =
|
|
[
|
|
"c-febe-vero|febe|running|43200|192.168.30.23:3000/alby96/febe:latest|img-rilascio|febe.ci.workflow=rilascio,febe.ci.run=777,febe.ci.ref=v0.1.0",
|
|
"c-febe-fermo|febe-main|exited|43200|192.168.30.23:3000/alby96/febe:main|img-main|febe.ci.workflow=verifica,febe.ci.run=888",
|
|
"c-febe-antico|febe-antico|exited|20000|img-penzolante-in-uso|img-penzolante-in-uso|febe.ci.run=111",
|
|
"c-prova-777|febe-prova-777|running|5|febe-ci:777|img-rilascio|febe.ci.workflow=rilascio,febe.ci.run=777,febe.ci.prova=777",
|
|
"c-prova-555|febe-prova-555|exited|300|febe-ci:555|img-ci555|febe.ci.run=555,febe.ci.prova=555",
|
|
"c-prova-556|febe-prova-556|running|300|febe-ci:556|img-ci556|febe.ci.run=556,febe.ci.prova=556",
|
|
"c-prova-557|febe-prova-557|exited|10|febe-ci:557|img-ci557|febe.ci.run=557,febe.ci.prova=557",
|
|
"c-nome-strano|febe-prova-558-bis|exited|300|encelado:latest|img-encelado|febe.ci.prova=558",
|
|
"c-segno-diverso|febe-prova-559|exited|300|encelado:latest|img-encelado|febe.ci.prova=560",
|
|
"c-senza-segno|febe-prova-561|exited|300|encelado:latest|img-encelado|",
|
|
"c-encelado|encelado|exited|5000|encelado:latest|img-encelado|",
|
|
"b-vecchio|buildx_buildkit_febe-ci-4560|running|300|moby/buildkit:buildx-stable-1|img-buildkit||buildx_buildkit_febe-ci-4560_state",
|
|
"b-finto|buildx_buildkit_febe-ci-4570|running|300|encelado:latest|img-encelado||buildx_buildkit_febe-ci-4570_state",
|
|
"b-giovane|buildx_buildkit_febe-ci-7890|running|10|moby/buildkit:buildx-stable-1|img-buildkit||buildx_buildkit_febe-ci-7890_state",
|
|
"b-altro|altro_buildx_buildkit_febe-ci-10|running|300|moby/buildkit:buildx-stable-1|img-buildkit|",
|
|
"b-777|buildx_buildkit_febe-ci-7770|running|20|moby/buildkit:buildx-stable-1|img-buildkit||buildx_buildkit_febe-ci-7770_state",
|
|
];
|
|
|
|
/// <summary>The same daemon without the running tried container and the builder that is not one.</summary>
|
|
public static readonly string[] Clean = [.. Full.Where(c => !c.StartsWith("c-prova-556|", StringComparison.Ordinal) && !c.StartsWith("b-finto|", StringComparison.Ordinal))];
|
|
|
|
public static readonly string[] Images =
|
|
[
|
|
"img-rilascio|192.168.30.23:3000/alby96/febe:latest,192.168.30.23:3000/alby96/febe:0.1.0,febe-ci:777|43200|febe.ci.run=777",
|
|
"img-main|192.168.30.23:3000/alby96/febe:main|43200|febe.ci.run=888",
|
|
"img-ci555|febe-ci:555|300|febe.ci.run=555",
|
|
"img-ci556|febe-ci:556|300|febe.ci.run=556",
|
|
"img-ci557|febe-ci:557|10|febe.ci.run=557",
|
|
"img-penzolante-febe||300|febe.ci.run=999",
|
|
"img-penzolante-vecchia||6000|",
|
|
"img-penzolante-in-uso||20000|febe.ci.run=111",
|
|
"img-encelado|encelado:latest|5000|",
|
|
"img-buildkit|moby/buildkit:buildx-stable-1|50000|",
|
|
"img-legacy|febe:ci|6000|",
|
|
];
|
|
|
|
public static readonly string[] Volumes =
|
|
[
|
|
"buildx_buildkit_febe-ci-4560_state",
|
|
"buildx_buildkit_febe-ci-4570_state",
|
|
"buildx_buildkit_febe-ci-7890_state",
|
|
"buildx_buildkit_febe-ci-7770_state",
|
|
"encelado-dati",
|
|
];
|
|
|
|
public static World WorldOf(string[] containers) => new(containers, Images, Volumes, []);
|
|
|
|
public static List<string> ContainersOf(string[] world) => [.. world.Select(c => c[..c.IndexOf('|', StringComparison.Ordinal)])];
|
|
|
|
/// <summary>
|
|
/// «id|names» of each image once febe-ci:777 is gone (the image of the release keeps its registry names), without
|
|
/// the images given.
|
|
/// </summary>
|
|
public static List<string> ImagesWithout777(params string[] gone) =>
|
|
[
|
|
.. Images
|
|
.Select(i => string.Join('|', i.Split('|')[..2]).Replace(",febe-ci:777", string.Empty, StringComparison.Ordinal))
|
|
.Where(i => !gone.Contains(i[..i.IndexOf('|', StringComparison.Ordinal)])),
|
|
];
|
|
}
|
|
|
|
/// <summary>
|
|
/// A daemon as the runner's is likely to be (format in fake-docker.sh): a real Febe and Unraid apps, running and
|
|
/// stopped; the job container of the cleanup itself; leftovers of act_runner, with the names of today's act_runner
|
|
/// («_WORKFLOW-…») and of older ones («-WORKFLOW-…» with a hash), and look-alikes; leftovers of the CI of Febe;
|
|
/// images used and unused, named and dangling, old and young; volumes and networks of every kind.
|
|
/// </summary>
|
|
private static class SharedDaemon
|
|
{
|
|
private const string Job53 = "GITEA-ACTIONS-TASK-53_WORKFLOW-verifica_JOB-prove";
|
|
private const string Job41 = "GITEA-ACTIONS-TASK-41-WORKFLOW-verifica-JOB-prove-9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08";
|
|
private const string Job90 = "GITEA-ACTIONS-TASK-90_WORKFLOW-pulizia_JOB-docker";
|
|
|
|
public static readonly string[] Containers =
|
|
[
|
|
"c-febe-vero|febe|running|43200|192.168.30.23:3000/alby96/febe:latest|img-rilascio|febe.ci.workflow=rilascio,febe.ci.run=777,febe.ci.ref=v0.1.0|febe-dati|bridge",
|
|
"c-plex|plex|exited|90000|plexinc/pms-docker:latest|img-plex||plex-config|br0",
|
|
"c-encelado|encelado|exited|5000|encelado:latest|img-encelado|||encelado_default",
|
|
$"c-lavoro|{Job90}|running|5|docker.gitea.com/runner-images:ubuntu-latest|img-runner||{Job90},{Job90}-env,act-toolcache|{Job90}-docker-network",
|
|
$"c-act-fermo|{Job53}|exited|3000|node:24-trixie|img-node||{Job53},{Job53}-env,act-toolcache|{Job53}-prove-network",
|
|
$"c-act-antico|{Job41}|dead|20000|node:24-trixie|img-node||{Job41}-env|",
|
|
"c-act-giovane|GITEA-ACTIONS-TASK-89_WORKFLOW-verifica_JOB-controlli|exited|30|docker.gitea.com/runner-images:ubuntu-latest|img-runner||GITEA-ACTIONS-TASK-89_WORKFLOW-verifica_JOB-controlli|",
|
|
"c-act-acceso|GITEA-ACTIONS-TASK-60_WORKFLOW-encelado_JOB-build|running|3000|docker.gitea.com/runner-images:ubuntu-latest|img-runner||GITEA-ACTIONS-TASK-60_WORKFLOW-encelado_JOB-build|GITEA-ACTIONS-TASK-60_WORKFLOW-encelado_JOB-build-build-network",
|
|
"c-quasi-act|mio-GITEA-ACTIONS-TASK-7_WORKFLOW-x|exited|3000|encelado:latest|img-encelado||GITEA-ACTIONS-TASK-77_WORKFLOW-y_JOB-z|",
|
|
"c-senza-numero|GITEA-ACTIONS-TASK-x_WORKFLOW-y|exited|3000|encelado:latest|img-encelado|",
|
|
"c-prova-555|febe-prova-555|exited|300|febe-ci:555|img-ci555|febe.ci.run=555,febe.ci.prova=555",
|
|
"c-febe-antico|febe-antico|exited|20000|img-penzolante-in-uso|img-penzolante-in-uso|febe.ci.run=111",
|
|
"b-vecchio|buildx_buildkit_febe-ci-4560|running|300|moby/buildkit:buildx-stable-1|img-buildkit||buildx_buildkit_febe-ci-4560_state|",
|
|
"b-altro|buildx_buildkit_encelado0|running|3000|moby/buildkit:buildx-stable-1|img-buildkit||buildx_buildkit_encelado0_state|",
|
|
];
|
|
|
|
public static readonly string[] Images =
|
|
[
|
|
"img-rilascio|192.168.30.23:3000/alby96/febe:latest,192.168.30.23:3000/alby96/febe:0.1.0|43200|febe.ci.run=777|412MB",
|
|
"img-febe-vecchia|192.168.30.23:3000/alby96/febe:0.0.9|50000||400MB",
|
|
"img-plex|plexinc/pms-docker:latest|100000||300MB",
|
|
"img-plex-precedente||100000||300MB",
|
|
"img-encelado|encelado:latest|5000||250MB",
|
|
"img-encelado-dev|encelado:dev|3000||250MB",
|
|
"img-mimante-nuova|mimante:latest|60||180MB",
|
|
"img-runner|docker.gitea.com/runner-images:ubuntu-latest|20000||1.2GB",
|
|
"img-node|node:24-trixie|20000||410MB",
|
|
"img-buildkit|moby/buildkit:buildx-stable-1|50000||210MB",
|
|
"img-penzolante-giovane||30||40MB",
|
|
"img-penzolante-in-uso||20000|febe.ci.run=111|400MB",
|
|
"img-ci555|febe-ci:555|300|febe.ci.run=555|412MB",
|
|
"img-legacy|febe:ci|6000||400MB",
|
|
];
|
|
|
|
public static readonly string[] Volumes =
|
|
[
|
|
$"{Job53}|3000",
|
|
$"{Job53}-env|3000",
|
|
$"{Job41}-env|20000",
|
|
$"{Job90}|5",
|
|
$"{Job90}-env|5",
|
|
"GITEA-ACTIONS-TASK-89_WORKFLOW-verifica_JOB-controlli|30",
|
|
"GITEA-ACTIONS-TASK-60_WORKFLOW-encelado_JOB-build|3000",
|
|
"GITEA-ACTIONS-TASK-12_WORKFLOW-vecchio_JOB-x|50000",
|
|
"GITEA-ACTIONS-TASK-88_WORKFLOW-nuovo_JOB-y|30",
|
|
"GITEA-ACTIONS-TASK-77_WORKFLOW-y_JOB-z|50000",
|
|
"act-toolcache|50000",
|
|
"encelado-dati|50000",
|
|
"febe-dati|43200",
|
|
"plex-config|100000",
|
|
"3f9a2b7c1d0e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a|50000",
|
|
"mio-GITEA-ACTIONS-TASK-3_WORKFLOW-x|50000",
|
|
"buildx_buildkit_febe-ci-4560_state",
|
|
"buildx_buildkit_encelado0_state",
|
|
];
|
|
|
|
public static readonly string[] Networks =
|
|
[
|
|
"net-bridge|bridge|100000",
|
|
"net-host|host|100000",
|
|
"net-none|none|100000",
|
|
"net-br0|br0|100000",
|
|
"net-encelado|encelado_default|5000",
|
|
$"net-act-53|{Job53}-prove-network|3000",
|
|
$"net-act-90|{Job90}-docker-network|5",
|
|
"net-act-60|GITEA-ACTIONS-TASK-60_WORKFLOW-encelado_JOB-build-build-network|3000",
|
|
"net-act-12|GITEA-ACTIONS-TASK-12_WORKFLOW-vecchio_JOB-x-x-network|50000",
|
|
"net-act-88|GITEA-ACTIONS-TASK-88_WORKFLOW-nuovo_JOB-y-y-network|30",
|
|
"net-quasi|altro-GITEA-ACTIONS-TASK-5_WORKFLOW-x-network|50000",
|
|
];
|
|
|
|
public static readonly World World = new(Containers, Images, Volumes, Networks);
|
|
|
|
public static readonly List<string> ImageIds = [.. Images.Select(First)];
|
|
|
|
public static readonly List<string> VolumeNames = [.. Volumes.Select(First)];
|
|
|
|
public static readonly List<string> NetworkNames = [.. Networks.Select(n => n.Split('|')[1])];
|
|
|
|
/// <summary>
|
|
/// What the complete cleanup takes: stopped act_runner containers older than 90 minutes, a stopped tried
|
|
/// container and a builder of Febe; the volumes and networks of act_runner nothing else uses; the images no
|
|
/// container uses created more than a day ago (node:24-trixie only once its stopped containers are gone).
|
|
/// </summary>
|
|
public static readonly string[] Removed =
|
|
[
|
|
"c-act-fermo", "c-act-antico", "c-prova-555", "b-vecchio",
|
|
"img-febe-vecchia", "img-plex-precedente", "img-encelado-dev", "img-node", "img-ci555", "img-legacy",
|
|
$"{Job53}", $"{Job53}-env", $"{Job41}-env", "GITEA-ACTIONS-TASK-12_WORKFLOW-vecchio_JOB-x", "buildx_buildkit_febe-ci-4560_state",
|
|
"net-act-53", "net-act-12",
|
|
|
|
// How the cleanup names what it removes: by id or by name, and the local names of the images.
|
|
"buildx_buildkit_febe-ci-4560", "febe-ci:555", "febe:ci", "febe-ci-4560",
|
|
];
|
|
|
|
public static readonly List<string> ContainersLeft = [.. FakeDaemon.ContainersOf(Containers).Except(Removed)];
|
|
|
|
public static readonly List<string> ImagesLeft = [.. ImageIds.Except(Removed)];
|
|
|
|
public static readonly List<string> VolumesLeft = [.. VolumeNames.Except(Removed)];
|
|
|
|
public static readonly List<string> NetworksLeft = [.. Networks.Where(n => !Removed.Contains(First(n))).Select(n => n.Split('|')[1])];
|
|
|
|
private static string First(string line) => line.Split('|')[0];
|
|
}
|
|
|
|
/// <summary>A fake daemon (format in fake-docker.sh) and, for the registry, a fake Gitea (fake-curl.sh).</summary>
|
|
private sealed record World(string[] Containers, string[] Images, string[] Volumes, string[] Networks)
|
|
{
|
|
/// <summary>Docker commands that fail as if the daemon refused them («image prune», «builder prune»).</summary>
|
|
public string[] Broken { get; init; } = [];
|
|
|
|
/// <summary>The registry; without it the cleanup runs with no REGISTRY_TOKEN.</summary>
|
|
public FakeRegistry? Registry { get; init; }
|
|
}
|
|
|
|
/// <summary>
|
|
/// The packages API of Gitea with the pages of versioni-registro.json, for the token given. Sent is the token the
|
|
/// cleanup gets (the same, if null); Refuse answers 403 to everything.
|
|
/// </summary>
|
|
private sealed record FakeRegistry(string Token, bool Refuse = false, string? Sent = null);
|
|
|
|
private sealed record CleanupRun(int Code, string Output, string Errors)
|
|
{
|
|
/// <summary>The ids of the containers left.</summary>
|
|
public List<string> Containers { get; init; } = [];
|
|
|
|
/// <summary>«id|names» of the images left.</summary>
|
|
public List<string> Images { get; init; } = [];
|
|
|
|
public List<string> Volumes { get; init; } = [];
|
|
|
|
public List<string> Networks { get; init; } = [];
|
|
|
|
/// <summary>Every docker call, as fake-docker.sh writes it.</summary>
|
|
public List<string> Calls { get; init; } = [];
|
|
|
|
/// <summary>Every call to the API of the registry, «METHOD URL».</summary>
|
|
public List<string> RegistryCalls { get; init; } = [];
|
|
|
|
/// <summary>The versions deleted from the registry.</summary>
|
|
public List<string> Deleted { get; init; } = [];
|
|
|
|
public List<string> ImageIds => [.. Images.Select(i => i.Split('|')[0])];
|
|
|
|
public string Report => $"codice {Code}\n{Output}\n{Errors}";
|
|
}
|
|
|
|
/// <summary>
|
|
/// pulizia-docker.sh against the fake daemon and, with a registry, the fake curl. DOCKER_HOST points nowhere and the
|
|
/// API is on a domain that cannot exist (.invalid): even if a real docker or curl came first on the PATH they could
|
|
/// reach nothing, and the test fails because the fakes recorded no call or curl complained on stderr.
|
|
/// </summary>
|
|
private async Task<CleanupRun> RunCleanupAsync(string bash, World world, params string[] arguments)
|
|
{
|
|
using var folder = new TempFolder("febe-pulizia");
|
|
var bin = folder.Combine("bin");
|
|
var registry = folder.Combine("registro");
|
|
var temporary = folder.Combine("tmp");
|
|
foreach (var directory in new[] { bin, registry, temporary })
|
|
{
|
|
Directory.CreateDirectory(directory);
|
|
}
|
|
|
|
InstallFake("fake-docker.sh", Path.Combine(bin, "docker"));
|
|
await WriteLinesAsync(folder.Combine("containers"), world.Containers);
|
|
await WriteLinesAsync(folder.Combine("images"), world.Images);
|
|
await WriteLinesAsync(folder.Combine("volumes"), world.Volumes);
|
|
await WriteLinesAsync(folder.Combine("networks"), world.Networks);
|
|
if (world.Broken.Length > 0)
|
|
{
|
|
await WriteLinesAsync(folder.Combine("broken"), world.Broken);
|
|
}
|
|
|
|
if (world.Registry is { } fake)
|
|
{
|
|
InstallFake("fake-curl.sh", Path.Combine(bin, "curl"));
|
|
await File.WriteAllTextAsync(Path.Combine(registry, "token"), fake.Token, TestContext.CancellationToken);
|
|
await File.WriteAllTextAsync(Path.Combine(registry, "base"), $"{RegistryApi}/packages/Alby96/container/febe", TestContext.CancellationToken);
|
|
if (fake.Refuse)
|
|
{
|
|
await File.WriteAllTextAsync(Path.Combine(registry, "refuse"), string.Empty, TestContext.CancellationToken);
|
|
}
|
|
|
|
await WriteRegistryPagesAsync(registry);
|
|
}
|
|
|
|
// The fakes go first on the PATH from inside bash: Git Bash puts its own folders (with a real curl) before the
|
|
// PATH it is given.
|
|
string[] script = ["-c", "bin=\"$FAKE_BIN\"; if command -v cygpath > /dev/null; then bin=\"$(cygpath -u \"$bin\")\"; fi; PATH=\"$bin:$PATH\"; exec bash \"$@\"", "bash", ".gitea/scripts/pulizia-docker.sh"];
|
|
var result = await RunProcessAsync(bash, [.. script, .. arguments], start =>
|
|
{
|
|
start.Environment["FAKE_BIN"] = bin;
|
|
start.Environment["FAKE_DOCKER_WORLD"] = folder.Path.Replace('\\', '/');
|
|
start.Environment["FAKE_CURL_WORLD"] = registry.Replace('\\', '/');
|
|
start.Environment["TMPDIR"] = temporary.Replace('\\', '/');
|
|
start.Environment["DOCKER_HOST"] = OperatingSystem.IsWindows() ? "npipe:////./pipe/febe-nessun-demone" : "unix:///nonexistent/febe-nessun-demone.sock";
|
|
start.Environment.Remove("DOCKER_CONTEXT");
|
|
start.Environment.Remove("BUILDX_BUILDER");
|
|
start.Environment.Remove("REGISTRY_TOKEN");
|
|
start.Environment["GITEA_API"] = RegistryApi;
|
|
start.Environment["PROPRIETARIO"] = "Alby96";
|
|
if (world.Registry is { } sent)
|
|
{
|
|
start.Environment["REGISTRY_TOKEN"] = sent.Sent ?? sent.Token;
|
|
}
|
|
});
|
|
|
|
var run = new CleanupRun(result.Code, result.Output, result.Errors)
|
|
{
|
|
Containers = FakeDaemon.ContainersOf([.. await ReadLinesAsync(folder.Combine("containers"))]),
|
|
Images = [.. (await ReadLinesAsync(folder.Combine("images"))).Select(i => string.Join('|', i.Split('|')[..2]))],
|
|
Volumes = [.. (await ReadLinesAsync(folder.Combine("volumes"))).Select(v => v.Split('|')[0])],
|
|
Networks = [.. (await ReadLinesAsync(folder.Combine("networks"))).Select(n => n.Split('|')[1])],
|
|
Calls = await ReadLinesAsync(folder.Combine("calls")),
|
|
RegistryCalls = await ReadLinesAsync(Path.Combine(registry, "calls")),
|
|
Deleted = await ReadLinesAsync(Path.Combine(registry, "deleted")),
|
|
};
|
|
Assert.IsNotEmpty(run.Calls, $"the fake docker client was not the one called\n{run.Report}");
|
|
Assert.DoesNotContain("unexpected call", run.Errors, run.Report);
|
|
Assert.DoesNotContain("fake curl:", run.Errors, run.Report);
|
|
Assert.DoesNotContain("curl: (", run.Errors, $"a real curl was called\n{run.Report}");
|
|
Assert.IsEmpty(Directory.EnumerateFileSystemEntries(temporary), $"the cleanup leaves no temporary files\n{run.Report}");
|
|
return run;
|
|
}
|
|
|
|
/// <summary>A program with its arguments, from the root of the repository; its output with Unix lines.</summary>
|
|
private async Task<(int Code, string Output, string Errors)> RunProcessAsync(string program, IEnumerable<string> arguments, Action<ProcessStartInfo>? configure = null)
|
|
{
|
|
var start = new ProcessStartInfo(program)
|
|
{
|
|
WorkingDirectory = Repository.Root()!,
|
|
RedirectStandardOutput = true,
|
|
RedirectStandardError = true,
|
|
StandardOutputEncoding = System.Text.Encoding.UTF8,
|
|
StandardErrorEncoding = System.Text.Encoding.UTF8,
|
|
};
|
|
foreach (var argument in arguments)
|
|
{
|
|
start.ArgumentList.Add(argument);
|
|
}
|
|
|
|
configure?.Invoke(start);
|
|
using var process = Process.Start(start)!;
|
|
var output = process.StandardOutput.ReadToEndAsync(TestContext.CancellationToken);
|
|
var errors = process.StandardError.ReadToEndAsync(TestContext.CancellationToken);
|
|
await process.WaitForExitAsync(TestContext.CancellationToken);
|
|
return (process.ExitCode, (await output).Replace("\r\n", "\n", StringComparison.Ordinal), (await errors).Replace("\r\n", "\n", StringComparison.Ordinal));
|
|
}
|
|
|
|
/// <summary>The pages of versioni-registro.json as Gitea would answer them, one file each.</summary>
|
|
private async Task<List<string>> WriteRegistryPagesAsync(string folder)
|
|
{
|
|
var fixture = await File.ReadAllTextAsync(Repository.PathOf("tests", "Febe.Tests", "Packaging", "versioni-registro.json"), TestContext.CancellationToken);
|
|
using var pages = JsonDocument.Parse(fixture);
|
|
var files = new List<string>();
|
|
foreach (var page in pages.RootElement.EnumerateArray())
|
|
{
|
|
var file = Path.Combine(folder, $"page-{files.Count + 1}.json");
|
|
await File.WriteAllTextAsync(file, page.GetRawText(), TestContext.CancellationToken);
|
|
files.Add(file);
|
|
}
|
|
|
|
return files;
|
|
}
|
|
|
|
private static void InstallFake(string name, string path)
|
|
{
|
|
File.Copy(Repository.PathOf("tests", "Febe.Tests", "Packaging", name), path);
|
|
if (!OperatingSystem.IsWindows())
|
|
{
|
|
File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
|
|
}
|
|
}
|
|
|
|
private async Task WriteLinesAsync(string path, IEnumerable<string> lines) =>
|
|
await File.WriteAllTextAsync(path, string.Concat(lines.Select(line => line + "\n")), TestContext.CancellationToken);
|
|
|
|
private async Task<List<string>> ReadLinesAsync(string path) =>
|
|
File.Exists(path) ? Lines(await File.ReadAllTextAsync(path, TestContext.CancellationToken)) : [];
|
|
|
|
private static List<string> Lines(string text) => [.. text.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n', StringSplitOptions.RemoveEmptyEntries)];
|
|
|
|
/// <summary>The number the summary of the cleanup gives for a kind of object, or null when it does not list it.</summary>
|
|
private static string? SummaryCount(string output, string kind)
|
|
{
|
|
var match = Regex.Match(output, $@"^ {Regex.Escape(kind)}: (?<count>[0-9]+)", RegexOptions.Multiline);
|
|
return match.Success ? match.Groups["count"].Value : null;
|
|
}
|
|
|
|
/// <summary>The body of a shell function of a script, from «name() {» to the closing brace at the start of a line.</summary>
|
|
private static string Function(string script, string name)
|
|
{
|
|
var match = Regex.Match(script, $@"^{Regex.Escape(name)}\(\) \{{\n(?<body>.*?)^\}}", RegexOptions.Multiline | RegexOptions.Singleline);
|
|
Assert.IsTrue(match.Success, $"manca la funzione {name}");
|
|
return match.Groups["body"].Value;
|
|
}
|
|
|
|
private static string RequireBash()
|
|
{
|
|
var bash = BashForScripts();
|
|
if (bash is null)
|
|
{
|
|
Assert.Inconclusive("Manca bash (su Windows serve Git Bash): la prova della pulizia su un demone finto si salta.");
|
|
}
|
|
|
|
Assert.IsTrue(File.Exists(CiPath("scripts", "pulizia-docker.sh")));
|
|
return bash;
|
|
}
|
|
|
|
/// <summary>node from the PATH: the registry part of the cleanup reads JSON with it, in the CI as here.</summary>
|
|
private static string RequireNode()
|
|
{
|
|
var names = OperatingSystem.IsWindows() ? new[] { "node.exe" } : ["node"];
|
|
var node = (Environment.GetEnvironmentVariable("PATH") ?? string.Empty)
|
|
.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)
|
|
.SelectMany(folder => names.Select(name => Path.Combine(folder.Trim('"'), name)))
|
|
.FirstOrDefault(File.Exists);
|
|
if (node is null)
|
|
{
|
|
Assert.Inconclusive("Manca node: la prova della scelta delle versioni del registro si salta.");
|
|
}
|
|
|
|
return node;
|
|
}
|
|
|
|
[GeneratedRegex(@"docker (?<what>[a-z]+) prune(?<args>[^\n]*)")]
|
|
private static partial Regex Prune();
|
|
|
|
[GeneratedRegex(@"label=febe\.ci\.(?!prova\b)")]
|
|
private static partial Regex ProvenanceLabelFilter();
|
|
|
|
[GeneratedRegex(@"docker (?:image rm|rmi)\s+(?:-\w+\s+)*-\w*f")]
|
|
private static partial Regex ForcedImageRemoval();
|
|
|
|
[GeneratedRegex(@"docker (?:rm|image rm|volume rm|network rm|buildx rm)\b|prune")]
|
|
private static partial Regex Removal();
|
|
|
|
[GeneratedRegex(@"docker (?:rm|image rm|volume rm|network rm)(?: -[a-z]+)* (?<target>\S+)$")]
|
|
private static partial Regex RemovalTarget();
|
|
|
|
[GeneratedRegex(@"docker (?:rm|kill|stop|image rm|rmi|image prune|builder prune|buildx rm|buildx prune|volume rm|volume prune|network rm|network prune|container prune|system prune)\b")]
|
|
private static partial Regex Destructive();
|
|
|
|
[GeneratedRegex(@"^::warning::", RegexOptions.Multiline)]
|
|
private static partial Regex WarningLine();
|
|
|
|
[GeneratedRegex(@"^sha-[0-9a-f]{7,40}\t")]
|
|
private static partial Regex ShaTagLine();
|
|
}
|