From ee0f8368867f56b1fde9e0fff6e25ed7fbcb8f04 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 13:10:12 -0500 Subject: [PATCH] fix(workers): capture worker stderr/stdout, forward it to the gateway log, and attach the stderr tail to early-exit StartupFailed (WRK-002, #259) The worker was started with CreateNoWindow and no redirection, so its log lines went to a hidden console of its own and were lost under both a console run and the NSSM service (verified on windev). The launcher now redirects both streams and WorkerOutputCapture drains them: each line is forwarded under the ZB.MOM.WW.MxGateway.Worker category at the worker's own level, the session nonce is scrubbed, and the last 50 lines / 4 KB of stderr are kept. The drain never waits on the logger (bounded drop-oldest queue) and ends at EOF when the worker exits. A worker that exits before connecting (session factory race) or that the probe finds already exited now fails StartupFailed with the stderr tail. --- docs/DesignDecisions.md | 3 +- docs/GatewayProcessDesign.md | 6 +- docs/MxAccessWorkerInstanceDesign.md | 9 +- docs/WorkerBootstrap.md | 2 +- docs/WorkerProcessLauncher.md | 65 +++- gateway.md | 3 +- .../WorkerLiveMxAccessSmokeTests.cs | 6 + .../Sessions/SessionWorkerClientFactory.cs | 25 +- .../Workers/IWorkerProcess.cs | 12 + .../Workers/SystemWorkerProcess.cs | 6 + .../Workers/WorkerOutputCapture.cs | 363 ++++++++++++++++++ .../Workers/WorkerProcessHandle.cs | 21 + .../Workers/WorkerProcessLauncher.cs | 62 ++- ...ssionWorkerClientFactoryFakeWorkerTests.cs | 49 ++- .../Workers/WorkerOutputCaptureTests.cs | 287 ++++++++++++++ .../Workers/WorkerProcessLauncherTests.cs | 89 +++++ .../TestSupport/FakeWorkerProcess.cs | 6 + .../Ipc/WorkerPipeSession.cs | 7 +- 18 files changed, 995 insertions(+), 26 deletions(-) create mode 100644 src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerOutputCapture.cs create mode 100644 src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerOutputCaptureTests.cs diff --git a/docs/DesignDecisions.md b/docs/DesignDecisions.md index fce12706..134a6ebc 100644 --- a/docs/DesignDecisions.md +++ b/docs/DesignDecisions.md @@ -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 diff --git a/docs/GatewayProcessDesign.md b/docs/GatewayProcessDesign.md index 02feb937..9597a569 100644 --- a/docs/GatewayProcessDesign.md +++ b/docs/GatewayProcessDesign.md @@ -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 diff --git a/docs/MxAccessWorkerInstanceDesign.md b/docs/MxAccessWorkerInstanceDesign.md index 3d1be6d9..42dc6830 100644 --- a/docs/MxAccessWorkerInstanceDesign.md +++ b/docs/MxAccessWorkerInstanceDesign.md @@ -537,10 +537,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: diff --git a/docs/WorkerBootstrap.md b/docs/WorkerBootstrap.md index c66f23c8..835439ee 100644 --- a/docs/WorkerBootstrap.md +++ b/docs/WorkerBootstrap.md @@ -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 diff --git a/docs/WorkerProcessLauncher.md b/docs/WorkerProcessLauncher.md index 82d0cedc..1b2fcab3 100644 --- a/docs/WorkerProcessLauncher.md +++ b/docs/WorkerProcessLauncher.md @@ -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 .` + +## 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 diff --git a/gateway.md b/gateway.md index 6fe1a62b..7c4de803 100644 --- a/gateway.md +++ b/gateway.md @@ -959,7 +959,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: diff --git a/src/ZB.MOM.WW.MxGateway.IntegrationTests/WorkerLiveMxAccessSmokeTests.cs b/src/ZB.MOM.WW.MxGateway.IntegrationTests/WorkerLiveMxAccessSmokeTests.cs index 392bf85f..c6c4542d 100644 --- a/src/ZB.MOM.WW.MxGateway.IntegrationTests/WorkerLiveMxAccessSmokeTests.cs +++ b/src/ZB.MOM.WW.MxGateway.IntegrationTests/WorkerLiveMxAccessSmokeTests.cs @@ -2493,6 +2493,12 @@ public sealed class WorkerLiveMxAccessSmokeTests(ITestOutputHelper output) /// public int? ExitCode => process.HasExited ? process.ExitCode : null; + /// Gets null: the factory reads both streams itself, into the test output. + public TextReader? StandardError => null; + + /// Gets null: the factory reads both streams itself, into the test output. + public TextReader? StandardOutput => null; + /// public async ValueTask WaitForExitAsync(CancellationToken cancellationToken) { diff --git a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionWorkerClientFactory.cs b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionWorkerClientFactory.cs index 8db661a2..d7ef5553 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionWorkerClientFactory.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Sessions/SessionWorkerClientFactory.cs @@ -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 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. /// /// The named pipe. - /// The launched worker process. + /// The launched worker process. /// Session id, for the failure message. /// Cancellation token (the startup deadline and the caller's). /// A task that represents the asynchronous operation. 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): diff --git a/src/ZB.MOM.WW.MxGateway.Server/Workers/IWorkerProcess.cs b/src/ZB.MOM.WW.MxGateway.Server/Workers/IWorkerProcess.cs index b36bcbdf..52e6a8db 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Workers/IWorkerProcess.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Workers/IWorkerProcess.cs @@ -20,6 +20,18 @@ public interface IWorkerProcess : IDisposable /// int? ExitCode { get; } + /// + /// The redirected standard error reader, or null when standard error is not redirected + /// or the implementation reads it itself. The launcher drains it (see ). + /// + TextReader? StandardError { get; } + + /// + /// The redirected standard output reader, or null when standard output is not + /// redirected or the implementation reads it itself. + /// + TextReader? StandardOutput { get; } + /// /// Waits for the process to exit with the specified cancellation token. /// diff --git a/src/ZB.MOM.WW.MxGateway.Server/Workers/SystemWorkerProcess.cs b/src/ZB.MOM.WW.MxGateway.Server/Workers/SystemWorkerProcess.cs index 69a5621e..288c6a46 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Workers/SystemWorkerProcess.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Workers/SystemWorkerProcess.cs @@ -16,6 +16,12 @@ internal sealed class SystemWorkerProcess(Process process) : IWorkerProcess /// public int? ExitCode => process.HasExited ? process.ExitCode : null; + /// + public TextReader? StandardError => process.StartInfo.RedirectStandardError ? process.StandardError : null; + + /// + public TextReader? StandardOutput => process.StartInfo.RedirectStandardOutput ? process.StandardOutput : null; + /// public async ValueTask WaitForExitAsync(CancellationToken cancellationToken) { diff --git a/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerOutputCapture.cs b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerOutputCapture.cs new file mode 100644 index 00000000..3508bde3 --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerOutputCapture.cs @@ -0,0 +1,363 @@ +using System.Threading.Channels; +using Microsoft.Extensions.Logging; + +namespace ZB.MOM.WW.MxGateway.Server.Workers; + +/// +/// 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). +/// +/// +/// +/// Before this capture existed the worker was started with CreateNoWindow 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 level=... event=... lines now appear in the gateway log under the +/// category, with the session id and worker process id as properties. +/// +/// +/// 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 Console.Error writes, which can run on its STA thread. +/// +/// +/// 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. +/// +/// +/// The worker redacts its own log lines (WorkerLogRedactor). 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 [redacted] before a line is logged or kept. +/// +/// +internal sealed class WorkerOutputCapture +{ + /// Logger category the forwarded worker lines are written under. + public const string LogCategory = "ZB.MOM.WW.MxGateway.Worker"; + + /// Most stderr lines kept for the startup-failure tail. + public const int MaxTailLines = 50; + + /// Most characters kept for the startup-failure tail. + public const int MaxTailCharacters = 4096; + + /// Longest single line forwarded or kept; the rest is cut and marked. + public const int MaxLineCharacters = 2048; + + /// Lines that may wait for the logger before the oldest are dropped. + 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 _forwardQueue; + private readonly Queue _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( + 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); + } + + /// + /// Gets a task that completes once both streams reached end-of-stream and every queued line + /// was logged. It never faults. + /// + public Task Completion => _completion; + + /// + /// Starts draining the redirected streams of , or returns + /// null when neither stream is redirected (test doubles, or a process factory that + /// reads the streams itself). + /// + /// The started worker process. + /// Session id, logged with every line. + /// The session's bootstrap nonce, scrubbed from every line. + /// Logger for the forwarded lines. + /// The running capture, or null. + 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); + } + + /// Starts draining the given readers. + /// Worker stderr, or null. + /// Worker stdout, or null. + /// Session id, logged with every line. + /// Worker process id, logged with every line. + /// The session's bootstrap nonce, scrubbed from every line. + /// Logger for the forwarded lines. + /// The running capture. + 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); + } + + /// + /// Waits, up to , for stderr to reach end-of-stream, so lines the + /// worker wrote just before it exited are in the tail. Never throws. + /// + /// Longest wait. + /// A task that represents the asynchronous operation. + 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. + } + } + + /// Gets the most recent stderr lines (at most lines and characters), oldest first. + /// The lines joined with newlines, or an empty string when nothing was captured. + public string GetStandardErrorTail() + { + lock (_tailLock) + { + return string.Join('\n', _tail); + } + } + + /// + /// 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. + /// + /// The capture, or null. + /// The failure message. + /// The message, with the tail appended when there is one. + 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; + } + + /// Maps a worker log line's level= prefix to a gateway log level. + /// The worker line. + /// The stream it came from. + /// The level to log it at. + internal static LogLevel MapLevel(string line, WorkerOutputStream stream) + { + if (line.StartsWith("level=", StringComparison.Ordinal)) + { + int end = line.IndexOf(' ', 6); + ReadOnlySpan 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); +} + +/// The worker stream a captured line came from. +internal enum WorkerOutputStream +{ + /// Standard error: the worker's log. + StandardError, + + /// Standard output: unused by the worker itself. + StandardOutput, +} diff --git a/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerProcessHandle.cs b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerProcessHandle.cs index fe4f0b04..6dd37604 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerProcessHandle.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerProcessHandle.cs @@ -11,11 +11,26 @@ public sealed class WorkerProcessHandle : IDisposable IWorkerProcess process, WorkerProcessCommandLine commandLine, DateTimeOffset launchedAt) + : this(process, commandLine, launchedAt, outputCapture: null) + { + } + + /// Initializes a new instance of the WorkerProcessHandle class with an output capture. + /// The underlying worker process. + /// The command line and arguments used to launch the process. + /// The time when the process was launched. + /// The capture draining the worker's redirected output, if any. + internal WorkerProcessHandle( + IWorkerProcess process, + WorkerProcessCommandLine commandLine, + DateTimeOffset launchedAt, + WorkerOutputCapture? outputCapture) { Process = process; ProcessId = process.Id; CommandLine = commandLine; LaunchedAt = launchedAt; + OutputCapture = outputCapture; } /// Gets the underlying worker process. @@ -30,6 +45,12 @@ public sealed class WorkerProcessHandle : IDisposable /// Gets the time when the process was launched. public DateTimeOffset LaunchedAt { get; } + /// + /// Gets the capture draining the worker's redirected stderr/stdout, or null. It needs no + /// disposal: it ends on its own at end-of-stream, when the worker exits. + /// + internal WorkerOutputCapture? OutputCapture { get; } + /// Disposes the underlying worker process. public void Dispose() { diff --git a/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerProcessLauncher.cs b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerProcessLauncher.cs index e9445b45..498dbe17 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerProcessLauncher.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerProcessLauncher.cs @@ -63,6 +63,13 @@ public sealed class WorkerProcessLauncher : IWorkerProcessLauncher private readonly WorkerOptions _workerOptions; private readonly AlarmsOptions _alarmsOptions; private readonly ILogger _logger; + private readonly ILogger _workerOutputLogger; + + /// + /// 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. + /// + internal static readonly TimeSpan StandardErrorDrainWait = TimeSpan.FromSeconds(1); /// /// Initializes the worker process launcher with gateway options and dependencies. @@ -73,13 +80,19 @@ public sealed class WorkerProcessLauncher : IWorkerProcessLauncher /// Gateway metrics collector. /// Optional logger for diagnostic output. /// Optional time provider for timestamps. + /// + /// Optional logger factory for the forwarded worker stderr/stdout lines (category + /// ). Without it the lines are still drained and + /// kept for startup-failure messages, but not logged. + /// public WorkerProcessLauncher( IOptions gatewayOptions, IWorkerProcessFactory processFactory, IWorkerStartupProbe startupProbe, GatewayMetrics metrics, ILogger? 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.Instance; + _workerOutputLogger = loggerFactory?.CreateLogger(WorkerOutputCapture.LogCategory) ?? NullLogger.Instance; } /// @@ -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 diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionWorkerClientFactoryFakeWorkerTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionWorkerClientFactoryFakeWorkerTests.cs index b46b9c0b..2b503dc8 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionWorkerClientFactoryFakeWorkerTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Sessions/SessionWorkerClientFactoryFakeWorkerTests.cs @@ -154,6 +154,35 @@ public sealed class SessionWorkerClientFactoryFakeWorkerTests : IAsyncLifetime Assert.True(launcher.Process.IsDisposed); } + /// + /// 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. + /// + /// A task that represents the asynchronous operation. + [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( + 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); + } + /// /// WRK-006: a Kill 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 } /// Fake launcher whose worker exits with code 3 shortly after start, never connecting. - private sealed class ExitBeforeConnectLauncher : IWorkerProcessLauncher + private sealed class ExitBeforeConnectLauncher(string? standardError = null) : IWorkerProcessLauncher { /// Gets the fake worker process. 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)); } } diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerOutputCaptureTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerOutputCaptureTests.cs new file mode 100644 index 00000000..859b931b --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerOutputCaptureTests.cs @@ -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; + +/// +/// 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. +/// +public sealed class WorkerOutputCaptureTests +{ + private const string SessionId = "session-259"; + private const string Nonce = "nonce-0123456789abcdef"; + private static readonly TimeSpan HangGuard = TimeSpan.FromSeconds(30); + + /// Worker log lines are logged at the level the worker gave them; anything unstructured on stderr is a Warning. + /// A task that represents the asynchronous operation. + [Fact] + public async Task Forwards_EachLine_AtTheWorkersLevel() + { + RecordingLogger 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); + } + + /// The session nonce never reaches the gateway log or the tail, even if the worker wrote it. + /// A task that represents the asynchronous operation. + [Fact] + public async Task Scrubs_TheSessionNonce_FromLogAndTail() + { + RecordingLogger 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)); + } + + /// The tail keeps only the newest lines, within both the line and character bounds, oldest first. + /// A task that represents the asynchronous operation. + [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()); + 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()); + 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()); + await oneHugeLine.Completion.WaitAsync(HangGuard); + Assert.True(oneHugeLine.GetStandardErrorTail().Length < WorkerOutputCapture.MaxLineCharacters + 32); + Assert.EndsWith("...[truncated]", oneHugeLine.GetStandardErrorTail(), StringComparison.Ordinal); + } + + /// + /// 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. + /// + /// A task that represents the asynchronous operation. + [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); + } + + /// A throwing log sink does not end the drain. + /// A task that represents the asynchronous operation. + [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()); + } + + /// Each reader is disposed when it reaches end-of-stream, so nothing outlives the worker. + /// A task that represents the asynchronous operation. + [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()); + + await capture.Completion.WaitAsync(HangGuard); + + Assert.True(standardError.Disposed); + Assert.True(standardOutput.Disposed); + } + + /// A process that exposes no redirected stream gets no capture. + [Fact] + public void StartIfRedirected_WithoutRedirectedStreams_ReturnsNull() + { + Assert.Null(WorkerOutputCapture.StartIfRedirected( + new FakeWorkerProcess(processId: 1), SessionId, Nonce, new RecordingLogger())); + } + + /// The tail is appended to a failure message only when there is one. + /// A task that represents the asynchronous operation. + [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()); + 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()); + await some.Completion.WaitAsync(HangGuard); + Assert.Equal("boom. Last worker stderr output:\nwhy", WorkerOutputCapture.AppendStandardErrorTail(some, "boom.")); + } + + /// + /// 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. + /// + /// A task that represents the asynchronous operation. + [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()); + 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 state) + where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func 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 _messages = []; + + public IReadOnlyList Messages + { + get + { + lock (_syncRoot) + { + return _messages.ToArray(); + } + } + } + + public void Release() => _gate.Set(); + + public IDisposable? BeginScope(TState state) + where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + { + _gate.Wait(HangGuard); + lock (_syncRoot) + { + _messages.Add(formatter(state, exception)); + } + } + + public void Dispose() => _gate.Dispose(); + } +} diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerProcessLauncherTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerProcessLauncherTests.cs index 55926b84..8108cfeb 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerProcessLauncherTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/WorkerProcessLauncherTests.cs @@ -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); } + /// + /// 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. + /// + /// A task that represents the asynchronous operation. + [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( + 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); } + /// Logger provider that records category and formatted message of every entry. + private sealed class RecordingLoggerProvider : Microsoft.Extensions.Logging.ILoggerProvider + { + private readonly System.Collections.Concurrent.ConcurrentQueue<(string Category, string Message)> _entries = new(); + + /// Gets the recorded entries. + public IReadOnlyCollection<(string Category, string Message)> Entries => _entries.ToArray(); + + /// + public Microsoft.Extensions.Logging.ILogger CreateLogger(string categoryName) => new Logger(categoryName, _entries); + + /// + 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 state) + where TState : notnull => null; + + public bool IsEnabled(Microsoft.Extensions.Logging.LogLevel logLevel) => true; + + public void Log( + Microsoft.Extensions.Logging.LogLevel logLevel, + Microsoft.Extensions.Logging.EventId eventId, + TState state, + Exception? exception, + Func formatter) => + entries.Enqueue((category, formatter(state, exception))); + } + } + /// Fake worker process factory for testing process launch logic. private sealed class FakeWorkerProcessFactory(IWorkerProcess process) : IWorkerProcessFactory { diff --git a/src/ZB.MOM.WW.MxGateway.Tests/TestSupport/FakeWorkerProcess.cs b/src/ZB.MOM.WW.MxGateway.Tests/TestSupport/FakeWorkerProcess.cs index 6e149217..8ec64f6b 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/TestSupport/FakeWorkerProcess.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/TestSupport/FakeWorkerProcess.cs @@ -32,6 +32,12 @@ public sealed class FakeWorkerProcess(int processId) : IWorkerProcess /// public int? ExitCode { get; set; } + /// + public TextReader? StandardError { get; set; } + + /// + public TextReader? StandardOutput { get; set; } + /// Gets the number of times was called. public int KillCount { get; private set; } diff --git a/src/ZB.MOM.WW.MxGateway.Worker/Ipc/WorkerPipeSession.cs b/src/ZB.MOM.WW.MxGateway.Worker/Ipc/WorkerPipeSession.cs index b1f64976..838f61d9 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/Ipc/WorkerPipeSession.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/Ipc/WorkerPipeSession.cs @@ -378,9 +378,10 @@ public sealed class WorkerPipeSession "WorkerRecordInfoPin", new Dictionary { ["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;