using System.Diagnostics; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using ZB.MOM.WW.MxGateway.Contracts; using ZB.MOM.WW.MxGateway.Server.Configuration; using ZB.MOM.WW.MxGateway.Server.Metrics; namespace ZB.MOM.WW.MxGateway.Server.Workers; /// /// Launches worker processes with startup probing and error handling. /// public sealed class WorkerProcessLauncher : IWorkerProcessLauncher { /// Environment variable for worker nonce. [Obsolete("Use WorkerLaunchEnvironment.WorkerNonce.")] public const string WorkerNonceEnvironmentVariableName = WorkerLaunchEnvironment.WorkerNonce; /// Environment variable for worker pipe connect attempt timeout. [Obsolete("Use WorkerLaunchEnvironment.PipeConnectAttemptTimeoutMilliseconds.")] public const string WorkerPipeConnectAttemptTimeoutEnvironmentVariableName = WorkerLaunchEnvironment.PipeConnectAttemptTimeoutMilliseconds; /// /// Conveys MxGateway:Worker:WriteCompletionWaitMilliseconds to the worker: /// the bounded wait for the OnWriteComplete callback on Write, Write2, /// WriteSecured, and WriteSecured2 replies. 0 disables the wait. /// [Obsolete("Use WorkerLaunchEnvironment.WriteCompletionWaitMilliseconds.")] public const string WorkerWriteCompletionWaitEnvironmentVariableName = WorkerLaunchEnvironment.WriteCompletionWaitMilliseconds; /// /// Conveys MxGateway:Alarms:PollIntervalMilliseconds to the worker: the /// cadence at which the worker's STA polls the AVEVA alarm consumer. /// [Obsolete("Use WorkerLaunchEnvironment.AlarmPollIntervalMilliseconds.")] public const string WorkerAlarmPollIntervalEnvironmentVariableName = WorkerLaunchEnvironment.AlarmPollIntervalMilliseconds; /// /// Conveys MxGateway:Alarms:MaxAlarmsPerFetch to the worker: the cap /// passed to GetXmlCurrentAlarms2, which is also the record count at /// which the worker treats a fetch as truncated. /// [Obsolete("Use WorkerLaunchEnvironment.MaxAlarmsPerFetch.")] public const string WorkerMaxAlarmsPerFetchEnvironmentVariableName = WorkerLaunchEnvironment.MaxAlarmsPerFetch; /// /// Conveys MxGateway:Worker:EventQueueCapacity to the worker: the capacity /// of the outbound MXAccess event queue, whose overflow faults the session. /// [Obsolete("Use WorkerLaunchEnvironment.EventQueueCapacity.")] public const string WorkerEventQueueCapacityEnvironmentVariableName = WorkerLaunchEnvironment.EventQueueCapacity; private readonly IWorkerProcessFactory _processFactory; private readonly IWorkerStartupProbe _startupProbe; private readonly GatewayMetrics _metrics; private readonly TimeProvider _timeProvider; 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. /// /// Gateway configuration options. /// Factory for creating worker processes. /// Probe for checking worker startup completion. /// 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, ILoggerFactory? loggerFactory = null) { ArgumentNullException.ThrowIfNull(gatewayOptions); ArgumentNullException.ThrowIfNull(processFactory); ArgumentNullException.ThrowIfNull(startupProbe); ArgumentNullException.ThrowIfNull(metrics); _workerOptions = gatewayOptions.Value.Worker; _alarmsOptions = gatewayOptions.Value.Alarms; _processFactory = processFactory; _startupProbe = startupProbe; _metrics = metrics; _timeProvider = timeProvider ?? TimeProvider.System; _logger = logger ?? NullLogger.Instance; _workerOutputLogger = loggerFactory?.CreateLogger(WorkerOutputCapture.LogCategory) ?? NullLogger.Instance; } /// public async Task LaunchAsync( WorkerProcessLaunchRequest request, CancellationToken cancellationToken = default) { try { return await LaunchCoreAsync(request, cancellationToken).ConfigureAwait(false); } catch { request.PipeReservation?.Dispose(); throw; } } private async Task LaunchCoreAsync( WorkerProcessLaunchRequest request, CancellationToken cancellationToken) { ValidateRequest(request); DateTimeOffset startedAt = _timeProvider.GetUtcNow(); ProcessStartInfo startInfo = CreateStartInfo(request, out WorkerProcessCommandLine commandLine); IWorkerProcess process; try { process = _processFactory.Start(startInfo); } catch (Exception exception) when (exception is not WorkerProcessLaunchException) { throw new WorkerProcessLaunchException( WorkerProcessLaunchErrorCode.StartFailed, "Worker process failed to start.", 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); startupTimeout.CancelAfter(TimeSpan.FromSeconds(_workerOptions.StartupTimeoutSeconds)); // Single-shot probe: the default WorkerProcessStartedProbe only checks HasExited, which can // never succeed on a retry, so there is deliberately no retry layer here (mxaccessgw#188). await _startupProbe .WaitUntilReadyAsync(process, request, startupTimeout.Token) .ConfigureAwait(false); return new WorkerProcessHandle(process, commandLine, startedAt, outputCapture); } catch (OperationCanceledException exception) when (!cancellationToken.IsCancellationRequested) { KillAndDispose(process, "StartupTimeout"); throw new WorkerProcessLaunchException( WorkerProcessLaunchErrorCode.StartupTimeout, "Worker process did not complete startup before the configured timeout.", exception); } catch (OperationCanceledException) { KillAndDispose(process, "LaunchCanceled"); throw; } catch (Exception exception) when (exception is not WorkerProcessLaunchException) { KillAndDispose(process, "StartupFailed"); throw new WorkerProcessLaunchException( WorkerProcessLaunchErrorCode.StartupFailed, "Worker process failed during startup.", exception); } 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; } } private ProcessStartInfo CreateStartInfo( WorkerProcessLaunchRequest request, out WorkerProcessCommandLine commandLine) { string executablePath = ResolveExecutablePath(); string workingDirectory = ResolveWorkingDirectory(executablePath); string[] arguments = [ "--session-id", request.SessionId, "--pipe-name", request.PipeName, "--protocol-version", request.ProtocolVersion.ToString(System.Globalization.CultureInfo.InvariantCulture), ]; ProcessStartInfo startInfo = new() { FileName = executablePath, WorkingDirectory = workingDirectory, 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) { startInfo.ArgumentList.Add(argument); } startInfo.Environment[WorkerLaunchEnvironment.WorkerNonce] = request.Nonce; startInfo.Environment[WorkerLaunchEnvironment.PipeConnectAttemptTimeoutMilliseconds] = _workerOptions.PipeConnectAttemptTimeoutMilliseconds.ToString(System.Globalization.CultureInfo.InvariantCulture); startInfo.Environment[WorkerLaunchEnvironment.WriteCompletionWaitMilliseconds] = _workerOptions.WriteCompletionWaitMilliseconds.ToString(System.Globalization.CultureInfo.InvariantCulture); startInfo.Environment[WorkerLaunchEnvironment.EventQueueCapacity] = _workerOptions.EventQueueCapacity.ToString(System.Globalization.CultureInfo.InvariantCulture); startInfo.Environment[WorkerLaunchEnvironment.AlarmPollIntervalMilliseconds] = _alarmsOptions.PollIntervalMilliseconds.ToString(System.Globalization.CultureInfo.InvariantCulture); startInfo.Environment[WorkerLaunchEnvironment.MaxAlarmsPerFetch] = _alarmsOptions.MaxAlarmsPerFetch.ToString(System.Globalization.CultureInfo.InvariantCulture); startInfo.Environment[WorkerLaunchEnvironment.AlarmAckClientName] = _alarmsOptions.AckClientName; startInfo.Environment[WorkerLaunchEnvironment.HeartbeatSendIntervalMilliseconds] = (_workerOptions.WorkerHeartbeatSendIntervalSeconds * 1000L).ToString(System.Globalization.CultureInfo.InvariantCulture); startInfo.Environment[WorkerLaunchEnvironment.HeartbeatGraceMilliseconds] = (_workerOptions.WorkerHeartbeatGraceSeconds * 1000L).ToString(System.Globalization.CultureInfo.InvariantCulture); startInfo.Environment[WorkerLaunchEnvironment.HeartbeatStuckCeilingMilliseconds] = (_workerOptions.WorkerHeartbeatStuckCeilingSeconds * 1000L).ToString(System.Globalization.CultureInfo.InvariantCulture); startInfo.Environment[WorkerLaunchEnvironment.StartupTimeoutMilliseconds] = (_workerOptions.StartupTimeoutSeconds * 1000L).ToString(System.Globalization.CultureInfo.InvariantCulture); commandLine = new WorkerProcessCommandLine(executablePath, arguments); return startInfo; } private string ResolveExecutablePath() { string executablePath; try { executablePath = Path.GetFullPath(_workerOptions.ExecutablePath); } catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException) { throw new WorkerProcessLaunchException( WorkerProcessLaunchErrorCode.InvalidExecutable, "Worker executable path is not a valid filesystem path.", exception); } if (!string.Equals(Path.GetExtension(executablePath), ".exe", StringComparison.OrdinalIgnoreCase)) { throw new WorkerProcessLaunchException( WorkerProcessLaunchErrorCode.InvalidExecutable, "Worker executable path must point to a .exe file."); } if (!File.Exists(executablePath)) { throw new WorkerProcessLaunchException( WorkerProcessLaunchErrorCode.ExecutableNotFound, "Worker executable does not exist."); } WorkerExecutableValidator.Validate(executablePath, _workerOptions.RequiredArchitecture); return executablePath; } private string ResolveWorkingDirectory(string executablePath) { if (string.IsNullOrWhiteSpace(_workerOptions.WorkingDirectory)) { return Path.GetDirectoryName(executablePath) ?? Environment.CurrentDirectory; } string workingDirectory; try { workingDirectory = Path.GetFullPath(_workerOptions.WorkingDirectory); } catch (Exception exception) when (exception is ArgumentException or NotSupportedException or PathTooLongException) { throw new WorkerProcessLaunchException( WorkerProcessLaunchErrorCode.InvalidWorkingDirectory, "Worker working directory is not a valid filesystem path.", exception); } if (!Directory.Exists(workingDirectory)) { throw new WorkerProcessLaunchException( WorkerProcessLaunchErrorCode.InvalidWorkingDirectory, "Worker working directory does not exist."); } return workingDirectory; } // Called from the launch-failure catch blocks, so it must never throw: Kill can raise // Win32Exception (the process is mid-termination, or access is denied) or AggregateException // (a descendant could not be terminated), and an exception escaping here would replace the // WorkerProcessLaunchException the caller is owed (WRK-006). private void KillAndDispose(IWorkerProcess process, string reason) { try { if (!process.HasExited) { process.Kill(entireProcessTree: true); _metrics.WorkerKilled(reason); } } catch (Exception exception) { _logger.LogWarning( exception, "Killing worker process {ProcessId} after a failed launch ({Reason}) failed.", SafeProcessId(process), reason); } finally { process.Dispose(); } } private static bool HasExitedSafely(IWorkerProcess process) { try { return process.HasExited; } catch (InvalidOperationException) { return false; } } private static int? SafeProcessId(IWorkerProcess process) { try { return process.Id; } catch (InvalidOperationException) { return null; } } private static void ValidateRequest(WorkerProcessLaunchRequest request) { if (string.IsNullOrWhiteSpace(request.SessionId)) { throw new WorkerProcessLaunchException( WorkerProcessLaunchErrorCode.InvalidRequest, "Worker launch requires a session id."); } if (string.IsNullOrWhiteSpace(request.PipeName)) { throw new WorkerProcessLaunchException( WorkerProcessLaunchErrorCode.InvalidRequest, "Worker launch requires a pipe name."); } if (request.ProtocolVersion == 0) { throw new WorkerProcessLaunchException( WorkerProcessLaunchErrorCode.InvalidRequest, "Worker launch requires a non-zero protocol version."); } if (string.IsNullOrWhiteSpace(request.Nonce)) { throw new WorkerProcessLaunchException( WorkerProcessLaunchErrorCode.InvalidRequest, "Worker launch requires a nonce."); } } }