tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
Test fetching the MicroVM's files, the exceptions and the agent's protocol
- Commit
0598973ffbb469275e5d32415ca35bbabdeaca39- Author
- Leitwolf11 ·
- Parents
75553ff1825d
Changes
.github/workflows/ci.yml | 16 +++ src/Progmasoft.Tazel/MicroVM/MicroVMFiles.cs | 48 ++++++--- tests/Progmasoft.Tazel.Tests/ExceptionTests.cs | 70 +++++++++++++ .../Progmasoft.Tazel.Tests/MicroVMDownloadTests.cs | 114 +++++++++++++++++++++ 4 files changed, 235 insertions(+), 13 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d0c4364..8445697 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -204,6 +204,14 @@ jobs: --filter-class Progmasoft.Tazel.Tests.EnvsTests --coverlet --coverlet-output-format cobertura --results-directory artifacts/coverage + - name: Test ExceptionTests (macOS) + if: runner.os == 'macOS' + timeout-minutes: 10 + run: >- + dotnet test --project tests/Progmasoft.Tazel.Tests -c Release --no-build --output Detailed + --filter-class Progmasoft.Tazel.Tests.ExceptionTests + --coverlet --coverlet-output-format cobertura --results-directory artifacts/coverage + - name: Test GlobTests (macOS) if: runner.os == 'macOS' timeout-minutes: 10 @@ -244,6 +252,14 @@ jobs: --filter-class Progmasoft.Tazel.Tests.MicroVMBootTests --coverlet --coverlet-output-format cobertura --results-directory artifacts/coverage + - name: Test MicroVMDownloadTests (macOS) + if: runner.os == 'macOS' + timeout-minutes: 10 + run: >- + dotnet test --project tests/Progmasoft.Tazel.Tests -c Release --no-build --output Detailed + --filter-class Progmasoft.Tazel.Tests.MicroVMDownloadTests + --coverlet --coverlet-output-format cobertura --results-directory artifacts/coverage + - name: Test MicroVMFilesTests (macOS) if: runner.os == 'macOS' timeout-minutes: 10 diff --git a/src/Progmasoft.Tazel/MicroVM/MicroVMFiles.cs b/src/Progmasoft.Tazel/MicroVM/MicroVMFiles.cs index 1e66983..6560452 100644 --- a/src/Progmasoft.Tazel/MicroVM/MicroVMFiles.cs +++ b/src/Progmasoft.Tazel/MicroVM/MicroVMFiles.cs @@ -13,6 +13,21 @@ using Progmasoft.Tazel.Driver; namespace Progmasoft.Tazel.MicroVM; +/// <summary>Where the files of a MicroVM come from: the releases of Tazel, the monitor and its SHA-256, and KVM.</summary> +/// <param name="Releases">The address the image of a Tazel release is under, as <c>tazel-<version>/<name></c>.</param> +/// <param name="Monitor">The address of the static Cloud Hypervisor.</param> +/// <param name="MonitorSha256">The SHA-256 the monitor must have.</param> +/// <param name="Kvm">The KVM device.</param> +internal sealed record MicroVMSources(string Releases, string Monitor, string MonitorSha256, string Kvm) +{ + /// <summary>The releases on GitHub and the host's KVM.</summary> + public static MicroVMSources Published { get; } = new( + "https://github.com/Progmasoft/tazel/releases/download", + $"https://github.com/cloud-hypervisor/cloud-hypervisor/releases/download/{MicroVMFiles.MonitorVersion}/cloud-hypervisor-static", + "ce7133bf535ed5a4e2a63ea1f26025445a5b1241f73ddfb81ff2fbcb2e803a59", + "/dev/kvm"); +} + /// <summary>What a MicroVM is started from: the guest kernel and initramfs, the monitor, and virtiofsd.</summary> /// <param name="Kernel">The guest kernel, an ELF vmlinux that boots through PVH.</param> /// <param name="Initramfs">The initramfs with the agent.</param> @@ -23,27 +38,30 @@ internal sealed record MicroVMFiles(string Kernel, string Initramfs, string Moni /// <summary>The Cloud Hypervisor release Tazel runs, and the SHA-256 of its static x86_64 program.</summary> public const string MonitorVersion = "v55.0"; - private const string MonitorSha256 = "ce7133bf535ed5a4e2a63ea1f26025445a5b1241f73ddfb81ff2fbcb2e803a59"; - /// <summary> /// Finds every file, fetching what is missing into the cache of the user: the image from /// <c>TAZEL_MICROVM_IMAGE</c> (a directory with <c>SHA256SUMS</c>, as <c>microvm/build.cs</c> writes it) or the /// release of this Tazel, the monitor from <c>TAZEL_CLOUD_HYPERVISOR</c> or its release, and virtiofsd from the /// host. Each file is checked against its SHA-256 before it is used. /// </summary> - public static async Task<MicroVMFiles> FindAsync(Version tazel, Action<string> status, CancellationToken cancel) + public static Task<MicroVMFiles> FindAsync(Version tazel, Action<string> status, CancellationToken cancel) => + FindAsync(tazel, status, MicroVMSources.Published, cancel); + + /// <summary>The same, from <paramref name="sources"/>.</summary> + internal static async Task<MicroVMFiles> FindAsync(Version tazel, Action<string> status, MicroVMSources sources, CancellationToken cancel) { ArgumentNullException.ThrowIfNull(tazel); ArgumentNullException.ThrowIfNull(status); + ArgumentNullException.ThrowIfNull(sources); if (!OperatingSystem.IsLinux() || RuntimeInformation.OSArchitecture != Architecture.X64) { throw new MicroVMException( $"this Tazel starts its MicroVM on x86_64 Linux with KVM, and this machine is {RuntimeInformation.RuntimeIdentifier}"); } - if (!File.Exists("/dev/kvm")) + if (!File.Exists(sources.Kvm)) { - throw new MicroVMException("/dev/kvm is not there; the MicroVM needs KVM, so turn on virtualization in the firmware"); + throw new MicroVMException($"{sources.Kvm} is not there; the MicroVM needs KVM, so turn on virtualization in the firmware"); } var cache = Path.Combine(Environment.GetEnvironmentVariable("XDG_CACHE_HOME") is { Length: > 0 } xdg @@ -51,11 +69,11 @@ internal sealed record MicroVMFiles(string Kernel, string Initramfs, string Moni : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".cache"), "tazel"); var image = Environment.GetEnvironmentVariable("TAZEL_MICROVM_IMAGE") is { Length: > 0 } given ? given - : await FetchImageAsync(tazel, Path.Combine(cache, "microvm", tazel.ToString(3)), status, cancel).ConfigureAwait(false); + : await FetchImageAsync(tazel, Path.Combine(cache, "microvm", tazel.ToString(3)), sources, status, cancel).ConfigureAwait(false); CheckImage(image); var monitor = Environment.GetEnvironmentVariable("TAZEL_CLOUD_HYPERVISOR") is { Length: > 0 } chosen ? chosen - : await FetchMonitorAsync(Path.Combine(cache, "cloud-hypervisor", MonitorVersion), status, cancel).ConfigureAwait(false); + : await FetchMonitorAsync(Path.Combine(cache, "cloud-hypervisor", MonitorVersion), sources, status, cancel).ConfigureAwait(false); var virtiofsd = Environment.GetEnvironmentVariable("TAZEL_VIRTIOFSD") is { Length: > 0 } daemon ? daemon : new[] { "/usr/libexec/virtiofsd", "/usr/lib/virtiofsd", "/usr/lib/qemu/virtiofsd" }.FirstOrDefault(File.Exists) @@ -86,7 +104,9 @@ internal sealed record MicroVMFiles(string Kernel, string Initramfs, string Moni } } - private static async Task<string> FetchImageAsync(Version tazel, string directory, Action<string> status, CancellationToken cancel) + /// <summary>The image of <paramref name="tazel"/>'s release in <paramref name="directory"/>, fetched once and checked.</summary> + internal static async Task<string> FetchImageAsync( + Version tazel, string directory, MicroVMSources sources, Action<string> status, CancellationToken cancel) { if (File.Exists(Path.Combine(directory, "SHA256SUMS"))) { @@ -95,7 +115,7 @@ internal sealed record MicroVMFiles(string Kernel, string Initramfs, string Moni var version = tazel.ToString(3); var name = $"tazel-microvm-{version}-x86_64.tazel.tar.xz"; - var url = $"https://github.com/Progmasoft/tazel/releases/download/tazel-{version}/{name}"; + var url = $"{sources.Releases}/tazel-{version}/{name}"; status($"fetching the MicroVM image {name}"); var downloads = directory + ".download"; Directory.CreateDirectory(downloads); @@ -119,21 +139,23 @@ internal sealed record MicroVMFiles(string Kernel, string Initramfs, string Moni return directory; } + /// <summary>Cloud Hypervisor in <paramref name="directory"/>, fetched once and checked against its SHA-256.</summary> [System.Runtime.Versioning.SupportedOSPlatform("linux")] - private static async Task<string> FetchMonitorAsync(string directory, Action<string> status, CancellationToken cancel) + internal static async Task<string> FetchMonitorAsync( + string directory, MicroVMSources sources, Action<string> status, CancellationToken cancel) { var path = Path.Combine(directory, "cloud-hypervisor"); - if (File.Exists(path) && Sha256Sums.Sha256(path) == MonitorSha256) + if (File.Exists(path) && Sha256Sums.Sha256(path) == sources.MonitorSha256) { return path; } status($"fetching Cloud Hypervisor {MonitorVersion}"); Directory.CreateDirectory(directory); - var url = $"https://github.com/cloud-hypervisor/cloud-hypervisor/releases/download/{MonitorVersion}/cloud-hypervisor-static"; + var url = sources.Monitor; await DownloadAsync(url, path + ".partial", cancel).ConfigureAwait(false); var actual = Sha256Sums.Sha256(path + ".partial"); - if (actual != MonitorSha256) + if (actual != sources.MonitorSha256) { File.Delete(path + ".partial"); throw new MicroVMException($"{url} has the SHA-256 {actual}, not that of Cloud Hypervisor {MonitorVersion}"); diff --git a/tests/Progmasoft.Tazel.Tests/ExceptionTests.cs b/tests/Progmasoft.Tazel.Tests/ExceptionTests.cs new file mode 100644 index 0000000..2a345cf --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/ExceptionTests.cs @@ -0,0 +1,70 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +extern alias guest; + +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading.Tasks; +using Progmasoft.Tazel.Cli; +using Progmasoft.Tazel.Dsl; +using Progmasoft.Tazel.Dsl.Custom; +using Progmasoft.Tazel.Dsl.Options; +using Progmasoft.Tazel.Label; +using Progmasoft.Tazel.MicroVM; +using Progmasoft.Tazel.PluginApi; +using Progmasoft.Tazel.Project; +using Xunit; +using GuestProtocol = guest::Progmasoft.Tazel.MicroVM.MicroVMProtocol; +using GuestKind = guest::Progmasoft.Tazel.MicroVM.MessageKind; +using GuestRun = guest::Progmasoft.Tazel.MicroVM.RunRequest; + +namespace Progmasoft.Tazel.Tests; + +/// <summary>The standard constructors of Tazel's exceptions, and the agent's own copy of the protocol.</summary> +public sealed class ExceptionTests +{ + public static TheoryData<string> Kinds => ["Dsl", "CommandLine", "Project", "Plugin", "Label", "TazelOptions", "MicroVM", "CustomCommands"]; + + private static Exception Make(string kind, params object[] arguments) => kind switch + { + "Dsl" => (Exception)Activator.CreateInstance(typeof(DslException), arguments)!, + "CommandLine" => (Exception)Activator.CreateInstance(typeof(CommandLineException), arguments)!, + "Project" => (Exception)Activator.CreateInstance(typeof(ProjectException), arguments)!, + "Plugin" => (Exception)Activator.CreateInstance(typeof(PluginException), arguments)!, + "Label" => (Exception)Activator.CreateInstance(typeof(LabelException), arguments)!, + "TazelOptions" => (Exception)Activator.CreateInstance(typeof(TazelOptionsException), arguments)!, + "MicroVM" => (Exception)Activator.CreateInstance(typeof(MicroVMException), arguments)!, + _ => (Exception)Activator.CreateInstance(typeof(CustomCommandsException), arguments)!, + }; + + [Theory] + [MemberData(nameof(Kinds))] + public void EachExceptionHasTheStandardConstructors(string kind) + { + Assert.NotNull(Make(kind).Message); + Assert.Equal("why", Make(kind, "why").Message); + var inner = new InvalidOperationException("under"); + var wrapped = Make(kind, "why", inner); + Assert.Equal("why", wrapped.Message); + Assert.Same(inner, wrapped.InnerException); + } + + [Fact] + public async Task TheAgentsCopyOfTheProtocolReadsWhatItWrites() + { + var request = new GuestRun(["sh", "-c", "true"], new Dictionary<string, string>(StringComparer.Ordinal) { ["A"] = "b" }, "/work"); + using var stream = new MemoryStream(); + await GuestProtocol.WriteAsync(stream, GuestKind.Run, GuestProtocol.Encode(request), TestContext.Current.CancellationToken); + await GuestProtocol.WriteAsync(stream, GuestKind.Exit, GuestProtocol.EncodeStatus(-3), TestContext.Current.CancellationToken); + stream.Position = 0; + + var run = await GuestProtocol.ReadAsync(stream, TestContext.Current.CancellationToken); + Assert.Equal(request.Arguments, GuestProtocol.DecodeRun(run!.Value.Payload).Arguments); + var exit = await GuestProtocol.ReadAsync(stream, TestContext.Current.CancellationToken); + Assert.Equal(-3, GuestProtocol.DecodeStatus(exit!.Value.Payload)); + Assert.Null(await GuestProtocol.ReadAsync(stream, TestContext.Current.CancellationToken)); + Assert.Equal("/a b/ü", GuestProtocol.DecodePath(GuestProtocol.EncodePath("/a b/ü"))); + } +} diff --git a/tests/Progmasoft.Tazel.Tests/MicroVMDownloadTests.cs b/tests/Progmasoft.Tazel.Tests/MicroVMDownloadTests.cs new file mode 100644 index 0000000..4298675 --- /dev/null +++ b/tests/Progmasoft.Tazel.Tests/MicroVMDownloadTests.cs @@ -0,0 +1,114 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: MIT + +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.Versioning; +using System.Threading.Tasks; +using Progmasoft.Tazel.Archive; +using Progmasoft.Tazel.MicroVM; +using Xunit; + +namespace Progmasoft.Tazel.Tests; + +/// <summary>Fetching the image and the monitor, from a server on this machine in place of the releases.</summary> +[SupportedOSPlatform("linux")] +public sealed class MicroVMDownloadTests +{ + private static readonly Version Tazel = new(0, 1, 0); + private const string ImageName = "tazel-microvm-0.1.0-x86_64.tazel.tar.xz"; + + private static MicroVMSources SourcesOf(FakePortal server, string monitorSha256) => + new($"{server.Address}/releases", $"{server.Address}/cloud-hypervisor-static", monitorSha256, "/dev/kvm"); + + /// <summary>An image archive with its .sha256sums on the server, as a release has it.</summary> + private static void PublishImage(TemporaryModule module, string served, bool goodSums = true) + { + module.Write("image/vmlinux", "kernel").Write("image/initramfs.cpio.gz", "initramfs").Write("image/SHA256SUMS", "sums\n"); + var directory = Path.Combine(served, "releases", "tazel-0.1.0"); + Directory.CreateDirectory(directory); + var archive = Path.Combine(directory, ImageName); + ModuleArchive.Write(Path.Combine(module.Root, "image"), "tazel-microvm-0.1.0-x86_64", archive, + ["SHA256SUMS", "initramfs.cpio.gz", "vmlinux"]); + File.WriteAllText(archive + ".sha256sums", goodSums ? Sha256Sums.SumsLine(archive) : $"{new string('0', 64)} {ImageName}\n"); + } + + [Fact] + public async Task TheImageOfTheReleaseIsFetchedCheckedAndKept() + { + Assert.SkipUnless(OperatingSystem.IsLinux(), "the MicroVM runs on Linux"); + using var module = new TemporaryModule(); + var served = Path.Combine(module.Root, "served"); + PublishImage(module, served); + var cache = Path.Combine(module.Root, "cache", "image"); + var said = new List<string>(); + using (var server = new FakePortal(served)) + { + var image = await MicroVMFiles.FetchImageAsync(Tazel, cache, SourcesOf(server, ""), said.Add, TestContext.Current.CancellationToken); + Assert.Equal(cache, image); + Assert.Equal("kernel", File.ReadAllText(Path.Combine(image, "vmlinux"))); + Assert.Contains($"fetching the MicroVM image {ImageName}", said); + Assert.False(Directory.Exists(cache + ".download")); + } + + // The server is gone: the image kept is used. + var nowhere = new MicroVMSources("http://127.0.0.1:9/releases", "http://127.0.0.1:9/monitor", "", "/dev/kvm"); + var again = await MicroVMFiles.FetchImageAsync(Tazel, cache, nowhere, said.Add, TestContext.Current.CancellationToken); + Assert.Equal(cache, again); + } + + [Fact] + public async Task AnImageThatDoesNotMatchItsSumsOrIsNotThereIsRefused() + { + Assert.SkipUnless(OperatingSystem.IsLinux(), "the MicroVM runs on Linux"); + using var module = new TemporaryModule(); + var served = Path.Combine(module.Root, "served"); + PublishImage(module, served, goodSums: false); + using var server = new FakePortal(served); + var error = await Assert.ThrowsAsync<MicroVMException>(() => MicroVMFiles.FetchImageAsync( + Tazel, Path.Combine(module.Root, "cache", "a"), SourcesOf(server, ""), _ => { }, TestContext.Current.CancellationToken)); + Assert.Contains("does not match its .sha256sums", error.Message, StringComparison.Ordinal); + + error = await Assert.ThrowsAsync<MicroVMException>(() => MicroVMFiles.FetchImageAsync( + new Version(9, 9, 9), Path.Combine(module.Root, "cache", "b"), SourcesOf(server, ""), _ => { }, TestContext.Current.CancellationToken)); + Assert.Contains("answered 404", error.Message, StringComparison.Ordinal); + Assert.Contains("TAZEL_MICROVM_IMAGE", error.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task TheMonitorIsFetchedOnceAndOnlyWithItsSha256() + { + Assert.SkipUnless(OperatingSystem.IsLinux(), "the MicroVM runs on Linux"); + using var module = new TemporaryModule().Write("served/cloud-hypervisor-static", "#!/bin/sh\necho monitor\n"); + var served = Path.Combine(module.Root, "served"); + var sha = Sha256Sums.Sha256(Path.Combine(served, "cloud-hypervisor-static")); + var directory = Path.Combine(module.Root, "cache", "monitor"); + using var server = new FakePortal(served); + + var error = await Assert.ThrowsAsync<MicroVMException>(() => MicroVMFiles.FetchMonitorAsync( + directory, SourcesOf(server, new string('0', 64)), _ => { }, TestContext.Current.CancellationToken)); + Assert.Contains("has the SHA-256", error.Message, StringComparison.Ordinal); + Assert.False(File.Exists(Path.Combine(directory, "cloud-hypervisor.partial"))); + + var said = new List<string>(); + var monitor = await MicroVMFiles.FetchMonitorAsync(directory, SourcesOf(server, sha), said.Add, TestContext.Current.CancellationToken); + Assert.True((File.GetUnixFileMode(monitor) & UnixFileMode.UserExecute) != 0); + Assert.Single(said); + + said.Clear(); + Assert.Equal(monitor, await MicroVMFiles.FetchMonitorAsync(directory, SourcesOf(server, sha), said.Add, TestContext.Current.CancellationToken)); + Assert.Empty(said); + } + + [Fact] + public async Task NoKvmIsSaid() + { + Assert.SkipUnless(OperatingSystem.IsLinux() && System.Runtime.InteropServices.RuntimeInformation.OSArchitecture == + System.Runtime.InteropServices.Architecture.X64, "the MicroVM runs on x86_64 Linux"); + var sources = MicroVMSources.Published with { Kvm = "/no/such/kvm" }; + var error = await Assert.ThrowsAsync<MicroVMException>(() => + MicroVMFiles.FindAsync(Tazel, _ => { }, sources, TestContext.Current.CancellationToken)); + Assert.Contains("/no/such/kvm is not there", error.Message, StringComparison.Ordinal); + } +}