fix(workers): orphan cleanup skips workers whose owning gateway is still running (WRK-009, #253)

This commit is contained in:
Joseph Doherty
2026-12-03 10:00:16 -05:00
parent 9c3a4c0eae
commit 87b8f8da09
6 changed files with 381 additions and 23 deletions
+11 -3
View File
@@ -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.
@@ -18,6 +18,16 @@ public interface IRunningProcessInspector
/// <summary>Forcibly terminates the process with the given identifier.</summary>
/// <param name="processId">Identifier of the process to terminate.</param>
void Kill(int processId);
/// <summary>
/// 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.
/// </summary>
/// <param name="processId">Identifier of the process to look up.</param>
/// <param name="startedAt">The process start time, or <see langword="null"/> when it cannot be read.</param>
/// <returns><see langword="true"/> when the process is running; otherwise <see langword="false"/>.</returns>
bool TryGetRunningProcess(int processId, out DateTimeOffset? startedAt);
}
/// <summary>Identifying information for a running process candidate.</summary>
@@ -26,4 +36,13 @@ public interface IRunningProcessInspector
/// Fully-qualified path to the process main module, or <see langword="null"/>
/// when it could not be read (e.g. access denied).
/// </param>
public sealed record RunningProcessInfo(int ProcessId, string? ExecutablePath);
/// <param name="CommandLine">
/// The process command line, or <see langword="null"/> when it could not be read (or the
/// platform offers no way to read it).
/// </param>
/// <param name="StartedAt">The process start time, or <see langword="null"/> when it could not be read.</param>
public sealed record RunningProcessInfo(
int ProcessId,
string? ExecutablePath,
string? CommandLine = null,
DateTimeOffset? StartedAt = null);
@@ -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;
/// <summary>
/// Extracts the owning gateway PID from a worker command line's <c>--pipe-name</c> value
/// (<c>mxgw-{gatewayPid}-{sessionUid}</c>, or the older <c>mxaccess-gateway-{gatewayPid}-…</c>).
/// </summary>
/// <param name="commandLine">The worker command line, or <see langword="null"/>.</param>
/// <param name="ownerProcessId">The parsed gateway PID.</param>
/// <returns><see langword="true"/> when an owner PID was found.</returns>
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<char> rest = commandLine.AsSpan(switchIndex + PipeNameSwitch.Length).TrimStart().TrimStart('"');
foreach (string prefix in (string[])["mxgw-", "mxaccess-gateway-"])
{
if (!rest.StartsWith(prefix, StringComparison.Ordinal))
{
continue;
}
ReadOnlySpan<char> 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()
@@ -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;
/// </summary>
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;
/// <inheritdoc />
public IReadOnlyList<RunningProcessInfo> 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);
}
/// <inheritdoc />
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;
}
}
/// <summary>
/// Reads another process's command line. Windows only; <see langword="null"/> elsewhere or
/// when it cannot be read (access denied, the process exited).
/// </summary>
/// <param name="processId">The process to read.</param>
/// <returns>The command line, or <see langword="null"/>.</returns>
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);
}
@@ -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;
}
}
}
@@ -8,8 +8,9 @@ namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Workers;
/// <summary>
/// Per <c>gateway.md</c> 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.
/// </summary>
public sealed class OrphanWorkerTerminatorTests
{
@@ -44,13 +45,13 @@ public sealed class OrphanWorkerTerminatorTests
Assert.Equal([101, 102], inspector.KilledProcessIds.Order());
}
/// <summary>Verifies that orphan workers are killed when executable path is unreadable but image name matches.</summary>
/// <summary>
/// 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.
/// </summary>
[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);
}
/// <summary>
/// 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.
/// </summary>
[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);
}
/// <summary>
/// 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.
/// </summary>
[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);
}
/// <summary>
/// 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.
/// </summary>
[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);
}
/// <summary>The owner PID parses from both the current and the older pipe-name formats, quoted or not.</summary>
/// <param name="commandLine">Worker command line.</param>
/// <param name="expected">Expected owner PID, or 0 when none should parse.</param>
[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);
}
/// <summary>
/// On Windows the system inspector reads a live process's command line (the cross-bitness
/// NtQueryInformationProcess path orphan cleanup depends on).
/// </summary>
[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";
/// <summary>Verifies that unrelated processes with the same image name are not killed.</summary>
[Fact]
public void TerminateOrphans_DoesNotKillUnrelatedProcessSharingImageName()
@@ -147,6 +244,9 @@ public sealed class OrphanWorkerTerminatorTests
/// <inheritdoc />
public IReadOnlyList<RunningProcessInfo> GetProcessesByName(string processName) => processes;
/// <summary>Gets the processes reported as running, by id, with their start times.</summary>
public Dictionary<int, DateTimeOffset?> RunningProcesses { get; } = [];
/// <inheritdoc />
public void Kill(int processId)
{
@@ -157,5 +257,9 @@ public sealed class OrphanWorkerTerminatorTests
KilledProcessIds.Add(processId);
}
/// <inheritdoc />
public bool TryGetRunningProcess(int processId, out DateTimeOffset? startedAt)
=> RunningProcesses.TryGetValue(processId, out startedAt);
}
}