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
@@ -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);
}