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
+2 -1
View File
@@ -210,7 +210,8 @@ Consequences, and how this sits with the existing failover/reconcile design:
per minute) `AlarmSnapshotTruncated` warning carrying the cap, the record
counts, and the running truncated-fetch total — identifiers and counts only,
never tag names, values, limits, or comments. Be honest about its reach: it
goes to the worker's console/stderr, which is captured on dev hosts but is
goes to the worker's stderr, which the gateway forwards to its own log
(since mxaccessgw#259; before that the line was lost), but it is
not a metric, not a dashboard tile, and not part of any session-status or
alarm-feed payload, so a production deployment can truncate indefinitely
without anyone noticing. The structural signal that fixes this landed
+4 -2
View File
@@ -508,8 +508,10 @@ read loop starts after readiness so the handshake has a single owner for its
ordered frames.
`WorkerReady.record_info_pin_status` carries the worker's `MXSTATUS_PROXY`
record-info pin outcome (see `MxAccessWorkerInstanceDesign.md`). The gateway does
not capture worker stderr, so `WorkerClient` is where operators see it: a status
record-info pin outcome (see `MxAccessWorkerInstanceDesign.md`). The worker's own
`WorkerRecordInfoPin` stderr line is forwarded to the gateway log at Information
(see `WorkerProcessLauncher.md`), so `WorkerClient` is where operators see the
outcome graded: a status
starting `pinned ` is logged at Information, anything else at Warning, because an
unpinned worker pays a type-library reload on every data change. It is kept as
`IWorkerClient.RecordInfoPinStatus` and shown on the dashboard's session details
+5 -4
View File
@@ -553,10 +553,11 @@ with the pin alone.
The pin only warms a cache. It changes no MXAccess behaviour, and a failure is never fatal. The
outcome is in `MxStatusProxyRecordInfoPin.Status`. During the handshake `WorkerPipeSession` logs it
as `WorkerRecordInfoPin` and copies it into `WorkerReady.record_info_pin_status`, unless the runtime
already filled that field. The copy is the one operators see: the worker's own log goes to stderr,
which the gateway's launcher does not redirect. The gateway logs the reported status (Warning when
it is not a successful pin) and shows it on the dashboard's session details page; see
`GatewayProcessDesign.md`.
already filled that field. The worker's own log goes to stderr, which the gateway forwards to its
log at the line's level (see `WorkerProcessLauncher.md`), so the `WorkerRecordInfoPin` line itself
is always Information. The copy in `WorkerReady` is the graded one: the gateway logs the reported
status (Warning when it is not a successful pin) and shows it on the dashboard's session details
page; see `GatewayProcessDesign.md`.
If COM creation fails, the worker should send a structured fault with:
+1 -1
View File
@@ -149,7 +149,7 @@ The production binding in `WorkerApplication.Run(string[])` is `EnvironmentVaria
## Logging
The worker writes structured key/value lines to standard error. Standard error is used rather than standard output because the gateway side reads worker stdout for diagnostic capture only, while stderr is reserved for log output that does not interfere with any future stdout-based channel.
The worker writes structured key/value lines to standard error, and nothing to standard output, so stdout stays free for any future stdout-based channel. The gateway's launcher redirects both streams and forwards every line to the gateway log under the `ZB.MOM.WW.MxGateway.Worker` category, at the level in the line's `level=` prefix. It also keeps the last stderr lines for the `StartupFailed` message of a worker that exits before connecting; see `WorkerProcessLauncher.md` "Worker Output Capture". Before mxaccessgw#259 the streams were not redirected and these lines were lost.
### The logger contract
+62 -3
View File
@@ -61,8 +61,63 @@ after that and before it connects is caught by the session factory instead:
so an early exit fails the open at once with `StartupFailed` and the worker's
exit code rather than holding the open (and its session slot) for the whole
startup timeout and reporting a timeout. Once the pipe is connected, a worker
exit surfaces as pipe end-of-stream in the handshake reads. The worker's stderr
is not redirected, so the failure carries the exit code only.
exit surfaces as pipe end-of-stream in the handshake reads. Both early-exit
failures (the probe's and the session factory's) end with the tail of the
worker's stderr, `Last worker stderr output:` followed by up to the last 50
lines / 4 KB. The factory first waits up to one second for stderr to reach
end-of-stream so the lines the worker wrote on its way out are included. The
`StartupFailed` message reaches the gateway log (`Failed to open gateway
session`) and the session's fault reason; a gRPC client still sees only
`Failed to open session <id>.`
## Worker Output Capture
The launcher starts the worker with `RedirectStandardError` and
`RedirectStandardOutput` set and hands both streams to `WorkerOutputCapture`
before anything else runs (mxaccessgw#259).
Before this change the worker's output was lost. It was started with
`CreateNoWindow` and no redirection, which gives the child a hidden console of
its own, so its `level=... event=...` log lines reached neither the gateway's
console (console run) nor the NSSM `AppStdout`/`AppStderr` files (service run).
This was checked on windev: a probe child's stderr did not appear in the
parent's redirected files, and the windev service's `stderr.log` and
`stdout.log` held no worker lines. Capturing the output therefore adds log lines
and loses none. Stdout is redirected as well because, once the child's standard
handles are set explicitly, an unredirected stdout would be the gateway's own
(the NSSM stdout log). The worker writes nothing to stdout itself.
Each line is forwarded to the gateway log under the category
`ZB.MOM.WW.MxGateway.Worker`, with the session id, worker process id and stream
as properties. It uses one category rather than one per session because the
logger factory caches categories for the life of the process. The level follows
the worker's own `level=` prefix (`Information`, `Warning`, `Error`). Any other
stderr text, such as CLR or native crash output, is logged as `Warning`, and
other stdout text as `Information`. Lines longer than 2048 characters are cut
and marked `...[truncated]`. The capture also keeps the most recent stderr lines
in a bounded tail for the startup-failure messages above.
The capture cannot block the worker or leak:
- The pipes are always drained. A reader only appends the line to the tail and
offers it to a bounded drop-oldest queue (1024 lines), which never waits. A
separate task does the logging. When the log sink falls behind, the oldest
queued lines are dropped and a `Dropped N worker output lines` warning is
logged. Backpressure never reaches the worker's `Console.Error` writes, some
of which run on its STA thread. A throwing log sink is ignored.
- The readers run until end-of-stream and then dispose their own reader.
End-of-stream arrives when the worker exits, and the gateway always kills the
worker before disposing its process handle, so the capture needs no
cancellation and does not cut off the worker's last lines.
The worker redacts its own lines (`WorkerLogRedactor`: nonce, secret, password,
token, credential and API-key fields and assignments; the unhandled-exception
hook logs the exception type only). As defense in depth, the capture also
replaces any occurrence of the session's bootstrap nonce, the one secret the
gateway gives the worker, with `[redacted]` before a line is logged or kept.
There is no option to turn the capture off. Worker log volume is low unless
`MXGATEWAY_WORKER_LOG_COMMANDS` is set, and that variable is what turns on the
noisy per-command lines.
The startup probe runs once, bounded by `WorkerOptions.StartupTimeoutSeconds`;
it is not retried. The default probe only checks that the process is still
@@ -88,9 +143,13 @@ the same rule.
Run the focused launcher tests after changing process launch behavior:
```bash
dotnet test src/ZB.MOM.WW.MxGateway.Tests/ZB.MOM.WW.MxGateway.Tests.csproj --filter WorkerProcessLauncherTests
dotnet test src/ZB.MOM.WW.MxGateway.Tests/ZB.MOM.WW.MxGateway.Tests.csproj --filter "FullyQualifiedName~WorkerProcessLauncherTests|FullyQualifiedName~WorkerOutputCaptureTests"
```
`WorkerOutputCaptureTests` includes a real child process (`/bin/sh`, or `cmd.exe`
on Windows) that writes well past a pipe buffer to stderr, to show the drain
cannot block the child.
Run the gateway build because the launcher is part of `ZB.MOM.WW.MxGateway.Server`:
```bash
+2 -1
View File
@@ -965,7 +965,8 @@ registry and reloads the type library on each call, which a production trace put
at about 70% of the STA's CPU. Holding one reference makes the lookup a cache
hit. A failed pin is never fatal, since MXAccess behaves the same either way, but
the gateway logs it as a warning and shows it on the dashboard's session details
page, because the worker's own stderr is not captured.
page. The worker's own stderr line for it is forwarded to the gateway log at
Information, so the gateway's grading of the reported status is the line to watch.
Worker shutdown:
@@ -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;