Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions ParallelKit.Harness.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -5063,6 +5063,67 @@ try {
}
Write-Host ""

Write-Host "=== BG: a missing Job Object, a refused program or a missing start lock is reported ===" -ForegroundColor Cyan
# Each costs the cleanup of programs left running if PowerShell is killed,
# so each warns, once a session, whichever path set things up.
Reset-Harness

# The Job Object set up by a program's start, when nothing set it up first:
# in a fresh PowerShell, since this one's is set up already.
$bgInitScript = Join-Path $env:TEMP ("pk-bg-init-" + [guid]::NewGuid().ToString("N") + ".ps1")
[System.IO.File]::WriteAllText($bgInitScript, @"
. '$kitPath'
`$bgWarn = [System.Collections.Generic.List[string]]::new()
Set-PkMessageHandler { param(`$Message, `$Level) if (`$Level -eq 'Warn') { `$bgWarn.Add(`$Message) } }.GetNewClosure()
[PkChildProcessJob]::TestFailInit = `$true
`$bgExits = foreach (`$i in 1..2) { (Invoke-PkProcessWithTimeout -FilePath '$cmdExe' -Arguments '/d /c exit 4').ExitCode }
Write-Output ('EXITS=' + (`$bgExits -join ',') + ' MODE=' + [PkChildProcessJob]::StartMode + ' WARNS=' + `$bgWarn.Count)
foreach (`$w in `$bgWarn) { Write-Output ('WARN: ' + `$w) }
"@)
$bgInit = Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments ('-NoProfile -ExecutionPolicy Bypass -File "' + $bgInitScript + '"') -TimeoutMs 60000
[System.IO.File]::Delete($bgInitScript)
$bgInitOut = [string]$bgInit.Stdout
Test-Assert ($bgInitOut -like '*EXITS=4,4 MODE=NoJob WARNS=1*' -and $bgInitOut -like '*WARN: *child-process cleanup*') ("a Job Object that a program's start can't set up warns once, and programs still run (" + $bgInitOut.Trim() + ")")

# A running program Windows won't add to the Job Object, on the
# Process.Start path.
Reset-Harness
[PkChildProcessJob]::TestResetJobWarnings()
$bgExits = @()
[PkChildProcessJob]::TestUseProcessStart = $true
[PkChildProcessJob]::TestFailAssign = $true
try {
foreach ($i in 1..2) { $bgExits += (Complete-PkProcess (Start-PkProcess -FilePath $pingExe -Arguments '-n 2 127.0.0.1') -Dispose).ExitCode }
} finally {
[PkChildProcessJob]::TestFailAssign = $false
[PkChildProcessJob]::TestUseProcessStart = $false
}
$bgAssign = @($script:messages | Where-Object { $_.Level -eq 'Warn' })
Test-Assert ($bgAssign.Count -eq 1 -and $bgAssign[0].Message -like "*wouldn't add a program*Win32 error 5*" -and ($bgExits -join ',') -eq '0,0') ("a running program Windows won't add to the Job Object warns once, naming the error, and still runs (" + $bgAssign.Count + " warning(s), exits " + ($bgExits -join ',') + ")")
[PkChildProcessJob]::TestResetJobWarnings()
# The reason comes from the call itself, also when the process can't be
# read at all (a disposed Process object throws on its handle).
$bgGone = Start-PkProcess -FilePath $cmdExe -Arguments '/d /c exit 0'
$null = Complete-PkProcess $bgGone -Dispose
$bgWhy = $null
$bgAssigned = [PkChildProcessJob]::Assign($bgGone['Proc'], [ref]$bgWhy)
Test-Assert (-not $bgAssigned -and -not [string]::IsNullOrEmpty($bgWhy) -and $bgWhy -notlike 'Win32 error*') ("a process that can't be read isn't added, and the reason says what was thrown (" + $bgWhy + ")")

# .NET's start lock not found, as a future .NET that moved it would bring.
Reset-Harness
[PkChildProcessJob]::TestResetFallbackWarning()
$bgMode = $null; $bgExits = @()
[PkChildProcessJob]::TestNoStartLock = $true
try {
$bgMode = [PkChildProcessJob]::StartMode
foreach ($i in 1..2) { $bgExits += (Complete-PkProcess (Start-PkProcess -FilePath $cmdExe -Arguments '/d /c exit 2') -Dispose).ExitCode }
} finally { [PkChildProcessJob]::TestNoStartLock = $false }
$bgLock = @($script:messages | Where-Object { $_.Level -eq 'Warn' })
Test-Assert ($bgMode -eq 'AddedToJob' -and $bgLock.Count -eq 1 -and $bgLock[0].Message -like "*process-start lock isn't where*" -and ($bgExits -join ',') -eq '2,2' -and [PkChildProcessJob]::StartMode -eq 'CreatedInJob') ("without .NET's start lock, StartMode is AddedToJob and the fallback warns once (" + $bgMode + ", " + $bgLock.Count + " warning(s), exits " + ($bgExits -join ',') + ")")
[PkChildProcessJob]::TestResetFallbackWarning()
Reset-Harness
Write-Host ""

Set-PkMessageHandler -Handler $null
Reset-PkAbortState

Expand Down
67 changes: 57 additions & 10 deletions ParallelKit.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ public static class PkState

// Bump this, and the check after the type definitions, whenever any C#
// in this file changes: a session keeps the types it compiled first.
public const int TypesVersion = 11;
public const int TypesVersion = 12;

// Locked: Register-/Unregister-PkCancellationSource are callable from
// worker runspaces, and List<T> is not safe for concurrent writers.
Expand Down Expand Up @@ -536,11 +536,17 @@ public static class PkChildProcessJob
public static bool IsInitialized { get { return _job != IntPtr.Zero; } }
public static int LastError { get; private set; }

// Harness only: make Initialize, or Assign, fail as if Windows refused
// (error 5), to test their warnings.
public static bool TestFailInit = false;
public static bool TestFailAssign = false;

public static bool Initialize()
{
lock (_lock)
{
if (_job != IntPtr.Zero) { return true; }
if (TestFailInit) { LastError = 5; return false; }
IntPtr job = CreateJobObject(IntPtr.Zero, null);
if (job == IntPtr.Zero) { LastError = Marshal.GetLastWin32Error(); return false; }

Expand Down Expand Up @@ -569,10 +575,27 @@ public static class PkChildProcessJob
// job (Windows nests it); without one, a kill uses taskkill.
public static bool Assign(System.Diagnostics.Process process)
{
if (_job == IntPtr.Zero || process == null) { return false; }
string reason;
return Assign(process, out reason);
}

// The same, saying why it failed ("Win32 error 5", or what was thrown);
// null when it worked. Per call: LastError is shared, and another
// thread's start can change it before the caller reads it.
public static bool Assign(System.Diagnostics.Process process, out string reason)
{
reason = null;
if (_job == IntPtr.Zero || process == null) { reason = "no Job Object"; return false; }
if (TestFailAssign) { LastError = 5; reason = "Win32 error 5"; return false; }
try
{
if (!AssignProcessToJobObject(_job, process.Handle)) { LastError = Marshal.GetLastWin32Error(); return false; }
if (!AssignProcessToJobObject(_job, process.Handle))
{
int e = Marshal.GetLastWin32Error();
LastError = e;
reason = "Win32 error " + e;
return false;
}
if (!TestNoTreeJob)
{
IntPtr treeJob = CreateJobObject(IntPtr.Zero, null);
Expand All @@ -583,7 +606,7 @@ public static class PkChildProcessJob
}
return true;
}
catch { return false; }
catch (Exception ex) { reason = ex.Message; return false; } // a process whose handle can't be read: say what was thrown
}

// ---- Starting a program inside the job from its first instruction ----
Expand Down Expand Up @@ -736,10 +759,15 @@ public static class PkChildProcessJob
private static StartLock _startLock;
private static bool _startLockLooked;

// Harness only: act as if .NET's start lock weren't found, to test the
// warning a .NET that moved it would bring.
public static bool TestNoStartLock = false;

private static StartLock GetStartLock()
{
lock (_lock)
{
if (TestNoStartLock) { return null; }
if (_startLockLooked) { return _startLock; }
_startLockLooked = true;
// .NET Framework: s_CreateProcessLock. .NET (Core) on Windows: s_createProcessLock.
Expand Down Expand Up @@ -804,6 +832,12 @@ public static class PkChildProcessJob
private static int _fallbackWarned = 0;
public static bool ClaimFallbackWarning() { return Interlocked.Exchange(ref _fallbackWarned, 1) == 0; }
public static void TestResetFallbackWarning() { Interlocked.Exchange(ref _fallbackWarned, 0); }
// The same, once each, for a Job Object that couldn't be set up when
// first needed, and for a running program Windows wouldn't add to it.
private static int _initWarned = 0, _assignWarned = 0;
public static bool ClaimInitWarning() { return Interlocked.Exchange(ref _initWarned, 1) == 0; }
public static bool ClaimAssignWarning() { return Interlocked.Exchange(ref _assignWarned, 1) == 0; }
public static void TestResetJobWarnings() { Interlocked.Exchange(ref _initWarned, 0); Interlocked.Exchange(ref _assignWarned, 0); }

private static StringBuilder BuildCommandLine(string fileName, string arguments)
{
Expand Down Expand Up @@ -1005,7 +1039,7 @@ public static class PkChildProcessJob
# A session that loaded an older copy keeps its compiled types. Say so,
# rather than fail later with a missing-method error. Keep this number in
# sync with [PkState]::TypesVersion.
if ((& { try { [PkState]::TypesVersion } catch { 0 } }) -ne 11) {
if ((& { try { [PkState]::TypesVersion } catch { 0 } }) -ne 12) {
throw "ParallelKit: this PowerShell session already loaded an older version of the kit, and its compiled parts can't be swapped out. Close this window and start a new one."
}

Expand Down Expand Up @@ -1154,8 +1188,14 @@ function Register-PkAbortHandler {
}

function Initialize-PkChildProcessJob {
# -Once: warn only the first time it fails in this session. For the
# setup a start does when nothing set the job up first, which retries on
# every start after a failure. Write-PkMessage: a start can be in a worker.
param([switch]$Once)
if ([PkChildProcessJob]::Initialize()) { return $true }
Invoke-PkMessageHandler -Level Warn -Message ("[WARNING] Could not set up child-process cleanup (Win32 error " + [PkChildProcessJob]::LastError + ") - if this window is force-closed mid-run, a running child process may be left behind and need ending in Task Manager.")
if (-not $Once -or [PkChildProcessJob]::ClaimInitWarning()) {
Write-PkMessage -Level Warn -Message ("[WARNING] Could not set up child-process cleanup (Win32 error " + [PkChildProcessJob]::LastError + ") - if this window is force-closed mid-run, a running child process may be left behind and need ending in Task Manager.")
}
return $false
}

Expand Down Expand Up @@ -1645,8 +1685,9 @@ function Start-PkProcessCore {
)
$encoding = Resolve-PkEncoding -Encoding $OutputEncoding
$commandLine = Resolve-PkArguments -Arguments $Arguments -FilePath $FilePath
# For a caller who never ran Initialize-ParallelKit. No-ops once done.
if (-not [PkChildProcessJob]::IsInitialized) { $null = [PkChildProcessJob]::Initialize() }
# For a caller who never ran Initialize-ParallelKit. No-ops once done;
# a failure warns once, as Initialize-ParallelKit would.
if (-not [PkChildProcessJob]::IsInitialized) { $null = Initialize-PkChildProcessJob -Once }

$psi = [System.Diagnostics.ProcessStartInfo]::new()
$psi.FileName = $FilePath
Expand Down Expand Up @@ -1717,7 +1758,13 @@ function Start-PkProcessCore {
Stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
}
}
$null = [PkChildProcessJob]::Assign($proc)
# Windows also refuses a program that has already exited (error 5), as
# quick ones often have by now: only one still running is a real gap.
# With no job at all, the setup above has warned already.
$assignWhy = $null
if (-not [PkChildProcessJob]::Assign($proc, [ref]$assignWhy) -and [PkChildProcessJob]::IsInitialized -and -not $proc.HasExited -and [PkChildProcessJob]::ClaimAssignWarning()) {
Write-PkMessage ("[WARNING] Windows wouldn't add a program to the kit's Job Object (process " + $proc.Id + ", " + $psi.FileName + ": " + $assignWhy + "). It isn't cleaned up if PowerShell is killed outright, and killing it reaches what it started only through taskkill. Shown once.") -Level Warn
}
return @{
Proc = $proc
StdoutTask = [PkStreamReadTask]::Run($proc.StandardOutput, $MaxOutputChars)
Expand Down Expand Up @@ -3163,7 +3210,7 @@ function Invoke-PkProcessBatch {

function Get-PkWorkerSafeFunctionNames {
# Kit functions every worker runspace gets automatically.
return @('Write-PkMessage', 'Test-PkAbortSignal', 'Test-PkCancelRequested', 'Stop-PkProcessTree', 'Stop-PkProcessTreeCore', 'Split-PkTaskkillArguments', 'Stop-PkJobProcesses', 'Get-PkProcessDuration', 'Resolve-PkEncoding',
return @('Write-PkMessage', 'Test-PkAbortSignal', 'Test-PkCancelRequested', 'Initialize-PkChildProcessJob', 'Stop-PkProcessTree', 'Stop-PkProcessTreeCore', 'Split-PkTaskkillArguments', 'Stop-PkJobProcesses', 'Get-PkProcessDuration', 'Resolve-PkEncoding',
'Start-PkProcess', 'Wait-PkProcess', 'Wait-PkRunningJobs', 'Complete-PkProcess', 'Invoke-PkProcessWithTimeout',
'Invoke-PkProcessDispatch', 'Invoke-PkProcessDispatchCore', 'Invoke-PkProcessBatch',
'Register-PkCancellationSource', 'Unregister-PkCancellationSource', 'New-PkBatchResult', 'Get-PkJobMaxOutputChars', 'ConvertTo-PkArgumentString', 'Get-PkForceStopReason', 'Resolve-PkFileSystemPath', 'Add-PkDispatchGroupJobs', 'Start-PkProcessCore', 'Get-PkJobTimeLimit', 'Stop-PkTimedOutJob', 'Get-PkStartFailureCause', 'Resolve-PkArguments', 'Invoke-PkCallback', 'Write-PkCallbackLoopWarning', 'ConvertTo-PkArgumentStringCore')
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ ParallelKit uses Windows Job Objects to clean up programs and their descendants.
<details>
<summary>The three cases</summary>

- **`AddedToJob`.** Creating a program inside the Job Object relies on a private part of .NET. Where the kit can't do that, it starts the program and adds it to the Job Object just after, and warns once. A child the program starts in that moment can escape.
- **`NoJob`.** If Windows won't give the kit a Job Object at all, it warns, and programs left running when PowerShell is killed stay running.
- **`AddedToJob`.** Creating a program inside the Job Object relies on a private part of .NET. Where the kit can't do that, it starts the program and adds it to the Job Object just after, and warns once. A child the program starts in that moment can escape. If Windows refuses to add a program that's still running, the kit warns once more, naming the process: that program isn't cleaned up if PowerShell is killed.
- **`NoJob`.** If Windows won't give the kit a Job Object at all, it warns (once, when the first program's start is what sets it up), and programs left running when PowerShell is killed stay running.
- **Killing a program's tree** (a time limit, an abort's force-stop, `Stop-PkProcessTree`). A program the kit started is killed through a Job Object of its own, along with everything it started. One without that job (with `NoJob`, or where Windows refused it) goes to `taskkill /T` instead, and if `taskkill` can't start, fails or hangs, only the program itself is killed. Its children then run until PowerShell exits, or past that with `NoJob`.

</details>
Expand Down
Loading