ee0f836886
ci / windows-x86 (push) Successful in 3m50s
ci / java (push) Failing after 10m14s
ci / portable (push) Failing after 19m55s
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.
288 lines
13 KiB
C#
288 lines
13 KiB
C#
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();
|
|
}
|
|
}
|