Files
mxaccessgw/src/ZB.MOM.WW.MxGateway.Server/Workers/WorkerOutputCapture.cs
T
Joseph Doherty ee0f836886
ci / windows-x86 (push) Successful in 3m50s
ci / java (push) Failing after 10m14s
ci / portable (push) Failing after 19m55s
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.
2026-12-03 13:10:12 -05:00

364 lines
14 KiB
C#

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,
}