From 87b8f8da0970d014e5bfadefa36bd11ea0eccb03 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 10:00:16 -0500 Subject: [PATCH] fix(workers): orphan cleanup skips workers whose owning gateway is still running (WRK-009, #253) --- gateway.md | 14 +- .../Workers/IRunningProcessInspector.cs | 21 ++- .../Workers/OrphanWorkerTerminator.cs | 101 +++++++++++-- .../Workers/SystemRunningProcessInspector.cs | 140 +++++++++++++++++- .../OrphanWorkerCleanupHostedServiceTests.cs | 6 + .../Workers/OrphanWorkerTerminatorTests.cs | 122 +++++++++++++-- 6 files changed, 381 insertions(+), 23 deletions(-) diff --git a/gateway.md b/gateway.md index 6b0b4412..0ce6dd3a 100644 --- a/gateway.md +++ b/gateway.md @@ -1050,9 +1050,17 @@ Policy: - stuck workers are killed by process id, - gateway restart does not reattach old workers; `OrphanWorkerCleanupHostedService` runs `OrphanWorkerTerminator` once on startup — before the server accepts - sessions — to kill leftover `ZB.MOM.WW.MxGateway.Worker.exe` processes (matched by the - configured worker executable path, or by image name when the x64 gateway cannot - introspect the x86 worker's module) left behind by a previous unclean run. + sessions — to kill leftover `ZB.MOM.WW.MxGateway.Worker.exe` processes left behind by + a previous unclean run. A candidate must match the configured worker executable path + (when its path is readable), and its command line's `--pipe-name` + (`mxgw-{gatewayPid}-{sessionUid}`) must name a gateway process that is no longer running + (or whose id was recycled: it started after the worker). A worker of a gateway that is + still running — a second gateway from the same build output, a test host — is left + alone. When neither the path nor the command line can be read, the process is left + alone and logged, since an image-name match alone could be another build's worker; when + the path matches but the command line cannot be read, the path decides, as before. The + command line is read with `NtQueryInformationProcess(ProcessCommandLineInformation)`, + which works from the x64 gateway on the x86 worker. Because each client owns one worker, a crash or leak affects only that session. diff --git a/src/ZB.MOM.WW.MxGateway.Server/Workers/IRunningProcessInspector.cs b/src/ZB.MOM.WW.MxGateway.Server/Workers/IRunningProcessInspector.cs index fda5caa0..e85f70e1 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Workers/IRunningProcessInspector.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Workers/IRunningProcessInspector.cs @@ -18,6 +18,16 @@ public interface IRunningProcessInspector /// Forcibly terminates the process with the given identifier. /// Identifier of the process to terminate. void Kill(int processId); + + /// + /// Reports whether a process with the given identifier is running, and when it started. + /// Orphan cleanup uses it to tell a worker whose owning gateway is still alive from a real + /// orphan, and the start time to reject a recycled process id. + /// + /// Identifier of the process to look up. + /// The process start time, or when it cannot be read. + /// when the process is running; otherwise . + bool TryGetRunningProcess(int processId, out DateTimeOffset? startedAt); } /// Identifying information for a running process candidate. @@ -26,4 +36,13 @@ public interface IRunningProcessInspector /// Fully-qualified path to the process main module, or /// when it could not be read (e.g. access denied). /// -public sealed record RunningProcessInfo(int ProcessId, string? ExecutablePath); +/// +/// The process command line, or when it could not be read (or the +/// platform offers no way to read it). +/// +/// The process start time, or when it could not be read. +public sealed record RunningProcessInfo( + int ProcessId, + string? ExecutablePath, + string? CommandLine = null, + DateTimeOffset? StartedAt = null); diff --git a/src/ZB.MOM.WW.MxGateway.Server/Workers/OrphanWorkerTerminator.cs b/src/ZB.MOM.WW.MxGateway.Server/Workers/OrphanWorkerTerminator.cs index 7ac29c2d..3fbeb0c0 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Workers/OrphanWorkerTerminator.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Workers/OrphanWorkerTerminator.cs @@ -60,7 +60,7 @@ public sealed class OrphanWorkerTerminator continue; } - if (!IsOrphanWorker(candidate, configuredPath)) + if (!IsOrphanWorker(candidate, configuredPath, currentProcessId)) { continue; } @@ -94,21 +94,104 @@ public sealed class OrphanWorkerTerminator return terminated; } - private static bool IsOrphanWorker(RunningProcessInfo candidate, string? configuredPath) + private bool IsOrphanWorker(RunningProcessInfo candidate, string? configuredPath, int currentProcessId) { // When the executable path is readable, require an exact match against // the configured worker path so unrelated processes that merely share // the image name are never killed. - if (candidate.ExecutablePath is { } path) + if (candidate.ExecutablePath is { } path + && (configuredPath is null + || !string.Equals(path, configuredPath, StringComparison.OrdinalIgnoreCase))) { - return configuredPath is not null - && string.Equals(path, configuredPath, StringComparison.OrdinalIgnoreCase); + return false; } - // A null path means the x64 gateway could not introspect the module — - // the expected case for the x86 worker. Image-name match is the only - // signal available; treat it as an orphan. - return true; + // Ownership (WRK-009): the worker's --pipe-name carries the PID of the gateway that + // launched it (mxgw-{gatewayPid}-{sessionUid}). A worker whose gateway is still running + // belongs to that gateway — a second gateway started from the same build output, a test + // host — and killing it would fault that gateway's live sessions. + if (TryParseOwnerGatewayProcessId(candidate.CommandLine, out int ownerProcessId)) + { + if (ownerProcessId == currentProcessId) + { + return false; + } + + if (_inspector.TryGetRunningProcess(ownerProcessId, out DateTimeOffset? ownerStartedAt) + && !IsRecycledProcessId(ownerStartedAt, candidate.StartedAt)) + { + _logger.LogInformation( + "Leaving worker process {ProcessId} alone: its gateway process {OwnerProcessId} is still running.", + candidate.ProcessId, + ownerProcessId); + return false; + } + + return true; + } + + if (candidate.ExecutablePath is not null) + { + // The configured path matches but the command line could not be read or carries no + // owner: the path is the only signal, as before. + return true; + } + + // Neither the path nor the command line could be read, so nothing ties the process to + // this gateway's worker build. Image name alone is not enough: a same-named worker from a + // different build (a CI checkout) would be killed. + _logger.LogWarning( + "Leaving worker-named process {ProcessId} alone: neither its executable path nor its command line could be read to confirm it is an orphan of this gateway's worker build.", + candidate.ProcessId); + return false; + } + + // An owner process that started after the worker cannot have launched it: the gateway that + // did is gone and its id was reused. Unknown start times give the live process the benefit + // of the doubt. + private static bool IsRecycledProcessId(DateTimeOffset? ownerStartedAt, DateTimeOffset? workerStartedAt) + => ownerStartedAt is { } owner + && workerStartedAt is { } worker + && owner > worker; + + /// + /// Extracts the owning gateway PID from a worker command line's --pipe-name value + /// (mxgw-{gatewayPid}-{sessionUid}, or the older mxaccess-gateway-{gatewayPid}-…). + /// + /// The worker command line, or . + /// The parsed gateway PID. + /// when an owner PID was found. + internal static bool TryParseOwnerGatewayProcessId(string? commandLine, out int ownerProcessId) + { + ownerProcessId = 0; + if (string.IsNullOrEmpty(commandLine)) + { + return false; + } + + const string PipeNameSwitch = "--pipe-name"; + int switchIndex = commandLine.IndexOf(PipeNameSwitch, StringComparison.Ordinal); + if (switchIndex < 0) + { + return false; + } + + ReadOnlySpan rest = commandLine.AsSpan(switchIndex + PipeNameSwitch.Length).TrimStart().TrimStart('"'); + foreach (string prefix in (string[])["mxgw-", "mxaccess-gateway-"]) + { + if (!rest.StartsWith(prefix, StringComparison.Ordinal)) + { + continue; + } + + ReadOnlySpan afterPrefix = rest[prefix.Length..]; + int dash = afterPrefix.IndexOf('-'); + return dash > 0 + && int.TryParse(afterPrefix[..dash], System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out ownerProcessId) + && ownerProcessId > 0; + } + + return false; } private string? ResolveConfiguredExecutablePath() diff --git a/src/ZB.MOM.WW.MxGateway.Server/Workers/SystemRunningProcessInspector.cs b/src/ZB.MOM.WW.MxGateway.Server/Workers/SystemRunningProcessInspector.cs index 5eabef13..c4a9769b 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Workers/SystemRunningProcessInspector.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Workers/SystemRunningProcessInspector.cs @@ -1,4 +1,5 @@ using System.Diagnostics; +using System.Runtime.InteropServices; namespace ZB.MOM.WW.MxGateway.Server.Workers; @@ -7,6 +8,14 @@ namespace ZB.MOM.WW.MxGateway.Server.Workers; /// public sealed class SystemRunningProcessInspector : IRunningProcessInspector { + // PROCESS_QUERY_LIMITED_INFORMATION: the least access that reads the image path, the command + // line and the start time, and the one granted across WOW64 (x64 gateway, x86 worker). + private const uint ProcessQueryLimitedInformation = 0x1000; + + // PROCESSINFOCLASS.ProcessCommandLineInformation (Windows 8.1+). Returns a UNICODE_STRING + // followed by its buffer, and works across bitness, unlike reading the target's PEB. + private const int ProcessCommandLineInformation = 60; + /// public IReadOnlyList GetProcessesByName(string processName) { @@ -16,7 +25,11 @@ public sealed class SystemRunningProcessInspector : IRunningProcessInspector { foreach (Process process in processes) { - results.Add(new RunningProcessInfo(process.Id, TryGetExecutablePath(process))); + results.Add(new RunningProcessInfo( + process.Id, + TryGetExecutablePath(process), + TryGetCommandLine(process.Id), + TryGetStartTime(process))); } } finally @@ -37,6 +50,102 @@ public sealed class SystemRunningProcessInspector : IRunningProcessInspector process.Kill(entireProcessTree: true); } + /// + public bool TryGetRunningProcess(int processId, out DateTimeOffset? startedAt) + { + startedAt = null; + Process process; + try + { + process = Process.GetProcessById(processId); + } + catch (ArgumentException) + { + // Not running. + return false; + } + catch (InvalidOperationException) + { + return false; + } + + using (process) + { + try + { + if (process.HasExited) + { + return false; + } + } + catch (Exception exception) when (exception is InvalidOperationException + or System.ComponentModel.Win32Exception + or NotSupportedException) + { + // Cannot open it to ask, but GetProcessById found it: treat it as running. + } + + startedAt = TryGetStartTime(process); + return true; + } + } + + /// + /// Reads another process's command line. Windows only; elsewhere or + /// when it cannot be read (access denied, the process exited). + /// + /// The process to read. + /// The command line, or . + internal static string? TryGetCommandLine(int processId) + { + if (!OperatingSystem.IsWindows()) + { + return null; + } + + IntPtr handle = OpenProcess(ProcessQueryLimitedInformation, inheritHandle: false, processId); + if (handle == IntPtr.Zero) + { + return null; + } + + try + { + // The sizing call fails with STATUS_INFO_LENGTH_MISMATCH and reports the size needed. + _ = NtQueryInformationProcess(handle, ProcessCommandLineInformation, IntPtr.Zero, 0, out int length); + if (length <= 0 || length > 1024 * 1024) + { + return null; + } + + IntPtr buffer = Marshal.AllocHGlobal(length); + try + { + int status = NtQueryInformationProcess(handle, ProcessCommandLineInformation, buffer, length, out _); + if (status != 0) + { + return null; + } + + // UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } — the + // pointer is naturally aligned, so it sits at offset IntPtr.Size. + int byteLength = (ushort)Marshal.ReadInt16(buffer); + IntPtr text = Marshal.ReadIntPtr(buffer, IntPtr.Size); + return byteLength == 0 || text == IntPtr.Zero + ? string.Empty + : Marshal.PtrToStringUni(text, byteLength / 2); + } + finally + { + Marshal.FreeHGlobal(buffer); + } + } + finally + { + _ = CloseHandle(handle); + } + } + private static string? TryGetExecutablePath(Process process) { try @@ -52,4 +161,33 @@ public sealed class SystemRunningProcessInspector : IRunningProcessInspector return null; } } + + private static DateTimeOffset? TryGetStartTime(Process process) + { + try + { + return new DateTimeOffset(process.StartTime.ToUniversalTime(), TimeSpan.Zero); + } + catch (Exception exception) when (exception is InvalidOperationException + or System.ComponentModel.Win32Exception + or NotSupportedException) + { + return null; + } + } + + [DllImport("kernel32.dll", SetLastError = true)] + private static extern IntPtr OpenProcess(uint desiredAccess, bool inheritHandle, int processId); + + [DllImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool CloseHandle(IntPtr handle); + + [DllImport("ntdll.dll")] + private static extern int NtQueryInformationProcess( + IntPtr processHandle, + int processInformationClass, + IntPtr processInformation, + int processInformationLength, + out int returnLength); } diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/OrphanWorkerCleanupHostedServiceTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/OrphanWorkerCleanupHostedServiceTests.cs index f41ba089..13cf0b55 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/OrphanWorkerCleanupHostedServiceTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/OrphanWorkerCleanupHostedServiceTests.cs @@ -98,5 +98,11 @@ public sealed class OrphanWorkerCleanupHostedServiceTests } public void Kill(int processId) => Killed.Add(processId); + + public bool TryGetRunningProcess(int processId, out DateTimeOffset? startedAt) + { + startedAt = null; + return false; + } } } diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/OrphanWorkerTerminatorTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/OrphanWorkerTerminatorTests.cs index df0eafc1..cb85873e 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/OrphanWorkerTerminatorTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Workers/OrphanWorkerTerminatorTests.cs @@ -8,8 +8,9 @@ namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Workers; /// /// Per gateway.md the gateway must terminate /// orphaned worker processes on startup. These tests pin that the terminator -/// kills leftover workers (matched by executable path, or by image name when -/// the path is unreadable) without touching unrelated processes or itself. +/// kills leftover workers (matched by executable path, or confirmed by a command line +/// whose pipe name names a gateway that is gone) without touching unrelated processes, +/// another live gateway's workers, or itself. /// public sealed class OrphanWorkerTerminatorTests { @@ -44,13 +45,13 @@ public sealed class OrphanWorkerTerminatorTests Assert.Equal([101, 102], inspector.KilledProcessIds.Order()); } - /// Verifies that orphan workers are killed when executable path is unreadable but image name matches. + /// + /// WRK-009: with neither the path nor the command line readable, an image-name match alone is + /// not enough to kill — it could be a same-named worker from another build. + /// [Fact] - public void TerminateOrphans_KillsImageNameMatchWhenExecutablePathUnreadable() + public void TerminateOrphans_LeavesImageNameMatchAloneWhenPathAndCommandLineUnreadable() { - // The x64 gateway cannot introspect the x86 worker's main module, so the - // path comes back null. Image-name match is the only signal — and it is - // exactly the orphan worker case, so the process must still be killed. FakeProcessInspector inspector = new( [ new RunningProcessInfo(201, ExecutablePath: null), @@ -59,10 +60,106 @@ public sealed class OrphanWorkerTerminatorTests int killed = terminator.TerminateOrphans(); - Assert.Equal(1, killed); - Assert.Equal([201], inspector.KilledProcessIds); + Assert.Equal(0, killed); + Assert.Empty(inspector.KilledProcessIds); } + /// + /// With the path unreadable, a command line whose pipe name names a gateway that is no longer + /// running confirms the orphan, and it is killed. + /// + [Fact] + public void TerminateOrphans_KillsWorkerWhoseOwningGatewayIsGone() + { + FakeProcessInspector inspector = new( + [ + new RunningProcessInfo(202, ExecutablePath: null, WorkerCommandLine(ownerPid: 9001)), + ]); + OrphanWorkerTerminator terminator = CreateTerminator(inspector); + + int killed = terminator.TerminateOrphans(); + + Assert.Equal(1, killed); + Assert.Equal([202], inspector.KilledProcessIds); + } + + /// + /// WRK-009: a worker whose owning gateway (from its pipe name) is still running belongs to + /// that gateway and is not killed, even when its path matches. + /// + [Fact] + public void TerminateOrphans_LeavesWorkerOfALiveGatewayAlone() + { + DateTimeOffset workerStarted = DateTimeOffset.UtcNow; + FakeProcessInspector inspector = new( + [ + new RunningProcessInfo(203, WorkerExecutablePath, WorkerCommandLine(ownerPid: 9002), workerStarted), + ]); + inspector.RunningProcesses[9002] = workerStarted.AddMinutes(-5); + OrphanWorkerTerminator terminator = CreateTerminator(inspector); + + int killed = terminator.TerminateOrphans(); + + Assert.Equal(0, killed); + Assert.Empty(inspector.KilledProcessIds); + } + + /// + /// An "owner" process that started after the worker is a recycled process id, not the + /// gateway that launched it, so the worker is still an orphan. + /// + [Fact] + public void TerminateOrphans_KillsWorkerWhoseOwnerPidWasRecycled() + { + DateTimeOffset workerStarted = DateTimeOffset.UtcNow.AddHours(-1); + FakeProcessInspector inspector = new( + [ + new RunningProcessInfo(204, WorkerExecutablePath, WorkerCommandLine(ownerPid: 9003), workerStarted), + ]); + inspector.RunningProcesses[9003] = workerStarted.AddMinutes(10); + OrphanWorkerTerminator terminator = CreateTerminator(inspector); + + int killed = terminator.TerminateOrphans(); + + Assert.Equal(1, killed); + Assert.Equal([204], inspector.KilledProcessIds); + } + + /// The owner PID parses from both the current and the older pipe-name formats, quoted or not. + /// Worker command line. + /// Expected owner PID, or 0 when none should parse. + [Theory] + [InlineData("Worker.exe --session-id session-x --pipe-name mxgw-1234-abcdef --protocol-version 1", 1234)] + [InlineData("\"C:\\w\\Worker.exe\" --pipe-name \"mxgw-77-abc\"", 77)] + [InlineData("Worker.exe --pipe-name mxaccess-gateway-555-session-1", 555)] + [InlineData("Worker.exe --pipe-name other-555-session-1", 0)] + [InlineData("Worker.exe --session-id x", 0)] + [InlineData("", 0)] + public void TryParseOwnerGatewayProcessId_ParsesPipeName(string commandLine, int expected) + { + bool parsed = OrphanWorkerTerminator.TryParseOwnerGatewayProcessId(commandLine, out int ownerProcessId); + + Assert.Equal(expected != 0, parsed); + Assert.Equal(expected, ownerProcessId); + } + + /// + /// On Windows the system inspector reads a live process's command line (the cross-bitness + /// NtQueryInformationProcess path orphan cleanup depends on). + /// + [ZB.MOM.WW.MxGateway.Tests.Gateway.Sessions.WindowsFact] + public void SystemInspector_ReadsCurrentProcessCommandLine() + { + string? commandLine = SystemRunningProcessInspector.TryGetCommandLine(Environment.ProcessId); + + Assert.False(string.IsNullOrEmpty(commandLine)); + Assert.True(new SystemRunningProcessInspector().TryGetRunningProcess(Environment.ProcessId, out DateTimeOffset? startedAt)); + Assert.NotNull(startedAt); + } + + private static string WorkerCommandLine(int ownerPid) + => $"\"{WorkerExecutablePath}\" --session-id session-1 --pipe-name mxgw-{ownerPid}-0123456789abcdef --protocol-version 1"; + /// Verifies that unrelated processes with the same image name are not killed. [Fact] public void TerminateOrphans_DoesNotKillUnrelatedProcessSharingImageName() @@ -147,6 +244,9 @@ public sealed class OrphanWorkerTerminatorTests /// public IReadOnlyList GetProcessesByName(string processName) => processes; + /// Gets the processes reported as running, by id, with their start times. + public Dictionary RunningProcesses { get; } = []; + /// public void Kill(int processId) { @@ -157,5 +257,9 @@ public sealed class OrphanWorkerTerminatorTests KilledProcessIds.Add(processId); } + + /// + public bool TryGetRunningProcess(int processId, out DateTimeOffset? startedAt) + => RunningProcesses.TryGetValue(processId, out startedAt); } }