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.
298 lines
14 KiB
C#
298 lines
14 KiB
C#
using System.IO.Pipes;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Options;
|
|
using ZB.MOM.WW.MxGateway.Contracts;
|
|
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
|
using ZB.MOM.WW.MxGateway.Server.Configuration;
|
|
using ZB.MOM.WW.MxGateway.Server.Metrics;
|
|
using ZB.MOM.WW.MxGateway.Server.Workers;
|
|
|
|
namespace ZB.MOM.WW.MxGateway.Server.Sessions;
|
|
|
|
/// <summary>Factory for creating worker clients and launching worker processes.</summary>
|
|
public sealed class SessionWorkerClientFactory : ISessionWorkerClientFactory
|
|
{
|
|
/// <summary>
|
|
/// Kernel buffer quota requested for each direction of a worker pipe. A zero quota — what the
|
|
/// short <see cref="NamedPipeServerStream"/> overloads request — makes every byte-mode write
|
|
/// rendezvous with a pending read, so writer latency is coupled to reader scheduling and a
|
|
/// writer with no reader parked blocks indefinitely. That is the failure class behind the
|
|
/// historical windev full-suite wedge (all tests reported, testhost never exiting). A real
|
|
/// quota lets a whole frame land in the kernel and the writer return. 128 KiB comfortably
|
|
/// holds the control traffic and typical event batches without reserving nonpaged pool per
|
|
/// session for the rare maximum-sized frame, which still streams through in chunks.
|
|
/// </summary>
|
|
private const int PipeBufferSizeBytes = 128 * 1024;
|
|
|
|
private readonly IWorkerProcessLauncher _workerProcessLauncher;
|
|
private readonly GatewayMetrics _metrics;
|
|
private readonly TimeProvider _timeProvider;
|
|
private readonly ILoggerFactory _loggerFactory;
|
|
private readonly GatewayOptions _options;
|
|
|
|
/// <summary>Initializes a new instance of the SessionWorkerClientFactory class.</summary>
|
|
/// <param name="workerProcessLauncher">Service for launching worker processes.</param>
|
|
/// <param name="options">Configuration options.</param>
|
|
/// <param name="metrics">Metrics collector for gateway events.</param>
|
|
/// <param name="loggerFactory">Logger factory for creating loggers.</param>
|
|
/// <param name="timeProvider">Optional time provider for testing; defaults to system time.</param>
|
|
public SessionWorkerClientFactory(
|
|
IWorkerProcessLauncher workerProcessLauncher,
|
|
IOptions<GatewayOptions> options,
|
|
GatewayMetrics metrics,
|
|
ILoggerFactory loggerFactory,
|
|
TimeProvider? timeProvider = null)
|
|
{
|
|
_workerProcessLauncher = workerProcessLauncher ?? throw new ArgumentNullException(nameof(workerProcessLauncher));
|
|
ArgumentNullException.ThrowIfNull(options);
|
|
_metrics = metrics ?? throw new ArgumentNullException(nameof(metrics));
|
|
_loggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
|
|
_timeProvider = timeProvider ?? TimeProvider.System;
|
|
_options = options.Value;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task<IWorkerClient> CreateAsync(
|
|
GatewaySession session,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(session);
|
|
|
|
NamedPipeServerStream? pipe = CreatePipe(session.PipeName);
|
|
WorkerProcessHandle? processHandle = null;
|
|
IWorkerClient? workerClient = null;
|
|
using CancellationTokenSource startupCancellation =
|
|
CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
|
startupCancellation.CancelAfter(session.StartupTimeout);
|
|
try
|
|
{
|
|
session.TransitionTo(SessionState.StartingWorker);
|
|
processHandle = await _workerProcessLauncher
|
|
.LaunchAsync(
|
|
new WorkerProcessLaunchRequest(
|
|
session.SessionId,
|
|
session.PipeName,
|
|
GatewayContractInfo.WorkerProtocolVersion,
|
|
session.Nonce,
|
|
pipe),
|
|
startupCancellation.Token)
|
|
.ConfigureAwait(false);
|
|
|
|
session.TransitionTo(SessionState.WaitingForPipe);
|
|
await WaitForPipeConnectionAsync(pipe, processHandle, session.SessionId, startupCancellation.Token)
|
|
.ConfigureAwait(false);
|
|
|
|
session.TransitionTo(SessionState.Handshaking);
|
|
WorkerFrameProtocolOptions frameOptions = new(
|
|
session.SessionId,
|
|
GatewayContractInfo.WorkerProtocolVersion,
|
|
_options.Worker.MaxMessageBytes);
|
|
WorkerClientConnection connection = new(
|
|
session.SessionId,
|
|
session.Nonce,
|
|
pipe,
|
|
frameOptions,
|
|
processHandle);
|
|
WorkerClientOptions clientOptions = CreateWorkerClientOptions(_options);
|
|
|
|
workerClient = new WorkerClient(
|
|
connection,
|
|
clientOptions,
|
|
_metrics,
|
|
_timeProvider,
|
|
_loggerFactory.CreateLogger<WorkerClient>());
|
|
|
|
pipe = null;
|
|
processHandle = null;
|
|
|
|
session.TransitionTo(SessionState.InitializingWorker);
|
|
await workerClient.StartAsync(startupCancellation.Token).ConfigureAwait(false);
|
|
|
|
return workerClient;
|
|
}
|
|
catch (Exception exception)
|
|
{
|
|
if (workerClient is not null)
|
|
{
|
|
try
|
|
{
|
|
workerClient.Kill("OpenSessionFailed");
|
|
}
|
|
catch
|
|
{
|
|
// Preserve the startup failure while still disposing below.
|
|
}
|
|
|
|
await workerClient.DisposeAsync().ConfigureAwait(false);
|
|
}
|
|
else
|
|
{
|
|
// Must not throw (WRK-006): Kill can raise Win32Exception or AggregateException for
|
|
// a process that is mid-termination, and an exception here would replace the
|
|
// startup failure the caller is owed and skip the pipe dispose, leaking the
|
|
// pipe server handle.
|
|
try
|
|
{
|
|
if (processHandle is not null && !processHandle.Process.HasExited)
|
|
{
|
|
processHandle.Process.Kill(entireProcessTree: true);
|
|
_metrics.WorkerKilled("OpenSessionFailed");
|
|
}
|
|
}
|
|
catch (Exception killException)
|
|
{
|
|
_loggerFactory.CreateLogger<SessionWorkerClientFactory>().LogWarning(
|
|
killException,
|
|
"Killing the worker of session {SessionId} after a failed open failed.",
|
|
session.SessionId);
|
|
}
|
|
finally
|
|
{
|
|
processHandle?.Dispose();
|
|
pipe?.Dispose();
|
|
}
|
|
}
|
|
|
|
if (exception is OperationCanceledException
|
|
&& startupCancellation.IsCancellationRequested
|
|
&& !cancellationToken.IsCancellationRequested)
|
|
{
|
|
throw new TimeoutException(
|
|
$"Worker session {session.SessionId} did not complete startup within {session.StartupTimeout}.",
|
|
exception);
|
|
}
|
|
|
|
throw;
|
|
}
|
|
}
|
|
|
|
/// <summary>Creates a named pipe for worker communication.</summary>
|
|
/// <param name="pipeName">The pipe name.</param>
|
|
/// <returns>Named pipe server stream.</returns>
|
|
/// <remarks>
|
|
/// The buffer sizes are explicit so the pipe is not created with a zero quota; see
|
|
/// <see cref="PipeBufferSizeBytes"/>. On Unix hosts (the macOS test matrix, where named pipes
|
|
/// are Unix domain sockets) the sizes are advisory — the fix targets Windows production.
|
|
/// Access is restricted to the gateway's own account (#187): on Windows by the explicit ACL
|
|
/// from <see cref="WorkerPipeSecurity"/>, elsewhere by <see cref="PipeOptions.CurrentUserOnly"/>.
|
|
/// </remarks>
|
|
internal static NamedPipeServerStream CreatePipe(string pipeName)
|
|
{
|
|
if (OperatingSystem.IsWindows())
|
|
{
|
|
return NamedPipeServerStreamAcl.Create(
|
|
pipeName,
|
|
PipeDirection.InOut,
|
|
maxNumberOfServerInstances: 1,
|
|
PipeTransmissionMode.Byte,
|
|
PipeOptions.Asynchronous,
|
|
inBufferSize: PipeBufferSizeBytes,
|
|
outBufferSize: PipeBufferSizeBytes,
|
|
WorkerPipeSecurity.CreateForCurrentUser());
|
|
}
|
|
|
|
return new NamedPipeServerStream(
|
|
pipeName,
|
|
PipeDirection.InOut,
|
|
maxNumberOfServerInstances: 1,
|
|
PipeTransmissionMode.Byte,
|
|
WorkerPipeSecurity.UnixPipeOptions,
|
|
inBufferSize: PipeBufferSizeBytes,
|
|
outBufferSize: PipeBufferSizeBytes);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Waits for the worker to connect to the pipe, failing fast if the worker process exits
|
|
/// first (WRK-002).
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// The launcher's startup probe checks <c>HasExited</c> once, right after the process starts,
|
|
/// which is almost always false. A worker that then dies before connecting (a missing
|
|
/// dependency, a bad argument, security software, an unhandled startup exception) used to
|
|
/// hold the open — and its session slot — for the full startup timeout and surface as a
|
|
/// 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="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,
|
|
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();
|
|
Task first = await Task.WhenAny(connect, exit).ConfigureAwait(false);
|
|
|
|
if (first == exit && exit.IsCompletedSuccessfully && !connect.IsCompletedSuccessfully)
|
|
{
|
|
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,
|
|
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):
|
|
// stop watching the process and let the connect decide the outcome.
|
|
await raceCancellation.CancelAsync().ConfigureAwait(false);
|
|
await ObserveQuietlyAsync(exit).ConfigureAwait(false);
|
|
await connect.ConfigureAwait(false);
|
|
}
|
|
|
|
private static async Task ObserveQuietlyAsync(Task task)
|
|
{
|
|
try
|
|
{
|
|
await task.ConfigureAwait(false);
|
|
}
|
|
catch (Exception exception) when (exception is OperationCanceledException or IOException or ObjectDisposedException or InvalidOperationException)
|
|
{
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Maps the bound <c>MxGateway:*</c> options onto the per-session <see cref="WorkerClientOptions"/>.
|
|
/// Every <see cref="WorkerClientOptions"/> field is set from configuration here, so none is left
|
|
/// silently on its compile-time default.
|
|
/// </summary>
|
|
/// <param name="options">The bound gateway options.</param>
|
|
/// <returns>The worker client options for a new session.</returns>
|
|
internal static WorkerClientOptions CreateWorkerClientOptions(GatewayOptions options)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(options);
|
|
|
|
return new WorkerClientOptions
|
|
{
|
|
HeartbeatGrace = TimeSpan.FromSeconds(options.Worker.HeartbeatGraceSeconds),
|
|
HeartbeatCheckInterval = TimeSpan.FromSeconds(options.Worker.ResolveHeartbeatCheckIntervalSeconds()),
|
|
HeartbeatStuckCeiling = TimeSpan.FromSeconds(options.Worker.HeartbeatStuckCeilingSeconds),
|
|
EventChannelCapacity = options.Events.QueueCapacity,
|
|
EventChannelFullModeTimeout = TimeSpan.FromMilliseconds(options.Worker.EventChannelFullModeTimeoutMilliseconds),
|
|
MaxPendingCommands = options.Sessions.MaxPendingCommandsPerSession,
|
|
};
|
|
}
|
|
}
|