tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
Write two-letter acronyms in capitals, and check guest paths by POSIX rules
- Commit
1d9ffae05ac35a683dd4773e97b11cebefebfc2a- Author
- Leitwolf11 ·
- Parents
9b468e9f7448
Changes
.github/workflows/ci.yml | 6 +- docs/microvm.md | 2 +- docs/project-files.md | 2 +- src/Progmasoft.Tazel.Dsl/Build/Prelude/Families.cs | 2 +- src/Progmasoft.Tazel.Dsl/Common/Platform.cs | 30 +++++----- src/Progmasoft.Tazel.Guest/Agent.cs | 65 +++++++++++++++++----- src/Progmasoft.Tazel.Guest/Libc.cs | 4 +- .../Progmasoft.Tazel.Guest.csproj | 2 +- src/Progmasoft.Tazel.Guest/Program.cs | 2 +- src/Progmasoft.Tazel/Cli/Commands.cs | 2 +- src/Progmasoft.Tazel/Cli/MoreCommands.cs | 16 +++--- src/Progmasoft.Tazel/Driver/CCPlanner.cs | 12 ++-- src/Progmasoft.Tazel/Driver/Planner.cs | 20 +++---- src/Progmasoft.Tazel/Driver/ZigPlanner.cs | 4 +- src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs | 20 +++---- .../MicroVmFiles.cs => MicroVM/MicroVMFiles.cs} | 34 +++++------ .../{MicroVm => MicroVM}/Sandbox.cs | 52 ++++++++--------- src/Progmasoft.Tazel/Output/ErrorCodes.cs | 4 +- src/Progmasoft.Tazel/Program.cs | 4 +- .../{MicroVmProtocol.cs => MicroVMProtocol.cs} | 4 +- .../{MicroVmTests.cs => MicroVMTests.cs} | 35 ++++++------ tests/Progmasoft.Tazel.Tests/TemporaryModule.cs | 5 +- tests/Progmasoft.Tazel.Tests/TextFileTests.cs | 10 ++-- 23 files changed, 189 insertions(+), 148 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2ec0e97..f6ce205 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -184,7 +184,7 @@ jobs: TAZEL_REQUIRE_MICROVM: "1" run: >- dotnet test --solution Tazel.slnx -c Release - --filter-class 'Progmasoft.Tazel.Tests.MicroVmBootTests' - --filter-class 'Progmasoft.Tazel.Tests.MicroVmProtocolTests' - --filter-class 'Progmasoft.Tazel.Tests.MicroVmFilesTests' + --filter-class 'Progmasoft.Tazel.Tests.MicroVMBootTests' + --filter-class 'Progmasoft.Tazel.Tests.MicroVMProtocolTests' + --filter-class 'Progmasoft.Tazel.Tests.MicroVMFilesTests' --no-progress diff --git a/docs/microvm.md b/docs/microvm.md index a2e9e58..b47331e 100644 --- a/docs/microvm.md +++ b/docs/microvm.md @@ -46,7 +46,7 @@ tazel ──vsock (Cloud Hypervisor's Unix socket, CONNECT 1024)──▶ tazel- loader as the first process, so the guest's `/lib` is free to be the host's `/usr/lib`. - The agent reaches the C library through `[LibraryImport]`; it refuses a working directory outside what was shared for writing. -- The messages are a kind byte, a little-endian length and a payload (`src/Shared/MicroVmProtocol.cs`, the same file +- The messages are a kind byte, a little-endian length and a payload (`src/Shared/MicroVMProtocol.cs`, the same file on both sides). - Cloud Hypervisor and virtiofsd are processes of their own: when one of them dies, the command fails with E0504 and the end of the guest's console; Tazel goes on. At the end Tazel asks the guest to power off, then stops what is left diff --git a/docs/project-files.md b/docs/project-files.md index f3c6b56..336f8ec 100644 --- a/docs/project-files.md +++ b/docs/project-files.md @@ -123,7 +123,7 @@ CC.Test("math_test", new() `ObjectiveC` targets build for the two macOS platforms. `//...` leaves out a target that does not build for the platform of the command, with every target that depends on it, and says how many it left out; naming it is an error. `Tags = ["manual"]` keeps a target out of `//...` as well. -- **Conditions** are C#: `Build.Mode` (`BuildMode.Debug`, `Release`), `Build.Platform`, `Build.Os`, `Build.Arch`. +- **Conditions** are C#: `Build.Mode` (`BuildMode.Debug`, `Release`), `Build.Platform`, `Build.OS`, `Build.Arch`. - **Headers** of a target are found below the root of its module and below its `IncludeDirectories`, by it and by what depends on it. diff --git a/src/Progmasoft.Tazel.Dsl/Build/Prelude/Families.cs b/src/Progmasoft.Tazel.Dsl/Build/Prelude/Families.cs index 77c9216..e2da586 100644 --- a/src/Progmasoft.Tazel.Dsl/Build/Prelude/Families.cs +++ b/src/Progmasoft.Tazel.Dsl/Build/Prelude/Families.cs @@ -118,7 +118,7 @@ public sealed class BuildContext public Platform Platform { get; } /// <summary>The operating system of <see cref="Platform"/>.</summary> - public Os Os => Platform.GetOs(); + public OS OS => Platform.GetOS(); /// <summary>The architecture of <see cref="Platform"/>.</summary> public Arch Arch => Platform.GetArch(); diff --git a/src/Progmasoft.Tazel.Dsl/Common/Platform.cs b/src/Progmasoft.Tazel.Dsl/Common/Platform.cs index 66e7df9..3209cb3 100644 --- a/src/Progmasoft.Tazel.Dsl/Common/Platform.cs +++ b/src/Progmasoft.Tazel.Dsl/Common/Platform.cs @@ -47,7 +47,7 @@ public enum Platform } /// <summary>An operating system, as conditions in a project file see it.</summary> -public enum Os +public enum OS { /// <summary>Linux.</summary> Linux, @@ -91,19 +91,19 @@ public enum BuildMode /// <summary>The names, systems and architectures of the platforms.</summary> public static class Platforms { - private static readonly (Platform Platform, string Name, Os Os, Arch Arch)[] All = + private static readonly (Platform Platform, string Name, OS OS, Arch Arch)[] All = [ - (Platform.LinuxAmd64, "linux-amd64", Os.Linux, Arch.X64), - (Platform.LinuxAarch64, "linux-aarch64", Os.Linux, Arch.Arm64), - (Platform.WindowsX64, "windows-x64", Os.Windows, Arch.X64), - (Platform.WindowsArm64, "windows-arm64", Os.Windows, Arch.Arm64), - (Platform.MacOSX86_64, "macos-x86_64", Os.MacOS, Arch.X64), - (Platform.MacOSArm64, "macos-arm64", Os.MacOS, Arch.Arm64), - (Platform.FreeBSDAmd64, "freebsd-amd64", Os.FreeBSD, Arch.X64), - (Platform.FreeBSDAarch64, "freebsd-aarch64", Os.FreeBSD, Arch.Arm64), - (Platform.OpenBSDAmd64, "openbsd-amd64", Os.OpenBSD, Arch.X64), - (Platform.OpenBSDAarch64, "openbsd-aarch64", Os.OpenBSD, Arch.Arm64), - (Platform.DragonFlyBSDAmd64, "dragonfly-bsd-amd64", Os.DragonFlyBSD, Arch.X64), + (Platform.LinuxAmd64, "linux-amd64", OS.Linux, Arch.X64), + (Platform.LinuxAarch64, "linux-aarch64", OS.Linux, Arch.Arm64), + (Platform.WindowsX64, "windows-x64", OS.Windows, Arch.X64), + (Platform.WindowsArm64, "windows-arm64", OS.Windows, Arch.Arm64), + (Platform.MacOSX86_64, "macos-x86_64", OS.MacOS, Arch.X64), + (Platform.MacOSArm64, "macos-arm64", OS.MacOS, Arch.Arm64), + (Platform.FreeBSDAmd64, "freebsd-amd64", OS.FreeBSD, Arch.X64), + (Platform.FreeBSDAarch64, "freebsd-aarch64", OS.FreeBSD, Arch.Arm64), + (Platform.OpenBSDAmd64, "openbsd-amd64", OS.OpenBSD, Arch.X64), + (Platform.OpenBSDAarch64, "openbsd-aarch64", OS.OpenBSD, Arch.Arm64), + (Platform.DragonFlyBSDAmd64, "dragonfly-bsd-amd64", OS.DragonFlyBSD, Arch.X64), ]; /// <summary>Every platform name, in the order of the enum.</summary> @@ -113,7 +113,7 @@ public static class Platforms public static string Name(this Platform platform) => Find(platform).Name; /// <summary>The operating system of <paramref name="platform"/>.</summary> - public static Os GetOs(this Platform platform) => Find(platform).Os; + public static OS GetOS(this Platform platform) => Find(platform).OS; /// <summary>The architecture of <paramref name="platform"/>.</summary> public static Arch GetArch(this Platform platform) => Find(platform).Arch; @@ -134,7 +134,7 @@ public static class Platforms return false; } - private static (Platform Platform, string Name, Os Os, Arch Arch) Find(Platform platform) + private static (Platform Platform, string Name, OS OS, Arch Arch) Find(Platform platform) { foreach (var entry in All) { diff --git a/src/Progmasoft.Tazel.Guest/Agent.cs b/src/Progmasoft.Tazel.Guest/Agent.cs index 28926ff..363bbec 100644 --- a/src/Progmasoft.Tazel.Guest/Agent.cs +++ b/src/Progmasoft.Tazel.Guest/Agent.cs @@ -9,7 +9,7 @@ using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; -using Progmasoft.Tazel.MicroVm; +using Progmasoft.Tazel.MicroVM; namespace Progmasoft.Tazel.Guest; @@ -37,7 +37,7 @@ internal sealed record Share(string Tag, string Path, bool ReadOnly) throw new FormatException($"'{word}' is not tazel.share=tag,ro|rw,path"); } - var path = MicroVmProtocol.DecodePath(parts[2]); + var path = MicroVMProtocol.DecodePath(parts[2]); if (!path.StartsWith('/') || path.Split('/').Contains("..")) { throw new FormatException($"the share {parts[0]} has the path '{path}'"); @@ -58,7 +58,7 @@ internal sealed record Share(string Tag, string Path, bool ReadOnly) internal sealed class Agent(IReadOnlyList<Share> shares) { /// <summary>The PATH of the agent and the one it searches when a command brings none.</summary> - public const string DefaultPath = MicroVmProtocol.DefaultPath; + public const string DefaultPath = MicroVMProtocol.DefaultPath; public static string Version => typeof(Agent).Assembly.GetName().Version?.ToString(3) ?? "0.0.0"; @@ -101,10 +101,10 @@ internal sealed class Agent(IReadOnlyList<Share> shares) throw new IOException($"vsock: {Libc.LastError()}"); } - var address = new Libc.SockaddrVm { Family = Libc.AfVsock, Port = MicroVmProtocol.Port, Cid = Libc.VmaddrCidAny }; + var address = new Libc.SockaddrVM { Family = Libc.AfVsock, Port = MicroVMProtocol.Port, Cid = Libc.VmaddrCidAny }; if (Libc.Bind(listener, address, 16) != 0 || Libc.Listen(listener, 64) != 0) { - throw new IOException($"vsock port {MicroVmProtocol.Port}: {Libc.LastError()}"); + throw new IOException($"vsock port {MicroVMProtocol.Port}: {Libc.LastError()}"); } using var off = new ManualResetEventSlim(); @@ -151,11 +151,48 @@ internal sealed class Agent(IReadOnlyList<Share> shares) /// <summary>Whether <paramref name="directory"/> is inside a share the guest may write.</summary> public bool Inside(string directory) { - var full = Path.GetFullPath(directory); - return shares.Any(share => !share.ReadOnly && + var full = Normalize(directory); + return full is not null && shares.Any(share => !share.ReadOnly && (full == share.Path || full.StartsWith(share.Path.TrimEnd('/') + "/", StringComparison.Ordinal))); } + /// <summary> + /// An absolute guest path with its "." and ".." taken out, by the rules of the guest whatever runs this code; null + /// for a path that is not absolute or climbs above the root. + /// </summary> + public static string? Normalize(string path) + { + ArgumentNullException.ThrowIfNull(path); + if (!path.StartsWith('/')) + { + return null; + } + + var parts = new List<string>(); + foreach (var part in path.Split('/', StringSplitOptions.RemoveEmptyEntries)) + { + if (part == ".") + { + continue; + } + + if (part == "..") + { + if (parts.Count == 0) + { + return null; + } + + parts.RemoveAt(parts.Count - 1); + continue; + } + + parts.Add(part); + } + + return "/" + string.Join('/', parts); + } + [System.Runtime.Versioning.SupportedOSPlatform("linux")] private async Task ServeAsync(VsockStream stream, ManualResetEventSlim off) { @@ -163,15 +200,15 @@ internal sealed class Agent(IReadOnlyList<Share> shares) { try { - var message = await MicroVmProtocol.ReadAsync(stream, CancellationToken.None).ConfigureAwait(false); + var message = await MicroVMProtocol.ReadAsync(stream, CancellationToken.None).ConfigureAwait(false); switch (message?.Kind) { case MessageKind.Hello: - await MicroVmProtocol.WriteAsync(stream, MessageKind.Ready, Encoding.UTF8.GetBytes(Version), CancellationToken.None) + await MicroVMProtocol.WriteAsync(stream, MessageKind.Ready, Encoding.UTF8.GetBytes(Version), CancellationToken.None) .ConfigureAwait(false); break; case MessageKind.Run: - await RunAsync(stream, MicroVmProtocol.DecodeRun(message.Value.Payload)).ConfigureAwait(false); + await RunAsync(stream, MicroVMProtocol.DecodeRun(message.Value.Payload)).ConfigureAwait(false); break; case MessageKind.PowerOff: off.Set(); @@ -243,7 +280,7 @@ internal sealed class Agent(IReadOnlyList<Share> shares) // The host sends Stop, or goes away, while the command runs. try { - await MicroVmProtocol.ReadAsync(stream, CancellationToken.None).ConfigureAwait(false); + await MicroVMProtocol.ReadAsync(stream, CancellationToken.None).ConfigureAwait(false); } catch (Exception error) when (error is IOException or InvalidDataException or EndOfStreamException) { @@ -258,7 +295,7 @@ internal sealed class Agent(IReadOnlyList<Share> shares) var errors = Pump(process.StandardError.BaseStream, 2, stream); await Task.WhenAll(output, errors).ConfigureAwait(false); await process.WaitForExitAsync().ConfigureAwait(false); - await MicroVmProtocol.WriteAsync(stream, MessageKind.Exit, MicroVmProtocol.EncodeStatus(process.ExitCode), CancellationToken.None) + await MicroVMProtocol.WriteAsync(stream, MessageKind.Exit, MicroVMProtocol.EncodeStatus(process.ExitCode), CancellationToken.None) .ConfigureAwait(false); _ = stop; } @@ -276,14 +313,14 @@ internal sealed class Agent(IReadOnlyList<Share> shares) } buffer[0] = which; - await MicroVmProtocol.WriteAsync(to, MessageKind.Output, buffer.AsMemory(0, read + 1), CancellationToken.None) + await MicroVMProtocol.WriteAsync(to, MessageKind.Output, buffer.AsMemory(0, read + 1), CancellationToken.None) .ConfigureAwait(false); } } [System.Runtime.Versioning.SupportedOSPlatform("linux")] private static Task Refuse(VsockStream stream, string why) => - MicroVmProtocol.WriteAsync(stream, MessageKind.Error, Encoding.UTF8.GetBytes(why), CancellationToken.None); + MicroVMProtocol.WriteAsync(stream, MessageKind.Error, Encoding.UTF8.GetBytes(why), CancellationToken.None); [System.Runtime.Versioning.SupportedOSPlatform("linux")] private static void MountOrFail(string source, string target, string type, ulong flags, string? data) diff --git a/src/Progmasoft.Tazel.Guest/Libc.cs b/src/Progmasoft.Tazel.Guest/Libc.cs index 8bb5313..90a5494 100644 --- a/src/Progmasoft.Tazel.Guest/Libc.cs +++ b/src/Progmasoft.Tazel.Guest/Libc.cs @@ -46,7 +46,7 @@ internal static partial class Libc public static partial int Socket(int domain, int type, int protocol); [LibraryImport(Library, EntryPoint = "bind", SetLastError = true)] - public static partial int Bind(int socket, in SockaddrVm address, uint length); + public static partial int Bind(int socket, in SockaddrVM address, uint length); [LibraryImport(Library, EntryPoint = "listen", SetLastError = true)] public static partial int Listen(int socket, int backlog); @@ -68,7 +68,7 @@ internal static partial class Libc /// <summary><c>struct sockaddr_vm</c>.</summary> [StructLayout(LayoutKind.Sequential)] - public struct SockaddrVm + public struct SockaddrVM { public ushort Family; public ushort Reserved; diff --git a/src/Progmasoft.Tazel.Guest/Progmasoft.Tazel.Guest.csproj b/src/Progmasoft.Tazel.Guest/Progmasoft.Tazel.Guest.csproj index 24504fc..2b750a3 100644 --- a/src/Progmasoft.Tazel.Guest/Progmasoft.Tazel.Guest.csproj +++ b/src/Progmasoft.Tazel.Guest/Progmasoft.Tazel.Guest.csproj @@ -15,7 +15,7 @@ <EventSourceSupport>false</EventSourceSupport> </PropertyGroup> <ItemGroup> - <Compile Include="../Shared/MicroVmProtocol.cs" Link="Shared/MicroVmProtocol.cs" /> + <Compile Include="../Shared/MicroVMProtocol.cs" Link="Shared/MicroVMProtocol.cs" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Progmasoft.Tazel.Tests" /> diff --git a/src/Progmasoft.Tazel.Guest/Program.cs b/src/Progmasoft.Tazel.Guest/Program.cs index 25177c4..f143413 100644 --- a/src/Progmasoft.Tazel.Guest/Program.cs +++ b/src/Progmasoft.Tazel.Guest/Program.cs @@ -25,7 +25,7 @@ internal static class Program var shares = Share.Parse(File.ReadAllText("/proc/cmdline")); var agent = new Agent(shares); agent.Boot(); - Console.Error.WriteLine($"tazel-guest {Agent.Version}: ready on vsock port {MicroVm.MicroVmProtocol.Port}"); + Console.Error.WriteLine($"tazel-guest {Agent.Version}: ready on vsock port {MicroVM.MicroVMProtocol.Port}"); agent.Serve(); } catch (Exception error) when (error is IOException or FormatException or UnauthorizedAccessException) diff --git a/src/Progmasoft.Tazel/Cli/Commands.cs b/src/Progmasoft.Tazel/Cli/Commands.cs index 8318e71..ad13661 100644 --- a/src/Progmasoft.Tazel/Cli/Commands.cs +++ b/src/Progmasoft.Tazel/Cli/Commands.cs @@ -180,7 +180,7 @@ internal sealed partial class Commands(Reporter reporter, string workingDirector if (sandboxFile is not null) { - return await CustomInMicroVmAsync(command, arguments, options, sandboxFile, cancel).ConfigureAwait(false); + return await CustomInMicroVMAsync(command, arguments, options, sandboxFile, cancel).ConfigureAwait(false); } var environment = Processes.Inherited(); diff --git a/src/Progmasoft.Tazel/Cli/MoreCommands.cs b/src/Progmasoft.Tazel/Cli/MoreCommands.cs index b6ff0b6..dcd67e7 100644 --- a/src/Progmasoft.Tazel/Cli/MoreCommands.cs +++ b/src/Progmasoft.Tazel/Cli/MoreCommands.cs @@ -175,20 +175,20 @@ internal sealed partial class Commands /// Runs the steps of a custom command inside a MicroVM that sees the module, or the directory of the command when /// it is in no module, and the host's /usr read-only; a shell step goes to the guest's /bin/sh. /// </summary> - private async Task<int> CustomInMicroVmAsync( + private async Task<int> CustomInMicroVMAsync( Dsl.Custom.CustomCommand command, IReadOnlyList<string> arguments, TazelOptions options, string sandboxFile, CancellationToken cancel) { - if (options.MicrovmNetwork) + if (options.MicroVMNetwork) { - throw new MicroVm.MicroVmException( + throw new MicroVM.MicroVMException( $"{sandboxFile} asks for microvm-network, and this Tazel's MicroVM has no network, so nothing ran; " + "set microvm-network: false;"); } if (!OperatingSystem.IsLinux()) { - throw new MicroVm.MicroVmException( + throw new MicroVM.MicroVMException( $"{sandboxFile} asks for sandboxing-with-microvm, and this Tazel starts its MicroVM on Linux only"); } @@ -202,11 +202,11 @@ internal sealed partial class Commands shared = Path.GetFullPath(workingDirectory); } - var files = await MicroVm.MicroVmFiles.FindAsync(TazelVersion, reporter.Status, cancel).ConfigureAwait(false); - var size = new MicroVm.MicroVmSize( - options.MicrovmMemory.Amount ?? 1024, options.MicrovmCpus.Amount ?? Math.Clamp(Environment.ProcessorCount / 2, 1, 4)); + var files = await MicroVM.MicroVMFiles.FindAsync(TazelVersion, reporter.Status, cancel).ConfigureAwait(false); + var size = new MicroVM.MicroVMSize( + options.MicroVMMemory.Amount ?? 1024, options.MicroVMCpus.Amount ?? Math.Clamp(Environment.ProcessorCount / 2, 1, 4)); reporter.Status($"starting the MicroVM ({size.MemoryMiB} MiB, {size.Processors} processor{(size.Processors == 1 ? "" : "s")})"); - var sandbox = await MicroVm.Sandbox.StartAsync(files, [new MicroVm.SharedDirectory(shared, ReadOnly: false)], size, cancel) + var sandbox = await MicroVM.Sandbox.StartAsync(files, [new MicroVM.SharedDirectory(shared, ReadOnly: false)], size, cancel) .ConfigureAwait(false); await using (sandbox.ConfigureAwait(false)) { diff --git a/src/Progmasoft.Tazel/Driver/CCPlanner.cs b/src/Progmasoft.Tazel/Driver/CCPlanner.cs index 9828bb2..f07cfe3 100644 --- a/src/Progmasoft.Tazel/Driver/CCPlanner.cs +++ b/src/Progmasoft.Tazel/Driver/CCPlanner.cs @@ -87,7 +87,7 @@ internal sealed partial class Planner var objectsDirectory = $"{directory}/_objs/{target.Label.Name}"; var packageRoot = FileSets.ToRoot(target.PackageDirectory, Layout.MainRoot); var pic = target.Kind != TargetKind.Executable && target.Kind != TargetKind.Test && - Options.Platform.GetOs() != Os.Windows; + Options.Platform.GetOS() != OS.Windows; var objc = settings as IObjectiveCSettings; var nonArc = objc is null ? new HashSet<string>(StringComparer.Ordinal) @@ -212,7 +212,7 @@ internal sealed partial class Planner else { // Apple's ar has no D; ZERO_AR_DATE in the environment of the actions makes it deterministic instead. - var appleAr = Host.Platform.GetOs() == Os.MacOS && + var appleAr = Host.Platform.GetOS() == OS.MacOS && Path.GetFileNameWithoutExtension(toolchain.Archiver.Program) == "ar"; command.Add(appleAr ? "rcs" : "rcsD"); command.AddRange(Flags(features, CCAction.CppLinkStaticLibrary)); @@ -250,9 +250,9 @@ internal sealed partial class Planner var version = ((CCSharedLibrarySettings)settings).LibraryVersion; var (file, linkWith, soname) = SharedLibraryNames(directory, target.Label.Name, version); output = file; - var os = Options.Platform.GetOs(); - command.Add(os == Os.MacOS ? "-dynamiclib" : "-shared"); - if (os == Os.MacOS) + var os = Options.Platform.GetOS(); + command.Add(os == OS.MacOS ? "-dynamiclib" : "-shared"); + if (os == OS.MacOS) { command.AddRange(["-install_name", $"@rpath/{soname}"]); if (version is not null) @@ -261,7 +261,7 @@ internal sealed partial class Planner "-compatibility_version", $"{version.Major}.0.0"]); } } - else if (os != Os.Windows && soname is not null) + else if (os != OS.Windows && soname is not null) { command.Add($"-Wl,-soname,{soname}"); } diff --git a/src/Progmasoft.Tazel/Driver/Planner.cs b/src/Progmasoft.Tazel/Driver/Planner.cs index 2b0f5b7..dc6ad9e 100644 --- a/src/Progmasoft.Tazel/Driver/Planner.cs +++ b/src/Progmasoft.Tazel/Driver/Planner.cs @@ -149,7 +149,7 @@ internal sealed partial class Planner var actions = new List<BuildAction>(); var sharedDirectories = new List<string>(); var tail = new List<string>(); - var os = Options.Platform.GetOs(); + var os = Options.Platform.GetOS(); foreach (var (_, products) in LinkOrder(target)) { if (products.Main is { } main) @@ -162,7 +162,7 @@ internal sealed partial class Planner inputs.Add(library); if (products.AlwaysLink && !products.IsShared && !forZig) { - arguments.AddRange(os == Os.MacOS + arguments.AddRange(os == OS.MacOS ? [$"-Wl,-force_load,{library}"] : ["-Wl,--whole-archive", library, "-Wl,--no-whole-archive"]); } @@ -188,11 +188,11 @@ internal sealed partial class Planner { var relative = Path.GetRelativePath(outputDirectory, directory).Replace('\\', '/'); var suffix = relative == "." ? "" : "/" + relative; - if (os == Os.MacOS) + if (os == OS.MacOS) { arguments.Add($"-Wl,-rpath,@loader_path{suffix}"); } - else if (os != Os.Windows) + else if (os != OS.Windows) { arguments.Add($"-Wl,-rpath,$ORIGIN{suffix}"); } @@ -206,18 +206,18 @@ internal sealed partial class Planner /// <summary>The file names of libraries and programs on the platform of the build.</summary> private string StaticLibraryName(string name) => - Options.Platform.GetOs() == Os.Windows ? $"{name}.lib" : $"lib{name}.a"; + Options.Platform.GetOS() == OS.Windows ? $"{name}.lib" : $"lib{name}.a"; - private string ExecutableName(string name) => Options.Platform.GetOs() == Os.Windows ? $"{name}.exe" : name; + private string ExecutableName(string name) => Options.Platform.GetOS() == OS.Windows ? $"{name}.exe" : name; /// <summary>The file a shared library is written to, the file its dependents link, and its soname.</summary> private (string File, string LinkWith, string? Soname) SharedLibraryNames(string directory, string name, Version? version) { - switch (Options.Platform.GetOs()) + switch (Options.Platform.GetOS()) { - case Os.Windows: + case OS.Windows: return ($"{directory}/{name}.dll", $"{directory}/{name}.lib", null); - case Os.MacOS: + case OS.MacOS: var mac = version is null ? $"lib{name}.dylib" : $"lib{name}.{version.Major}.dylib"; return ($"{directory}/{mac}", $"{directory}/{mac}", mac); default: @@ -236,7 +236,7 @@ internal sealed partial class Planner /// <summary>Makes <c>libx.so.1</c> and <c>libx.so</c> point at <c>libx.so.1.2.0</c>.</summary> private Action? SonameLinks(string file, string? soname, string name) { - if (Options.Platform.GetOs() is Os.Windows or Os.MacOS || soname is null || Path.GetFileName(file) == soname) + if (Options.Platform.GetOS() is OS.Windows or OS.MacOS || soname is null || Path.GetFileName(file) == soname) { return null; } diff --git a/src/Progmasoft.Tazel/Driver/ZigPlanner.cs b/src/Progmasoft.Tazel/Driver/ZigPlanner.cs index d5824a0..fffc4e8 100644 --- a/src/Progmasoft.Tazel/Driver/ZigPlanner.cs +++ b/src/Progmasoft.Tazel/Driver/ZigPlanner.cs @@ -76,7 +76,7 @@ internal sealed partial class Planner output = file; products.Library = linkWith; products.IsShared = true; - if (soname is not null && Options.Platform.GetOs() != Os.Windows) + if (soname is not null && Options.Platform.GetOS() != OS.Windows) { command.Add($"-fsoname={soname}"); } @@ -145,7 +145,7 @@ internal sealed partial class Planner command.AddRange(arguments); foreach (var shared in sharedDirectories) { - command.AddRange(["-rpath", Options.Platform.GetOs() == Os.MacOS ? "@loader_path/" + Relative(directory, shared) + command.AddRange(["-rpath", Options.Platform.GetOS() == OS.MacOS ? "@loader_path/" + Relative(directory, shared) : "$ORIGIN/" + Relative(directory, shared)]); } diff --git a/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs b/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs index a5630ba..00c8a30 100644 --- a/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs +++ b/src/Progmasoft.Tazel/Dsl/Options/TazelOptions.cs @@ -29,16 +29,16 @@ public sealed record TazelOptions /// <summary> /// Whether what a project brings to run, custom commands and the build among it, runs inside a MicroVM. /// </summary> - public bool SandboxingWithMicrovm { get; init; } + public bool SandboxingWithMicroVM { get; init; } /// <summary>Whether the MicroVM reaches the network.</summary> - public bool MicrovmNetwork { get; init; } + public bool MicroVMNetwork { get; init; } /// <summary>The memory of the MicroVM, in MiB.</summary> - public Allocation MicrovmMemory { get; init; } = Allocation.Auto; + public Allocation MicroVMMemory { get; init; } = Allocation.Auto; /// <summary>The processors of the MicroVM.</summary> - public Allocation MicrovmCpus { get; init; } = Allocation.Auto; + public Allocation MicroVMCpus { get; init; } = Allocation.Auto; /// <summary>The platform commands build for unless <c>--platform</c> names one; default: the host's.</summary> public Platform? Platform { get; init; } @@ -156,8 +156,8 @@ public static class TazelOptionsFile return (new TazelOptions(), null); } - var asking = files.FirstOrDefault(entry => entry.Options.SandboxingWithMicrovm).File; - return (files[0].Options with { SandboxingWithMicrovm = asking is not null }, asking); + var asking = files.FirstOrDefault(entry => entry.Options.SandboxingWithMicroVM).File; + return (files[0].Options with { SandboxingWithMicroVM = asking is not null }, asking); } private static TazelOptions Read(string file) @@ -215,10 +215,10 @@ public static class TazelOptionsFile var value = tokens[_position++]; options = key.Text switch { - "sandboxing-with-microvm" => options with { SandboxingWithMicrovm = Boolean(value) }, - "microvm-network" => options with { MicrovmNetwork = Boolean(value) }, - "microvm-memory" => options with { MicrovmMemory = Amount(value, MinMemory, MaxMemory, "MiB") }, - "microvm-cpus" => options with { MicrovmCpus = Amount(value, 1, MaxCpus, "processors") }, + "sandboxing-with-microvm" => options with { SandboxingWithMicroVM = Boolean(value) }, + "microvm-network" => options with { MicroVMNetwork = Boolean(value) }, + "microvm-memory" => options with { MicroVMMemory = Amount(value, MinMemory, MaxMemory, "MiB") }, + "microvm-cpus" => options with { MicroVMCpus = Amount(value, 1, MaxCpus, "processors") }, _ => options with { Platform = PlatformOf(value) }, }; diff --git a/src/Progmasoft.Tazel/MicroVm/MicroVmFiles.cs b/src/Progmasoft.Tazel/MicroVM/MicroVMFiles.cs similarity index 89% rename from src/Progmasoft.Tazel/MicroVm/MicroVmFiles.cs rename to src/Progmasoft.Tazel/MicroVM/MicroVMFiles.cs index 9a555f0..1e66983 100644 --- a/src/Progmasoft.Tazel/MicroVm/MicroVmFiles.cs +++ b/src/Progmasoft.Tazel/MicroVM/MicroVMFiles.cs @@ -11,14 +11,14 @@ using System.Threading.Tasks; using Progmasoft.Tazel.Archive; using Progmasoft.Tazel.Driver; -namespace Progmasoft.Tazel.MicroVm; +namespace Progmasoft.Tazel.MicroVM; /// <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> /// <param name="Monitor">Cloud Hypervisor.</param> /// <param name="Virtiofsd">The virtio-fs daemon of the host.</param> -internal sealed record MicroVmFiles(string Kernel, string Initramfs, string Monitor, string Virtiofsd) +internal sealed record MicroVMFiles(string Kernel, string Initramfs, string Monitor, string Virtiofsd) { /// <summary>The Cloud Hypervisor release Tazel runs, and the SHA-256 of its static x86_64 program.</summary> public const string MonitorVersion = "v55.0"; @@ -31,19 +31,19 @@ internal sealed record MicroVmFiles(string Kernel, string Initramfs, string Moni /// 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 async Task<MicroVMFiles> FindAsync(Version tazel, Action<string> status, CancellationToken cancel) { ArgumentNullException.ThrowIfNull(tazel); ArgumentNullException.ThrowIfNull(status); if (!OperatingSystem.IsLinux() || RuntimeInformation.OSArchitecture != Architecture.X64) { - throw new MicroVmException( + 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")) { - throw new MicroVmException("/dev/kvm is not there; the MicroVM needs KVM, so turn on virtualization in the firmware"); + throw new MicroVMException("/dev/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 @@ -60,8 +60,8 @@ internal sealed record MicroVmFiles(string Kernel, string Initramfs, string Moni ? daemon : new[] { "/usr/libexec/virtiofsd", "/usr/lib/virtiofsd", "/usr/lib/qemu/virtiofsd" }.FirstOrDefault(File.Exists) ?? Host.Which("virtiofsd") - ?? throw new MicroVmException("virtiofsd is not installed; the MicroVM shares the module through it (the package is virtiofsd)"); - return new MicroVmFiles(Path.Combine(image, "vmlinux"), Path.Combine(image, "initramfs.cpio.gz"), monitor, virtiofsd); + ?? throw new MicroVMException("virtiofsd is not installed; the MicroVM shares the module through it (the package is virtiofsd)"); + return new MicroVMFiles(Path.Combine(image, "vmlinux"), Path.Combine(image, "initramfs.cpio.gz"), monitor, virtiofsd); } /// <summary>Checks that every file of an image matches its <c>SHA256SUMS</c>.</summary> @@ -70,18 +70,18 @@ internal sealed record MicroVmFiles(string Kernel, string Initramfs, string Moni var sums = Path.Combine(directory, "SHA256SUMS"); if (!File.Exists(sums)) { - throw new MicroVmException($"{directory} has no SHA256SUMS, so its image cannot be checked"); + throw new MicroVMException($"{directory} has no SHA256SUMS, so its image cannot be checked"); } var text = File.ReadAllText(sums); foreach (var name in new[] { "vmlinux", "initramfs.cpio.gz" }) { var expected = Sha256Sums.SumFor(text, name, sums) - ?? throw new MicroVmException($"{sums} does not name {name}"); + ?? throw new MicroVMException($"{sums} does not name {name}"); var path = Path.Combine(directory, name); if (!File.Exists(path) || !string.Equals(Sha256Sums.Sha256(path), expected, StringComparison.Ordinal)) { - throw new MicroVmException($"{path} does not match its SHA256SUMS; build or fetch the image again"); + throw new MicroVMException($"{path} does not match its SHA256SUMS; build or fetch the image again"); } } } @@ -105,7 +105,7 @@ internal sealed record MicroVmFiles(string Kernel, string Initramfs, string Moni var expected = Sha256Sums.SumFor(await File.ReadAllTextAsync(sums, cancel).ConfigureAwait(false), name, url + ".sha256sums"); if (expected is null || !string.Equals(Sha256Sums.Sha256(archive), expected, StringComparison.Ordinal)) { - throw new MicroVmException($"{url} does not match its .sha256sums"); + throw new MicroVMException($"{url} does not match its .sha256sums"); } var root = ModuleArchive.Unpack(archive, directory + ".partial", "vmlinux"); @@ -136,7 +136,7 @@ internal sealed record MicroVmFiles(string Kernel, string Initramfs, string Moni if (actual != MonitorSha256) { File.Delete(path + ".partial"); - throw new MicroVmException($"{url} has the SHA-256 {actual}, not that of Cloud Hypervisor {MonitorVersion}"); + throw new MicroVMException($"{url} has the SHA-256 {actual}, not that of Cloud Hypervisor {MonitorVersion}"); } File.SetUnixFileMode(path + ".partial", UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); @@ -150,7 +150,7 @@ internal sealed record MicroVmFiles(string Kernel, string Initramfs, string Moni using var response = await http.GetAsync(new Uri(url), HttpCompletionOption.ResponseHeadersRead, cancel).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { - throw new MicroVmException( + throw new MicroVMException( $"{url} answered {(int)response.StatusCode}; build the image with dotnet run microvm/build.cs and set TAZEL_MICROVM_IMAGE"); } @@ -165,21 +165,21 @@ internal sealed record MicroVmFiles(string Kernel, string Initramfs, string Moni } /// <summary>The MicroVM could not be started or stopped answering.</summary> -public sealed class MicroVmException : Exception +public sealed class MicroVMException : Exception { /// <summary>What went wrong.</summary> - public MicroVmException(string message) + public MicroVMException(string message) : base(message) { } /// <summary>Nothing to say.</summary> - public MicroVmException() + public MicroVMException() { } /// <summary>What went wrong, and why.</summary> - public MicroVmException(string message, Exception inner) + public MicroVMException(string message, Exception inner) : base(message, inner) { } diff --git a/src/Progmasoft.Tazel/MicroVm/Sandbox.cs b/src/Progmasoft.Tazel/MicroVM/Sandbox.cs similarity index 89% rename from src/Progmasoft.Tazel/MicroVm/Sandbox.cs rename to src/Progmasoft.Tazel/MicroVM/Sandbox.cs index f8a8ae2..d7192a0 100644 --- a/src/Progmasoft.Tazel/MicroVm/Sandbox.cs +++ b/src/Progmasoft.Tazel/MicroVM/Sandbox.cs @@ -12,7 +12,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; -namespace Progmasoft.Tazel.MicroVm; +namespace Progmasoft.Tazel.MicroVM; /// <summary>A directory of the host the MicroVM sees at the same path.</summary> /// <param name="Path">The directory.</param> @@ -22,7 +22,7 @@ internal sealed record SharedDirectory(string Path, bool ReadOnly); /// <summary>How big a MicroVM is.</summary> /// <param name="MemoryMiB">Its memory.</param> /// <param name="Processors">Its processors.</param> -internal sealed record MicroVmSize(int MemoryMiB, int Processors); +internal sealed record MicroVMSize(int MemoryMiB, int Processors); /// <summary> /// One MicroVM: Cloud Hypervisor and a virtiofsd per shared directory, each a process of its own, so the death of any @@ -35,7 +35,7 @@ internal sealed class Sandbox : IAsyncDisposable /// <summary>The environment every command inside gets, and nothing of the host's.</summary> public static readonly IReadOnlyDictionary<string, string> Environment = new Dictionary<string, string>(StringComparer.Ordinal) { - ["PATH"] = MicroVmProtocol.DefaultPath, + ["PATH"] = MicroVMProtocol.DefaultPath, ["HOME"] = "/root", ["TMPDIR"] = "/tmp", ["LANG"] = "C.UTF-8", @@ -57,7 +57,7 @@ internal sealed class Sandbox : IAsyncDisposable /// <summary>Starts a MicroVM that sees <paramref name="shares"/> and waits until its agent answers.</summary> public static async Task<Sandbox> StartAsync( - MicroVmFiles files, IReadOnlyList<SharedDirectory> shares, MicroVmSize size, CancellationToken cancel) + MicroVMFiles files, IReadOnlyList<SharedDirectory> shares, MicroVMSize size, CancellationToken cancel) { ArgumentNullException.ThrowIfNull(files); ArgumentNullException.ThrowIfNull(shares); @@ -79,7 +79,7 @@ internal sealed class Sandbox : IAsyncDisposable arguments.AddRange(["--fs", $"tag={tag},socket={socket},num_queues=1,queue_size=512"]); var guestPath = i == all.Count - 1 ? "/etc" : all[i].Path; command.Append(CultureInfo.InvariantCulture, - $" tazel.share={tag},{(all[i].ReadOnly ? "ro" : "rw")},{MicroVmProtocol.EncodePath(guestPath)}"); + $" tazel.share={tag},{(all[i].ReadOnly ? "ro" : "rw")},{MicroVMProtocol.EncodePath(guestPath)}"); } command.Append(" -- --library-path /tazel/lib /tazel/agent/tazel-guest"); @@ -107,7 +107,7 @@ internal sealed class Sandbox : IAsyncDisposable start.ArgumentList.Add(argument); } - var monitor = Process.Start(start) ?? throw new MicroVmException($"{files.Monitor} could not be started"); + var monitor = Process.Start(start) ?? throw new MicroVMException($"{files.Monitor} could not be started"); monitor.StandardInput.Close(); var sandbox = new Sandbox(runtime, monitor, vsock, console); sandbox._daemons.AddRange(daemons); @@ -139,12 +139,12 @@ internal sealed class Sandbox : IAsyncDisposable var stream = new NetworkStream(connection, ownsSocket: false); await using (stream.ConfigureAwait(false)) { - await MicroVmProtocol.WriteAsync(stream, MessageKind.Run, - MicroVmProtocol.Encode(new RunRequest(arguments, Environment, directory)), cancel).ConfigureAwait(false); + await MicroVMProtocol.WriteAsync(stream, MessageKind.Run, + MicroVMProtocol.Encode(new RunRequest(arguments, Environment, directory)), cancel).ConfigureAwait(false); using var stop = cancel.Register(() => connection.Shutdown(SocketShutdown.Both)); while (true) { - var message = await MicroVmProtocol.ReadAsync(stream, CancellationToken.None).ConfigureAwait(false); + var message = await MicroVMProtocol.ReadAsync(stream, CancellationToken.None).ConfigureAwait(false); switch (message?.Kind) { case MessageKind.Output: @@ -153,14 +153,14 @@ internal sealed class Sandbox : IAsyncDisposable await target.FlushAsync(CancellationToken.None).ConfigureAwait(false); break; case MessageKind.Exit: - return MicroVmProtocol.DecodeStatus(message.Value.Payload); + return MicroVMProtocol.DecodeStatus(message.Value.Payload); case MessageKind.Error: - throw new MicroVmException(Encoding.UTF8.GetString(message.Value.Payload)); + throw new MicroVMException(Encoding.UTF8.GetString(message.Value.Payload)); case null: cancel.ThrowIfCancellationRequested(); - throw new MicroVmException($"the MicroVM stopped answering while {arguments[0]} ran{ConsoleTail()}"); + throw new MicroVMException($"the MicroVM stopped answering while {arguments[0]} ran{ConsoleTail()}"); default: - throw new MicroVmException($"the agent sent a message of the kind {message.Value.Kind}"); + throw new MicroVMException($"the agent sent a message of the kind {message.Value.Kind}"); } } } @@ -177,7 +177,7 @@ internal sealed class Sandbox : IAsyncDisposable var stream = new NetworkStream(connection, ownsSocket: false); await using (stream.ConfigureAwait(false)) { - await MicroVmProtocol.WriteAsync(stream, MessageKind.PowerOff, ReadOnlyMemory<byte>.Empty, CancellationToken.None) + await MicroVMProtocol.WriteAsync(stream, MessageKind.PowerOff, ReadOnlyMemory<byte>.Empty, CancellationToken.None) .ConfigureAwait(false); } @@ -185,7 +185,7 @@ internal sealed class Sandbox : IAsyncDisposable await _monitor.WaitForExitAsync(wait.Token).ConfigureAwait(false); } } - catch (Exception error) when (error is MicroVmException or IOException or SocketException or OperationCanceledException) + catch (Exception error) when (error is MicroVMException or IOException or SocketException or OperationCanceledException) { // It does not answer; it is stopped below. } @@ -231,7 +231,7 @@ internal sealed class Sandbox : IAsyncDisposable start.ArgumentList.Add(argument); } - var process = Process.Start(start) ?? throw new MicroVmException($"{program} could not be started"); + var process = Process.Start(start) ?? throw new MicroVMException($"{program} could not be started"); process.OutputDataReceived += (_, _) => { }; process.ErrorDataReceived += (_, _) => { }; process.BeginOutputReadLine(); @@ -245,7 +245,7 @@ internal sealed class Sandbox : IAsyncDisposable { if (daemon.HasExited) { - throw new MicroVmException($"{what} ended with {daemon.ExitCode} before it was ready"); + throw new MicroVMException($"{what} ended with {daemon.ExitCode} before it was ready"); } await Task.Delay(50, cancel).ConfigureAwait(false); @@ -253,7 +253,7 @@ internal sealed class Sandbox : IAsyncDisposable if (!File.Exists(socket)) { - throw new MicroVmException($"{what} did not open {socket} within five seconds"); + throw new MicroVMException($"{what} did not open {socket} within five seconds"); } } @@ -265,7 +265,7 @@ internal sealed class Sandbox : IAsyncDisposable if (_monitor.HasExited) { var errors = await _monitor.StandardError.ReadToEndAsync(cancel).ConfigureAwait(false); - throw new MicroVmException( + throw new MicroVMException( $"Cloud Hypervisor ended with {_monitor.ExitCode} while the MicroVM started: {errors.Trim()}{ConsoleTail()}"); } @@ -275,14 +275,14 @@ internal sealed class Sandbox : IAsyncDisposable var stream = new NetworkStream(connection, ownsSocket: false); await using (stream.ConfigureAwait(false)) { - await MicroVmProtocol.WriteAsync(stream, MessageKind.Hello, ReadOnlyMemory<byte>.Empty, cancel).ConfigureAwait(false); - if (await MicroVmProtocol.ReadAsync(stream, cancel).ConfigureAwait(false) is { Kind: MessageKind.Ready }) + await MicroVMProtocol.WriteAsync(stream, MessageKind.Hello, ReadOnlyMemory<byte>.Empty, cancel).ConfigureAwait(false); + if (await MicroVMProtocol.ReadAsync(stream, cancel).ConfigureAwait(false) is { Kind: MessageKind.Ready }) { return; } } } - catch (Exception error) when (error is MicroVmException or IOException or SocketException) + catch (Exception error) when (error is MicroVMException or IOException or SocketException) { // The agent is not listening yet. } @@ -290,7 +290,7 @@ internal sealed class Sandbox : IAsyncDisposable await Task.Delay(100, cancel).ConfigureAwait(false); } - throw new MicroVmException($"the agent of the MicroVM did not answer within a minute{ConsoleTail()}"); + throw new MicroVMException($"the agent of the MicroVM did not answer within a minute{ConsoleTail()}"); } /// <summary>A connection to the agent: Cloud Hypervisor's hybrid vsock takes "CONNECT port" and answers "OK".</summary> @@ -302,14 +302,14 @@ internal sealed class Sandbox : IAsyncDisposable try { await socket.ConnectAsync(new UnixDomainSocketEndPoint(_vsock), limit.Token).ConfigureAwait(false); - await socket.SendAsync(Encoding.ASCII.GetBytes($"CONNECT {MicroVmProtocol.Port}\n"), limit.Token).ConfigureAwait(false); + await socket.SendAsync(Encoding.ASCII.GetBytes($"CONNECT {MicroVMProtocol.Port}\n"), limit.Token).ConfigureAwait(false); var line = new List<byte>(); var one = new byte[1]; while (line.Count < 64) { if (await socket.ReceiveAsync(one, limit.Token).ConfigureAwait(false) == 0) { - throw new MicroVmException("the monitor closed the vsock connection"); + throw new MicroVMException("the monitor closed the vsock connection"); } if (one[0] == '\n') @@ -322,7 +322,7 @@ internal sealed class Sandbox : IAsyncDisposable return Encoding.ASCII.GetString(line.ToArray()).StartsWith("OK ", StringComparison.Ordinal) ? socket - : throw new MicroVmException("the agent is not listening"); + : throw new MicroVMException("the agent is not listening"); } catch { diff --git a/src/Progmasoft.Tazel/Output/ErrorCodes.cs b/src/Progmasoft.Tazel/Output/ErrorCodes.cs index 335bab1..5f0277f 100644 --- a/src/Progmasoft.Tazel/Output/ErrorCodes.cs +++ b/src/Progmasoft.Tazel/Output/ErrorCodes.cs @@ -75,7 +75,7 @@ internal static partial class ErrorCodes public const string ActionsFailed = "E0501"; public const string NoDaemon = "E0502"; public const string Stopped = "E0503"; - public const string MicroVm = "E0504"; + public const string MicroVM = "E0504"; public const string Label = "E0600"; private const string Lexer = "the text files: tazel_custom.txt, tazel_options.txt and tazel_envs.txt"; @@ -239,7 +239,7 @@ internal static partial class ErrorCodes new(Stopped, "the command was stopped", "Ctrl+C or a signal stopped Tazel. The actions that were running were stopped too; what finished is kept, and " + "the next build goes on from there.", null, null, "MODULE.csx, BUILD.csx and builds"), - new(MicroVm, "the MicroVM could not run the command", + new(MicroVM, "the MicroVM could not run the command", "tazel_options.txt asks for sandboxing-with-microvm, so tazel custom runs inside a MicroVM: a Linux guest " + "under Cloud Hypervisor that sees the module and the host's /usr, read-only, and nothing else of the host. It " + "needs x86_64 Linux with KVM (/dev/kvm), virtiofsd, and the image of the guest: Tazel fetches the image of its " + diff --git a/src/Progmasoft.Tazel/Program.cs b/src/Progmasoft.Tazel/Program.cs index 84d048e..a95ad55 100644 --- a/src/Progmasoft.Tazel/Program.cs +++ b/src/Progmasoft.Tazel/Program.cs @@ -62,9 +62,9 @@ internal static class Program reporter.Diagnostic(diagnostic); return 1; } - catch (MicroVm.MicroVmException error) + catch (MicroVM.MicroVMException error) { - reporter.Error(ErrorCodes.MicroVm, error.Message, null, + reporter.Error(ErrorCodes.MicroVM, error.Message, null, "The sandbox stayed shut, and so did the door to your machine."); return 1; } diff --git a/src/Shared/MicroVmProtocol.cs b/src/Shared/MicroVMProtocol.cs similarity index 99% rename from src/Shared/MicroVmProtocol.cs rename to src/Shared/MicroVMProtocol.cs index aafe00d..689353d 100644 --- a/src/Shared/MicroVmProtocol.cs +++ b/src/Shared/MicroVMProtocol.cs @@ -9,7 +9,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; -namespace Progmasoft.Tazel.MicroVm; +namespace Progmasoft.Tazel.MicroVM; /// <summary>The kinds of message between Tazel and the agent of its MicroVM.</summary> internal enum MessageKind : byte @@ -49,7 +49,7 @@ internal sealed record RunRequest(IReadOnlyList<string> Arguments, IReadOnlyDict /// The messages of a MicroVM connection: a kind byte, a little-endian 32-bit length, and the payload. Strings are a /// length and UTF-8. It is the same file in Tazel and in the agent; no JSON library is needed on either side. /// </summary> -internal static class MicroVmProtocol +internal static class MicroVMProtocol { /// <summary>The vsock port the agent listens on.</summary> public const uint Port = 1024; diff --git a/tests/Progmasoft.Tazel.Tests/MicroVmTests.cs b/tests/Progmasoft.Tazel.Tests/MicroVMTests.cs similarity index 84% rename from tests/Progmasoft.Tazel.Tests/MicroVmTests.cs rename to tests/Progmasoft.Tazel.Tests/MicroVMTests.cs index 6005aa7..b07971f 100644 --- a/tests/Progmasoft.Tazel.Tests/MicroVmTests.cs +++ b/tests/Progmasoft.Tazel.Tests/MicroVMTests.cs @@ -10,12 +10,12 @@ using System.Linq; using System.Threading.Tasks; using Agent = guest::Progmasoft.Tazel.Guest.Agent; using Share = guest::Progmasoft.Tazel.Guest.Share; -using Progmasoft.Tazel.MicroVm; +using Progmasoft.Tazel.MicroVM; using Xunit; namespace Progmasoft.Tazel.Tests; -public sealed class MicroVmProtocolTests +public sealed class MicroVMProtocolTests { [Fact] public async Task ARunRequestCrossesTheConnectionUnchanged() @@ -23,22 +23,22 @@ public sealed class MicroVmProtocolTests var request = new RunRequest(["sh", "-c", "echo ü \"x\""], new Dictionary<string, string>(StringComparer.Ordinal) { ["PATH"] = "/usr/bin", ["EMPTY"] = "" }, "/work/my module"); using var stream = new MemoryStream(); - await MicroVmProtocol.WriteAsync(stream, MessageKind.Run, MicroVmProtocol.Encode(request), TestContext.Current.CancellationToken); + await MicroVMProtocol.WriteAsync(stream, MessageKind.Run, MicroVMProtocol.Encode(request), TestContext.Current.CancellationToken); stream.Position = 0; - var message = await MicroVmProtocol.ReadAsync(stream, TestContext.Current.CancellationToken); + var message = await MicroVMProtocol.ReadAsync(stream, TestContext.Current.CancellationToken); Assert.Equal(MessageKind.Run, message!.Value.Kind); - var read = MicroVmProtocol.DecodeRun(message.Value.Payload); + var read = MicroVMProtocol.DecodeRun(message.Value.Payload); Assert.Equal(request.Arguments, read.Arguments); Assert.Equal(request.Environment.OrderBy(e => e.Key), read.Environment.OrderBy(e => e.Key)); Assert.Equal(request.Directory, read.Directory); - Assert.Null(await MicroVmProtocol.ReadAsync(stream, TestContext.Current.CancellationToken)); + Assert.Null(await MicroVMProtocol.ReadAsync(stream, TestContext.Current.CancellationToken)); } [Fact] public void AStatusIsFourBytes() { - Assert.Equal(-1, MicroVmProtocol.DecodeStatus(MicroVmProtocol.EncodeStatus(-1))); - Assert.Throws<InvalidDataException>(() => MicroVmProtocol.DecodeStatus([1, 2])); + Assert.Equal(-1, MicroVMProtocol.DecodeStatus(MicroVMProtocol.EncodeStatus(-1))); + Assert.Throws<InvalidDataException>(() => MicroVMProtocol.DecodeStatus([1, 2])); } [Theory] @@ -47,14 +47,14 @@ public sealed class MicroVmProtocolTests public async Task ABrokenStreamIsRefused(byte[] bytes) { using var stream = new MemoryStream(bytes); - var error = await Assert.ThrowsAnyAsync<Exception>(() => MicroVmProtocol.ReadAsync(stream, TestContext.Current.CancellationToken)); + var error = await Assert.ThrowsAnyAsync<Exception>(() => MicroVMProtocol.ReadAsync(stream, TestContext.Current.CancellationToken)); Assert.True(error is InvalidDataException or EndOfStreamException, error.GetType().Name); } [Fact] public void ARunMessageWithBytesLeftOverIsRefused() => - Assert.Throws<InvalidDataException>(() => MicroVmProtocol.DecodeRun( - [.. MicroVmProtocol.Encode(new RunRequest(["x"], new Dictionary<string, string>(), "/")), 0])); + Assert.Throws<InvalidDataException>(() => MicroVMProtocol.DecodeRun( + [.. MicroVMProtocol.Encode(new RunRequest(["x"], new Dictionary<string, string>(), "/")), 0])); [Theory] [InlineData("/home/someone/my module")] @@ -62,7 +62,7 @@ public sealed class MicroVmProtocolTests [InlineData("/")] public void SharesNameTheirPathOnTheKernelCommandLine(string path) { - var shares = Share.Parse($"console=hvc0 tazel.share=s0,rw,{MicroVmProtocol.EncodePath(path)} quiet tazel.share=s1,ro,{MicroVmProtocol.EncodePath("/usr")}"); + var shares = Share.Parse($"console=hvc0 tazel.share=s0,rw,{MicroVMProtocol.EncodePath(path)} quiet tazel.share=s1,ro,{MicroVMProtocol.EncodePath("/usr")}"); Assert.Equal([new Share("s0", path, false), new Share("s1", "/usr", true)], shares); } @@ -83,20 +83,23 @@ public sealed class MicroVmProtocolTests Assert.False(agent.Inside("/work/module-other")); Assert.False(agent.Inside("/work/module/../other")); Assert.False(agent.Inside("/usr/bin")); + Assert.False(agent.Inside("relative/path")); + Assert.False(agent.Inside("/../work/module")); + Assert.True(agent.Inside("/work/./module/x/..")); } } -public sealed class MicroVmFilesTests +public sealed class MicroVMFilesTests { [Fact] public void AnImageThatDoesNotMatchItsSumsIsRefused() { using var image = new TemporaryModule().Write("vmlinux", "kernel").Write("initramfs.cpio.gz", "initramfs"); - Assert.Contains("has no SHA256SUMS", Assert.Throws<MicroVmException>(() => MicroVmFiles.CheckImage(image.Root)).Message, + Assert.Contains("has no SHA256SUMS", Assert.Throws<MicroVMException>(() => MicroVMFiles.CheckImage(image.Root)).Message, StringComparison.Ordinal); image.Write("SHA256SUMS", $"{Archive.Sha256Sums.Sha256(Path.Combine(image.Root, "vmlinux"))} vmlinux\n{new string('0', 64)} initramfs.cpio.gz\n"); - Assert.Contains("initramfs.cpio.gz does not match", Assert.Throws<MicroVmException>(() => MicroVmFiles.CheckImage(image.Root)).Message, + Assert.Contains("initramfs.cpio.gz does not match", Assert.Throws<MicroVMException>(() => MicroVMFiles.CheckImage(image.Root)).Message, StringComparison.Ordinal); } @@ -126,7 +129,7 @@ public sealed class MicroVmFilesTests /// <summary> /// The MicroVM itself, booted: on x86_64 Linux with KVM and an image named by TAZEL_MICROVM_IMAGE, as CI has them. /// </summary> -public sealed class MicroVmBootTests +public sealed class MicroVMBootTests { private static string? Unavailable() { diff --git a/tests/Progmasoft.Tazel.Tests/TemporaryModule.cs b/tests/Progmasoft.Tazel.Tests/TemporaryModule.cs index aea8149..029f185 100644 --- a/tests/Progmasoft.Tazel.Tests/TemporaryModule.cs +++ b/tests/Progmasoft.Tazel.Tests/TemporaryModule.cs @@ -57,9 +57,10 @@ internal sealed class TemporaryModule : IDisposable { Directory.Delete(Root, recursive: true); } - catch (IOException) + catch (Exception error) when (error is IOException or UnauthorizedAccessException) { - // A program a test started may still hold a file on Windows; the system's temporary directory keeps it. + // On Windows a program a test started, or a plugin the test process loaded, may still hold a file; the + // system's temporary directory keeps it. } } } diff --git a/tests/Progmasoft.Tazel.Tests/TextFileTests.cs b/tests/Progmasoft.Tazel.Tests/TextFileTests.cs index ad92a1b..424305b 100644 --- a/tests/Progmasoft.Tazel.Tests/TextFileTests.cs +++ b/tests/Progmasoft.Tazel.Tests/TextFileTests.cs @@ -90,10 +90,10 @@ public sealed class TazelOptionsTests microvm-cpus: "auto"; platform: macos-x86_64 """); - Assert.True(options.SandboxingWithMicrovm); - Assert.False(options.MicrovmNetwork); - Assert.Equal(new Allocation(2048), options.MicrovmMemory); - Assert.Equal(Allocation.Auto, options.MicrovmCpus); + Assert.True(options.SandboxingWithMicroVM); + Assert.False(options.MicroVMNetwork); + Assert.Equal(new Allocation(2048), options.MicroVMMemory); + Assert.Equal(Allocation.Auto, options.MicroVMCpus); Assert.Equal(Platform.MacOSX86_64, options.Platform); } @@ -117,7 +117,7 @@ public sealed class TazelOptionsTests module.Write("tazel_options.txt", "sandboxing-with-microvm: true;") .Write("inner/tazel_options.txt", "sandboxing-with-microvm: false; platform: linux-aarch64;"); var (options, file) = TazelOptionsFile.Effective(Path.Combine(module.Root, "inner")); - Assert.True(options.SandboxingWithMicrovm); + Assert.True(options.SandboxingWithMicroVM); Assert.Equal(Platform.LinuxAarch64, options.Platform); Assert.Equal(Path.Combine(module.Root, "tazel_options.txt"), file); }