diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 5785296..272cda4 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -16,6 +16,14 @@ jobs: 8.0.x 10.0.x - run: dotnet build Bowl.slnx -c Release + - if: runner.os == 'Windows' + shell: pwsh + run: | + & .\src\Bowl.Host\bin\Release\net8.0\Applications\Windows\procdump64.exe -accepteula -? + if ((Get-ItemProperty 'HKCU:\Software\Sysinternals\ProcDump').EulaAccepted -ne 1) { + throw 'ProcDump license acceptance was not recorded.' + } + $global:LASTEXITCODE = 0 - run: dotnet test Bowl.slnx -c Release --no-build - if: runner.os == 'Windows' shell: pwsh diff --git a/README.md b/README.md index 57643bd..4750f8a 100644 --- a/README.md +++ b/README.md @@ -11,10 +11,10 @@ This repository contains two independently usable components: | `src\Bowl.Host` | .NET 8 | Versioned disk protocol, updater/application supervision, optional rollback and persistent HTTP outbox | | `src\GeneralUpdate.Bowl` | .NET Standard 2.0 | Existing diagnostic library, platform strategies, procdump integration and `BowlContext.OnCrash` callback | -The host has no GeneralUpdate project/source dependency and does not depend on -procdump. It records metadata by default and never collects or uploads dumps. -The library remains available for applications explicitly opting into richer -diagnostics; its tool-success result does **not** establish application health. +The host records metadata by default. An explicit v1 request option enables +best-effort Windows mini-dump capture using GeneralUpdate.Bowl and the bundled +procdump; the host never uploads crash artifacts. The diagnostic tool result +does **not** establish application health. ## Build, test and deploy @@ -43,7 +43,9 @@ GeneralUpdate's `Monitoring.Enabled` is opt-in. Set `ExecutablePath` to the host `DiagnosticsDirectory` to a durable protected state root, and explicitly choose `AutoRollback` and `VerifyLaunch`. If enabled monitoring cannot become ready, the updater aborts before file modification. No dump is required to detect an -abnormally terminated updater or failed application startup. +abnormally terminated updater or failed application startup. Crash collection is +a separate opt-in and requires a GeneralUpdate client configured to scan the +state-root crash outbox. See [the complete protocol and operations guide](docs/protocol-v1.md). diff --git a/docs/migration-manifest.csv b/docs/migration-manifest.csv index 5e3f527..50b67dc 100644 --- a/docs/migration-manifest.csv +++ b/docs/migration-manifest.csv @@ -28,7 +28,7 @@ "src/GeneralUpdate.Bowl/Strategies/IBowlStrategy.cs","f18d0ece481e04867ba731f8711520123b97fc30","1253","ce0708f309c9056d29fe6161d53ef46a7e9f7fb5cbd81feb09b5a85a1041a510","ce0708f309c9056d29fe6161d53ef46a7e9f7fb5cbd81feb09b5a85a1041a510" "src/GeneralUpdate.Bowl/Strategies/LinuxBowlStrategy.cs","c72a75bd24f7717159c574670b9e0def1aa9e7b2","9944","02dfe4fe9598c8872251da6f9fec3a3a0135d939f699e5e17e5ae70ca12a7fa7","02dfe4fe9598c8872251da6f9fec3a3a0135d939f699e5e17e5ae70ca12a7fa7" "src/GeneralUpdate.Bowl/Strategies/ProcessExitResult.cs","26615802a835e19a96d2b6b9a5a38a0454020612","436","236bfb4043711d3ee223f39fa229e3465eec1156056694c5d3ceb3b33a50c1d4","236bfb4043711d3ee223f39fa229e3465eec1156056694c5d3ceb3b33a50c1d4" -"src/GeneralUpdate.Bowl/Strategies/ProcessRunner.cs","e988378c3a01ffa7df899c7364a2be49c254a0d1","3874","7f8588283b884bcd760b677fe2d3dd19aceb3b181a32e3a1d5080cb0e36cbe7a","7f8588283b884bcd760b677fe2d3dd19aceb3b181a32e3a1d5080cb0e36cbe7a" +"src/GeneralUpdate.Bowl/Strategies/ProcessRunner.cs","e988378c3a01ffa7df899c7364a2be49c254a0d1","3874","7f8588283b884bcd760b677fe2d3dd19aceb3b181a32e3a1d5080cb0e36cbe7a","2f3e04c3dca0dd0a286871b00c7d123d44598fe5cbf09357eb70c2b9e22f3aae" "src/GeneralUpdate.Bowl/Strategies/StrategyFactory.cs","a38ef0f67de6739740c57e235959cc0958ccb4ce","917","2dc189b4059b6c0de62379bc4e5fc01c3ea9383ce5b1989e445b73aded7ecc6a","0eba66e306d30bad882399f2b08399b2a00e24c57cb2b9b4ddb081e12ba6bff6" "src/GeneralUpdate.Bowl/Strategies/WindowsBowlStrategy.cs","52c321de7be274bf27bb77d11939ee8c1e70e0e0","2395","67c5296557666ca63cf7f8f3ac846fda5bedc03532051a0dc1e543b35d781c15","0c8fd298c17db75472c1628b08d75470a490d0c55f2dc140de6c0128fe447d31" "src/GeneralUpdate.Bowl/Tracer/GeneralTracer.cs","11084795534480d2426faedf7e486b70c8053c0e","4963","411e4bd5db32487102b418d690ed04c395531d2d18e56066f530b59b95cad25e","9ff850c6c2ca5a704765d016d8becc8e92f66b6f7128a51e1b882e10b14cd64b" diff --git a/docs/migration.md b/docs/migration.md index 7f2e757..cf85abb 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -34,6 +34,7 @@ Intentional edits to imported files: | `src\GeneralUpdate.Bowl\BowlContext.cs` | `Normalize()` default work model is now `"Normal"` — recovery semantics (`Upgrade` + `AutoRestore`) are an explicit opt-in; the restore decision belongs to the update pipeline (Core RollbackManager) | | `src\GeneralUpdate.Bowl\Strategies\StrategyFactory.cs` | Added `CreateWithFallback(out WatcherTier)` three-tier watcher probing (procdump → runtime createdump → exit-code fallback) for the console supervisor; `Create()` and the embedded single-shot API are unchanged | | `src\GeneralUpdate.Bowl\Strategies\WindowsBowlStrategy.cs` | Resolve procdump from the watchdog directory before the target installation | +| `src\GeneralUpdate.Bowl\Strategies\ProcessRunner.cs` | Drain asynchronous output handlers before returning the process output | | `src\GeneralUpdate.Bowl\Applications\Windows\export.bat` | Accept the evidence directory via a per-process environment variable or manual argument | | `src\GeneralUpdate.Bowl\Internal\WindowsSystemInfoProvider.cs` | Launch export with a child-specific working directory and environment | | `src\GeneralUpdate.Bowl\Tracer\GeneralTracer.cs` | Fall back to console logging when file initialization or rotation fails | @@ -47,7 +48,7 @@ Intentional edits to imported files: New files added alongside the import (not part of the 61 migrated entries): `src\GeneralUpdate.Bowl\InternalsVisibleTo.cs` (friend assemblies `bowl` and -`Bowl.Console.Tests`), `src\GeneralUpdate.Bowl\Strategies\WatcherTier.cs`, +`Bowl.Console.Tests` and `Bowl.Host`), `src\GeneralUpdate.Bowl\Strategies\WatcherTier.cs`, `src\GeneralUpdate.Bowl\Strategies\ExitCodeWatcherStrategy.cs`, `src\GeneralUpdate.Bowl\Strategies\CreatedumpStrategy.cs`, and the console project `src\GeneralUpdate.Bowl.Console` with its test project @@ -67,9 +68,10 @@ references. The original .NET Standard library, callbacks, strategies and tests remain compatible. `Bowl.slnx`, independent test dependency versions, host tests, CI and root documentation provide standalone build/test/publish entry points. -The host's default metadata-only diagnostics intentionally do not run bundled -procdump or export system information. Optional legacy diagnostics remain an -explicit caller choice; no-dump results do not establish health. +The host's default metadata-only diagnostics do not run bundled procdump or +export system information. The separate opt-in Windows capture now uses the +library and bundled procdump as described in `protocol-v1.md`; no-dump results +do not establish health. ## Validation and removal gate diff --git a/docs/protocol-v1.md b/docs/protocol-v1.md index 4bc4ded..f510e36 100644 --- a/docs/protocol-v1.md +++ b/docs/protocol-v1.md @@ -25,6 +25,7 @@ Each attempt uses `\attempts\\`: | `result.json` | Bowl | Durable decision and recovery journal | | `outbox.json` | Bowl | One stable terminal event and delivery state | | `host.lock` | Bowl | Exclusive attempt owner, held open | +| `capture-status.json` | Bowl | Optional local capture status, not an update verdict | `locks\.lock` coordinates attempts for the same installation. Its `.owner.json` sidecar records the latest owning attempt @@ -66,6 +67,7 @@ and staging locations). Never include it in packages or restoration scopes. "healthTimeoutSeconds": 5, "updateTimeoutSeconds": 600, "autoRollback": false, + "crashCollectionEnabled": false, "report": { "url": "https://updates.example.test/report", "recordId": 42, @@ -105,6 +107,12 @@ Stages: `preparing`, `filesApplying`, `filesApplied`, `launching`, - Invalid/missing protocol data or inaccessible observation is `monitorUnavailable`, not an application failure. + `crashCollectionEnabled` defaults to false. When true, `targetVersion` must be a + nonempty safe single directory name (at most 128 characters; no separators, + control characters, Windows reserved characters or device names, or trailing + space/dot). Invalid configuration is rejected before readiness. Collection and + upload must be separately authorized; enabling supervision alone does neither. + `processAlive` means process survival, **not business health**. No `health.json` signal is part of v1. No dump is ever used as success evidence. @@ -122,7 +130,7 @@ signal is part of v1. No dump is ever used as success evidence. | `currentVersion`, `targetVersion` | Copied immutable request versions | | `observedAtUtc` | Decision timestamp | | `error` | Original structured producer failure, or monitoring exception type | -| `diagnostics` | `metadataOnly`; no implicit dump/system-information capture | +| `diagnostics` | `metadataOnly`; describes this result record, not the separate opt-in crash outbox | | `rollback` | `notRequested`, `pending`, `inProgress`, `deferred`, `succeeded`, `failed` | | `rollbackError` | Bounded error classification, never credentials or response body | @@ -180,7 +188,7 @@ Only after recovery settles does Bowl create `outbox.json`: `monitorUnavailable` are local-only, never fake network acknowledgements. The HTTP JSON shape is exactly `recordId`, `status`, `type`; status remains 2 Success / 3 Failure, type remains 1 poll / 2 push. Structured diagnostics and -dumps are never uploaded. `Idempotency-Key` carries the stable event ID; a +dumps are never uploaded by this HTTP outbox. `Idempotency-Key` carries the stable event ID; a legacy server can ignore it, so delivery is **at least once**, not exactly once. Each invocation sends at most once per eligible attempt. Before sending, persist @@ -216,9 +224,48 @@ fragment. Never put secrets on the command line, in a URL or in the request. Provision host credentials separately; Update's in-process HTTP callbacks cannot cross the process boundary. -Protect local paths, stack traces and binaries with ACLs. The existing diagnostic -library and bundled procdump tools are a separate explicit opt-in, not a host -startup dependency. No full dump upload option is enabled by this protocol. +## Optional crash evidence + +Only when `crashCollectionEnabled` is true, the Windows host asks the bundled +GeneralUpdate.Bowl procdump strategy to attach to the exact updater identity and, +once available, the exact application identity. It checks PID and start time +and holds a process handle, never searches by name. Capture is best-effort: +attach can miss a fast exit, require permissions or a previously accepted tool +license, or fail because the tool is unavailable. The host monitors only the +v1 update and startup-survival window, not the application's later lifetime. +Other platforms explicitly report capture unavailable. A missing dump is not +proof of health, a crash or a failed update. No system-info export, automatic +restore or crash hook is run by the diagnostic library. + +A successful, nonempty **mini dump** and GeneralUpdate.Bowl crash report are +flushed into a staging directory beneath +`\crash-outbox\`; a schema 2 manifest is written +last, then the whole directory is atomically renamed to a new canonical GUID. +The manifest has `schema`, `guid`, `kind:"crash"`, `targetName`, `version`, +`exitCode:null`, `createdAtUtc`, `files:["crash.json","crash.dmp"]`, +`state:"pending"` and `attempts:0`. No case is published without both complete +files. Core Client owns uploading, retries and acknowledged-case deletion; +the host neither uploads nor mutates a published case. The state root is outside +the installation and backup trees, so rollback cannot erase pending cases. + +The attempt's `capture-status.json` records per-target `capturing`, `published`, +`noDump`, `unavailable` or `interrupted`. `noDump` does not distinguish a normal +exit from tool failure. Capture errors are also logged to stderr and +never change the v1 outcome or rollback. The host waits at most three seconds +for evidence after a failed observation, then sends a console interrupt to each +owned ProcDump so it can detach without terminating the monitored process; an owned +Windows job closes them if the host exits. An abrupt host exit or failed graceful +detach can therefore terminate a process that ProcDump is debugging. A crash or failure before publication +can leave a non-GUID `.partial` directory: it is not scanned or automatically +retried or deleted. Operators must inspect it and securely remove or archive it; +restarting an already completed attempt cannot recreate an unattached dump. +Published cases remain pending until Client succeeds; configure and monitor +Client's retry schedule and disk capacity. No host GC evicts pending evidence. + +Mini dumps and crash reports can contain sensitive memory, paths and process +details. Protect the entire state root with restrictive ACLs, provision enough +disk space, and disclose both collection and Client upload to the operator. +These guarantees assume trusted local writers and atomic rename on local storage. For `--attempt`, exit 0 means supervised application/file success; exit 1 means a recorded non-success; exit 2 means invocation/ownership/storage failure or diff --git a/scripts/Verify-Migration.ps1 b/scripts/Verify-Migration.ps1 index 603f215..a692f8c 100644 --- a/scripts/Verify-Migration.ps1 +++ b/scripts/Verify-Migration.ps1 @@ -9,6 +9,7 @@ try { 'src/GeneralUpdate.Bowl/Applications/Windows/export.bat', 'src/GeneralUpdate.Bowl/Internal/WindowsSystemInfoProvider.cs', 'src/GeneralUpdate.Bowl/Strategies/WindowsBowlStrategy.cs', + 'src/GeneralUpdate.Bowl/Strategies/ProcessRunner.cs', 'src/GeneralUpdate.Bowl/Strategies/StrategyFactory.cs', 'src/GeneralUpdate.Bowl/Tracer/GeneralTracer.cs', 'src/GeneralUpdate.Bowl/Tracer/TextTraceListener.cs', diff --git a/src/Bowl.Host/Bowl.Host.csproj b/src/Bowl.Host/Bowl.Host.csproj index 4772898..a9f8b6a 100644 --- a/src/Bowl.Host/Bowl.Host.csproj +++ b/src/Bowl.Host/Bowl.Host.csproj @@ -11,6 +11,7 @@ https://github.com/GeneralLibrary/Bowl + diff --git a/src/Bowl.Host/CaptureConsole.cs b/src/Bowl.Host/CaptureConsole.cs new file mode 100644 index 0000000..5149d03 --- /dev/null +++ b/src/Bowl.Host/CaptureConsole.cs @@ -0,0 +1,31 @@ +using System.ComponentModel; +using System.Runtime.InteropServices; + +namespace Bowl.Host; + +internal static class CaptureConsole +{ + public static void Stop(int pid) + { + if (!FreeConsole() || !AttachConsole((uint)pid)) + throw new Win32Exception(Marshal.GetLastWin32Error()); + if (!SetConsoleCtrlHandler(IntPtr.Zero, true) || !GenerateConsoleCtrlEvent(0, 0)) + throw new Win32Exception(Marshal.GetLastWin32Error()); + } + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool FreeConsole(); + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool AttachConsole(uint processId); + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool SetConsoleCtrlHandler(IntPtr handler, bool add); + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool GenerateConsoleCtrlEvent(uint controlEvent, uint processGroupId); +} diff --git a/src/Bowl.Host/CaptureJob.cs b/src/Bowl.Host/CaptureJob.cs new file mode 100644 index 0000000..6ef4b1c --- /dev/null +++ b/src/Bowl.Host/CaptureJob.cs @@ -0,0 +1,80 @@ +using System.ComponentModel; +using System.Diagnostics; +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; + +namespace Bowl.Host; + +internal sealed class CaptureJob(SafeFileHandle handle) : IDisposable +{ + public static CaptureJob Create() + { + var handle = CreateJobObject(IntPtr.Zero, null); + if (handle.IsInvalid) + { + var error = Marshal.GetLastWin32Error(); + handle.Dispose(); + throw new Win32Exception(error); + } + var limits = new ExtendedLimitInformation + { + BasicLimitInformation = new BasicLimitInformation { LimitFlags = 0x2000 } + }; + if (!SetInformationJobObject(handle, 9, ref limits, (uint)Marshal.SizeOf())) + { + var error = Marshal.GetLastWin32Error(); + handle.Dispose(); + throw new Win32Exception(error); + } + return new CaptureJob(handle); + } + + public void Assign(Process process) + { + if (!AssignProcessToJobObject(handle, process.Handle)) + throw new Win32Exception(Marshal.GetLastWin32Error()); + } + + public void Dispose() => handle.Dispose(); + + [StructLayout(LayoutKind.Sequential)] + private struct BasicLimitInformation + { + public long PerProcessUserTimeLimit; + public long PerJobUserTimeLimit; + public uint LimitFlags; + public UIntPtr MinimumWorkingSetSize; + public UIntPtr MaximumWorkingSetSize; + public uint ActiveProcessLimit; + public UIntPtr Affinity; + public uint PriorityClass; + public uint SchedulingClass; + } + + [StructLayout(LayoutKind.Sequential)] + private struct IoCounters + { + public ulong ReadOperationCount, WriteOperationCount, OtherOperationCount; + public ulong ReadTransferCount, WriteTransferCount, OtherTransferCount; + } + + [StructLayout(LayoutKind.Sequential)] + private struct ExtendedLimitInformation + { + public BasicLimitInformation BasicLimitInformation; + public IoCounters IoInfo; + public UIntPtr ProcessMemoryLimit, JobMemoryLimit, PeakProcessMemoryUsed, PeakJobMemoryUsed; + } + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern SafeFileHandle CreateJobObject(IntPtr attributes, string? name); + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool SetInformationJobObject(SafeFileHandle job, int informationClass, + ref ExtendedLimitInformation information, uint length); + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool AssignProcessToJobObject(SafeFileHandle job, IntPtr process); +} diff --git a/src/Bowl.Host/CrashCollection.cs b/src/Bowl.Host/CrashCollection.cs new file mode 100644 index 0000000..31ffac9 --- /dev/null +++ b/src/Bowl.Host/CrashCollection.cs @@ -0,0 +1,250 @@ +using System.ComponentModel; +using System.Collections.Concurrent; +using System.Diagnostics; +using System.Text.Json; +using GeneralUpdate.Bowl; +using GeneralUpdate.Bowl.Internal; +using GeneralUpdate.Bowl.Strategies; + +namespace Bowl.Host; + +// Diagnostic capture is independent of the v1 outcome and recovery journal. +internal sealed class CrashCollection(string root, Request request) +{ + private readonly List<(CancellationTokenSource Cancel, Task Work)> sessions = []; + private readonly HashSet started = []; + private readonly ConcurrentDictionary states = new(); + + internal static bool SafeVersion(string? version) + { + if (string.IsNullOrWhiteSpace(version) || version.Length > 128 || + version is "." or ".." || version.EndsWith(' ') || version.EndsWith('.') || + version.Any(c => char.IsControl(c) || "<>:\"/\\|?*".Contains(c))) + return false; + var stem = version.Split('.')[0].TrimEnd(' '); + if (stem.Equals("CON", StringComparison.OrdinalIgnoreCase) || + stem.Equals("PRN", StringComparison.OrdinalIgnoreCase) || + stem.Equals("AUX", StringComparison.OrdinalIgnoreCase) || + stem.Equals("NUL", StringComparison.OrdinalIgnoreCase)) + return false; + return !(stem.Length == 4 && + (stem.StartsWith("COM", StringComparison.OrdinalIgnoreCase) || + stem.StartsWith("LPT", StringComparison.OrdinalIgnoreCase)) && + (stem[3] is >= '1' and <= '9' or '\u00b9' or '\u00b2' or '\u00b3')); + } + + public void Start(ProcessIdentity identity) + { + if (!request.CrashCollectionEnabled || !started.Add(identity)) + return; + states[identity] = "capturing"; + var cancel = new CancellationTokenSource(); + sessions.Add((cancel, Task.Run(() => CaptureAsync(identity, cancel.Token)))); + } + + public CaptureStatus Status() => new() + { + AttemptId = request.AttemptId, + Targets = states.Select(entry => new CaptureTargetStatus(entry.Key, entry.Value)).ToArray() + }; + + public async Task StopAsync(bool failure) + { + if (failure && sessions.Count != 0) + await Task.WhenAny(Task.WhenAll(sessions.Select(s => s.Work)), Task.Delay(TimeSpan.FromSeconds(3))); + foreach (var session in sessions) + session.Cancel.Cancel(); + var all = Task.WhenAll(sessions.Select(s => s.Work)); + if (await Task.WhenAny(all, Task.Delay(TimeSpan.FromSeconds(3))) != all) + Console.Error.WriteLine("Crash collection did not stop in time; partial evidence requires inspection."); + else + { + await all; + foreach (var session in sessions) + session.Cancel.Dispose(); + } + } + + private async Task CaptureAsync(ProcessIdentity identity, CancellationToken token) + { + string? staging = null; + try + { + token.ThrowIfCancellationRequested(); + if (!OperatingSystem.IsWindows()) + throw new PlatformNotSupportedException("Host crash capture requires Windows procdump."); + if (identity.Pid == Environment.ProcessId) + throw new InvalidDataException("Host cannot capture itself."); + using var target = Process.GetProcessById(identity.Pid); + _ = target.Handle; + if (target.HasExited || !Processes.SameProcessStart(target.StartTime.ToUniversalTime(), identity.StartTimeUtc)) + throw new InvalidDataException("Capture target identity is unavailable."); + var targetName = Path.GetFileName(target.MainModule?.FileName); + if (string.IsNullOrWhiteSpace(targetName)) + throw new InvalidDataException("Capture target name is unavailable."); + + var versionRoot = Path.Combine(root, "crash-outbox", request.TargetVersion!); + Paths.NoLinks(versionRoot); + Directory.CreateDirectory(versionRoot); + var guid = Guid.NewGuid().ToString("D"); + staging = Path.Combine(versionRoot, "." + request.AttemptId + "-" + guid + ".partial"); + Paths.NoLinks(staging); + Directory.CreateDirectory(staging); + var context = new BowlContext + { + ProcessNameOrId = identity.Pid.ToString(System.Globalization.CultureInfo.InvariantCulture), + DumpFileName = "crash.dmp", + FailFileName = "crash.json", + TargetPath = request.InstallPath, + FailDirectory = staging, + BackupDirectory = string.Empty, + WorkModel = "Normal", + ExtendedField = request.TargetVersion!, + DumpType = DumpType.Mini, + AutoRestore = false + }; + GeneralTracer.SetTracingEnabled(false); + var info = new WindowsBowlStrategy().Prepare(context) + ?? throw new InvalidOperationException("Capture tool unavailable."); + if (!Paths.Contains(Paths.Absolute(AppContext.BaseDirectory), Path.GetFullPath(info.FileName))) + throw new InvalidDataException("Capture tool must be deployed with the host."); + Paths.NoLinks(info.FileName); + if (!File.Exists(info.FileName)) + throw new FileNotFoundException("Capture tool unavailable."); + token.ThrowIfCancellationRequested(); + if (target.HasExited || !Processes.SameProcessStart(target.StartTime.ToUniversalTime(), identity.StartTimeUtc)) + throw new InvalidDataException("Capture target exited before attach."); + using var job = CaptureJob.Create(); + using var tool = Process.Start(info) ?? throw new InvalidOperationException("Capture tool failed to start."); + try { job.Assign(tool); } + catch (Win32Exception) + { + if (!tool.HasExited) + tool.Kill(); + throw; + } + var stdout = tool.StandardOutput.BaseStream.CopyToAsync(Stream.Null); + var stderr = tool.StandardError.BaseStream.CopyToAsync(Stream.Null); + var exit = tool.WaitForExitAsync(); + var canceled = Task.Delay(Timeout.InfiniteTimeSpan, token); + if (await Task.WhenAny(exit, canceled) == canceled && !tool.HasExited) + await StopToolAsync(tool); + await exit; + await Task.WhenAll(stdout, stderr); + token.ThrowIfCancellationRequested(); + var dump = Path.Combine(staging, context.DumpFileName); + Paths.NoLinks(dump); + if (tool.ExitCode == 0 && !File.Exists(dump)) + { + states[identity] = "noDump"; + Console.Error.WriteLine("Crash capture finished without a dump; the cause is unknown."); + return; + } + if (!DumpSucceeded(tool.ExitCode, dump)) + { + Console.Error.WriteLine($"Crash capture produced no complete dump (tool exit {tool.ExitCode})."); + throw new InvalidOperationException("Crash capture did not produce a complete dump."); + } + + await new CrashReporter().GenerateReportAsync(context, Array.Empty(), token); + Publish(staging, guid, targetName, request.TargetVersion!); + staging = null; + states[identity] = "published"; + } + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + states[identity] = "interrupted"; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or + InvalidOperationException or Win32Exception or ArgumentException or NotSupportedException or + System.Security.SecurityException or JsonException or TypeInitializationException) + { + states[identity] = "unavailable"; + Console.Error.WriteLine($"Crash collection unavailable: {ex.GetType().Name}."); + } + finally + { + if (staging != null && Directory.Exists(staging)) + { + try + { + if (!Directory.EnumerateFileSystemEntries(staging).Any()) + Directory.Delete(staging); + else + Console.Error.WriteLine("Incomplete crash evidence retained for operator inspection."); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { Console.Error.WriteLine($"Crash evidence cleanup unavailable: {ex.GetType().Name}."); } + } + } + } + + private static async Task StopToolAsync(Process tool) + { + var executable = Environment.ProcessPath + ?? throw new InvalidOperationException("Host executable is unavailable."); + var info = new ProcessStartInfo + { + FileName = executable, + UseShellExecute = false, + CreateNoWindow = true + }; + if (Path.GetFileNameWithoutExtension(executable).Equals("dotnet", StringComparison.OrdinalIgnoreCase)) + info.ArgumentList.Add(typeof(Program).Assembly.Location); + info.ArgumentList.Add("--stop-capture"); + info.ArgumentList.Add(tool.Id.ToString(System.Globalization.CultureInfo.InvariantCulture)); + using var helper = Process.Start(info) ?? throw new InvalidOperationException("Capture stop helper failed to start."); + await helper.WaitForExitAsync(); + if (helper.ExitCode != 0 && !tool.HasExited) + throw new InvalidOperationException("Capture stop helper failed."); + } + + // ProcDump returns the number of captured dumps, not zero on success. + internal static bool DumpSucceeded(int exitCode, string dump) => + exitCode == 1 && File.Exists(dump) && new FileInfo(dump).Length != 0; + + internal static void Publish(string staging, string guid, string targetName, string version) + { + if (!Guid.TryParseExact(guid, "D", out var id) || id.ToString("D") != guid || + !SafeVersion(version) || string.IsNullOrWhiteSpace(targetName) || + Path.GetFileName(Path.GetDirectoryName(staging)) != version) + throw new InvalidDataException("Invalid crash case identity."); + Paths.NoLinks(staging); + foreach (var file in new[] { Path.Combine(staging, "crash.dmp"), Path.Combine(staging, "crash.json") }) + { + Paths.NoLinks(file); + using var stream = new FileStream(file, FileMode.Open, FileAccess.ReadWrite, FileShare.None); + if (stream.Length == 0) + throw new InvalidDataException("Crash evidence is empty."); + stream.Flush(flushToDisk: true); + } + WriteManifest(staging, guid, targetName, version); + Directory.Move(staging, Path.Combine(Path.GetDirectoryName(staging)!, guid)); + } + + private static void WriteManifest(string staging, string guid, string targetName, string version) + { + var path = Path.Combine(staging, "manifest.json"); + Paths.NoLinks(path); + using var stream = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None, + 4096, FileOptions.WriteThrough); + using var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }); + writer.WriteStartObject(); + writer.WriteNumber("schema", 2); + writer.WriteString("guid", guid); + writer.WriteString("kind", "crash"); + writer.WriteString("targetName", targetName); + writer.WriteString("version", version); + writer.WriteNull("exitCode"); + writer.WriteString("createdAtUtc", DateTimeOffset.UtcNow); + writer.WriteStartArray("files"); + writer.WriteStringValue("crash.json"); + writer.WriteStringValue("crash.dmp"); + writer.WriteEndArray(); + writer.WriteString("state", "pending"); + writer.WriteNumber("attempts", 0); + writer.WriteEndObject(); + writer.Flush(); + stream.Flush(flushToDisk: true); + } +} diff --git a/src/Bowl.Host/Disk.cs b/src/Bowl.Host/Disk.cs index 1535415..238b529 100644 --- a/src/Bowl.Host/Disk.cs +++ b/src/Bowl.Host/Disk.cs @@ -148,6 +148,9 @@ public static void Validate(Request request, string root) else if (request.AutoRollback) throw new InvalidDataException("Automatic rollback requires a snapshot directory."); + if (request.CrashCollectionEnabled && !CrashCollection.SafeVersion(request.TargetVersion)) + throw new InvalidDataException("Crash collection requires a safe target version."); + if (request.Updater is null || request.Updater.Pid <= 0 || request.Updater.StartTimeUtc == default || request.CreatedAtUtc == default || request.CreatedAtUtc > DateTimeOffset.UtcNow.AddMinutes(5) || diff --git a/src/Bowl.Host/Program.cs b/src/Bowl.Host/Program.cs index 36721e2..819100a 100644 --- a/src/Bowl.Host/Program.cs +++ b/src/Bowl.Host/Program.cs @@ -9,6 +9,13 @@ public static async Task Main(string[] args) { try { + if (args.Length == 2 && args[0] == "--stop-capture" && OperatingSystem.IsWindows()) + { + if (!int.TryParse(args[1], out var capturePid) || capturePid <= 0) + throw new ArgumentException("Invalid capture process ID."); + CaptureConsole.Stop(capturePid); + return 0; + } if (args.Length != 4 || args[2] != "--state-root" || args[0] is not ("--attempt" or "--retry")) throw new ArgumentException("Use --attempt --state-root or --retry --state-root ."); diff --git a/src/Bowl.Host/Protocol.cs b/src/Bowl.Host/Protocol.cs index 34ec1e0..fe430c0 100644 --- a/src/Bowl.Host/Protocol.cs +++ b/src/Bowl.Host/Protocol.cs @@ -32,6 +32,7 @@ internal sealed record Request : Envelope public int HealthTimeoutSeconds { get; init; } = 5; public int UpdateTimeoutSeconds { get; init; } = 600; public bool AutoRollback { get; init; } + public bool CrashCollectionEnabled { get; init; } public ReportConfiguration Report { get; init; } = new(); } @@ -100,6 +101,13 @@ internal sealed record Outbox : Envelope public string? LastError { get; init; } } +internal sealed record CaptureStatus : Envelope +{ + public required CaptureTargetStatus[] Targets { get; init; } +} + +internal sealed record CaptureTargetStatus(ProcessIdentity Identity, string State); + [JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, WriteIndented = true)] [JsonSerializable(typeof(Request))] @@ -108,5 +116,6 @@ internal sealed record Outbox : Envelope [JsonSerializable(typeof(Producer))] [JsonSerializable(typeof(Result))] [JsonSerializable(typeof(Outbox))] +[JsonSerializable(typeof(CaptureStatus))] [JsonSerializable(typeof(LegacyPayload))] internal partial class ProtocolJson : JsonSerializerContext; diff --git a/src/Bowl.Host/Supervisor.cs b/src/Bowl.Host/Supervisor.cs index de4b416..8543087 100644 --- a/src/Bowl.Host/Supervisor.cs +++ b/src/Bowl.Host/Supervisor.cs @@ -43,8 +43,29 @@ result.Rollback is "pending" or "inProgress" or "deferred" { AttemptId = attempt, Host = ProcessIdentity.Current() }, ProtocolJson.Default.Ready); - result = await ObserveAsync(directory, request, token); - Disk.Write(resultPath, result, ProtocolJson.Default.Result); + var collection = new CrashCollection(root, request); + collection.Start(request.Updater); + try + { + result = await ObserveAsync(directory, request, collection, token); + Disk.Write(resultPath, result, ProtocolJson.Default.Result); + } + finally + { + await collection.StopAsync(result != null && result.Outcome != "success"); + if (request.CrashCollectionEnabled) + { + try + { + Disk.Write(Path.Combine(directory, "capture-status.json"), collection.Status(), + ProtocolJson.Default.CaptureStatus); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException) + { + Console.Error.WriteLine($"Crash capture status unavailable: {ex.GetType().Name}."); + } + } + } } Disk.Validate(result, attempt); if (result.EventId != attempt + "-terminal-v1" || result.Updater != request.Updater || @@ -86,7 +107,7 @@ previousResult.Rollback is not ("notRequested" or "succeeded" or "failed")) Disk.Write(ownerPath, new Envelope { AttemptId = request.AttemptId }, ProtocolJson.Default.Envelope); } - private async Task ObserveAsync(string directory, Request request, CancellationToken token) + private async Task ObserveAsync(string directory, Request request, CrashCollection collection, CancellationToken token) { Producer? producer = null; ProcessIdentity? observedApplication = null; @@ -130,6 +151,7 @@ private async Task ObserveAsync(string directory, Request request, Cance observedApplication = application; if (!processes.IsAlive(application)) return Finish(request, producer, "healthCheckFailure"); + collection.Start(application); health ??= Stopwatch.StartNew(); if (health.Elapsed >= TimeSpan.FromSeconds(request.HealthTimeoutSeconds)) return Finish(request, producer, "success", "processAlive"); diff --git a/src/GeneralUpdate.Bowl/InternalsVisibleTo.cs b/src/GeneralUpdate.Bowl/InternalsVisibleTo.cs index 796cb67..0a7e5c4 100644 --- a/src/GeneralUpdate.Bowl/InternalsVisibleTo.cs +++ b/src/GeneralUpdate.Bowl/InternalsVisibleTo.cs @@ -1,6 +1,6 @@ using System.Runtime.CompilerServices; -// Friend assemblies (assembly names, not project names): the console binary is `bowl` -// (AssemblyName in the csproj) and the console test project is `Bowl.Console.Tests`. +// Friend assembly names, including the console binary's `bowl` AssemblyName. [assembly: InternalsVisibleTo("bowl")] [assembly: InternalsVisibleTo("Bowl.Console.Tests")] +[assembly: InternalsVisibleTo("Bowl.Host")] diff --git a/src/GeneralUpdate.Bowl/Strategies/ProcessRunner.cs b/src/GeneralUpdate.Bowl/Strategies/ProcessRunner.cs index e988378..c2d0a8a 100644 --- a/src/GeneralUpdate.Bowl/Strategies/ProcessRunner.cs +++ b/src/GeneralUpdate.Bowl/Strategies/ProcessRunner.cs @@ -75,6 +75,7 @@ public static async Task RunAsync( try { await delayTask; } catch (OperationCanceledException) { /* cancelled — expected */ } var exitCode = await tcs.Task; GeneralTracer.Info($"ProcessRunner.RunAsync: process exited, ExitCode={exitCode}"); + process.WaitForExit(); // Snapshot output under lock to avoid race with in-flight handlers IReadOnlyList snapshot; lock (outputLines) { snapshot = outputLines.ToArray(); } diff --git a/tests/Bowl.Host.Tests/CrashCollectionTests.cs b/tests/Bowl.Host.Tests/CrashCollectionTests.cs new file mode 100644 index 0000000..75db920 --- /dev/null +++ b/tests/Bowl.Host.Tests/CrashCollectionTests.cs @@ -0,0 +1,183 @@ +using System.Text.Json; +using System.Diagnostics; +using Bowl.Host; + +namespace Bowl.Host.Tests; + +public sealed class CrashCollectionTests +{ + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(".")] + [InlineData("..")] + [InlineData("../other")] + [InlineData("a\\b")] + [InlineData("a:b")] + [InlineData("CON.txt")] + [InlineData("lpt1")] + [InlineData("com\u00b9.txt")] + [InlineData("version.")] + [InlineData("version ")] + [InlineData("version\u007f")] + public void UnsafeVersionsAreRejected(string? version) => + Assert.False(CrashCollection.SafeVersion(version)); + + [Theory] + [InlineData("1.2.3")] + [InlineData("release-candidate")] + public void SafeVersionsAreAccepted(string version) => + Assert.True(CrashCollection.SafeVersion(version)); + + [Fact] + public async Task UnsafeVersionIsRejectedBeforeReady() + { + using var f = new Fixture(); + f.Request = f.Request with { CrashCollectionEnabled = true, TargetVersion = "../bad" }; + await Assert.ThrowsAsync(f.Run); + Assert.False(File.Exists(Path.Combine(f.DirectoryPath, "ready.json"))); + } + + [Fact] + public async Task DisabledCollectionDoesNotCreateEvidenceOrStatus() + { + using var f = new Fixture(); + f.Producer("completed"); + Assert.Equal("success", (await f.Run()).Outcome); + Assert.False(Directory.Exists(Path.Combine(f.Root, "crash-outbox"))); + Assert.False(File.Exists(Path.Combine(f.DirectoryPath, "capture-status.json"))); + } + + [Fact] + public async Task CaptureFailureDoesNotChangeSuccessfulUpdate() + { + using var f = new Fixture(); + f.Request = f.Request with + { + CrashCollectionEnabled = true, + TargetVersion = "1.2.3", + Updater = new ProcessIdentity(int.MaxValue, DateTimeOffset.UtcNow) + }; + f.Producer("completed"); + Assert.Equal("success", (await f.Run()).Outcome); + var status = Disk.Read(Path.Combine(f.DirectoryPath, "capture-status.json"), + ProtocolJson.Default.CaptureStatus)!; + Assert.Single(status.Targets); + Assert.Contains(status.Targets[0].State, new[] { "unavailable", "interrupted" }); + Assert.Equal("acknowledged", f.Outbox.State); + } + + [Fact] + public async Task RollbackPreservesPublishedEvidenceOutsideInstallation() + { + using var f = new Fixture(); + f.Request = f.Request with + { + AutoRollback = true, + CrashCollectionEnabled = true, + TargetVersion = "1.2.3", + Updater = new ProcessIdentity(int.MaxValue, DateTimeOffset.UtcNow) + }; + f.Snapshot(); + f.Processes.Alive = false; + var staging = Path.Combine(f.Root, "crash-outbox", "1.2.3", ".partial"); + Directory.CreateDirectory(staging); + File.WriteAllText(Path.Combine(staging, "crash.json"), "{}"); + File.WriteAllBytes(Path.Combine(staging, "crash.dmp"), [1]); + var guid = Guid.NewGuid().ToString("D"); + CrashCollection.Publish(staging, guid, "app.exe", "1.2.3"); + f.Producer("failed", error: new Failure { Category = "updateFailure" }); + + var result = await f.Run(); + + Assert.Equal("updateFailure", result.Outcome); + Assert.Equal("succeeded", result.Rollback); + Assert.True(File.Exists(Path.Combine(f.Root, "crash-outbox", "1.2.3", guid, "crash.dmp"))); + Assert.Equal("old", File.ReadAllText(Path.Combine(f.Request.InstallPath, "application.txt"))); + } + + [Fact] + public void CompleteCasePublishesSchemaTwoInOneDirectoryMove() + { + using var f = new Fixture(); + var versionRoot = Path.Combine(f.Root, "crash-outbox", "1.2.3"); + var staging = Path.Combine(versionRoot, ".partial"); + Directory.CreateDirectory(staging); + File.WriteAllText(Path.Combine(staging, "crash.json"), "{}"); + File.WriteAllBytes(Path.Combine(staging, "crash.dmp"), [1, 2, 3]); + var guid = Guid.NewGuid().ToString("D"); + + CrashCollection.Publish(staging, guid, "app.exe", "1.2.3"); + + Assert.False(Directory.Exists(staging)); + var destination = Path.Combine(versionRoot, guid); + using var manifest = JsonDocument.Parse(File.ReadAllText(Path.Combine(destination, "manifest.json"))); + var root = manifest.RootElement; + Assert.Equal(2, root.GetProperty("schema").GetInt32()); + Assert.Equal(guid, root.GetProperty("guid").GetString()); + Assert.Equal("crash", root.GetProperty("kind").GetString()); + Assert.Equal("app.exe", root.GetProperty("targetName").GetString()); + Assert.Equal("1.2.3", root.GetProperty("version").GetString()); + Assert.Equal("pending", root.GetProperty("state").GetString()); + Assert.Equal(0, root.GetProperty("attempts").GetInt32()); + Assert.Equal(new[] { "crash.json", "crash.dmp" }, + root.GetProperty("files").EnumerateArray().Select(x => x.GetString()).ToArray()); + } + + [Fact] + public void IncompleteCaseNeverBecomesVisible() + { + using var f = new Fixture(); + var staging = Path.Combine(f.Root, "crash-outbox", "1.2.3", ".partial"); + Directory.CreateDirectory(staging); + File.WriteAllText(Path.Combine(staging, "crash.json"), "{}"); + File.WriteAllBytes(Path.Combine(staging, "crash.dmp"), []); + var guid = Guid.NewGuid().ToString("D"); + Assert.Throws(() => CrashCollection.Publish(staging, guid, "app.exe", "1.2.3")); + Assert.False(Directory.Exists(Path.Combine(Path.GetDirectoryName(staging)!, guid))); + Assert.True(Directory.Exists(staging)); + } + + [Fact] + public void ProcdumpSuccessMeansOneCompleteDump() + { + using var f = new Fixture(); + var dump = Path.Combine(f.Root, "capture.dmp"); + Assert.False(CrashCollection.DumpSucceeded(1, dump)); + File.WriteAllBytes(dump, []); + Assert.False(CrashCollection.DumpSucceeded(1, dump)); + File.WriteAllBytes(dump, [1]); + Assert.True(CrashCollection.DumpSucceeded(1, dump)); + Assert.False(CrashCollection.DumpSucceeded(0, dump)); + } + + [Fact] + public async Task CaptureJobStopsItsOwnedProcessOnClose() + { + if (!OperatingSystem.IsWindows()) + return; + using var process = Process.Start(new ProcessStartInfo + { + FileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "WindowsPowerShell", + "v1.0", "powershell.exe"), + Arguments = "-NoProfile -NonInteractive -Command \"Start-Sleep -Seconds 30\"", + UseShellExecute = false, + CreateNoWindow = true + })!; + try + { + using (var job = CaptureJob.Create()) + job.Assign(process); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); + await process.WaitForExitAsync(timeout.Token); + } + finally + { + if (!process.HasExited) + { + process.Kill(); + await process.WaitForExitAsync(); + } + } + } +} diff --git a/tests/Bowl.Host.Tests/ProcessTests.cs b/tests/Bowl.Host.Tests/ProcessTests.cs index 63e693c..9203507 100644 --- a/tests/Bowl.Host.Tests/ProcessTests.cs +++ b/tests/Bowl.Host.Tests/ProcessTests.cs @@ -1,5 +1,6 @@ using System.Diagnostics; using System.Linq; +using System.Text.Json; using Bowl.Host; namespace Bowl.Host.Tests; @@ -30,8 +31,9 @@ private static Process Start(string dll, params string[] arguments) return Process.Start("dotnet", commandLine)!; } - private static Process Peer(int milliseconds) => Start(Path.Combine(Repository, "tests", "Bowl.TestPeer", - "bin", Configuration, "net8.0", "Bowl.TestPeer.dll"), milliseconds.ToString()); + private static Process Peer(int milliseconds, params string[] arguments) => Start( + Path.Combine(Repository, "tests", "Bowl.TestPeer", "bin", Configuration, "net8.0", "Bowl.TestPeer.dll"), + new[] { milliseconds.ToString(System.Globalization.CultureInfo.InvariantCulture) }.Concat(arguments).ToArray()); private static Process Host(Fixture f) => Start(Path.Combine(Repository, "src", "Bowl.Host", "bin", Configuration, "net8.0", "Bowl.Host.dll"), @@ -75,7 +77,7 @@ public async Task RealHostCrashCanResumeObservationAndRollbackWithRetainedSnapsh private static async Task Wait(Process process) { - using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(15)); + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30)); await process.WaitForExitAsync(timeout.Token); } @@ -153,6 +155,81 @@ public async Task RealUpdaterTerminationWithoutDumpIsRecorded() finally { Cleanup(host); Cleanup(updater); } } + [Fact] + public async Task RealCrashPublishesDumpAndReport() + { + if (!OperatingSystem.IsWindows()) + return; + using var f = new Fixture(); + using var updater = Peer(10_000, "--crash"); + var updaterIdentity = Identity(updater); + f.Request = f.Request with + { + Updater = updaterIdentity, CrashCollectionEnabled = true, TargetVersion = "1.2.3", + UpdateTimeoutSeconds = 30, Report = new() + }; + f.Save(); + f.Producer("filesApplying"); + using var host = Host(f); + try + { + await Ready(f, host); + await Wait(updater); + await Wait(host); + + var result = Disk.Read(Path.Combine(f.DirectoryPath, "result.json"), ProtocolJson.Default.Result)!; + Assert.Equal("updaterTerminated", result.Outcome); + var status = Disk.Read(Path.Combine(f.DirectoryPath, "capture-status.json"), + ProtocolJson.Default.CaptureStatus)!; + Assert.Equal("published", Assert.Single(status.Targets).State); + var versionRoot = Path.Combine(f.Root, "crash-outbox", "1.2.3"); + var caseDirectory = Assert.Single(Directory.GetDirectories(versionRoot)); + Assert.True(new FileInfo(Path.Combine(caseDirectory, "crash.dmp")).Length > 0); + Assert.True(new FileInfo(Path.Combine(caseDirectory, "crash.json")).Length > 0); + using var manifest = JsonDocument.Parse(File.ReadAllText(Path.Combine(caseDirectory, "manifest.json"))); + Assert.Equal(new[] { "crash.json", "crash.dmp" }, + manifest.RootElement.GetProperty("files").EnumerateArray().Select(x => x.GetString()).ToArray()); + } + finally { Cleanup(host); Cleanup(updater); } + } + + [Fact] + public async Task ProcessAliveSuccessCancelsCaptureWithoutStoppingApplication() + { + if (!OperatingSystem.IsWindows()) + return; + using var f = new Fixture(); + using var updater = Peer(60_000); + using var application = Peer(60_000); + var applicationIdentity = Identity(application); + f.Request = f.Request with + { + Updater = Identity(updater), LaunchMode = "processAlive", HealthTimeoutSeconds = 12, + CrashCollectionEnabled = true, TargetVersion = "1.2.3", Report = new() + }; + f.Save(); + f.Producer("awaitingHealth", applicationIdentity); + using var host = Host(f); + try + { + await Ready(f, host); + await Wait(host); + + var result = Disk.Read(Path.Combine(f.DirectoryPath, "result.json"), ProtocolJson.Default.Result)!; + Assert.Equal("success", result.Outcome); + Assert.Equal("processAlive", result.Verification); + Assert.False(application.HasExited); + Assert.False(updater.HasExited); + var status = Disk.Read(Path.Combine(f.DirectoryPath, "capture-status.json"), + ProtocolJson.Default.CaptureStatus)!; + Assert.Contains(status.Targets, target => + target.Identity == applicationIdentity && target.State == "interrupted"); + Assert.Contains(status.Targets, target => + target.Identity == f.Request.Updater && target.State == "interrupted"); + } + finally { Cleanup(host); Cleanup(application); Cleanup(updater); } + } + [Theory] [InlineData(false)] [InlineData(true)] diff --git a/tests/Bowl.TestPeer/Program.cs b/tests/Bowl.TestPeer/Program.cs index 3534b6f..52d100f 100644 --- a/tests/Bowl.TestPeer/Program.cs +++ b/tests/Bowl.TestPeer/Program.cs @@ -1,3 +1,5 @@ // A real, isolated process for PID/start-time and exit tests. It never touches // installation files or performs production monitor duties. await Task.Delay(int.Parse(args[0], System.Globalization.CultureInfo.InvariantCulture)); +if (args.Length > 1 && args[1] == "--crash") + throw new InvalidOperationException("Intentional test crash.");