tazel
A build system for C, C++, Objective-C, Objective-C++ and Zig, with C# project files.
Clonegit clone https://git.progmasoft.com/tazel
Measure the agent inside the MicroVM, and fix two ways a MicroVM was left running
- Commit
a9e85dd8a6d0d08848f1c735caa4c388e73529f7- Author
- Leitwolf11 ·
- Parents
09a1e0ce128d
Changes
.github/workflows/ci.yml | 18 +++--------- docs/microvm.md | 11 +++++++- dotnet-tools.json | 7 +++++ microvm/build.cs | 30 ++++++++++++++++---- microvm/guest-coverage.sh | 49 +++++++++++++++++++++++++++++++++ src/Progmasoft.Tazel.Guest/Agent.cs | 24 +++++++++++++++- src/Progmasoft.Tazel/MicroVM/Sandbox.cs | 35 ++++++++++++++++++++--- 7 files changed, 149 insertions(+), 25 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8e5d775..4415e43 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -493,21 +493,11 @@ jobs: path: ${{ runner.temp }}/microvm-work/linux-* key: microvm-kernel-${{ hashFiles('microvm/kernel.config', 'microvm/build.cs') }} - - name: Build the MicroVM image + # The image is built from an agent Coverlet instruments, the MicroVM tests boot it, and the agent's lines are + # measured inside the guest beside the host's (microvm/guest-coverage.sh). + - name: Build the MicroVM image, boot it and run commands inside shell: bash - run: dotnet run microvm/build.cs -- "$RUNNER_TEMP/microvm-work" "$RUNNER_TEMP/microvm-image" - - - name: Boot it and run commands inside - shell: bash - env: - TAZEL_MICROVM_IMAGE: ${{ runner.temp }}/microvm-image - 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' - --no-progress --coverlet --coverlet-output-format cobertura --results-directory artifacts/coverage + run: microvm/guest-coverage.sh "$RUNNER_TEMP/microvm-work" "$RUNNER_TEMP/microvm-image" artifacts/coverage/guest.cobertura.xml - name: Upload coverage if: always() diff --git a/docs/microvm.md b/docs/microvm.md index b47331e..1aea780 100644 --- a/docs/microvm.md +++ b/docs/microvm.md @@ -42,7 +42,8 @@ tazel ──vsock (Cloud Hypervisor's Unix socket, CONNECT 1024)──▶ tazel- - The guest kernel is a long-term Linux of kernel.org on top of `tinyconfig` with `microvm/kernel.config`: virtio (PCI, console, vsock, file system), PVH boot, no modules and no network device. - The initramfs holds `tazel-guest` (`src/Progmasoft.Tazel.Guest`), published self-contained for linux-musl and - trimmed, beside musl's loader, and the libraries of Alpine it needs (musl, libgcc, libstdc++). The kernel starts the + trimmed, beside musl's loader, and the libraries of Alpine it needs (musl, libgcc, libstdc++), with `/dev/console`, + `/dev/random` and `/dev/urandom`, which the agent needs before it mounts `/dev`. The kernel starts the 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. @@ -59,6 +60,14 @@ dotnet run microvm/build.cs -- <work directory> <output directory> TAZEL_MICROVM_IMAGE=<output directory> tazel custom <command> ``` +`--agent <directory>` takes an agent published elsewhere instead of publishing one. + +The agent runs only as the guest's first process, so its coverage is measured inside the guest: +`microvm/guest-coverage.sh <work directory> <output directory> <report>` publishes it with its symbols, has Coverlet +instrument it, builds the image from it and runs the MicroVM tests with `TAZEL_MICROVM_COVERAGE` naming the directory of +Coverlet's hits. Tazel shares that directory with the guest at the same path, and the agent runs the process-exit +handlers before it powers off, so Coverlet's are among them. CI runs it in the MicroVM job. + It needs make, a C compiler, flex, bison and bc for the kernel. Every download (the kernel and the three Alpine packages) is checked against the SHA-256 in `microvm/build.cs`, and the same inputs give the same bytes. diff --git a/dotnet-tools.json b/dotnet-tools.json index 152e946..5216595 100644 --- a/dotnet-tools.json +++ b/dotnet-tools.json @@ -15,6 +15,13 @@ "docfx" ], "rollForward": false + }, + "coverlet.console": { + "version": "10.1.1", + "commands": [ + "coverlet" + ], + "rollForward": false } } } \ No newline at end of file diff --git a/microvm/build.cs b/microvm/build.cs index 37f9925..2a28056 100644 --- a/microvm/build.cs +++ b/microvm/build.cs @@ -36,12 +36,15 @@ if (!OperatingSystem.IsLinux()) return 2; } -if (args.Length != 2) +// --agent takes an agent published elsewhere: the coverage job publishes it with its symbols and instruments it. +if (args is not ([_, _] or [_, _, "--agent", _])) { - Console.Error.WriteLine("usage: dotnet run microvm/build.cs -- <work directory> <output directory>"); + Console.Error.WriteLine("usage: dotnet run microvm/build.cs -- <work directory> <output directory> [--agent <published agent>]"); return 2; } +var published = args.Length == 4 ? Path.GetFullPath(args[3]) : null; + var repository = Path.GetFullPath(Path.Combine(AppContext.GetData("EntryPointFileDirectoryPath") as string ?? "microvm", "..")); var work = Path.GetFullPath(args[0]); var output = Path.GetFullPath(args[1]); @@ -76,8 +79,21 @@ if (Directory.Exists(root)) var agent = Path.Combine(root, "tazel", "agent"); var libraries = Path.Combine(root, "tazel", "lib"); Directory.CreateDirectory(libraries); -Run(repository, "dotnet", "publish", "src/Progmasoft.Tazel.Guest", "-c", "Release", "-r", "linux-musl-x64", "--self-contained", - "-p:PublishTrimmed=true", "-p:DebugType=none", "-o", agent); +if (published is null) +{ + Run(repository, "dotnet", "publish", "src/Progmasoft.Tazel.Guest", "-c", "Release", "-r", "linux-musl-x64", "--self-contained", + "-p:PublishTrimmed=true", "-p:DebugType=none", "-o", agent); +} +else +{ + Directory.CreateDirectory(agent); + foreach (var file in Directory.EnumerateFiles(published, "*", SearchOption.AllDirectories)) + { + var to = Path.Combine(agent, Path.GetRelativePath(published, file)); + Directory.CreateDirectory(Path.GetDirectoryName(to)!); + File.Copy(file, to, overwrite: true); + } +} var unpacked = Path.Combine(work, "alpine"); foreach (var (file, sha) in packages) { @@ -172,7 +188,9 @@ static string CultureInvariant(FormattableString text) => FormattableString.Inva /// <summary> /// The "newc" cpio format the kernel unpacks: files sorted by path, owned by root, dated at the epoch, with -/// /dev/console as a device, so the agent has a console before it mounts /dev. +/// /dev/console, /dev/random and /dev/urandom as devices, so the agent has a console and random bytes before it mounts +/// /dev: .NET reads /dev/urandom for them, and the first Guid of a process (Coverlet's, in the coverage job) comes +/// before any line of the agent. /// </summary> [System.Runtime.Versioning.SupportedOSPlatform("linux")] static class Cpio @@ -198,6 +216,8 @@ static class Cpio if (name == "dev") { Entry(stream, inode++, "dev/console", 0x2000 | 0x180, [], 5, 1); + Entry(stream, inode++, "dev/random", 0x2000 | 0x1B6, [], 1, 8); + Entry(stream, inode++, "dev/urandom", 0x2000 | 0x1B6, [], 1, 9); } } else diff --git a/microvm/guest-coverage.sh b/microvm/guest-coverage.sh new file mode 100755 index 0000000..f3ab351 --- /dev/null +++ b/microvm/guest-coverage.sh @@ -0,0 +1,49 @@ +#!/bin/bash +# SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +# SPDX-License-Identifier: MIT + +# The coverage of the agent, which runs only as the first process of the MicroVM's guest. +# +# The agent is published with its symbols and without trimming, and Coverlet instruments it. The MicroVM image is built +# from that agent and the MicroVM tests boot it; the guest sees the directory Coverlet writes its hits to at the same +# path (TAZEL_MICROVM_COVERAGE), and the agent runs Coverlet's exit handlers before it powers off. Coverlet writes the +# report once the tests end. +# +# Usage: microvm/guest-coverage.sh <work directory> <output directory for the image> <coverage report> +# Coverlet runs the second stage itself: microvm/guest-coverage.sh --boot <work> <image> <agent> <hits> +set -euo pipefail +repository=$(cd "$(dirname "$0")/.." && pwd) +cd "$repository" + +if [ "${1:-}" = "--boot" ]; then + work=$2 image=$3 agent=$4 hits=$5 + # The hits path is fixed when Coverlet instruments; the tests keep the temporary directory of the caller, so their + # modules are not under the directory the guest shares for the hits. + export TMPDIR="$GUEST_COVERAGE_TMPDIR" + dotnet run microvm/build.cs -- "$work" "$image" --agent "$agent" + # The host's side of the same tests is measured as well, next to the agent's report. + TAZEL_MICROVM_IMAGE="$image" TAZEL_MICROVM_COVERAGE="$hits" TAZEL_REQUIRE_MICROVM=1 \ + dotnet test --project tests/Progmasoft.Tazel.Tests -c Release --no-build \ + --filter-class Progmasoft.Tazel.Tests.MicroVMBootTests --filter-class Progmasoft.Tazel.Tests.MicroVMProtocolTests \ + --filter-class Progmasoft.Tazel.Tests.MicroVMFilesTests \ + --coverlet --coverlet-output-format cobertura --results-directory "$GUEST_COVERAGE_RESULTS" + exit +fi + +work=$(realpath -m "$1") +image=$(realpath -m "$2") +report=$(realpath -m "$3") +agent="$work/agent-coverage" +hits="$work/coverage-hits" +rm -rf "$agent" "$hits" +mkdir -p "$hits" "$(dirname "$report")" + +dotnet tool restore +dotnet publish src/Progmasoft.Tazel.Guest -c Release -r linux-musl-x64 --self-contained \ + -p:PublishTrimmed=false -p:DebugType=portable -o "$agent" +dotnet build tests/Progmasoft.Tazel.Tests -c Release + +# Coverlet names its hits file under the temporary directory: here, the directory the guest shares. The paths hold no +# spaces (realpath of the arguments, chosen by the caller), so the target's arguments need no quoting. +GUEST_COVERAGE_RESULTS=$(dirname "$report") GUEST_COVERAGE_TMPDIR="${TMPDIR:-/tmp}" TMPDIR="$hits" dotnet coverlet "$agent" --include '[tazel-guest]*' --format cobertura --output "$report" \ + --target "$repository/microvm/guest-coverage.sh" --targetargs "--boot $work $image $agent $hits" diff --git a/src/Progmasoft.Tazel.Guest/Agent.cs b/src/Progmasoft.Tazel.Guest/Agent.cs index 1f6e1e0..4d15608 100644 --- a/src/Progmasoft.Tazel.Guest/Agent.cs +++ b/src/Progmasoft.Tazel.Guest/Agent.cs @@ -123,15 +123,37 @@ internal sealed class Agent(IReadOnlyList<Share> shares) off.Wait(); } - /// <summary>Writes everything out and powers off; the monitor ends with the machine.</summary> + /// <summary> + /// Runs the process-exit handlers, writes everything out and powers off; the monitor ends with the machine. As the + /// first process the agent never exits, so the handlers a normal exit runs (among them those of Coverlet, which + /// write the lines the agent ran) run here. + /// </summary> [System.Runtime.Versioning.SupportedOSPlatform("linux")] public static void PowerOff() { + RunExitHandlers(); Libc.Sync(); _ = Libc.Reboot(Libc.RebootPowerOff); Thread.Sleep(Timeout.Infinite); } + /// <summary>Raises <see cref="AppDomain.ProcessExit"/> as the runtime does when a process exits.</summary> + [System.Diagnostics.CodeAnalysis.DynamicDependency("OnProcessExit", typeof(AppContext))] + internal static void RunExitHandlers() + { + var onProcessExit = typeof(AppContext).GetMethod("OnProcessExit", + System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static); + try + { + onProcessExit?.Invoke(null, null); + } + catch (System.Reflection.TargetInvocationException error) + { + // A handler that fails does not keep the machine on. + Console.Error.WriteLine($"tazel-guest: an exit handler failed: {error.InnerException?.Message}"); + } + } + /// <summary>The program <paramref name="name"/> names: itself when it has a slash, else the first on <paramref name="path"/>.</summary> [System.Runtime.Versioning.SupportedOSPlatform("linux")] public static string? Find(string name, string path) diff --git a/src/Progmasoft.Tazel/MicroVM/Sandbox.cs b/src/Progmasoft.Tazel/MicroVM/Sandbox.cs index ef89495..29bef81 100644 --- a/src/Progmasoft.Tazel/MicroVM/Sandbox.cs +++ b/src/Progmasoft.Tazel/MicroVM/Sandbox.cs @@ -66,10 +66,17 @@ internal sealed class Sandbox : IAsyncDisposable var runtime = Directory.CreateTempSubdirectory("tazel-microvm-").FullName; File.SetUnixFileMode(runtime, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); var daemons = new List<Process>(); + Process? started = null; try { - // The guest's /usr is the host's, read-only, and its /etc a few files of Tazel's. - var all = new List<SharedDirectory>(shares) { new("/usr", ReadOnly: true), new(WriteEtc(runtime), ReadOnly: true) }; + // The guest's /usr is the host's, read-only, and its /etc a few files of Tazel's; /etc stays last. + var all = new List<SharedDirectory>(shares) { new("/usr", ReadOnly: true) }; + if (CoverageDirectory() is { } coverage) + { + all.Add(new SharedDirectory(coverage, ReadOnly: false)); + } + + all.Add(new SharedDirectory(WriteEtc(runtime), ReadOnly: true)); var command = new StringBuilder("console=hvc0 quiet panic=0 rdinit=/tazel/agent/ld-musl-x86_64.so.1"); var arguments = new List<string>(); for (var i = 0; i < all.Count; i++) @@ -109,6 +116,7 @@ internal sealed class Sandbox : IAsyncDisposable } var monitor = Process.Start(start) ?? throw new MicroVMException($"{files.Monitor} could not be started"); + started = monitor; monitor.StandardInput.Close(); var sandbox = new Sandbox(runtime, monitor, vsock, console); sandbox._daemons.AddRange(daemons); @@ -117,6 +125,13 @@ internal sealed class Sandbox : IAsyncDisposable } catch { + // A machine that did not become ready is stopped with what shares its directories. + if (started is not null) + { + Kill(started); + started.Dispose(); + } + foreach (var daemon in daemons) { Kill(daemon); @@ -203,6 +218,17 @@ internal sealed class Sandbox : IAsyncDisposable } } + /// <summary> + /// The directory named by <c>TAZEL_MICROVM_COVERAGE</c>, shared for writing at the same path: an agent built with + /// Coverlet's instrumentation writes the lines it ran there before it powers off, and the coverage job of Tazel's CI + /// reads them. Null when the variable is not set or names no directory. + /// </summary> + internal static string? CoverageDirectory() => + System.Environment.GetEnvironmentVariable("TAZEL_MICROVM_COVERAGE") is { Length: > 0 } directory && + Path.IsPathFullyQualified(directory) && Directory.Exists(directory) + ? Path.GetFullPath(directory) + : null; + private static string WriteEtc(string runtime) { var etc = Path.Combine(runtime, "etc"); @@ -284,9 +310,10 @@ internal sealed class Sandbox : IAsyncDisposable } } } - catch (Exception error) when (error is MicroVMException or IOException or SocketException) + catch (Exception error) when (error is MicroVMException or IOException or SocketException || + (error is OperationCanceledException && !cancel.IsCancellationRequested)) { - // The agent is not listening yet. + // The agent is not listening yet, or a try took longer than its second. } await Task.Delay(100, cancel).ConfigureAwait(false);