Unione di main: la pulizia della CI, accanto alle prove d'interfaccia senza attese fisse
Il ramo si aggiorna con main (PR #9) prima dell'unione, come vuole la protezione di main. Conflitti solo dove i due rami aggiungono righe allo stesso punto: la sezione 0.1.2 del CHANGELOG e il fondo di docs/decisioni.md, tenute tutte. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
2e1d81d4b8
18 files changed
+2425
-413
No files matched your search
@@ -0,0 +1,977 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Febe.Tests.Desktop.Support;
|
||||
using Febe.Tests.Support;
|
||||
|
||||
namespace Febe.Tests.Packaging;
|
||||
|
||||
/// <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";
|
||||
|
||||
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";
|
||||
|
||||
/// <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"];
|
||||
|
||||
/// <summary>The untagged versions of the container febe in versioni-registro.json (manifests of an index), oldest first.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <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. 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.
|
||||
/// </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-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<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>«containerd» for the containerd image store; null for the classic one.</summary>
|
||||
public string? Store { 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 Task<CleanupRun> RunCleanupAsync(string bash, World world, params string[] arguments) =>
|
||||
RunCleanupAsync(bash, world, touchesDocker: true, arguments);
|
||||
|
||||
/// <summary>
|
||||
/// As <see cref="RunCleanupAsync(string, World, string[])"/>; with <paramref name="touchesDocker"/> false the run
|
||||
/// may call no docker at all (wrong arguments stop before it).
|
||||
/// </summary>
|
||||
private async Task<CleanupRun> 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;
|
||||
}
|
||||
|
||||
/// <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 «run: |» block of a step without its indentation, as the runner writes it to a script.</summary>
|
||||
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"));
|
||||
}
|
||||
|
||||
/// <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();
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text.RegularExpressions;
|
||||
using Febe.Tests.Desktop.Support;
|
||||
using Febe.Tests.Support;
|
||||
@@ -10,8 +9,8 @@ namespace Febe.Tests.Packaging;
|
||||
/// text: the rules that must survive later edits. Every push of every branch is verified and nothing else triggers
|
||||
/// it twice; the tests run only through tests/Febe.Tests, with the browser, and again with the seed of the run; the
|
||||
/// image is published only from main and never as :latest; credentials are never printed; the external tools are
|
||||
/// pinned and checked; the cleanup touches only what the CI of Febe made, never a real Febe on the same daemon; the
|
||||
/// tried container never has a network.
|
||||
/// pinned and checked; the tried container never has a network. The cleanup, which runs against fake docker and curl
|
||||
/// clients, is in PipelineTests.Pulizia.cs.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed partial class PipelineTests
|
||||
@@ -163,41 +162,6 @@ public sealed partial class PipelineTests
|
||||
StringAssert.Contains(scan, "--exit-code 1");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheCleanupTouchesOnlyWhatTheCiOfFebeMade()
|
||||
{
|
||||
var cleanup = Code(Script("pulizia-docker.sh"));
|
||||
foreach (var forbidden in new[] { "system prune", "builder prune", "volume prune", "container prune", "image prune -a", "prune --all", "image prune -f -a" })
|
||||
{
|
||||
Assert.DoesNotContain(forbidden, cleanup, "the daemon is shared with Alberto's other projects");
|
||||
}
|
||||
|
||||
Assert.HasCount(1, ImagePrune().Matches(cleanup), "only dangling images, older than three days");
|
||||
StringAssert.Contains(cleanup, "docker image prune -f --filter \"until=72h\"");
|
||||
StringAssert.Contains(cleanup, "^buildx_buildkit_(febe-ci-[0-9]+)0$");
|
||||
|
||||
// The febe.ci.* labels of the image are in every container made from a published image, a real Febe too: they
|
||||
// never choose what goes. Containers are chosen by febe.ci.prova (and their exact name), the builders by name,
|
||||
// and an image only by its local name febe-ci:<run>, never by id and never forced.
|
||||
Assert.IsFalse(ProvenanceLabelFilter().IsMatch(cleanup), "the cleanup filters on febe.ci.prova only");
|
||||
foreach (var line in cleanup.Split('\n').Where(l => l.Contains("docker ps", StringComparison.Ordinal)))
|
||||
{
|
||||
Assert.IsTrue(
|
||||
line.Contains("--filter \"label=febe.ci.prova", StringComparison.Ordinal) || line.Contains("--filter \"name=buildx_buildkit_febe-ci-\"", StringComparison.Ordinal) || line.Contains("--filter \"ancestor=", StringComparison.Ordinal),
|
||||
$"«{line.Trim()}» lists containers without the mark of the tried container");
|
||||
}
|
||||
|
||||
StringAssert.Contains(cleanup, "\"febe-prova-$valore\"", "the name must match the mark");
|
||||
StringAssert.Contains(cleanup, "contenitori_di_prova \"\" exited created dead", "the sweeps take only stopped tried containers");
|
||||
Assert.IsFalse(ForcedImageRemoval().IsMatch(cleanup), "an image is never removed by force");
|
||||
StringAssert.Contains(cleanup, "[[ \"$riferimento\" =~ ^febe-ci:[0-9]+$ ]]");
|
||||
|
||||
var weekly = Workflow("pulizia.yml");
|
||||
StringAssert.Contains(weekly, "schedule:");
|
||||
StringAssert.Contains(weekly, "workflow_dispatch:");
|
||||
StringAssert.Contains(weekly, "bash .gitea/scripts/pulizia-docker.sh settimanale");
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void TheTriedContainerNeverHasANetworkAndAlwaysCarriesTheMarkNoImageHas()
|
||||
{
|
||||
@@ -218,186 +182,6 @@ public sealed partial class PipelineTests
|
||||
Assert.DoesNotContain("febe.ci.prova", Code(Read(Repository.PathOf("docker", "Dockerfile"))));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[Timeout(180_000, CooperativeCancellation = true)]
|
||||
public async Task OnADaemonSharedWithARealFebeTheCleanupTakesOnlyWhatTheCiMade()
|
||||
{
|
||||
var script = CiPath("scripts", "pulizia-docker.sh");
|
||||
var bash = BashForScripts();
|
||||
if (bash is null)
|
||||
{
|
||||
Assert.Inconclusive("Manca bash (su Windows serve Git Bash): la prova della pulizia su un demone finto si salta.");
|
||||
}
|
||||
|
||||
Assert.IsTrue(File.Exists(script));
|
||||
|
||||
// At the start or the end of a run (a release run again keeps its id, so the published image has the same
|
||||
// febe.ci.run as the run): only the tried container, the local name and the builder of that run.
|
||||
var run = await RunCleanupAsync(bash, FakeDaemon.Full, "esecuzione", "777");
|
||||
Assert.AreEqual(0, run.Code, run.Report);
|
||||
Assert.DoesNotContain("::warning::", run.Output, run.Report);
|
||||
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Full).Except(["c-prova-777", "b-777"]).ToList(), run.Containers, run.Report);
|
||||
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777(), run.Images, run.Report);
|
||||
CollectionAssert.AreEquivalent(FakeDaemon.Volumes.Except(["buildx_buildkit_febe-ci-7770_state"]).ToList(), run.Volumes, run.Report);
|
||||
|
||||
// Leftovers of interrupted runs: stopped tried containers, febe-ci images and builders older than 90 minutes.
|
||||
var leftovers = await RunCleanupAsync(bash, FakeDaemon.Full, "residui", "90");
|
||||
Assert.AreEqual(0, leftovers.Code, leftovers.Report);
|
||||
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Full).Except(["c-prova-555", "b-vecchio"]).ToList(), leftovers.Containers, leftovers.Report);
|
||||
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777("img-ci555"), leftovers.Images, leftovers.Report);
|
||||
CollectionAssert.AreEquivalent(FakeDaemon.Volumes.Except(["buildx_buildkit_febe-ci-4560_state"]).ToList(), leftovers.Volumes, leftovers.Report);
|
||||
StringAssert.Contains(leftovers.Output, "::warning::Il contenitore di prova febe-prova-556 è acceso", "a running tried container is reported, not removed");
|
||||
StringAssert.Contains(leftovers.Output, "::warning::Il contenitore buildx_buildkit_febe-ci-4570 non è un builder buildx", leftovers.Report);
|
||||
|
||||
// Every week, on a daemon without anything odd: the same, the old febe:ci and the dangling images older than
|
||||
// 72 hours that no container uses. Green.
|
||||
var weekly = await RunCleanupAsync(bash, FakeDaemon.Clean, "settimanale");
|
||||
Assert.AreEqual(0, weekly.Code, weekly.Report);
|
||||
CollectionAssert.AreEquivalent(FakeDaemon.ContainersOf(FakeDaemon.Clean).Except(["c-prova-555", "b-vecchio"]).ToList(), weekly.Containers, weekly.Report);
|
||||
CollectionAssert.AreEquivalent(FakeDaemon.ImagesWithout777("img-ci555", "img-ci556", "img-legacy", "img-penzolante-vecchia"), weekly.Images, weekly.Report);
|
||||
|
||||
// With something left for a person to look at, the weekly cleanup goes red.
|
||||
var noticed = await RunCleanupAsync(bash, FakeDaemon.Full, "settimanale");
|
||||
Assert.AreEqual(1, noticed.Code, noticed.Report);
|
||||
CollectionAssert.Contains(noticed.Containers, "c-prova-556");
|
||||
CollectionAssert.Contains(noticed.Containers, "c-febe-vero");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The daemon the cleanup runs against in <see cref="OnADaemonSharedWithARealFebeTheCleanupTakesOnlyWhatTheCiMade"/>
|
||||
/// (format in fake-docker.sh). A real Febe started from :latest and one from :main carry the febe.ci.* labels of
|
||||
/// their images, as Docker gives them; the image of the release also has the local name of run 777.
|
||||
/// </summary>
|
||||
private static class FakeDaemon
|
||||
{
|
||||
public static readonly string[] Full =
|
||||
[
|
||||
"c-febe-vero|febe|running|43200|192.168.30.23:3000/alby96/febe:latest|img-rilascio|febe.ci.workflow=rilascio,febe.ci.run=777,febe.ci.ref=v0.1.0",
|
||||
"c-febe-fermo|febe-main|exited|43200|192.168.30.23:3000/alby96/febe:main|img-main|febe.ci.workflow=verifica,febe.ci.run=888",
|
||||
"c-febe-antico|febe-antico|exited|20000|img-penzolante-in-uso|img-penzolante-in-uso|febe.ci.run=111",
|
||||
"c-prova-777|febe-prova-777|running|5|febe-ci:777|img-rilascio|febe.ci.workflow=rilascio,febe.ci.run=777,febe.ci.prova=777",
|
||||
"c-prova-555|febe-prova-555|exited|300|febe-ci:555|img-ci555|febe.ci.run=555,febe.ci.prova=555",
|
||||
"c-prova-556|febe-prova-556|running|300|febe-ci:556|img-ci556|febe.ci.run=556,febe.ci.prova=556",
|
||||
"c-prova-557|febe-prova-557|exited|10|febe-ci:557|img-ci557|febe.ci.run=557,febe.ci.prova=557",
|
||||
"c-nome-strano|febe-prova-558-bis|exited|300|encelado:latest|img-encelado|febe.ci.prova=558",
|
||||
"c-segno-diverso|febe-prova-559|exited|300|encelado:latest|img-encelado|febe.ci.prova=560",
|
||||
"c-senza-segno|febe-prova-561|exited|300|encelado:latest|img-encelado|",
|
||||
"c-encelado|encelado|exited|5000|encelado:latest|img-encelado|",
|
||||
"b-vecchio|buildx_buildkit_febe-ci-4560|running|300|moby/buildkit:buildx-stable-1|img-buildkit|",
|
||||
"b-finto|buildx_buildkit_febe-ci-4570|running|300|encelado:latest|img-encelado|",
|
||||
"b-giovane|buildx_buildkit_febe-ci-7890|running|10|moby/buildkit:buildx-stable-1|img-buildkit|",
|
||||
"b-altro|altro_buildx_buildkit_febe-ci-10|running|300|moby/buildkit:buildx-stable-1|img-buildkit|",
|
||||
"b-777|buildx_buildkit_febe-ci-7770|running|20|moby/buildkit:buildx-stable-1|img-buildkit|",
|
||||
];
|
||||
|
||||
/// <summary>The same daemon without the running tried container and the builder that is not one.</summary>
|
||||
public static readonly string[] Clean = [.. Full.Where(c => !c.StartsWith("c-prova-556|", StringComparison.Ordinal) && !c.StartsWith("b-finto|", StringComparison.Ordinal))];
|
||||
|
||||
public static readonly string[] Images =
|
||||
[
|
||||
"img-rilascio|192.168.30.23:3000/alby96/febe:latest,192.168.30.23:3000/alby96/febe:0.1.0,febe-ci:777|43200|febe.ci.run=777",
|
||||
"img-main|192.168.30.23:3000/alby96/febe:main|43200|febe.ci.run=888",
|
||||
"img-ci555|febe-ci:555|300|febe.ci.run=555",
|
||||
"img-ci556|febe-ci:556|300|febe.ci.run=556",
|
||||
"img-ci557|febe-ci:557|10|febe.ci.run=557",
|
||||
"img-penzolante-febe||300|febe.ci.run=999",
|
||||
"img-penzolante-vecchia||6000|",
|
||||
"img-penzolante-in-uso||20000|febe.ci.run=111",
|
||||
"img-encelado|encelado:latest|5000|",
|
||||
"img-buildkit|moby/buildkit:buildx-stable-1|50000|",
|
||||
"img-legacy|febe:ci|6000|",
|
||||
];
|
||||
|
||||
public static readonly string[] Volumes =
|
||||
[
|
||||
"buildx_buildkit_febe-ci-4560_state",
|
||||
"buildx_buildkit_febe-ci-4570_state",
|
||||
"buildx_buildkit_febe-ci-7890_state",
|
||||
"buildx_buildkit_febe-ci-7770_state",
|
||||
"encelado-dati",
|
||||
];
|
||||
|
||||
public static List<string> ContainersOf(string[] world) => [.. world.Select(c => c[..c.IndexOf('|', StringComparison.Ordinal)])];
|
||||
|
||||
/// <summary>
|
||||
/// «id|names» of each image once febe-ci:777 is gone (the image of the release keeps its registry names), without
|
||||
/// the images given.
|
||||
/// </summary>
|
||||
public static List<string> ImagesWithout777(params string[] gone) =>
|
||||
[
|
||||
.. Images
|
||||
.Select(i => string.Join('|', i.Split('|')[..2]).Replace(",febe-ci:777", string.Empty, StringComparison.Ordinal))
|
||||
.Where(i => !gone.Contains(i[..i.IndexOf('|', StringComparison.Ordinal)])),
|
||||
];
|
||||
}
|
||||
|
||||
private sealed record CleanupRun(int Code, string Output, string Errors, List<string> Containers, List<string> Images, List<string> Volumes)
|
||||
{
|
||||
public string Report => $"codice {Code}\n{Output}\n{Errors}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// pulizia-docker.sh against the fake daemon. DOCKER_HOST points nowhere: even if a real docker client came first on
|
||||
/// the PATH it could not reach a daemon, and the test fails because the fake recorded no call.
|
||||
/// </summary>
|
||||
private async Task<CleanupRun> RunCleanupAsync(string bash, string[] containers, params string[] arguments)
|
||||
{
|
||||
using var world = new TempFolder("febe-pulizia");
|
||||
var bin = world.Combine("bin");
|
||||
Directory.CreateDirectory(bin);
|
||||
var docker = Path.Combine(bin, "docker");
|
||||
File.Copy(Repository.PathOf("tests", "Febe.Tests", "Packaging", "fake-docker.sh"), docker);
|
||||
if (!OperatingSystem.IsWindows())
|
||||
{
|
||||
File.SetUnixFileMode(docker, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
|
||||
}
|
||||
|
||||
await WriteLinesAsync(world.Combine("containers"), containers);
|
||||
await WriteLinesAsync(world.Combine("images"), FakeDaemon.Images);
|
||||
await WriteLinesAsync(world.Combine("volumes"), FakeDaemon.Volumes);
|
||||
|
||||
var start = new ProcessStartInfo(bash)
|
||||
{
|
||||
WorkingDirectory = Repository.Root()!,
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
StandardOutputEncoding = System.Text.Encoding.UTF8,
|
||||
StandardErrorEncoding = System.Text.Encoding.UTF8,
|
||||
};
|
||||
start.ArgumentList.Add(".gitea/scripts/pulizia-docker.sh");
|
||||
foreach (var argument in arguments)
|
||||
{
|
||||
start.ArgumentList.Add(argument);
|
||||
}
|
||||
|
||||
start.Environment["PATH"] = bin + Path.PathSeparator + Environment.GetEnvironmentVariable("PATH");
|
||||
start.Environment["FAKE_DOCKER_WORLD"] = world.Path.Replace('\\', '/');
|
||||
start.Environment["DOCKER_HOST"] = OperatingSystem.IsWindows() ? "npipe:////./pipe/febe-nessun-demone" : "unix:///nonexistent/febe-nessun-demone.sock";
|
||||
start.Environment.Remove("DOCKER_CONTEXT");
|
||||
using var process = Process.Start(start)!;
|
||||
var output = process.StandardOutput.ReadToEndAsync(TestContext.CancellationToken);
|
||||
var errors = process.StandardError.ReadToEndAsync(TestContext.CancellationToken);
|
||||
await process.WaitForExitAsync(TestContext.CancellationToken);
|
||||
|
||||
var result = new CleanupRun(
|
||||
process.ExitCode,
|
||||
(await output).Replace("\r\n", "\n", StringComparison.Ordinal),
|
||||
await errors,
|
||||
FakeDaemon.ContainersOf([.. await ReadLinesAsync(world.Combine("containers"))]),
|
||||
[.. (await ReadLinesAsync(world.Combine("images"))).Select(i => string.Join('|', i.Split('|')[..2]))],
|
||||
await ReadLinesAsync(world.Combine("volumes")));
|
||||
var calls = world.Combine("calls");
|
||||
Assert.IsTrue(File.Exists(calls) && (await File.ReadAllTextAsync(calls, TestContext.CancellationToken)).Contains("docker ps", StringComparison.Ordinal), $"the fake docker client was not the one called\n{result.Report}");
|
||||
Assert.DoesNotContain("unexpected call", result.Errors, result.Report);
|
||||
return result;
|
||||
}
|
||||
|
||||
private async Task WriteLinesAsync(string path, IEnumerable<string> lines) =>
|
||||
await File.WriteAllTextAsync(path, string.Concat(lines.Select(line => line + "\n")), TestContext.CancellationToken);
|
||||
|
||||
private async Task<List<string>> ReadLinesAsync(string path) =>
|
||||
[.. (await File.ReadAllTextAsync(path, TestContext.CancellationToken)).Split('\n', StringSplitOptions.RemoveEmptyEntries)];
|
||||
|
||||
/// <summary>bash for the scripts of the CI: the system one on Linux, Git Bash on Windows (not the one of WSL).</summary>
|
||||
private static string? BashForScripts()
|
||||
{
|
||||
@@ -473,15 +257,6 @@ public sealed partial class PipelineTests
|
||||
[GeneratedRegex(@"\b[0-9a-f]{64}\b")]
|
||||
private static partial Regex Sha256();
|
||||
|
||||
[GeneratedRegex(@"docker (?:image|container|volume|builder|system) prune")]
|
||||
private static partial Regex ImagePrune();
|
||||
|
||||
[GeneratedRegex(@"docker run\b(?:[^\n]*\\\n)*[^\n]*")]
|
||||
private static partial Regex DockerRun();
|
||||
|
||||
[GeneratedRegex(@"label=febe\.ci\.(?!prova\b)")]
|
||||
private static partial Regex ProvenanceLabelFilter();
|
||||
|
||||
[GeneratedRegex(@"docker (?:image rm|rmi)\s+(?:-\w+\s+)*-\w*f")]
|
||||
private static partial Regex ForcedImageRemoval();
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env bash
|
||||
# A fake curl for PipelineTests: the registry part of .gitea/scripts/pulizia-docker.sh talks to the packages API of
|
||||
# Gitea 28 through it. No network. It knows only the options the cleanup uses and answers like Gitea:
|
||||
# GET <base>?page=<n>&limit=50 the page $FAKE_CURL_WORLD/page-<n>.json, or [] after the last one (200)
|
||||
# DELETE <base>/<version> 204, and the version is written to $FAKE_CURL_WORLD/deleted
|
||||
# where <base> is the content of $FAKE_CURL_WORLD/base (…/api/v1/packages/<owner>/container/febe). Without the header
|
||||
# «Authorization: token <content of $FAKE_CURL_WORLD/token>» it answers 401; with $FAKE_CURL_WORLD/refuse it answers
|
||||
# 403 to every call; any other address is 404. Every call goes to $FAKE_CURL_WORLD/calls as «METHOD URL», never with
|
||||
# its headers. Any other option is an error (exit 3).
|
||||
set -uo pipefail
|
||||
|
||||
world="${FAKE_CURL_WORLD:?}"
|
||||
token="$(cat "$world/token" 2> /dev/null)"
|
||||
method=GET output="" write="" url="" authorized=0
|
||||
while (($#)); do
|
||||
case "$1" in
|
||||
-s | -S | -sS) ;;
|
||||
--max-time) shift ;;
|
||||
-X) method="$2"; shift ;;
|
||||
-H) [[ -n "$token" && "$2" == "Authorization: token $token" ]] && authorized=1; shift ;;
|
||||
-o) output="$2"; shift ;;
|
||||
-w) write="$2"; shift ;;
|
||||
-*) echo "fake curl: unexpected option $1" >&2; exit 3 ;;
|
||||
*)
|
||||
[[ -z "$url" ]] || { echo "fake curl: a second address $1" >&2; exit 3; }
|
||||
url="$1"
|
||||
;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
printf '%s %s\n' "$method" "$url" >> "$world/calls"
|
||||
[[ -z "$write" || "$write" == '%{http_code}' ]] || { echo "fake curl: unexpected -w $write" >&2; exit 3; }
|
||||
|
||||
answer() {
|
||||
local code="$1" body="${2:-}"
|
||||
if [[ -n "$output" ]]; then
|
||||
printf '%s' "$body" > "$output"
|
||||
else
|
||||
printf '%s' "$body"
|
||||
fi
|
||||
[[ -z "$write" ]] || printf '%s' "$code"
|
||||
exit 0
|
||||
}
|
||||
|
||||
[[ -f "$world/refuse" ]] && answer 403 '{"message":"token does not have at least one of required scope(s): [write:package]"}'
|
||||
((authorized)) || answer 401 '{"message":"token is required"}'
|
||||
|
||||
base="$(cat "$world/base")"
|
||||
case "$method $url" in
|
||||
"GET $base?page="*"&limit=50")
|
||||
page="${url#"$base?page="}"
|
||||
page="${page%%&*}"
|
||||
if [[ -f "$world/page-$page.json" ]]; then
|
||||
answer 200 "$(cat "$world/page-$page.json")"
|
||||
fi
|
||||
answer 200 "[]"
|
||||
;;
|
||||
"DELETE $base/"*)
|
||||
echo "${url#"$base/"}" >> "$world/deleted"
|
||||
answer 204
|
||||
;;
|
||||
*) answer 404 '{"message":"The target couldn'"'"'t be found."}' ;;
|
||||
esac
|
||||
@@ -3,32 +3,53 @@
|
||||
# files, and the test reads what is left. No daemon, no network. It models only what the cleanup relies on, the way
|
||||
# Docker does it:
|
||||
# - filters of «ps»: label filters must all match, the values of any other key are alternatives (status, name as a
|
||||
# regular expression, ancestor by name or id);
|
||||
# regular expression, ancestor by name or id, volume and network by name; stopped containers too);
|
||||
# - «rm» refuses a running container without -f;
|
||||
# - «image rm <name>» only untags when the image has other names, and refuses an image a container uses (always if the
|
||||
# container runs, without -f if it is stopped);
|
||||
# - «image prune --filter until=72h» takes only images without a name, older than 72 hours, used by no container.
|
||||
# Any other call is an error (exit 3), so the test sees every command the cleanup starts to use.
|
||||
# - «image prune» takes only images no container uses, running or stopped: without -a only those without a name, with
|
||||
# -a any; «until» keeps those created in the last 72 or 24 hours. With -a an image a container uses stays but loses
|
||||
# its extra names, as moby does it with the classic store or, with $FAKE_DOCKER_WORLD/store, with containerd;
|
||||
# - «builder prune» only answers (the cache is not modelled);
|
||||
# - «volume rm» refuses a volume a container mounts, running or stopped, even with -f;
|
||||
# - «network rm» refuses the predefined networks and a network a running container is attached to;
|
||||
# - creation times: containers and images in UTC with nanoseconds, volumes and networks two hours ahead with the
|
||||
# offset (+02:00), as a daemon in Italy writes them; the Created of a network is a time of Go, which the template
|
||||
# prints as «2026-10-21 06:17:03.123456789 +0200 CEST» and {{json .Created}} as RFC 3339 between quotes.
|
||||
# Any other call is an error (exit 3), so the test sees every command the cleanup starts to use. That includes any prune
|
||||
# other than those the cleanup may run: image prune -f [--filter until=72h], image prune -a -f --filter until=24h,
|
||||
# builder prune [-a] -f --filter until=24h.
|
||||
#
|
||||
# $FAKE_DOCKER_WORLD/containers id|name|state|minutes ago|image as given to «docker run»|image id|labels
|
||||
# (labels as Docker gives them to the container: those of the image plus those of «run»)
|
||||
# $FAKE_DOCKER_WORLD/images id|names (comma separated; empty: dangling)|minutes ago|labels
|
||||
# $FAKE_DOCKER_WORLD/volumes one name per line
|
||||
# $FAKE_DOCKER_WORLD/calls every call, one per line (written here)
|
||||
# $FAKE_DOCKER_WORLD/containers id|name|state|minutes ago|image as given to «docker run»|image id|labels|volumes|networks
|
||||
# (labels as Docker gives them to the container: those of the image plus those of «run»;
|
||||
# volumes and networks by name, comma separated; the last fields may be missing)
|
||||
# $FAKE_DOCKER_WORLD/images id|names (comma separated; empty: dangling)|minutes ago|labels|size
|
||||
# $FAKE_DOCKER_WORLD/volumes name|minutes ago (missing: just created)
|
||||
# $FAKE_DOCKER_WORLD/networks id|name|minutes ago
|
||||
# $FAKE_DOCKER_WORLD/store optional: «containerd» for the containerd image store (what «docker info» says);
|
||||
# otherwise the classic store of overlay2
|
||||
# $FAKE_DOCKER_WORLD/broken optional: commands («image prune», «builder prune») that fail as if the daemon refused
|
||||
# $FAKE_DOCKER_WORLD/calls every call, one per line (written here), after BUILDX_BUILDER=<value> when it is set
|
||||
set -uo pipefail
|
||||
|
||||
world="${FAKE_DOCKER_WORLD:?}"
|
||||
printf 'docker %s\n' "$*" >> "$world/calls"
|
||||
printf '%sdocker %s\n' "${BUILDX_BUILDER:+BUILDX_BUILDER=$BUILDX_BUILDER }" "$*" >> "$world/calls"
|
||||
now=$(date -u +%s)
|
||||
touch "$world/containers" "$world/images" "$world/volumes"
|
||||
touch "$world/containers" "$world/images" "$world/volumes" "$world/networks"
|
||||
|
||||
unexpected() {
|
||||
echo "fake docker: unexpected call: $*" >&2
|
||||
exit 3
|
||||
}
|
||||
|
||||
broken() {
|
||||
[[ -f "$world/broken" ]] && grep -qxF -- "$1" "$world/broken"
|
||||
}
|
||||
|
||||
created() { date -u -d "@$((now - $1 * 60))" +%Y-%m-%dT%H:%M:%S.123456789Z; }
|
||||
|
||||
created_in_italy() { date -u -d "@$((now - ${1:-0} * 60 + 7200))" "+%Y-%m-%dT%H:%M:%S${2:-}+02:00"; }
|
||||
|
||||
# The value of a label, or $3 when it is missing («docker ps» prints nothing, «inspect» prints <no value>).
|
||||
label_value() {
|
||||
local labels=",$1," key="$2" rest
|
||||
@@ -48,8 +69,8 @@ has_label() {
|
||||
|
||||
# Image id for a name or an id; empty when there is none.
|
||||
resolve_image() {
|
||||
local ref="$1" id names age labels
|
||||
while IFS='|' read -r id names age labels; do
|
||||
local ref="$1" id names rest
|
||||
while IFS='|' read -r id names rest; do
|
||||
[[ -n "$id" ]] || continue
|
||||
if [[ "$id" == "$ref" || ",$names," == *",$ref,"* ]]; then
|
||||
echo "$id"
|
||||
@@ -58,26 +79,29 @@ resolve_image() {
|
||||
done < "$world/images"
|
||||
}
|
||||
|
||||
# The image line for an id; empty when there is none.
|
||||
image_line() {
|
||||
local line
|
||||
# The line of a world file whose first field (or, with $3, whose field number $3) is $2; empty when there is none.
|
||||
line_of() {
|
||||
local file="$1" wanted="$2" field="${3:-1}" line fields
|
||||
while IFS= read -r line; do
|
||||
[[ -n "$line" && "${line%%|*}" == "$1" ]] && { echo "$line"; return; }
|
||||
done < "$world/images"
|
||||
}
|
||||
|
||||
# The container line for an id or a name; empty when there is none.
|
||||
find_container() {
|
||||
local ref="$1" line id name rest
|
||||
while IFS= read -r line; do
|
||||
IFS='|' read -r id name rest <<< "$line"
|
||||
if [[ -n "$id" && ("$id" == "$ref" || "$name" == "$ref") ]]; then
|
||||
[[ -n "$line" ]] || continue
|
||||
IFS='|' read -r -a fields <<< "$line"
|
||||
if [[ "${fields[0]}" == "$wanted" || "${fields[field - 1]:-}" == "$wanted" ]]; then
|
||||
echo "$line"
|
||||
return
|
||||
fi
|
||||
done < "$world/containers"
|
||||
done < "$file"
|
||||
}
|
||||
|
||||
image_line() { line_of "$world/images" "$1"; }
|
||||
|
||||
# The container line for an id or a name; empty when there is none.
|
||||
find_container() { line_of "$world/containers" "$1" 2; }
|
||||
|
||||
volume_line() { line_of "$world/volumes" "$1"; }
|
||||
|
||||
# The network line for an id or a name; empty when there is none.
|
||||
network_line() { line_of "$world/networks" "$1" 2; }
|
||||
|
||||
# Rewrites a world file without the lines whose first field is $2.
|
||||
drop() {
|
||||
local file="$1" id="$2" line
|
||||
@@ -88,18 +112,31 @@ drop() {
|
||||
mv "$file.new" "$file"
|
||||
}
|
||||
|
||||
# True when a container uses the image (any: in any state; running: only a running one).
|
||||
used_by() {
|
||||
local image="$1" want="$2" id name state age config image_id labels
|
||||
while IFS='|' read -r id name state age config image_id labels; do
|
||||
local image="$1" want="$2" id name state age config image_id labels volumes networks
|
||||
while IFS='|' read -r id name state age config image_id labels volumes networks; do
|
||||
[[ -n "$id" && "$image_id" == "$image" ]] || continue
|
||||
[[ "$want" == any || "$state" == running ]] && return 0
|
||||
done < "$world/containers"
|
||||
return 1
|
||||
}
|
||||
|
||||
# True when a container (any: in any state; running: only a running one) has the volume or the network.
|
||||
uses() {
|
||||
local field="$1" wanted="$2" want="$3" id name state age config image_id labels volumes networks list
|
||||
while IFS='|' read -r id name state age config image_id labels volumes networks; do
|
||||
[[ -n "$id" ]] || continue
|
||||
if [[ "$field" == volume ]]; then list="$volumes"; else list="$networks"; fi
|
||||
[[ ",$list," == *",$wanted,"* ]] || continue
|
||||
[[ "$want" == any || "$state" == running ]] && return 0
|
||||
done < "$world/containers"
|
||||
return 1
|
||||
}
|
||||
|
||||
matches() {
|
||||
local name="$1" state="$2" image_id="$3" labels="$4"
|
||||
shift 4
|
||||
local name="$1" state="$2" image_id="$3" labels="$4" volumes="$5" networks="$6"
|
||||
shift 6
|
||||
local -A seen=() ok=()
|
||||
local filter key value
|
||||
for filter in "$@"; do
|
||||
@@ -110,6 +147,8 @@ matches() {
|
||||
status) seen[$key]=1; [[ "$state" == "$value" ]] && ok[$key]=1 ;;
|
||||
name) seen[$key]=1; [[ "$name" =~ $value ]] && ok[$key]=1 ;;
|
||||
ancestor) seen[$key]=1; [[ -n "$image_id" && "$(resolve_image "$value")" == "$image_id" ]] && ok[$key]=1 ;;
|
||||
volume) seen[$key]=1; [[ ",$volumes," == *",$value,"* ]] && ok[$key]=1 ;;
|
||||
network) seen[$key]=1; [[ ",$networks," == *",$value,"* ]] && ok[$key]=1 ;;
|
||||
*) unexpected "filter $filter" ;;
|
||||
esac
|
||||
done
|
||||
@@ -131,10 +170,10 @@ ps_command() {
|
||||
esac
|
||||
shift
|
||||
done
|
||||
local id name state age config image_id labels out key
|
||||
while IFS='|' read -r id name state age config image_id labels; do
|
||||
local id name state age config image_id labels volumes networks out key
|
||||
while IFS='|' read -r id name state age config image_id labels volumes networks; do
|
||||
[[ -n "$id" ]] || continue
|
||||
matches "$name" "$state" "$image_id" "$labels" "${filters[@]}" || continue
|
||||
matches "$name" "$state" "$image_id" "$labels" "$volumes" "$networks" "${filters[@]}" || continue
|
||||
if ((quiet)); then
|
||||
echo "$id"
|
||||
continue
|
||||
@@ -145,6 +184,7 @@ ps_command() {
|
||||
key="${BASH_REMATCH[1]}"
|
||||
out="${out/"${BASH_REMATCH[0]}"/$(label_value "$labels" "$key" "")}"
|
||||
done
|
||||
[[ "$out" == *"{{"* ]] && unexpected "ps --format $format"
|
||||
printf '%s\n' "$out"
|
||||
done < "$world/containers"
|
||||
return 0
|
||||
@@ -153,18 +193,28 @@ ps_command() {
|
||||
container_inspect() {
|
||||
local format=""
|
||||
[[ "${1:-}" == -f ]] && { format="$2"; shift 2; }
|
||||
local line id name state age config image_id labels
|
||||
line=$(find_container "${1:?}")
|
||||
[[ -n "$line" ]] || { echo "Error: No such container: $1" >&2; exit 1; }
|
||||
IFS='|' read -r id name state age config image_id labels <<< "$line"
|
||||
case "$format" in
|
||||
"") echo "[{\"Id\": \"$id\"}]" ;;
|
||||
"{{.Created}}") created "$age" ;;
|
||||
"{{.Config.Image}}") echo "$config" ;;
|
||||
"{{.Name}}") echo "/$name" ;;
|
||||
'{{index .Config.Labels "febe.ci.prova"}}') label_value "$labels" febe.ci.prova "<no value>" ;;
|
||||
*) unexpected "container inspect -f $format" ;;
|
||||
esac
|
||||
(($#)) || unexpected "container inspect without a container"
|
||||
local ref line id name state age config image_id labels volumes networks status=0
|
||||
for ref in "$@"; do
|
||||
line=$(find_container "$ref")
|
||||
if [[ -z "$line" ]]; then
|
||||
echo "Error: No such container: $ref" >&2
|
||||
status=1
|
||||
continue
|
||||
fi
|
||||
IFS='|' read -r id name state age config image_id labels volumes networks <<< "$line"
|
||||
case "$format" in
|
||||
"") echo "[{\"Id\": \"$id\"}]" ;;
|
||||
"{{.Created}}") created "$age" ;;
|
||||
"{{.Config.Image}}") echo "$config" ;;
|
||||
"{{.Image}}") echo "$image_id" ;;
|
||||
"{{.Image}} {{.Config.Image}}") echo "$image_id $config" ;;
|
||||
"{{.Name}}") echo "/$name" ;;
|
||||
'{{index .Config.Labels "febe.ci.prova"}}') label_value "$labels" febe.ci.prova "<no value>" ;;
|
||||
*) unexpected "container inspect -f $format" ;;
|
||||
esac
|
||||
done
|
||||
return "$status"
|
||||
}
|
||||
|
||||
rm_command() {
|
||||
@@ -192,19 +242,31 @@ image_ls() {
|
||||
local format="" reference=""
|
||||
while (($#)); do
|
||||
case "$1" in
|
||||
--no-trunc) ;;
|
||||
--filter) [[ "$2" == reference=* ]] || unexpected "image ls --filter $2"; reference="${2#reference=}"; shift ;;
|
||||
--format) format="$2"; shift ;;
|
||||
*) unexpected "image ls $1" ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
[[ "$format" == "{{.Repository}}:{{.Tag}}" ]] || unexpected "image ls --format $format"
|
||||
local id names age labels tag
|
||||
while IFS='|' read -r id names age labels; do
|
||||
[[ -n "$format" ]] || unexpected "image ls without --format"
|
||||
local id names age labels size tag out
|
||||
while IFS='|' read -r id names age labels size; do
|
||||
[[ -n "$id" ]] || continue
|
||||
IFS=',' read -r -a tags <<< "$names"
|
||||
tags=()
|
||||
[[ -z "$names" ]] || IFS=',' read -r -a tags <<< "$names"
|
||||
if ((${#tags[@]} == 0)); then
|
||||
[[ -z "$reference" ]] || continue
|
||||
tags=("<none>:<none>")
|
||||
fi
|
||||
for tag in "${tags[@]}"; do
|
||||
[[ -z "$reference" || "${tag%:*}" == "$reference" || "$tag" == "$reference" ]] && echo "$tag"
|
||||
[[ -z "$reference" || "${tag%:*}" == "$reference" || "$tag" == "$reference" ]] || continue
|
||||
out="${format//"{{.ID}}"/$id}"
|
||||
out="${out//"{{.Repository}}"/${tag%:*}}"
|
||||
out="${out//"{{.Tag}}"/${tag##*:}}"
|
||||
out="${out//"{{.Size}}"/${size:-100MB}}"
|
||||
[[ "$out" == *"{{"* ]] && unexpected "image ls --format $format"
|
||||
printf '%s\n' "$out"
|
||||
done
|
||||
done < "$world/images"
|
||||
return 0
|
||||
@@ -213,34 +275,31 @@ image_ls() {
|
||||
image_inspect() {
|
||||
local format=""
|
||||
[[ "${1:-}" == -f ]] && { format="$2"; shift 2; }
|
||||
local wanted id names age labels
|
||||
local wanted id names age labels size
|
||||
wanted=$(resolve_image "${1:?}")
|
||||
[[ -n "$wanted" ]] || { echo "Error: No such image: $1" >&2; exit 1; }
|
||||
while IFS='|' read -r id names age labels; do
|
||||
[[ "$id" == "$wanted" ]] || continue
|
||||
case "$format" in
|
||||
"") echo "[{\"Id\": \"$id\"}]" ;;
|
||||
"{{.Created}}") created "$age" ;;
|
||||
"{{len .RepoTags}}") if [[ -z "$names" ]]; then echo 0; else IFS=',' read -r -a tags <<< "$names"; echo "${#tags[@]}"; fi ;;
|
||||
*) unexpected "image inspect -f $format" ;;
|
||||
esac
|
||||
done < "$world/images"
|
||||
IFS='|' read -r id names age labels size <<< "$(image_line "$wanted")"
|
||||
case "$format" in
|
||||
"") echo "[{\"Id\": \"$id\"}]" ;;
|
||||
"{{.Created}}") created "$age" ;;
|
||||
"{{len .RepoTags}}") if [[ -z "$names" ]]; then echo 0; else IFS=',' read -r -a tags <<< "$names"; echo "${#tags[@]}"; fi ;;
|
||||
*) unexpected "image inspect -f $format" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
image_rm() {
|
||||
local force=0
|
||||
[[ "${1:-}" == -f ]] && { force=1; shift; }
|
||||
local ref="${1:?}" wanted id names age labels left="" tag
|
||||
local ref="${1:?}" wanted id names age labels size left="" tag
|
||||
wanted=$(resolve_image "$ref")
|
||||
[[ -n "$wanted" ]] || { echo "Error: No such image: $ref" >&2; exit 1; }
|
||||
IFS='|' read -r id names age labels <<< "$(image_line "$wanted")"
|
||||
IFS='|' read -r id names age labels size <<< "$(image_line "$wanted")"
|
||||
tags=()
|
||||
[[ -z "$names" ]] || IFS=',' read -r -a tags <<< "$names"
|
||||
if [[ "$ref" != "$id" && ${#tags[@]} -gt 1 ]]; then
|
||||
for tag in "${tags[@]}"; do [[ "$tag" == "$ref" ]] || left="${left:+$left,}$tag"; done
|
||||
drop "$world/images" "$id"
|
||||
printf '%s|%s|%s|%s
|
||||
' "$id" "$left" "$age" "$labels" >> "$world/images"
|
||||
printf '%s|%s|%s|%s|%s\n' "$id" "$left" "$age" "$labels" "$size" >> "$world/images"
|
||||
echo "Untagged: $ref"
|
||||
return 0
|
||||
fi
|
||||
@@ -256,18 +315,232 @@ image_rm() {
|
||||
echo "Deleted: $id"
|
||||
}
|
||||
|
||||
# The full name of an image name, the way Docker sorts references: docker.io/library/ or docker.io/ before the names
|
||||
# of Docker Hub written without a domain, :latest when the tag is missing.
|
||||
full_name() {
|
||||
local name="$1" first
|
||||
[[ "${name##*/}" == *:* ]] || name="$name:latest"
|
||||
if [[ "$name" != */* ]]; then
|
||||
echo "docker.io/library/$name"
|
||||
return
|
||||
fi
|
||||
first="${name%%/*}"
|
||||
if [[ "$first" == *.* || "$first" == *:* || "$first" == localhost ]]; then echo "$name"; else echo "docker.io/$name"; fi
|
||||
}
|
||||
|
||||
# The names «image prune -a» leaves to an image a container uses, comma separated, the way moby does it. With the
|
||||
# classic store it removes the references in lexical order of their full names and only the last one is refused
|
||||
# (ImageDelete keeps the single reference of an image in use); with containerd it keeps the names the containers were
|
||||
# created from and, when a container uses the image by id and no name would be left, the last one in lexical order.
|
||||
names_kept() {
|
||||
local image="$1" names="$2" sorted name full cid cname state age config image_id rest by_id=0
|
||||
local -A from=()
|
||||
local kept=()
|
||||
sorted=$(IFS=','; for name in $names; do printf '%s %s\n' "$(full_name "$name")" "$name"; done | LC_ALL=C sort)
|
||||
if [[ "$(store)" == classic ]]; then
|
||||
tail -n 1 <<< "$sorted" | cut -d' ' -f2-
|
||||
return
|
||||
fi
|
||||
while IFS='|' read -r cid cname state age config image_id rest; do
|
||||
[[ -n "$cid" && "$image_id" == "$image" ]] || continue
|
||||
if [[ "$config" == "$image" ]]; then by_id=1; else from[$(full_name "$config")]=1; fi
|
||||
done < "$world/containers"
|
||||
while read -r full name; do
|
||||
[[ -n "${from[$full]:-}" ]] && kept+=("$name")
|
||||
done <<< "$sorted"
|
||||
((${#kept[@]} > 0 || !by_id)) || kept=("$(tail -n 1 <<< "$sorted" | cut -d' ' -f2-)")
|
||||
(IFS=','; echo "${kept[*]}")
|
||||
}
|
||||
|
||||
image_prune() {
|
||||
[[ "$*" == "-f --filter until=72h" ]] || unexpected "image prune $*"
|
||||
local id names age labels gone=()
|
||||
while IFS='|' read -r id names age labels; do
|
||||
[[ -n "$id" && -z "$names" && "$age" -ge $((72 * 60)) ]] || continue
|
||||
used_by "$id" any || gone+=("$id")
|
||||
local all=0 hours=0
|
||||
case "$*" in
|
||||
"-f") ;;
|
||||
"-f --filter until=72h") hours=72 ;;
|
||||
"-a -f --filter until=24h") all=1; hours=24 ;;
|
||||
*) unexpected "image prune $*" ;;
|
||||
esac
|
||||
broken "image prune" && { echo "Error response from daemon: a prune operation is already running" >&2; exit 1; }
|
||||
local id names age labels size gone=() untag=() tag left
|
||||
while IFS='|' read -r id names age labels size; do
|
||||
[[ -n "$id" ]] || continue
|
||||
((all)) || [[ -z "$names" ]] || continue
|
||||
((age >= hours * 60)) || continue
|
||||
if used_by "$id" any; then
|
||||
[[ "$names" == *,* ]] && untag+=("$id")
|
||||
else
|
||||
gone+=("$id")
|
||||
fi
|
||||
done < "$world/images"
|
||||
for id in "${gone[@]}"; do
|
||||
((${#gone[@]} + ${#untag[@]} == 0)) || echo "Deleted Images:"
|
||||
for id in "${untag[@]}"; do
|
||||
IFS='|' read -r id names age labels size <<< "$(image_line "$id")"
|
||||
left=$(names_kept "$id" "$names")
|
||||
IFS=',' read -r -a tags <<< "$names"
|
||||
for tag in "${tags[@]}"; do
|
||||
[[ ",$left," == *",$tag,"* ]] || echo "untagged: $tag"
|
||||
done
|
||||
drop "$world/images" "$id"
|
||||
echo "deleted: $id"
|
||||
printf '%s|%s|%s|%s|%s\n' "$id" "$left" "$age" "$labels" "$size" >> "$world/images"
|
||||
done
|
||||
echo "Total reclaimed space: 0B"
|
||||
for id in "${gone[@]}"; do
|
||||
IFS='|' read -r id names age labels size <<< "$(image_line "$id")"
|
||||
tags=()
|
||||
[[ -z "$names" ]] || IFS=',' read -r -a tags <<< "$names"
|
||||
for tag in "${tags[@]}"; do
|
||||
echo "untagged: $tag"
|
||||
echo "untagged: ${tag%:*}@sha256:0123456789abcdef"
|
||||
done
|
||||
drop "$world/images" "$id"
|
||||
echo "deleted: sha256:$id"
|
||||
done
|
||||
echo
|
||||
if ((${#gone[@]} > 0)); then
|
||||
echo "Total reclaimed space: ${#gone[@]}00MB"
|
||||
else
|
||||
echo "Total reclaimed space: 0B"
|
||||
fi
|
||||
}
|
||||
|
||||
builder_prune() {
|
||||
case "$*" in
|
||||
"-f --filter until=24h" | "-a -f --filter until=24h") ;;
|
||||
*) unexpected "builder prune $*" ;;
|
||||
esac
|
||||
broken "builder prune" && { echo "ERROR: failed to prune build cache: a prune operation is already running" >&2; exit 1; }
|
||||
printf 'Total:\t1.5GB\n'
|
||||
}
|
||||
|
||||
volume_ls() {
|
||||
local filters=() format='{{.Name}}' filter name age
|
||||
while (($#)); do
|
||||
case "$1" in
|
||||
-q) ;;
|
||||
--filter) filters+=("$2"); shift ;;
|
||||
--format) format="$2"; shift ;;
|
||||
*) unexpected "volume ls $1" ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
[[ "$format" == '{{.Name}}' ]] || unexpected "volume ls --format $format"
|
||||
while IFS='|' read -r name age; do
|
||||
[[ -n "$name" ]] || continue
|
||||
for filter in "${filters[@]}"; do
|
||||
case "$filter" in
|
||||
name=*) [[ "$name" =~ ${filter#name=} ]] || continue 2 ;;
|
||||
dangling=true) uses volume "$name" any && continue 2 ;;
|
||||
*) unexpected "volume ls --filter $filter" ;;
|
||||
esac
|
||||
done
|
||||
echo "$name"
|
||||
done < "$world/volumes"
|
||||
return 0
|
||||
}
|
||||
|
||||
volume_inspect() {
|
||||
local format=""
|
||||
[[ "${1:-}" == -f ]] && { format="$2"; shift 2; }
|
||||
local line name age
|
||||
line=$(volume_line "${1:?}")
|
||||
[[ -n "$line" ]] || { echo "Error response from daemon: get $1: no such volume" >&2; exit 1; }
|
||||
IFS='|' read -r name age <<< "$line"
|
||||
case "$format" in
|
||||
"") echo "[{\"Name\": \"$name\"}]" ;;
|
||||
"{{.CreatedAt}}") created_in_italy "$age" ;;
|
||||
*) unexpected "volume inspect -f $format" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
volume_rm() {
|
||||
[[ "${1:-}" == -f ]] && shift
|
||||
local name="${1:?}"
|
||||
[[ -n "$(volume_line "$name")" ]] || { echo "Error response from daemon: get $name: no such volume" >&2; exit 1; }
|
||||
if uses volume "$name" any; then
|
||||
echo "Error response from daemon: remove $name: volume is in use" >&2
|
||||
exit 1
|
||||
fi
|
||||
drop "$world/volumes" "$name"
|
||||
}
|
||||
|
||||
network_ls() {
|
||||
local filters=() format='{{.ID}} {{.Name}}' filter id name age
|
||||
while (($#)); do
|
||||
case "$1" in
|
||||
--no-trunc) ;;
|
||||
--filter) filters+=("$2"); shift ;;
|
||||
--format) format="$2"; shift ;;
|
||||
*) unexpected "network ls $1" ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
[[ "$format" == '{{.ID}} {{.Name}}' ]] || unexpected "network ls --format $format"
|
||||
while IFS='|' read -r id name age; do
|
||||
[[ -n "$id" ]] || continue
|
||||
for filter in "${filters[@]}"; do
|
||||
case "$filter" in
|
||||
name=*) [[ "$name" =~ ${filter#name=} ]] || continue 2 ;;
|
||||
*) unexpected "network ls --filter $filter" ;;
|
||||
esac
|
||||
done
|
||||
echo "$id $name"
|
||||
done < "$world/networks"
|
||||
return 0
|
||||
}
|
||||
|
||||
network_inspect() {
|
||||
local format=""
|
||||
[[ "${1:-}" == -f ]] && { format="$2"; shift 2; }
|
||||
local line id name age
|
||||
line=$(network_line "${1:?}")
|
||||
[[ -n "$line" ]] || { echo "Error response from daemon: network $1 not found" >&2; exit 1; }
|
||||
IFS='|' read -r id name age <<< "$line"
|
||||
case "$format" in
|
||||
"") echo "[{\"Id\": \"$id\", \"Name\": \"$name\"}]" ;;
|
||||
"{{json .Created}}") echo "\"$(created_in_italy "$age" .123456789)\"" ;;
|
||||
# Created of a network is a time.Time: the template prints it the way Go does, not as RFC 3339.
|
||||
"{{.Created}}") date -u -d "@$((now - ${age:-0} * 60 + 7200))" "+%Y-%m-%d %H:%M:%S.123456789 +0200 CEST" ;;
|
||||
*) unexpected "network inspect -f $format" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
network_rm() {
|
||||
local line id name age
|
||||
line=$(network_line "${1:?}")
|
||||
[[ -n "$line" ]] || { echo "Error response from daemon: network $1 not found" >&2; exit 1; }
|
||||
IFS='|' read -r id name age <<< "$line"
|
||||
case "$name" in
|
||||
bridge | host | none) echo "Error response from daemon: $name is a pre-defined network and cannot be removed" >&2; exit 1 ;;
|
||||
esac
|
||||
if uses network "$name" running; then
|
||||
echo "Error response from daemon: error while removing network: network $name id $id has active endpoints" >&2
|
||||
exit 1
|
||||
fi
|
||||
drop "$world/networks" "$id"
|
||||
}
|
||||
|
||||
store() {
|
||||
if [[ "$(cat "$world/store" 2> /dev/null)" == containerd ]]; then echo containerd; else echo classic; fi
|
||||
}
|
||||
|
||||
# The DriverStatus of «docker info» as Docker prints it: with the containerd image store the snapshotter, with the
|
||||
# classic one the details of overlay2.
|
||||
info_command() {
|
||||
[[ "$*" == "--format {{json .DriverStatus}}" ]] || unexpected "info $*"
|
||||
if [[ "$(store)" == containerd ]]; then
|
||||
echo '[["driver-type","io.containerd.snapshotter.v1"]]'
|
||||
else
|
||||
echo '[["Backing Filesystem","extfs"],["Supports d_type","true"],["Using metacopy","false"],["Native Overlay Diff","true"],["userxattr","false"]]'
|
||||
fi
|
||||
}
|
||||
|
||||
system_df() {
|
||||
case "$*" in
|
||||
"") echo "TYPE TOTAL ACTIVE SIZE RECLAIMABLE" ;;
|
||||
"--format {{.Type}}|{{.Size}}|{{.Reclaimable}}")
|
||||
printf '%s\n' "Images|9.1GB|6.2GB (68%)" "Containers|120MB|80MB (66%)" "Local Volumes|3.4GB|1.1GB (32%)" "Build Cache|5.3GB|4.8GB"
|
||||
;;
|
||||
*) unexpected "system df $*" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
@@ -285,18 +558,29 @@ case "${1:-}" in
|
||||
*) unexpected "image $sub" ;;
|
||||
esac
|
||||
;;
|
||||
builder) [[ "${2:-}" == prune ]] || unexpected "$*"; shift 2; builder_prune "$@" ;;
|
||||
buildx) [[ "${2:-}" == rm ]] || unexpected "$*"; echo "ERROR: no builder \"${4:-}\" found" >&2; exit 1 ;;
|
||||
volume)
|
||||
case "${2:-}" in
|
||||
inspect) grep -qxF -- "${3:?}" "$world/volumes" || { echo "Error: no such volume: $3" >&2; exit 1; } ;;
|
||||
rm)
|
||||
[[ "${3:-}" == -f ]] || unexpected "$*"
|
||||
grep -vxF -- "${4:?}" "$world/volumes" > "$world/volumes.new"
|
||||
mv "$world/volumes.new" "$world/volumes"
|
||||
;;
|
||||
*) unexpected "$*" ;;
|
||||
sub="${2:-}"
|
||||
shift 2
|
||||
case "$sub" in
|
||||
ls) volume_ls "$@" ;;
|
||||
inspect) volume_inspect "$@" ;;
|
||||
rm) volume_rm "$@" ;;
|
||||
*) unexpected "volume $sub" ;;
|
||||
esac
|
||||
;;
|
||||
system) [[ "${2:-}" == df ]] || unexpected "$*"; echo "TYPE TOTAL ACTIVE SIZE RECLAIMABLE" ;;
|
||||
network)
|
||||
sub="${2:-}"
|
||||
shift 2
|
||||
case "$sub" in
|
||||
ls) network_ls "$@" ;;
|
||||
inspect) network_inspect "$@" ;;
|
||||
rm) network_rm "$@" ;;
|
||||
*) unexpected "network $sub" ;;
|
||||
esac
|
||||
;;
|
||||
system) [[ "${2:-}" == df ]] || unexpected "$*"; shift 2; system_df "$@" ;;
|
||||
info) shift; info_command "$@" ;;
|
||||
*) unexpected "$*" ;;
|
||||
esac
|
||||
@@ -0,0 +1,36 @@
|
||||
[
|
||||
[
|
||||
{"id": 140, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "main", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/main", "created_at": "2026-10-20T19:42:15+02:00"},
|
||||
{"id": 142, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha256:d0e666bf0a465af6218c1825f3fd72143e2f9ddfc038a8cda19b0504656e0647", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha256:d0e666bf0a465af6218c1825f3fd72143e2f9ddfc038a8cda19b0504656e0647", "created_at": "2026-10-20T19:42:09+02:00"},
|
||||
{"id": 141, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha256:7c39e42c6e919ae17c7dfa17bd5fcf8cd38fa29c02be97e2b0134947b4674f3c", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha256:7c39e42c6e919ae17c7dfa17bd5fcf8cd38fa29c02be97e2b0134947b4674f3c", "created_at": "2026-10-20T19:42:09+02:00"},
|
||||
{"id": 139, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-d0a3b4c5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-d0a3b4c5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1", "created_at": "2026-10-20T19:42:11+02:00"},
|
||||
{"id": 138, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "0.1.1", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/0.1.1", "created_at": "2026-10-20T18:05:00+02:00"},
|
||||
{"id": 137, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "latest", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/latest", "created_at": "2026-10-14T10:00:00+02:00"},
|
||||
{"id": 136, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "0.1.0", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/0.1.0", "created_at": "2026-10-14T10:00:00+02:00"},
|
||||
{"id": 113, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-cf2a3b4", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-cf2a3b4", "created_at": "2026-10-13T09:00:00+02:00"},
|
||||
{"id": 101, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-0a1b2c3", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-0a1b2c3", "created_at": "2026-10-01T09:00:00+02:00"},
|
||||
{"id": 112, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-be1f2a3", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-be1f2a3", "created_at": "2026-10-12T09:00:00+02:00"},
|
||||
{"id": 111, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-ad0e1f2", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-ad0e1f2", "created_at": "2026-10-11T09:00:00+02:00"},
|
||||
{"id": 110, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-9d0e1f2", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-9d0e1f2", "created_at": "2026-10-10T09:00:00+02:00"},
|
||||
{"id": 99, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha256:4f3c2b1a0e9d8c7b6a5f4e3d2c1b0a9f8e7d6c5b4a3f2e1d0c9b8a7f6e5d4c3b", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha256:4f3c2b1a0e9d8c7b6a5f4e3d2c1b0a9f8e7d6c5b4a3f2e1d0c9b8a7f6e5d4c3b", "created_at": "2026-09-20T09:00:00+02:00"},
|
||||
{"id": 109, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-8c9d0e1", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-8c9d0e1", "created_at": "2026-10-09T09:00:00+02:00"}
|
||||
],
|
||||
[
|
||||
{"id": 113, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-cf2a3b4", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-cf2a3b4", "created_at": "2026-10-13T09:00:00+02:00"},
|
||||
{"id": 108, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-7b8c9d0", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-7b8c9d0", "created_at": "2026-10-08T09:00:00+02:00"},
|
||||
{"id": 107, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-6a7b8c9", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-6a7b8c9", "created_at": "2026-10-07T09:00:00+02:00"},
|
||||
{"id": 106, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-5f6a7b8", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-5f6a7b8", "created_at": "2026-10-06T09:00:00+02:00"},
|
||||
{"id": 105, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-4e5f6a7", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-4e5f6a7", "created_at": "2026-10-05T01:00:00+02:00"},
|
||||
{"id": 104, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-3d4e5f6", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-3d4e5f6", "created_at": "2026-10-04T23:30:00Z"},
|
||||
{"id": 103, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-2c3d4e5", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-2c3d4e5", "created_at": "2026-10-03T07:00:00Z"},
|
||||
{"id": 102, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-1b2c3d4", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-1b2c3d4", "created_at": "2026-10-02T09:00:00+02:00"},
|
||||
{"id": 100, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "0.2.0-rc.1", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/0.2.0-rc.1", "created_at": "2026-09-01T09:00:00+02:00"},
|
||||
{"id": 97, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-zzzzzzz", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-zzzzzzz", "created_at": "2026-09-01T09:00:00+02:00"},
|
||||
{"id": 96, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-1a2b3c", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-1a2b3c", "created_at": "2026-09-01T09:00:00+02:00"},
|
||||
{"id": 95, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-ABCDEF0", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-ABCDEF0", "created_at": "2026-09-01T09:00:00+02:00"},
|
||||
{"id": 94, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe", "version": "sha-e1f2a3b4", "html_url": "https://gitea.example/Alby96/-/packages/container/febe/sha-e1f2a3b4"},
|
||||
{"id": 93, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe-strumenti", "version": "sha-0000000", "html_url": "https://gitea.example/Alby96/-/packages/container/febe-strumenti/sha-0000000", "created_at": "2026-08-01T09:00:00+02:00"},
|
||||
{"id": 91, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "container", "name": "febe-strumenti", "version": "sha256:48f76e113cd23ae3e60a2657cf0f84618fce331ef675e8ea39527ba0937b34d0", "html_url": "https://gitea.example/Alby96/-/packages/container/febe-strumenti/sha256:48f76e113cd23ae3e60a2657cf0f84618fce331ef675e8ea39527ba0937b34d0", "created_at": "2026-08-01T09:00:00+02:00"},
|
||||
{"id": 92, "owner": {"id": 1, "login": "Alby96"}, "repository": null, "creator": {"id": 1, "login": "Alby96"}, "type": "generic", "name": "febe", "version": "sha-1111111", "html_url": "https://gitea.example/Alby96/-/packages/generic/febe/sha-1111111", "created_at": "2026-08-01T09:00:00+02:00"}
|
||||
]
|
||||
]
|
||||
Reference in new issue
Block a user