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
29 changes: 23 additions & 6 deletions ParallelKit.Harness.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -4990,6 +4990,19 @@ foreach ($rxCase in @(@{ Hook = 'TestFailTerminate'; Says = "*Windows wouldn't e
foreach ($l in $rxLeft) { Stop-Process -Id $l.ProcessId -Force -ErrorAction SilentlyContinue }
Test-Assert ($rxError -like '*could not start*' -and $rxError -like $rxCase.Says -and $rxError -notlike '*so it was stopped*' -and $rxLeft.Count -eq 1) ("a failed start whose leftovers can't be ended says so (" + $rxCase.Hook + ": " + $rxLeft.Count + " left running, error: " + $rxError + ")")
}
# The same with the program still running: taskkill /T kills it but misses a
# child whose parent has exited (a .cmd that starts the ping and exits).
$rsW++
$rxCmd = Join-Path $env:TEMP ('pk-harness-aw-' + $PID + '.cmd')
[System.IO.File]::WriteAllText($rxCmd, "@start `"`" /b ping -n 30 -w " + $rsW + " 127.0.0.1 >nul`r`n")
$rxError = $null
[PkChildProcessJob]::TestNoTreeJob = $true
[PkStreamReadTask]::TestFailRunAfter = 1
[PkStreamReadTask]::TestFailRunDelayMs = 3000
try { $null = Start-PkProcess -FilePath $cmdExe -Arguments ('/d /c start "" /b cmd /d /c "' + $rxCmd + '" & ping -n 30 127.0.0.1 >nul') } catch { $rxError = [string]$_ } finally { [PkStreamReadTask]::TestFailRunAfter = -1; [PkStreamReadTask]::TestFailRunDelayMs = 0; [PkChildProcessJob]::TestNoTreeJob = $false; Remove-Item -LiteralPath $rxCmd -ErrorAction SilentlyContinue }
$rxLeft = Get-HarnessRollbackLeft $rsW
foreach ($l in $rxLeft) { Stop-Process -Id $l.ProcessId -Force -ErrorAction SilentlyContinue }
Test-Assert ($rxError -like '*could not start*' -and $rxError -like '*was stopped, but it has no Job Object of its own, so what it started may still be running*' -and $rxLeft.Count -eq 1) ("a failed start that kills a program with no tree job says what may still be running (" + $rxLeft.Count + " left running, error: " + $rxError + ")")
Reset-Harness
$rsW++
$dxArgs = '/d /c start "" /b ping -n 30 -w ' + $rsW + ' 127.0.0.1 >nul'
Expand Down Expand Up @@ -6182,8 +6195,9 @@ try {
Test-Assert ($bjOk -and $bjLeft.Count -eq 0 -and $bjTreeWarn.Count -eq 0) ($bjCase.Name + " with -KillTreeOnExit kills the program and doesn't warn about its tree (as expected: " + $bjOk + ", pings left " + $bjLeft.Count + ", " + $bjTreeWarn.Count + " warning(s): " + (@($bjTreeWarn | ForEach-Object { $_.Message }) -join ' | ') + ")")
}

# A kill whose tree job Windows won't end (TestFailTerminate) misses a child
# whose parent exited, and warns once; otherwise nothing is left.
# A kill whose tree job Windows won't end (TestFailTerminate), or of a
# program with none (TestNoTreeJob, TestRefuseTreeJob), misses a child whose
# parent exited, and warns once; otherwise nothing is left.
$bjOrphanCmd = Join-Path $env:TEMP ('pk-harness-bj-' + $PID + '.cmd')
[System.IO.File]::WriteAllText($bjOrphanCmd, "@start `"`" /b ping -n 30 -w 4330 127.0.0.1 >nul`r`n")
$bjOrphan = '/d /c start "" /b cmd /d /c "' + $bjOrphanCmd + '" & ping -n 30 127.0.0.1 >nul'
Expand All @@ -6194,17 +6208,20 @@ try {
)
try {
foreach ($bjCase in $bjOrphanCases) {
foreach ($bjRefuse in $false, $true) {
foreach ($bjHook in '', 'TestFailTerminate', 'TestNoTreeJob', 'TestRefuseTreeJob') {
Reset-Harness
[PkChildProcessJob]::TestResetJobWarnings()
[PkChildProcessJob]::TestFailTerminate = $bjRefuse
try { $null = & $bjCase.Run } finally { [PkChildProcessJob]::TestFailTerminate = $false; Reset-PkAbortState }
if ($bjHook) { [PkChildProcessJob]::$bjHook = $true }
try { $null = & $bjCase.Run } finally { [PkChildProcessJob]::TestFailTerminate = $false; [PkChildProcessJob]::TestNoTreeJob = $false; [PkChildProcessJob]::TestRefuseTreeJob = $false; Reset-PkAbortState }
Start-Sleep -Milliseconds 500
$bjLeft = @(Get-CimInstance Win32_Process -Filter "Name='PING.EXE' AND CommandLine LIKE '%-w 4330 %'")
foreach ($p in $bjLeft) { Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue }
$bjWarn = @($script:messages | Where-Object { $_.Level -eq 'Warn' -and $_.Message -like "*Killing process * may have left what it started running*" })
if ($bjRefuse) {
if ($bjHook -eq 'TestFailTerminate') {
Test-Assert ($bjLeft.Count -eq 1 -and $bjWarn.Count -eq 1) ($bjCase.Name + " whose tree job Windows won't end says what may still be running, once (pings left " + $bjLeft.Count + ", " + $bjWarn.Count + " warning(s))")
} elseif ($bjHook) {
$bjNoTree = @($bjWarn | Where-Object { $_.Message -like '*has no Job Object of its own*' })
Test-Assert ($bjLeft.Count -eq 1 -and $bjWarn.Count -eq 1 -and $bjNoTree.Count -eq 1) ($bjCase.Name + " of a program with no tree job (" + $bjHook + ") says what may still be running, once (pings left " + $bjLeft.Count + ", " + $bjWarn.Count + " warning(s): " + (@($bjWarn | ForEach-Object { $_.Message }) -join ' | ') + ")")
} else {
Test-Assert ($bjLeft.Count -eq 0 -and $bjWarn.Count -eq 0) ($bjCase.Name + " ends a child whose parent has exited, through the tree job (pings left " + $bjLeft.Count + ", " + $bjWarn.Count + " warning(s))")
}
Expand Down
52 changes: 34 additions & 18 deletions ParallelKit.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -1989,16 +1989,22 @@ function Split-PkTaskkillArgumentList {
function Stop-PkJobProcess {
# Kills every running job's program in one Stop-PkProcessTree call (one
# taskkill at most), then ends each killed program's tree job once more and
# warns, with -Why, if Windows won't; then -KillTreeOnExit's leftovers. Used
# by the dispatcher's force-stop and Invoke-PkProcessWithTimeout's cleanup.
# warns, with -Why, if Windows won't or the program has none; then
# -KillTreeOnExit's leftovers. Used by the dispatcher's force-stop and
# Invoke-PkProcessWithTimeout's cleanup.
param([System.Collections.Generic.List[hashtable]]$Jobs, [string]$Why = 'a force-stop')
$procs = foreach ($job in $Jobs) { if ($job['Proc'] -is [System.Diagnostics.Process]) { $job['Proc'] } }
$running = @(foreach ($p in $procs) { if ($p.HasExited -eq $false) { $p } })
try { $null = Stop-PkProcessTree -Process @($procs) } catch { } # best effort; each job is still waited on and disposed after
$killed = $false
try { $killed = Stop-PkProcessTree -Process @($procs) } catch { } # best effort; each job is still waited on and disposed after
# Each killed program's tree job again, as Stop-PkProgramTree does after a
# kill: a second KillTree fails only if Windows won't end it.
# kill: a second KillTree fails only if Windows won't end it. A killed
# program with no tree job may have left a child whose parent had exited.
foreach ($p in $running) {
try { if ([PkChildProcessJob]::HasTree($p) -and -not [PkChildProcessJob]::KillTree($p)) { Write-PkKillTreeWarning -ProcessId $p.Id -Why $Why } } catch { } # best effort, as above
try {
if (-not [PkChildProcessJob]::HasTree($p)) { if ($killed -and $p.HasExited) { Write-PkKillTreeWarning -ProcessId $p.Id -Why $Why -NoTree } }
elseif (-not [PkChildProcessJob]::KillTree($p)) { Write-PkKillTreeWarning -ProcessId $p.Id -Why $Why }
} catch { } # best effort, as above
}
foreach ($job in $Jobs) { if ($job['KillTree']) { try { Stop-PkExitedJobTree -Job $job } catch { } } } # best effort, as above
# The kills are done: release each tree job's handle now rather than at
Expand Down Expand Up @@ -2060,9 +2066,9 @@ function Stop-PkTimedOutJob {
# attempt, not one per dispatcher pass.
$Job['TimeLimit'] = 0
$stopped = Stop-PkProgramTree -Process $proc
if ($stopped -eq 'Killed' -or $stopped -eq 'Refused') {
if ($stopped -eq 'Killed' -or $stopped -eq 'Refused' -or $stopped -eq 'KilledNoTree') {
$Job['TimedOut'] = $true
if ($stopped -eq 'Refused') { Write-PkKillTreeWarning -ProcessId $proc.Id -Why 'its time limit' }
if ($stopped -ne 'Killed') { Write-PkKillTreeWarning -ProcessId $proc.Id -Why 'its time limit' -NoTree:($stopped -eq 'KilledNoTree') }
} elseif ($stopped -eq 'NotKilled' -or $stopped -eq 'Unknown') {
Write-PkMessage ("ProcessDispatch: a job passed its time limit, but its program (process " + $proc.Id + ") couldn't be stopped. It holds its slot until it exits.") -Level Warn
}
Expand All @@ -2071,9 +2077,10 @@ function Stop-PkTimedOutJob {
function Stop-PkProgramTree {
# Ends one program (Stop-PkProcessTree), checks its tree job after a kill,
# and with -Leftovers ends what an exited one left. Returns Killed,
# NotKilled, Unknown (state unreadable), Exited, or Refused / NoTree when
# what it started may still be running. The force-stop kills in one batch
# instead, and Stop-PkJobProcess repeats this post-kill check.
# NotKilled, Unknown (state unreadable), Exited, or Refused / NoTree /
# KilledNoTree when what it started may still be running. The force-stop
# kills in one batch instead, and Stop-PkJobProcess repeats this post-kill
# check.
param([Parameter(Mandatory)][System.Diagnostics.Process]$Process, [switch]$Leftovers)
# A Process never started, or disposed, reads $null here (no throw): it
# can't be read or killed by its handle. Its tree job still works.
Expand All @@ -2096,9 +2103,10 @@ function Stop-PkProgramTree {
if ([PkChildProcessJob]::KillTree($Process)) { return $done }
return 'Refused'
}
# Without a tree job, a program taskkill /T just killed took what it
# could see with it; one that had exited can't be reached at all.
if ($killed) { return $done }
# Without a tree job, the kill (taskkill /T, or the program alone if
# taskkill failed) misses at least a child whose parent had exited; what a
# program that had exited left can't be reached at all.
if ($killed) { return 'KilledNoTree' }
return 'NoTree'
}

Expand All @@ -2121,21 +2129,29 @@ function Stop-PkFailedStartTree {
'Unknown' { return ($name + "'s state couldn't be read (its Process object was disposed), so it and what it started may still be running.") }
'Refused' { return ($name + " has ended, but Windows wouldn't end its own Job Object, so what it started may still be running. That ends when PowerShell does.") }
'NoTree' { return ($name + " had ended, and it has no Job Object of its own, so what it started may still be running.") }
'KilledNoTree' { return ($name + " was stopped, but it has no Job Object of its own, so what it started may still be running.") }
}
return ''
}

function Write-PkKillTreeWarning {
# A kill whose tree job Windows wouldn't end. Once per session, shared with
# -KillTreeOnExit's warning for the same refusal (Stop-PkExitedJobTree).
param([int]$ProcessId, [string]$Why)
# A kill whose tree job Windows wouldn't end, or (-NoTree) of a program
# with none. Each once per session, shared with -KillTreeOnExit's warning
# for the same cause (Stop-PkExitedJobTree).
param([int]$ProcessId, [string]$Why, [switch]$NoTree)
if ($NoTree) {
if (-not [PkChildProcessJob]::ClaimNoTreeWarning()) { return }
Write-PkMessage ("[WARNING] Killing process " + $ProcessId + " (" + $Why + ") may have left what it started running: the program has no Job Object of its own, so killing it can miss what it started, such as a child whose parent has already exited. Shown once.") -Level Warn
return
}
if (-not [PkChildProcessJob]::ClaimKillTreeWarning()) { return }
Write-PkMessage ("[WARNING] Killing process " + $ProcessId + " (" + $Why + ") may have left what it started running: Windows wouldn't end the program's own Job Object. It still ends when PowerShell does. Shown once.") -Level Warn
}

function Stop-PkExitedJobTree {
# -KillTreeOnExit: once a job's program has exited, ends what it left
# running. No tree job, or one Windows won't end, warns once per session.
# running. No tree job, or one Windows won't end, warns once per session,
# shared with Write-PkKillTreeWarning's warning for the same cause.
# KillTree is cleared first, so each job gets one attempt, though the
# dispatcher's poll calls this every pass.
param([hashtable]$Job)
Expand Down Expand Up @@ -2422,7 +2438,7 @@ function Invoke-PkProcessWithTimeout {
if (-not $exited) {
$stopped = 'Killed'
try { $stopped = Stop-PkProgramTree -Process $job['Proc'] } catch { } # best effort - the throw below still reports why
if ($stopped -eq 'Refused') { Write-PkKillTreeWarning -ProcessId $job['Proc'].Id -Why $(if ($remainingMs -le 0) { 'its time limit' } else { 'an abort' }) }
if ($stopped -eq 'Refused' -or $stopped -eq 'KilledNoTree') { Write-PkKillTreeWarning -ProcessId $job['Proc'].Id -Why $(if ($remainingMs -le 0) { 'its time limit' } else { 'an abort' }) -NoTree:($stopped -eq 'KilledNoTree') }
# Let the reads finish (the kill closes their pipes) before the
# process is disposed. Bounded.
try { $null = [System.Threading.Tasks.Task]::WaitAll(@($job['StdoutTask'], $job['StderrTask']), 500) } catch { } # a read error doesn't matter: the throw below reports the kill
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ ParallelKit uses Windows Job Objects to clean up programs and their descendants.

- **`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`. If Windows won't end a program's own Job Object, the kill also goes to `taskkill /T`, which misses a child whose parent has already exited; the kit warns about that once per session.
- **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), or whose job Windows won't end, goes to `taskkill /T` instead, which misses a child whose parent has already exited; if `taskkill` can't start, fails or hangs, only the program itself is killed. What's missed runs until PowerShell exits, or past that with `NoJob`. A time limit or a force-stop that may have missed something warns once per session.

</details>

Expand Down Expand Up @@ -312,7 +312,7 @@ The per-command keys go on the command itself, for example one that keeps all of

`-StreamTimeoutMs` (default 15000) is how long to wait for a program's output after it exits; see `StreamTimedOut` in [Process results](#process-results).

`-KillTreeOnExit` kills whatever a program started that's still running when the program itself exits, whether or not it holds the program's output open. It's off by default, since some tools leave a build server or a daemon running on purpose. A command's own `KillTreeOnExit` key, `$true` or `$false`, overrides it either way. `Invoke-PkProcessWithTimeout` and the dispatcher take it too; `Start-PkProcess` doesn't, since it returns before there's an exit to act on. It goes through the program's own Job Object, so for a program without one (`StartMode` `NoJob`, or Windows refused it) it can't kill anything; it warns once per session instead. If Windows won't end a program's Job Object, what it started may still be running, and that warns once per session too. `StartMode` `CreatedInJob` describes how programs start, not whether each one got its own Job Object. In `AddedToJob` mode it can miss a child the program started straight away.
`-KillTreeOnExit` kills whatever a program started that's still running when the program itself exits, whether or not it holds the program's output open. It's off by default, since some tools leave a build server or a daemon running on purpose. A command's own `KillTreeOnExit` key, `$true` or `$false`, overrides it either way. `Invoke-PkProcessWithTimeout` and the dispatcher take it too; `Start-PkProcess` doesn't, since it returns before there's an exit to act on. It goes through the program's own Job Object, so for a program without one (`StartMode` `NoJob`, or Windows refused it) it can't kill anything; it warns once per session instead. If Windows won't end a program's Job Object, what it started may still be running, and that warns once per session too. Neither warns again if a time limit or a force-stop has already warned about the same cause. `StartMode` `CreatedInJob` describes how programs start, not whether each one got its own Job Object. In `AddedToJob` mode it can miss a child the program started straight away.

</details>

Expand Down