Merge fix/259-followup

This commit is contained in:
Joseph Doherty
2026-12-03 13:14:22 -05:00
18 changed files with 995 additions and 26 deletions
@@ -2493,6 +2493,12 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output)
/// <inheritdoc />
public int? ExitCode => process.HasExited ? process.ExitCode : null;
/// <summary>Gets <c>null</c>: the factory reads both streams itself, into the test output.</summary>
public TextReader? StandardError => null;
/// <summary>Gets <c>null</c>: the factory reads both streams itself, into the test output.</summary>
public TextReader? StandardOutput => null;
/// <inheritdoc />
public async ValueTask WaitForExitAsync(CancellationToken cancellationToken)
{
@@ -79,7 +79,7 @@ public sealed class SessionWorkerClientFactory : ISessionWorkerClientFactory
.ConfigureAwait(false);
session.TransitionTo(SessionState.WaitingForPipe);
await WaitForPipeConnectionAsync(pipe, processHandle.Process, session.SessionId, startupCancellation.Token)
await WaitForPipeConnectionAsync(pipe, processHandle, session.SessionId, startupCancellation.Token)
.ConfigureAwait(false);
session.TransitionTo(SessionState.Handshaking);
@@ -213,18 +213,21 @@ public sealed class SessionWorkerClientFactory : ISessionWorkerClientFactory
/// timeout with no exit code. Racing the connect against the process exit reports the crash
/// as <see cref="WorkerProcessLaunchErrorCode.StartupFailed"/> with the exit code at once.
/// Once connected, a worker exit shows up as pipe EOF in the handshake reads.
/// The message ends with the tail of the worker's stderr when the launcher captured it
/// (mxaccessgw#259): a worker that dies this early usually said why on its way out.
/// </remarks>
/// <param name="pipe">The named pipe.</param>
/// <param name="process">The launched worker process.</param>
/// <param name="processHandle">The launched worker process.</param>
/// <param name="sessionId">Session id, for the failure message.</param>
/// <param name="cancellationToken">Cancellation token (the startup deadline and the caller's).</param>
/// <returns>A task that represents the asynchronous operation.</returns>
internal static async Task WaitForPipeConnectionAsync(
NamedPipeServerStream pipe,
IWorkerProcess process,
WorkerProcessHandle processHandle,
string sessionId,
CancellationToken cancellationToken)
{
IWorkerProcess process = processHandle.Process;
using CancellationTokenSource raceCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
Task connect = pipe.WaitForConnectionAsync(raceCancellation.Token);
Task exit = process.WaitForExitAsync(raceCancellation.Token).AsTask();
@@ -235,11 +238,21 @@ public sealed class SessionWorkerClientFactory : ISessionWorkerClientFactory
await raceCancellation.CancelAsync().ConfigureAwait(false);
await ObserveQuietlyAsync(connect).ConfigureAwait(false);
int? exitCode = process.ExitCode;
WorkerOutputCapture? outputCapture = processHandle.OutputCapture;
if (outputCapture is not null)
{
await outputCapture
.WaitForStandardErrorDrainedAsync(WorkerProcessLauncher.StandardErrorDrainWait)
.ConfigureAwait(false);
}
throw new WorkerProcessLaunchException(
WorkerProcessLaunchErrorCode.StartupFailed,
$"Worker process for session {sessionId} exited with code "
+ $"{(exitCode?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "unknown")} "
+ "before it connected to its pipe.");
WorkerOutputCapture.AppendStandardErrorTail(
outputCapture,
$"Worker process for session {sessionId} exited with code "
+ $"{(exitCode?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "unknown")} "
+ "before it connected to its pipe."));
}
// The connect won (or the exit wait itself failed, which says nothing about the worker):
@@ -20,6 +20,18 @@ public interface IWorkerProcess : IDisposable
/// </summary>
int? ExitCode { get; }
/// <summary>
/// The redirected standard error reader, or <c>null</c> when standard error is not redirected
/// or the implementation reads it itself. The launcher drains it (see <see cref="WorkerOutputCapture"/>).
/// </summary>
TextReader? StandardError { get; }
/// <summary>
/// The redirected standard output reader, or <c>null</c> when standard output is not
/// redirected or the implementation reads it itself.
/// </summary>
TextReader? StandardOutput { get; }
/// <summary>
/// Waits for the process to exit with the specified cancellation token.
/// </summary>
@@ -16,6 +16,12 @@ internal sealed class SystemWorkerProcess(Process process) : IWorkerProcess
/// <inheritdoc />
public int? ExitCode => process.HasExited ? process.ExitCode : null;
/// <inheritdoc />
public TextReader? StandardError => process.StartInfo.RedirectStandardError ? process.StandardError : null;
/// <inheritdoc />
public TextReader? StandardOutput => process.StartInfo.RedirectStandardOutput ? process.StandardOutput : null;
/// <inheritdoc />
public async ValueTask WaitForExitAsync(CancellationToken cancellationToken)
{
@@ -0,0 +1,363 @@
using System.Threading.Channels;
using Microsoft.Extensions.Logging;
namespace ZB.MOM.WW.MxGateway.Server.Workers;
/// <summary>
/// Drains a worker process's redirected standard error and standard output, forwards each line
/// to the gateway log, and keeps a bounded tail of recent stderr lines for startup-failure
/// messages (WRK-002, mxaccessgw#259).
/// </summary>
/// <remarks>
/// <para>
/// Before this capture existed the worker was started with <c>CreateNoWindow</c> and no
/// redirection, so its output went to a hidden console of its own and was discarded, both for a
/// console run and under the NSSM service. Redirecting it therefore loses nothing; the
/// worker's <c>level=... event=...</c> lines now appear in the gateway log under the
/// <see cref="LogCategory"/> category, with the session id and worker process id as properties.
/// </para>
/// <para>
/// The pipes are always drained, whatever the gateway logger is doing: each reader only
/// truncates the line, appends it to the tail and offers it to a bounded drop-oldest queue,
/// which never waits. A separate task logs from that queue. A slow log sink therefore drops
/// the oldest queued lines (and reports how many) rather than backing up the pipe and blocking
/// the worker's own <c>Console.Error</c> writes, which can run on its STA thread.
/// </para>
/// <para>
/// The readers run until end-of-stream, which arrives when the worker exits (the gateway kills
/// the worker before it disposes the process handle), and each disposes its own reader then. No
/// cancellation is needed, and lines the worker wrote just before it exited are not cut off.
/// </para>
/// <para>
/// The worker redacts its own log lines (<c>WorkerLogRedactor</c>). As a second line of defense
/// the capture replaces any occurrence of the session's bootstrap nonce, the one secret the
/// gateway hands the worker, with <c>[redacted]</c> before a line is logged or kept.
/// </para>
/// </remarks>
internal sealed class WorkerOutputCapture
{
/// <summary>Logger category the forwarded worker lines are written under.</summary>
public const string LogCategory = "ZB.MOM.WW.MxGateway.Worker";
/// <summary>Most stderr lines kept for the startup-failure tail.</summary>
public const int MaxTailLines = 50;
/// <summary>Most characters kept for the startup-failure tail.</summary>
public const int MaxTailCharacters = 4096;
/// <summary>Longest single line forwarded or kept; the rest is cut and marked.</summary>
public const int MaxLineCharacters = 2048;
/// <summary>Lines that may wait for the logger before the oldest are dropped.</summary>
public const int ForwardQueueCapacity = 1024;
private const string RedactedValue = "[redacted]";
private const string TruncatedMarker = "...[truncated]";
private readonly string _sessionId;
private readonly int _processId;
private readonly string? _nonce;
private readonly ILogger _logger;
private readonly Channel<WorkerOutputLine> _forwardQueue;
private readonly Queue<string> _tail = new();
private readonly object _tailLock = new();
private readonly Task _standardErrorDrained;
private readonly Task _completion;
private int _tailCharacters;
private long _droppedLines;
private int _drainedStreams;
private WorkerOutputCapture(
TextReader? standardError,
TextReader? standardOutput,
string sessionId,
int processId,
string? nonce,
ILogger logger)
{
_sessionId = sessionId;
_processId = processId;
_nonce = string.IsNullOrEmpty(nonce) ? null : nonce;
_logger = logger;
_forwardQueue = Channel.CreateBounded<WorkerOutputLine>(
new BoundedChannelOptions(ForwardQueueCapacity)
{
FullMode = BoundedChannelFullMode.DropOldest,
SingleReader = true,
SingleWriter = false,
},
_ => Interlocked.Increment(ref _droppedLines));
// A missing stream counts as drained from the start; the queue completes when both are.
_drainedStreams = (standardError is null ? 1 : 0) + (standardOutput is null ? 1 : 0);
if (_drainedStreams == 2)
{
_forwardQueue.Writer.TryComplete();
}
Task forwarding = Task.Run(ForwardLoopAsync);
_standardErrorDrained = standardError is null
? Task.CompletedTask
: Task.Run(() => DrainAsync(standardError, WorkerOutputStream.StandardError));
Task standardOutputDrained = standardOutput is null
? Task.CompletedTask
: Task.Run(() => DrainAsync(standardOutput, WorkerOutputStream.StandardOutput));
_completion = CompleteAsync(_standardErrorDrained, standardOutputDrained, forwarding);
}
/// <summary>
/// Gets a task that completes once both streams reached end-of-stream and every queued line
/// was logged. It never faults.
/// </summary>
public Task Completion => _completion;
/// <summary>
/// Starts draining the redirected streams of <paramref name="process"/>, or returns
/// <c>null</c> when neither stream is redirected (test doubles, or a process factory that
/// reads the streams itself).
/// </summary>
/// <param name="process">The started worker process.</param>
/// <param name="sessionId">Session id, logged with every line.</param>
/// <param name="nonce">The session's bootstrap nonce, scrubbed from every line.</param>
/// <param name="logger">Logger for the forwarded lines.</param>
/// <returns>The running capture, or <c>null</c>.</returns>
public static WorkerOutputCapture? StartIfRedirected(
IWorkerProcess process,
string sessionId,
string? nonce,
ILogger logger)
{
ArgumentNullException.ThrowIfNull(process);
ArgumentNullException.ThrowIfNull(logger);
TextReader? standardError = process.StandardError;
TextReader? standardOutput = process.StandardOutput;
if (standardError is null && standardOutput is null)
{
return null;
}
return Start(standardError, standardOutput, sessionId, process.Id, nonce, logger);
}
/// <summary>Starts draining the given readers.</summary>
/// <param name="standardError">Worker stderr, or <c>null</c>.</param>
/// <param name="standardOutput">Worker stdout, or <c>null</c>.</param>
/// <param name="sessionId">Session id, logged with every line.</param>
/// <param name="processId">Worker process id, logged with every line.</param>
/// <param name="nonce">The session's bootstrap nonce, scrubbed from every line.</param>
/// <param name="logger">Logger for the forwarded lines.</param>
/// <returns>The running capture.</returns>
public static WorkerOutputCapture Start(
TextReader? standardError,
TextReader? standardOutput,
string sessionId,
int processId,
string? nonce,
ILogger logger)
{
ArgumentNullException.ThrowIfNull(logger);
return new WorkerOutputCapture(standardError, standardOutput, sessionId, processId, nonce, logger);
}
/// <summary>
/// Waits, up to <paramref name="timeout"/>, for stderr to reach end-of-stream, so lines the
/// worker wrote just before it exited are in the tail. Never throws.
/// </summary>
/// <param name="timeout">Longest wait.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public async Task WaitForStandardErrorDrainedAsync(TimeSpan timeout)
{
try
{
await _standardErrorDrained.WaitAsync(timeout).ConfigureAwait(false);
}
catch (TimeoutException)
{
// Something else still holds the pipe's write end; report what has arrived so far.
}
}
/// <summary>Gets the most recent stderr lines (at most <see cref="MaxTailLines"/> lines and <see cref="MaxTailCharacters"/> characters), oldest first.</summary>
/// <returns>The lines joined with newlines, or an empty string when nothing was captured.</returns>
public string GetStandardErrorTail()
{
lock (_tailLock)
{
return string.Join('\n', _tail);
}
}
/// <summary>
/// Appends the stderr tail to a startup-failure message, or returns the message unchanged
/// when the capture is absent or nothing was written to stderr.
/// </summary>
/// <param name="capture">The capture, or <c>null</c>.</param>
/// <param name="message">The failure message.</param>
/// <returns>The message, with the tail appended when there is one.</returns>
public static string AppendStandardErrorTail(WorkerOutputCapture? capture, string message)
{
string tail = capture?.GetStandardErrorTail() ?? string.Empty;
return tail.Length == 0
? message
: message + " Last worker stderr output:\n" + tail;
}
/// <summary>Maps a worker log line's <c>level=</c> prefix to a gateway log level.</summary>
/// <param name="line">The worker line.</param>
/// <param name="stream">The stream it came from.</param>
/// <returns>The level to log it at.</returns>
internal static LogLevel MapLevel(string line, WorkerOutputStream stream)
{
if (line.StartsWith("level=", StringComparison.Ordinal))
{
int end = line.IndexOf(' ', 6);
ReadOnlySpan<char> level = end < 0 ? line.AsSpan(6) : line.AsSpan(6, end - 6);
if (level.Equals("Information", StringComparison.Ordinal))
{
return LogLevel.Information;
}
if (level.Equals("Warning", StringComparison.Ordinal))
{
return LogLevel.Warning;
}
if (level.Equals("Error", StringComparison.Ordinal))
{
return LogLevel.Error;
}
}
// Unstructured stderr is not the worker logger talking: it is the CLR, a native component
// or a crash, so it is worth a Warning. The worker writes nothing to stdout on purpose.
return stream == WorkerOutputStream.StandardError ? LogLevel.Warning : LogLevel.Information;
}
private static async Task CompleteAsync(Task standardError, Task standardOutput, Task forwarding)
{
await Task.WhenAll(standardError, standardOutput).ConfigureAwait(false);
await forwarding.ConfigureAwait(false);
}
private async Task DrainAsync(TextReader reader, WorkerOutputStream stream)
{
try
{
while (await reader.ReadLineAsync().ConfigureAwait(false) is { } rawLine)
{
string line = Sanitize(rawLine);
if (stream == WorkerOutputStream.StandardError)
{
AppendToTail(line);
}
// Never waits: a full queue drops its oldest line instead.
_forwardQueue.Writer.TryWrite(new WorkerOutputLine(stream, line));
}
}
catch (Exception exception) when (exception is IOException or ObjectDisposedException or InvalidOperationException)
{
// The pipe broke or was closed under us; the worker is gone either way.
}
finally
{
reader.Dispose();
if (Interlocked.Increment(ref _drainedStreams) == 2)
{
_forwardQueue.Writer.TryComplete();
}
}
}
private async Task ForwardLoopAsync()
{
long reportedDrops = 0;
await foreach (WorkerOutputLine item in _forwardQueue.Reader.ReadAllAsync().ConfigureAwait(false))
{
long dropped = Interlocked.Read(ref _droppedLines);
if (dropped != reportedDrops)
{
LogSafely(
LogLevel.Warning,
"Dropped {DroppedLineCount} worker output lines for session {SessionId} (pid {WorkerProcessId}) because the gateway log fell behind.",
dropped - reportedDrops);
reportedDrops = dropped;
}
ForwardSafely(item);
}
}
private void ForwardSafely(WorkerOutputLine item)
{
try
{
LogLevel level = MapLevel(item.Line, item.Stream);
if (_logger.IsEnabled(level))
{
_logger.Log(
level,
"Worker {SessionId} (pid {WorkerProcessId}) {WorkerStream}: {WorkerLogLine:l}",
_sessionId,
_processId,
item.Stream == WorkerOutputStream.StandardError ? "stderr" : "stdout",
item.Line);
}
}
catch (Exception)
{
// A failing log sink must not stop the drain; the line is still in the tail.
}
}
private void LogSafely(LogLevel level, string message, long count)
{
try
{
_logger.Log(level, message, count, _sessionId, _processId);
}
catch (Exception)
{
// See ForwardSafely.
}
}
private string Sanitize(string line)
{
if (_nonce is not null && line.Contains(_nonce, StringComparison.Ordinal))
{
line = line.Replace(_nonce, RedactedValue, StringComparison.Ordinal);
}
return line.Length <= MaxLineCharacters
? line
: string.Concat(line.AsSpan(0, MaxLineCharacters), TruncatedMarker);
}
private void AppendToTail(string line)
{
lock (_tailLock)
{
_tail.Enqueue(line);
_tailCharacters += line.Length;
while (_tail.Count > MaxTailLines || (_tail.Count > 1 && _tailCharacters > MaxTailCharacters))
{
_tailCharacters -= _tail.Dequeue().Length;
}
}
}
private readonly record struct WorkerOutputLine(WorkerOutputStream Stream, string Line);
}
/// <summary>The worker stream a captured line came from.</summary>
internal enum WorkerOutputStream
{
/// <summary>Standard error: the worker's log.</summary>
StandardError,
/// <summary>Standard output: unused by the worker itself.</summary>
StandardOutput,
}
@@ -11,11 +11,26 @@ public sealed class WorkerProcessHandle : IDisposable
IWorkerProcess process,
WorkerProcessCommandLine commandLine,
DateTimeOffset launchedAt)
: this(process, commandLine, launchedAt, outputCapture: null)
{
}
/// <summary>Initializes a new instance of the WorkerProcessHandle class with an output capture.</summary>
/// <param name="process">The underlying worker process.</param>
/// <param name="commandLine">The command line and arguments used to launch the process.</param>
/// <param name="launchedAt">The time when the process was launched.</param>
/// <param name="outputCapture">The capture draining the worker's redirected output, if any.</param>
internal WorkerProcessHandle(
IWorkerProcess process,
WorkerProcessCommandLine commandLine,
DateTimeOffset launchedAt,
WorkerOutputCapture? outputCapture)
{
Process = process;
ProcessId = process.Id;
CommandLine = commandLine;
LaunchedAt = launchedAt;
OutputCapture = outputCapture;
}
/// <summary>Gets the underlying worker process.</summary>
@@ -30,6 +45,12 @@ public sealed class WorkerProcessHandle : IDisposable
/// <summary>Gets the time when the process was launched.</summary>
public DateTimeOffset LaunchedAt { get; }
/// <summary>
/// Gets the capture draining the worker's redirected stderr/stdout, or <c>null</c>. It needs no
/// disposal: it ends on its own at end-of-stream, when the worker exits.
/// </summary>
internal WorkerOutputCapture? OutputCapture { get; }
/// <summary>Disposes the underlying worker process.</summary>
public void Dispose()
{
@@ -63,6 +63,13 @@ public sealed class WorkerProcessLauncher : IWorkerProcessLauncher
private readonly WorkerOptions _workerOptions;
private readonly AlarmsOptions _alarmsOptions;
private readonly ILogger<WorkerProcessLauncher> _logger;
private readonly ILogger _workerOutputLogger;
/// <summary>
/// How long a startup failure waits for the exited worker's stderr to reach end-of-stream, so
/// its last lines make it into the failure message.
/// </summary>
internal static readonly TimeSpan StandardErrorDrainWait = TimeSpan.FromSeconds(1);
/// <summary>
/// Initializes the worker process launcher with gateway options and dependencies.
@@ -73,13 +80,19 @@ public sealed class WorkerProcessLauncher : IWorkerProcessLauncher
/// <param name="metrics">Gateway metrics collector.</param>
/// <param name="logger">Optional logger for diagnostic output.</param>
/// <param name="timeProvider">Optional time provider for timestamps.</param>
/// <param name="loggerFactory">
/// Optional logger factory for the forwarded worker stderr/stdout lines (category
/// <see cref="WorkerOutputCapture.LogCategory"/>). Without it the lines are still drained and
/// kept for startup-failure messages, but not logged.
/// </param>
public WorkerProcessLauncher(
IOptions<GatewayOptions> gatewayOptions,
IWorkerProcessFactory processFactory,
IWorkerStartupProbe startupProbe,
GatewayMetrics metrics,
ILogger<WorkerProcessLauncher>? logger = null,
TimeProvider? timeProvider = null)
TimeProvider? timeProvider = null,
ILoggerFactory? loggerFactory = null)
{
ArgumentNullException.ThrowIfNull(gatewayOptions);
ArgumentNullException.ThrowIfNull(processFactory);
@@ -93,6 +106,7 @@ public sealed class WorkerProcessLauncher : IWorkerProcessLauncher
_metrics = metrics;
_timeProvider = timeProvider ?? TimeProvider.System;
_logger = logger ?? NullLogger<WorkerProcessLauncher>.Instance;
_workerOutputLogger = loggerFactory?.CreateLogger(WorkerOutputCapture.LogCategory) ?? NullLogger.Instance;
}
/// <inheritdoc />
@@ -133,6 +147,14 @@ public sealed class WorkerProcessLauncher : IWorkerProcessLauncher
exception);
}
// Started before anything else so the worker can never block on a full stderr pipe. It
// runs until the worker exits, whichever way this launch ends.
WorkerOutputCapture? outputCapture = WorkerOutputCapture.StartIfRedirected(
process,
request.SessionId,
request.Nonce,
_workerOutputLogger);
try
{
using CancellationTokenSource startupTimeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
@@ -144,7 +166,7 @@ public sealed class WorkerProcessLauncher : IWorkerProcessLauncher
.WaitUntilReadyAsync(process, request, startupTimeout.Token)
.ConfigureAwait(false);
return new WorkerProcessHandle(process, commandLine, startedAt);
return new WorkerProcessHandle(process, commandLine, startedAt, outputCapture);
}
catch (OperationCanceledException exception) when (!cancellationToken.IsCancellationRequested)
{
@@ -167,9 +189,23 @@ public sealed class WorkerProcessLauncher : IWorkerProcessLauncher
"Worker process failed during startup.",
exception);
}
catch (WorkerProcessLaunchException)
catch (WorkerProcessLaunchException exception)
{
bool exited = HasExitedSafely(process);
KillAndDispose(process, "StartupFailed");
if (outputCapture is not null
&& exited
&& exception.ErrorCode == WorkerProcessLaunchErrorCode.StartupFailed)
{
// The probe saw the worker already gone: say what it wrote on the way out.
await outputCapture.WaitForStandardErrorDrainedAsync(StandardErrorDrainWait).ConfigureAwait(false);
string message = WorkerOutputCapture.AppendStandardErrorTail(outputCapture, exception.Message);
if (!ReferenceEquals(message, exception.Message))
{
throw new WorkerProcessLaunchException(exception.ErrorCode, message, exception);
}
}
throw;
}
}
@@ -197,6 +233,14 @@ public sealed class WorkerProcessLauncher : IWorkerProcessLauncher
UseShellExecute = false,
CreateNoWindow = true,
ErrorDialog = false,
// The worker logs to stderr. Without redirection CreateNoWindow gives it a hidden
// console of its own and every line is lost; redirected, WorkerOutputCapture forwards
// the lines to the gateway log and keeps a tail for startup failures (#259). Stdout is
// redirected too, so a stray write cannot land in the gateway's own stdout (the NSSM
// stdout log) now that the child's standard handles are set explicitly.
RedirectStandardError = true,
RedirectStandardOutput = true,
};
foreach (string argument in arguments)
@@ -324,6 +368,18 @@ public sealed class WorkerProcessLauncher : IWorkerProcessLauncher
}
}
private static bool HasExitedSafely(IWorkerProcess process)
{
try
{
return process.HasExited;
}
catch (InvalidOperationException)
{
return false;
}
}
private static int? SafeProcessId(IWorkerProcess process)
{
try
@@ -154,6 +154,35 @@ public sealed class SessionWorkerClientFactoryFakeWorkerTests : IAsyncLifetime
Assert.True(launcher.Process.IsDisposed);
}
/// <summary>
/// mxaccessgw#259: the early-exit failure ends with the tail of the worker's stderr, so the
/// operator sees why it died, not only its exit code.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task CreateAsync_WhenWorkerExitsBeforeConnecting_FailureCarriesStderrTail()
{
ExitBeforeConnectLauncher launcher = new(
"level=Information event=WorkerBootstrapSucceeded session_id=s\n"
+ "level=Error event=WorkerBootstrapUnexpectedFailure exit_code=3 exception_type=System.IO.FileNotFoundException\n");
using GatewayMetrics metrics = new();
SessionWorkerClientFactory factory = new(
launcher,
Options.Create(CreateOptions(startupTimeoutSeconds: 20)),
metrics,
NullLoggerFactory.Instance);
GatewaySession session = CreateSession(startupTimeout: TimeSpan.FromSeconds(20));
WorkerProcessLaunchException exception = await Assert.ThrowsAsync<WorkerProcessLaunchException>(
async () => await factory.CreateAsync(session, CancellationToken.None).WaitAsync(HangGuardTimeout));
Assert.Equal(WorkerProcessLaunchErrorCode.StartupFailed, exception.ErrorCode);
Assert.Contains("exited with code 3", exception.Message);
Assert.Contains("Last worker stderr output:", exception.Message);
Assert.EndsWith("exception_type=System.IO.FileNotFoundException", exception.Message);
Assert.True(launcher.Process.IsDisposed);
}
/// <summary>
/// WRK-006: a <c>Kill</c> that throws during launch-failure cleanup does not replace the
/// startup failure, and the process handle is still disposed.
@@ -461,7 +490,7 @@ public sealed class SessionWorkerClientFactoryFakeWorkerTests : IAsyncLifetime
}
/// <summary>Fake launcher whose worker exits with code 3 shortly after start, never connecting.</summary>
private sealed class ExitBeforeConnectLauncher : IWorkerProcessLauncher
private sealed class ExitBeforeConnectLauncher(string? standardError = null) : IWorkerProcessLauncher
{
/// <summary>Gets the fake worker process.</summary>
public FakeWorkerProcess Process { get; } = new(processId: 5791);
@@ -473,7 +502,23 @@ public sealed class SessionWorkerClientFactoryFakeWorkerTests : IAsyncLifetime
{
_ = Task.Delay(TimeSpan.FromMilliseconds(50), CancellationToken.None)
.ContinueWith(_ => Process.MarkExited(3), TaskScheduler.Default);
return Task.FromResult(CreateHandle(Process));
if (standardError is null)
{
return Task.FromResult(CreateHandle(Process));
}
WorkerOutputCapture capture = WorkerOutputCapture.Start(
new StringReader(standardError),
standardOutput: null,
request.SessionId,
Process.Id,
request.Nonce,
Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance);
return Task.FromResult(new WorkerProcessHandle(
Process,
new WorkerProcessCommandLine("fake-worker.exe", []),
DateTimeOffset.UtcNow,
capture));
}
}
@@ -0,0 +1,287 @@
using System.Diagnostics;
using System.Text;
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.MxGateway.Server.Workers;
using ZB.MOM.WW.MxGateway.Tests.TestSupport;
namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Workers;
/// <summary>
/// mxaccessgw#259: the worker's redirected stderr/stdout is drained, forwarded to the gateway log
/// at the worker's own level, scrubbed of the bootstrap nonce, and kept as a bounded tail.
/// </summary>
public sealed class WorkerOutputCaptureTests
{
private const string SessionId = "session-259";
private const string Nonce = "nonce-0123456789abcdef";
private static readonly TimeSpan HangGuard = TimeSpan.FromSeconds(30);
/// <summary>Worker log lines are logged at the level the worker gave them; anything unstructured on stderr is a Warning.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Forwards_EachLine_AtTheWorkersLevel()
{
RecordingLogger<WorkerOutputCaptureTests> logger = new();
WorkerOutputCapture capture = WorkerOutputCapture.Start(
new StringReader(
"level=Information event=WorkerBootstrapSucceeded session_id=s\n"
+ "level=Warning event=AlarmPollFailed hresult=none\n"
+ "level=Error event=WorkerPipeConnectionFailed exit_code=3\n"
+ "Unhandled Exception: System.IO.FileNotFoundException\n"),
new StringReader("stray stdout\n"),
SessionId,
processId: 4242,
Nonce,
logger);
await capture.Completion.WaitAsync(HangGuard);
Assert.Equal(5, logger.Entries.Count);
Assert.Contains(logger.Entries, e => e.Level == LogLevel.Information && e.Message.Contains("WorkerBootstrapSucceeded", StringComparison.Ordinal));
Assert.Contains(logger.Entries, e => e.Level == LogLevel.Warning && e.Message.Contains("AlarmPollFailed", StringComparison.Ordinal));
Assert.Contains(logger.Entries, e => e.Level == LogLevel.Error && e.Message.Contains("WorkerPipeConnectionFailed", StringComparison.Ordinal));
Assert.Contains(logger.Entries, e => e.Level == LogLevel.Warning && e.Message.Contains("Unhandled Exception", StringComparison.Ordinal));
Assert.Contains(logger.Entries, e => e.Level == LogLevel.Information && e.Message.Contains("stdout: stray stdout", StringComparison.Ordinal));
Assert.All(logger.Entries, e => Assert.Contains(SessionId, e.Message, StringComparison.Ordinal));
Assert.All(logger.Entries, e => Assert.Contains("4242", e.Message, StringComparison.Ordinal));
// The tail is stderr only.
Assert.DoesNotContain("stray stdout", capture.GetStandardErrorTail(), StringComparison.Ordinal);
Assert.EndsWith("Unhandled Exception: System.IO.FileNotFoundException", capture.GetStandardErrorTail(), StringComparison.Ordinal);
}
/// <summary>The session nonce never reaches the gateway log or the tail, even if the worker wrote it.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Scrubs_TheSessionNonce_FromLogAndTail()
{
RecordingLogger<WorkerOutputCaptureTests> logger = new();
WorkerOutputCapture capture = WorkerOutputCapture.Start(
new StringReader($"crash dump env MXGATEWAY_WORKER_NONCE={Nonce} end\n"),
standardOutput: null,
SessionId,
processId: 1,
Nonce,
logger);
await capture.Completion.WaitAsync(HangGuard);
Assert.DoesNotContain(Nonce, capture.GetStandardErrorTail(), StringComparison.Ordinal);
Assert.Contains("[redacted]", capture.GetStandardErrorTail(), StringComparison.Ordinal);
Assert.All(logger.Entries, e => Assert.DoesNotContain(Nonce, e.Message, StringComparison.Ordinal));
}
/// <summary>The tail keeps only the newest lines, within both the line and character bounds, oldest first.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Tail_IsBoundedByLinesAndCharacters()
{
StringBuilder many = new();
for (int i = 0; i < 500; i++)
{
many.Append("line ").Append(i).Append('\n');
}
WorkerOutputCapture byLines = WorkerOutputCapture.Start(
new StringReader(many.ToString()), null, SessionId, 1, Nonce, new RecordingLogger<WorkerOutputCaptureTests>());
await byLines.Completion.WaitAsync(HangGuard);
string[] lines = byLines.GetStandardErrorTail().Split('\n');
Assert.Equal(WorkerOutputCapture.MaxTailLines, lines.Length);
Assert.Equal("line 450", lines[0]);
Assert.Equal("line 499", lines[^1]);
string wide = new('x', 1000);
WorkerOutputCapture byCharacters = WorkerOutputCapture.Start(
new StringReader(string.Concat(Enumerable.Repeat(wide + "\n", 20)) + "last\n"),
null,
SessionId,
1,
Nonce,
new RecordingLogger<WorkerOutputCaptureTests>());
await byCharacters.Completion.WaitAsync(HangGuard);
string tail = byCharacters.GetStandardErrorTail();
Assert.True(tail.Length <= WorkerOutputCapture.MaxTailCharacters + WorkerOutputCapture.MaxTailLines, $"tail length {tail.Length}");
Assert.EndsWith("last", tail, StringComparison.Ordinal);
WorkerOutputCapture oneHugeLine = WorkerOutputCapture.Start(
new StringReader(new string('y', 100_000) + "\n"), null, SessionId, 1, Nonce, new RecordingLogger<WorkerOutputCaptureTests>());
await oneHugeLine.Completion.WaitAsync(HangGuard);
Assert.True(oneHugeLine.GetStandardErrorTail().Length < WorkerOutputCapture.MaxLineCharacters + 32);
Assert.EndsWith("...[truncated]", oneHugeLine.GetStandardErrorTail(), StringComparison.Ordinal);
}
/// <summary>
/// A log sink that blocks never stops the drain: stderr still reaches end-of-stream and the
/// tail is complete, and once the sink recovers the dropped lines are reported.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task BlockedLogger_DoesNotStopTheDrain()
{
using BlockingLogger logger = new();
StringBuilder many = new();
for (int i = 0; i < 5000; i++)
{
many.Append("level=Information event=Line n=").Append(i).Append('\n');
}
WorkerOutputCapture capture = WorkerOutputCapture.Start(
new StringReader(many.ToString()), null, SessionId, 1, Nonce, logger);
Task drained = capture.WaitForStandardErrorDrainedAsync(HangGuard);
await drained.WaitAsync(HangGuard);
Assert.EndsWith("n=4999", capture.GetStandardErrorTail(), StringComparison.Ordinal);
Assert.False(capture.Completion.IsCompleted);
logger.Release();
await capture.Completion.WaitAsync(HangGuard);
Assert.Contains(logger.Messages, m => m.Contains("Dropped", StringComparison.Ordinal));
Assert.True(logger.Messages.Count < 5000);
}
/// <summary>A throwing log sink does not end the drain.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ThrowingLogger_DoesNotStopTheDrain()
{
WorkerOutputCapture capture = WorkerOutputCapture.Start(
new StringReader("a\nb\nc\n"), null, SessionId, 1, Nonce, new ThrowingLogger());
await capture.Completion.WaitAsync(HangGuard);
Assert.Equal("a\nb\nc", capture.GetStandardErrorTail());
}
/// <summary>Each reader is disposed when it reaches end-of-stream, so nothing outlives the worker.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Readers_AreDisposedAtEndOfStream()
{
TrackingReader standardError = new("e\n");
TrackingReader standardOutput = new("o\n");
WorkerOutputCapture capture = WorkerOutputCapture.Start(
standardError, standardOutput, SessionId, 1, Nonce, new RecordingLogger<WorkerOutputCaptureTests>());
await capture.Completion.WaitAsync(HangGuard);
Assert.True(standardError.Disposed);
Assert.True(standardOutput.Disposed);
}
/// <summary>A process that exposes no redirected stream gets no capture.</summary>
[Fact]
public void StartIfRedirected_WithoutRedirectedStreams_ReturnsNull()
{
Assert.Null(WorkerOutputCapture.StartIfRedirected(
new FakeWorkerProcess(processId: 1), SessionId, Nonce, new RecordingLogger<WorkerOutputCaptureTests>()));
}
/// <summary>The tail is appended to a failure message only when there is one.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task AppendStandardErrorTail_LeavesTheMessageAloneWithoutOutput()
{
Assert.Equal("boom.", WorkerOutputCapture.AppendStandardErrorTail(null, "boom."));
WorkerOutputCapture empty = WorkerOutputCapture.Start(
new StringReader(string.Empty), null, SessionId, 1, Nonce, new RecordingLogger<WorkerOutputCaptureTests>());
await empty.Completion.WaitAsync(HangGuard);
Assert.Equal("boom.", WorkerOutputCapture.AppendStandardErrorTail(empty, "boom."));
WorkerOutputCapture some = WorkerOutputCapture.Start(
new StringReader("why\n"), null, SessionId, 1, Nonce, new RecordingLogger<WorkerOutputCaptureTests>());
await some.Completion.WaitAsync(HangGuard);
Assert.Equal("boom. Last worker stderr output:\nwhy", WorkerOutputCapture.AppendStandardErrorTail(some, "boom."));
}
/// <summary>
/// Real child process writing far more than a pipe buffer to stderr: with the stream
/// redirected and drained the child runs to completion instead of blocking on a full pipe,
/// and its last line is in the tail.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task RealProcess_WritingMoreThanThePipeBuffer_DoesNotBlock()
{
ProcessStartInfo startInfo = OperatingSystem.IsWindows()
? new ProcessStartInfo(
Path.Combine(Environment.SystemDirectory, "cmd.exe"),
"/d /c \"for /L %i in (1,1,3000) do @echo stderr line %i 1>&2\"")
: new ProcessStartInfo(
"/bin/sh",
["-c", "i=1; while [ $i -le 3000 ]; do echo \"stderr line $i\" >&2; i=$((i+1)); done"]);
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardOutput = true;
using IWorkerProcess process = new SystemWorkerProcessFactory().Start(startInfo);
WorkerOutputCapture? capture = WorkerOutputCapture.StartIfRedirected(
process, SessionId, Nonce, new RecordingLogger<WorkerOutputCaptureTests>());
Assert.NotNull(capture);
await process.WaitForExitAsync(CancellationToken.None).AsTask().WaitAsync(HangGuard);
await capture.Completion.WaitAsync(HangGuard);
Assert.Equal(0, process.ExitCode);
Assert.EndsWith("stderr line 3000", capture.GetStandardErrorTail().TrimEnd(), StringComparison.Ordinal);
}
private sealed class TrackingReader(string text) : StringReader(text)
{
public bool Disposed { get; private set; }
protected override void Dispose(bool disposing)
{
Disposed = true;
base.Dispose(disposing);
}
}
private sealed class ThrowingLogger : ILogger
{
public IDisposable? BeginScope<TState>(TState state)
where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) =>
throw new InvalidOperationException("sink down");
}
private sealed class BlockingLogger : ILogger, IDisposable
{
private readonly ManualResetEventSlim _gate = new(initialState: false);
private readonly object _syncRoot = new();
private readonly List<string> _messages = [];
public IReadOnlyList<string> Messages
{
get
{
lock (_syncRoot)
{
return _messages.ToArray();
}
}
}
public void Release() => _gate.Set();
public IDisposable? BeginScope<TState>(TState state)
where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
_gate.Wait(HangGuard);
lock (_syncRoot)
{
_messages.Add(formatter(state, exception));
}
}
public void Dispose() => _gate.Dispose();
}
}
@@ -1,4 +1,5 @@
using System.Diagnostics;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.MxGateway.Contracts;
using ZB.MOM.WW.MxGateway.Server.Configuration;
@@ -49,6 +50,8 @@ public sealed class WorkerProcessLauncherTests
Assert.Equal(Path.GetFullPath(executablePath), processFactory.LastStartInfo.FileName);
Assert.False(processFactory.LastStartInfo.UseShellExecute);
Assert.True(processFactory.LastStartInfo.CreateNoWindow);
Assert.True(processFactory.LastStartInfo.RedirectStandardError);
Assert.True(processFactory.LastStartInfo.RedirectStandardOutput);
Assert.Equal(
["--session-id", SessionId, "--pipe-name", PipeName, "--protocol-version", "1"],
processFactory.LastStartInfo.ArgumentList);
@@ -339,6 +342,57 @@ public sealed class WorkerProcessLauncherTests
Assert.True(process.DisposeCalled);
}
/// <summary>
/// mxaccessgw#259: a worker the probe finds already exited fails with its stderr tail in the
/// message, and its stderr is forwarded to the worker log category without the nonce.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task LaunchAsync_WhenWorkerAlreadyExited_FailureCarriesStderrTail()
{
using TestDirectory directory = TestDirectory.Create();
string executablePath = directory.CreateWorkerExecutable(machine: 0x014c);
FakeWorkerProcess process = new(processId: 1234)
{
HasExited = true,
ExitCode = 2,
StandardError = new StringReader(
$"level=Error event=WorkerBootstrapFailed exit_code=2 errors=Unknown option '--bogus'. {Nonce}\n"),
};
RecordingLoggerProvider loggers = new();
using Microsoft.Extensions.Logging.ILoggerFactory loggerFactory =
Microsoft.Extensions.Logging.LoggerFactory.Create(builder => builder.AddProvider(loggers));
GatewayOptions options = new()
{
Worker = new WorkerOptions
{
ExecutablePath = executablePath,
RequiredArchitecture = WorkerArchitecture.X86,
},
};
WorkerProcessLauncher launcher = new(
Options.Create(options),
new FakeWorkerProcessFactory(process),
new WorkerProcessStartedProbe(),
new GatewayMetrics(),
loggerFactory: loggerFactory);
WorkerProcessLaunchException exception =
await Assert.ThrowsAsync<WorkerProcessLaunchException>(
async () => await launcher.LaunchAsync(CreateRequest()));
Assert.Equal(WorkerProcessLaunchErrorCode.StartupFailed, exception.ErrorCode);
Assert.Contains("exit code 2", exception.Message);
Assert.Contains("Last worker stderr output:", exception.Message);
Assert.Contains("WorkerBootstrapFailed", exception.Message);
Assert.DoesNotContain(Nonce, exception.Message);
await Eventually.WaitUntilAsync(
() => loggers.Entries.Any(e => e.Category == WorkerOutputCapture.LogCategory
&& e.Message.Contains("WorkerBootstrapFailed", StringComparison.Ordinal)),
TimeSpan.FromSeconds(10));
Assert.DoesNotContain(loggers.Entries, e => e.Message.Contains(Nonce, StringComparison.Ordinal));
}
private static WorkerProcessLauncher CreateLauncher(
string executablePath,
IWorkerProcessFactory processFactory,
@@ -383,6 +437,41 @@ public sealed class WorkerProcessLauncherTests
pipeReservation);
}
/// <summary>Logger provider that records category and formatted message of every entry.</summary>
private sealed class RecordingLoggerProvider : Microsoft.Extensions.Logging.ILoggerProvider
{
private readonly System.Collections.Concurrent.ConcurrentQueue<(string Category, string Message)> _entries = new();
/// <summary>Gets the recorded entries.</summary>
public IReadOnlyCollection<(string Category, string Message)> Entries => _entries.ToArray();
/// <inheritdoc />
public Microsoft.Extensions.Logging.ILogger CreateLogger(string categoryName) => new Logger(categoryName, _entries);
/// <inheritdoc />
public void Dispose()
{
}
private sealed class Logger(
string category,
System.Collections.Concurrent.ConcurrentQueue<(string Category, string Message)> entries) : Microsoft.Extensions.Logging.ILogger
{
public IDisposable? BeginScope<TState>(TState state)
where TState : notnull => null;
public bool IsEnabled(Microsoft.Extensions.Logging.LogLevel logLevel) => true;
public void Log<TState>(
Microsoft.Extensions.Logging.LogLevel logLevel,
Microsoft.Extensions.Logging.EventId eventId,
TState state,
Exception? exception,
Func<TState, Exception?, string> formatter) =>
entries.Enqueue((category, formatter(state, exception)));
}
}
/// <summary>Fake worker process factory for testing process launch logic.</summary>
private sealed class FakeWorkerProcessFactory(IWorkerProcess process) : IWorkerProcessFactory
{
@@ -32,6 +32,12 @@ public sealed class FakeWorkerProcess(int processId) : IWorkerProcess
/// <inheritdoc />
public int? ExitCode { get; set; }
/// <inheritdoc />
public TextReader? StandardError { get; set; }
/// <inheritdoc />
public TextReader? StandardOutput { get; set; }
/// <summary>Gets the number of times <see cref="Kill"/> was called.</summary>
public int KillCount { get; private set; }
@@ -378,9 +378,10 @@ public sealed class WorkerPipeSession
"WorkerRecordInfoPin",
new Dictionary<string, object?> { ["status"] = pinStatus });
// The gateway does not capture worker stderr, so the log line above is rarely
// seen; WorkerReady carries the outcome to the gateway, which logs it and shows it
// on the dashboard. A runtime that already filled the field keeps its own value.
// The gateway forwards the line above at Information whatever it says; WorkerReady
// carries the outcome to the gateway, which grades it (Warning when unpinned) and
// shows it on the dashboard. A runtime that already filled the field keeps its own
// value.
if (string.IsNullOrEmpty(ready.RecordInfoPinStatus))
{
ready.RecordInfoPinStatus = pinStatus;