diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index d31f838..ba7c4f4 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -191,6 +191,15 @@ function Invoke-LimitGroup { # The pings a test started, told apart by their -n count. function Get-LimitPing { param([int]$N) return @(Get-CimInstance Win32_Process -Filter "Name = 'PING.EXE'" | Where-Object { $_.CommandLine -like ("*-n " + $N + " 127.0.0.1*") }) } function Get-LimitPingCount { param([int]$N) return @(Get-LimitPing $N).Count } +# The pings left after a kill. Ending a Job Object returns before Windows has +# torn its processes down, so a count taken at once can still see one: wait up +# to 5 s for them to go. +function Get-LimitPingLeft { + param([int]$N) + $sw = [System.Diagnostics.Stopwatch]::StartNew() + do { $left = Get-LimitPingCount $N; if ($left -eq 0) { break }; Start-Sleep -Milliseconds 100 } while ($sw.Elapsed.TotalSeconds -lt 5) + return $left +} function Stop-StrayPings { param([int]$N) Get-LimitPing $N | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue } @@ -3412,7 +3421,7 @@ try { -JobStarter { param($job) $s = Start-PkProcess -FilePath $job['FilePath'] -Arguments $job['Arguments']; $job['Proc'] = $s.Proc; throw "starter failed after starting" } ` -JobFinalize { param($job, $q) $null = Complete-PkProcess -Job $job } } catch { Write-Host " throwing-starter run threw: $_" } -$stopLeft = Get-LimitPingCount 48 +$stopLeft = Get-LimitPingLeft 48 Stop-StrayPings 48 Test-Assert ($null -ne $stopResult -and $stopResult.JobStarterFailedCount -eq 1 -and $stopLeft -eq 0 -and $stopBudget.CurrentCount -eq 2) ("a starter that throws after starting its program doesn't leave it running (" + $stopLeft + " left, " + $stopBudget.CurrentCount + " of 2 slots free)") @@ -3441,7 +3450,7 @@ try { }.GetNewClosure() ` -JobFinalize { param($job, $q) $null = Complete-PkProcess -Job $job; if ($job['Name'] -eq 'b') { throw "finalize failed" } } } catch { $stopProblem = [string]$_ } -$stopLeft = Get-LimitPingCount 47 +$stopLeft = Get-LimitPingLeft 47 Stop-StrayPings 47 Test-Assert ($stopProblem -like '*finalize failed*' -and $stopLeft -eq 0) ("an error after a job was finalized in the same pass still kills the running ones (" + $stopLeft + " left, problem: " + $stopProblem + ")") @@ -3467,7 +3476,7 @@ try { }.GetNewClosure() ` -JobFinalize { param($job, $q) $null = Complete-PkProcess -Job $job -Dispose; throw "finalize failed after dispose" } } catch { $dispProblem = [string]$_ } -$dispLeft = Get-LimitPingCount 51 +$dispLeft = Get-LimitPingLeft 51 Stop-StrayPings 51 Test-Assert ($dispProblem -like '*finalize failed after dispose*' -and $dispLeft -eq 0) ("a -JobFinalize that disposes its process and throws still has the running jobs killed (" + $dispLeft + " of 3 left, problem: " + $dispProblem + ")") @@ -3482,10 +3491,7 @@ while ((Get-LimitPingCount 53) -lt 1 -and $dispWait.Elapsed.TotalSeconds -lt 5) $dispThrew = $null $dispKilled = $false try { $dispKilled = Stop-PkProcessTree -Process @($dispGone.Proc, $dispLive.Proc) } catch { $dispThrew = [string]$_ } -# Ending a Job Object returns before Windows has torn its processes down: -# give the ping a moment to go. -$dispWait = [System.Diagnostics.Stopwatch]::StartNew() -do { $dispLeft = Get-LimitPingCount 53; if ($dispLeft -eq 0) { break }; Start-Sleep -Milliseconds 100 } while ($dispWait.Elapsed.TotalSeconds -lt 5) +$dispLeft = Get-LimitPingLeft 53 Stop-StrayPings 53 Test-Assert ($null -eq $dispThrew -and $dispKilled -and $dispLeft -eq 0 -and $dispLive.Proc.HasExited) ("Stop-PkProcessTree kills a live tree listed beside a disposed process (" + $dispLeft + " left, returned " + $dispKilled + ", threw: " + $dispThrew + ")") try { if (-not $dispLive.Proc.HasExited) { $dispLive.Proc.Kill() } } catch { } # cleanup after a failure; already-exited is fine @@ -3513,7 +3519,7 @@ try { -JobFinalize { param($job, $q) $null = Complete-PkProcess -Job $job; throw "finalize failed" } ` -JobAbortCleanup { param($job) $fcCleaned.Add($job['Name']) }.GetNewClosure() } catch { $fcProblem = [string]$_ } -$fcLeft = Get-LimitPingCount 55 +$fcLeft = Get-LimitPingLeft 55 Stop-StrayPings 55 Test-Assert ($fcProblem -like '*finalize failed*' -and ($fcCleaned -join ',') -eq 'run' -and $fcLeft -eq 0 -and $fcBudget.CurrentCount -eq 2) ("a -JobFinalize that throws gets no -JobAbortCleanup for its finished job, only for the killed one (cleaned: " + ($fcCleaned -join ',') + ", " + $fcLeft + " left, " + $fcBudget.CurrentCount + " of 2 slots free)") @@ -3789,7 +3795,7 @@ $kwLabeled = 'unset' :kwOuter foreach ($kwI in 1..1) { $kwLabeled = Invoke-PkProcessBatch -MaxConcurrent 2 -Commands @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }, @{ FilePath = $pingExe; Arguments = '-n 35 127.0.0.1' }) -OnComplete { param($c, $r) break kwOuter } } -$kwLeft = Get-LimitPingCount 35 +$kwLeft = Get-LimitPingLeft 35 Stop-StrayPings 35 Test-Assert ($kwLabeled -eq 'unset' -and $kwLeft -eq 0) ("a labeled break out of a callback leaves the call and kills its programs (" + $kwLeft + " left)") Reset-Harness @@ -5605,11 +5611,17 @@ try { $bfUp = Wait-HarnessTagPings @('4325', '4326') $bfHas = [PkChildProcessJob]::TestHasTree($bfJob['Proc']) $bfKilled = Stop-PkProcessTree -Process $bfJob['Proc'] - $bfReleased = -not [PkChildProcessJob]::TestHasTree($bfJob['Proc']) + # The kill keeps the tree job, so a later KillTree on it succeeds; + # Complete-PkProcess lets go of it. + $bfKept = [PkChildProcessJob]::TestHasTree($bfJob['Proc']) Start-Sleep -Milliseconds 300 $bfOrphans = @(Get-HarnessTagPings '4325').Count; $bfOwn = @(Get-HarnessTagPings '4326').Count - Test-Assert ($bfUp -and $bfHas -and $bfKilled -and $bfReleased -and $bfJob['Proc'].HasExited -and $bfOrphans -eq 0 -and $bfOwn -eq 0) ($bfMode + ": Stop-PkProcessTree kills a child whose parent already exited, and lets go of the tree job (both pings up: " + $bfUp + ", tree job: " + $bfHas + ", released: " + $bfReleased + ", orphans left " + $bfOrphans + ", own left " + $bfOwn + ")") - $null = Complete-PkProcess -Job $bfJob -StreamTimeoutMs 0 -Dispose + $bfAgain = [PkChildProcessJob]::KillTree($bfJob['Proc']) + $null = Complete-PkProcess -Job $bfJob -StreamTimeoutMs 0 + $bfReleased = -not [PkChildProcessJob]::TestHasTree($bfJob['Proc']) + $bfExited = $bfJob['Proc'].HasExited + $bfJob['Proc'].Dispose() + Test-Assert ($bfUp -and $bfHas -and $bfKilled -and $bfKept -and $bfAgain -and $bfReleased -and $bfExited -and $bfOrphans -eq 0 -and $bfOwn -eq 0) ($bfMode + ": Stop-PkProcessTree kills a child whose parent already exited; the tree job stays until Complete-PkProcess (both pings up: " + $bfUp + ", tree job: " + $bfHas + ", kept after the kill: " + $bfKept + ", killed again: " + $bfAgain + ", released: " + $bfReleased + ", orphans left " + $bfOrphans + ", own left " + $bfOwn + ")") Stop-HarnessTagPings } @@ -6056,6 +6068,24 @@ try { try { Test-HarnessKillTree 'tree job not ended, a second time' { Invoke-HarnessTreeBatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{} $bjHeld } -Left } finally { [PkChildProcessJob]::TestFailTerminate = $false } Test-Assert (@($script:messages | Where-Object { $_.Message -like '*may still be running*' }).Count -eq 1) ("and only once per process (" + @($script:messages | Where-Object { $_.Message -like '*may still be running*' }).Count + " warning(s) after a second program)") + # A program the kit kills (its time limit, Invoke-PkProcessWithTimeout's + # limit, an abort's force-stop) has had its tree ended by that kill, so + # -KillTreeOnExit ending it again afterwards has nothing to warn about. + $bjKilled = @( + @{ Name = 'a time-limit kill in a batch'; Run = { $r = (Invoke-PkProcessBatch -TimeoutSeconds 1 -KillTreeOnExit -Commands @(@{ FilePath = $pingExe; Arguments = '-n 30 -w 4329 127.0.0.1' })).Results[0]; [bool]$r.TimedOut } } + @{ Name = "Invoke-PkProcessWithTimeout's limit"; Run = { $t = $false; try { $null = Invoke-PkProcessWithTimeout -FilePath $pingExe -Arguments '-n 30 -w 4329 127.0.0.1' -TimeoutMs 1000 -KillTreeOnExit } catch { $t = ([string]$_ -like '*killed*') }; $t } } + @{ Name = "an abort's force-stop"; Run = { $b = Invoke-PkProcessBatch -MaxConcurrent 2 -AbortTimeoutSeconds 1 -KillTreeOnExit -OnComplete { param($c, $r) if ($c['Key'] -eq 'quick') { Request-PkAbort } } -Commands @(@{ FilePath = $pingExe; Arguments = '-n 30 -w 4329 127.0.0.1'; Key = 'long' }, @{ FilePath = $cmdExe; Arguments = '/d /c ping -n 3 127.0.0.1 >nul'; Key = 'quick' }); Reset-PkAbortState; ($b.Aborted -and $b.ForceKilledCount -eq 1) } } + ) + foreach ($bjCase in $bjKilled) { + Reset-Harness + [PkChildProcessJob]::TestResetJobWarnings() + $bjOk = & $bjCase.Run + $bjLeft = @(Get-CimInstance Win32_Process -Filter "Name='PING.EXE' AND CommandLine LIKE '%-w 4329 %'") + foreach ($p in $bjLeft) { Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue } + $bjTreeWarn = @($script:messages | Where-Object { $_.Message -like '*-KillTreeOnExit*' }) + 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 force-stop: the program has exited, but the caller's poll never says # done, so neither the poll nor Complete-PkProcess kills what it left. Reset-Harness diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 2c63253..8198f3b 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -520,7 +520,10 @@ public static class PkChildProcessJob } // Kills every process in the program's tree job. False if it has none, - // or Windows refused: the caller then uses taskkill. + // or Windows refused: the caller then uses taskkill. The job stays open + // until ReleaseTree (Complete-PkProcess, or the kit's own kill paths) or + // garbage collection, so a second KillTree, as -KillTreeOnExit makes + // after a time-limit kill or a force-stop, ends an empty job and succeeds. public static bool KillTree(Process process) { if (process == null) { return false; } @@ -534,8 +537,6 @@ public static class PkChildProcessJob } catch (ObjectDisposedException) { return false; } // released meanwhile: taskkill instead finally { if (added) { j.DangerousRelease(); } } - // The tree is gone: its job's handle can go now rather than with the Process. - if (ended) { ReleaseTree(process); } return ended; } @@ -2003,6 +2004,9 @@ function Stop-PkJobProcess { $procs = foreach ($job in $Jobs) { if ($job['Proc'] -is [System.Diagnostics.Process]) { $job['Proc'] } } try { $null = Stop-PkProcessTree -Process @($procs) } catch { } # best effort; each job is still waited on and disposed after foreach ($job in $Jobs) { if ($job['KillTree']) { try { Stop-PkExitedJobTree -Job $job } catch { } } } # best effort, as above + # The kills are done: the tree jobs' handles can go now, not at garbage + # collection (KillTree leaves them open, and these jobs aren't completed). + foreach ($job in $Jobs) { if ($job['Proc'] -is [System.Diagnostics.Process]) { try { [PkChildProcessJob]::ReleaseTree($job['Proc']) } catch { } } } # nothing to report } function Get-PkJobTimeLimit { @@ -2385,6 +2389,9 @@ function Invoke-PkProcessWithTimeout { try { if (-not $job['Proc'].HasExited) { $null = Stop-PkProcessTree -Process $job['Proc'] } } catch { } # Stopped between the program's exit and Complete-PkProcess. As above. try { if ($job['KillTree']) { Stop-PkExitedJobTree -Job $job } } catch { } + # Its tree job's handle, when a kill (which leaves it open) came + # instead of Complete-PkProcess, which closes it. + try { [PkChildProcessJob]::ReleaseTree($job['Proc']) } catch { } # nothing to report $job['Proc'].Dispose() } } diff --git a/README.md b/README.md index 156fa59..b1604d0 100644 --- a/README.md +++ b/README.md @@ -683,6 +683,7 @@ Other pieces: `Request-PkAbort` triggers the same abort from code. `Test-PkAbort - If a program can't be started inside the Job Object (`Initialize-ParallelKit`'s `StartMode` isn't `CreatedInJob`, or the one-time warning says so), then on Windows PowerShell with a UTF-8 console its stdin isn't quite empty: .NET Framework puts a byte-order mark in it. - A program's output is collected in memory and handed over when it exits; there's no live line-by-line output. A program that prints gigabytes will use that much memory, unless `-MaxOutputChars` caps what's kept. A batch keeps every result, output included, until it returns, which adds up over thousands of chatty programs. If you only need the output in `-OnComplete`, drop it there with `$result.Stdout = $null; $result.Stderr = $null` and it's freed as the batch goes. - A program can't start a child outside the kit's Job Object. One that tries (`CREATE_BREAKAWAY_FROM_JOB`) gets "access denied" from Windows, which can look like a bug in the program. The kit doesn't allow it on purpose, since that child would escape the cleanup. +- A program whose path is longer than 260 characters can't be started, even with long paths enabled and in the `\\?\` form: Windows refuses it, and the start fails with "The filename or extension is too long" (or, for a plain path on PowerShell 7, "The system cannot find the file specified"). - Child-process cleanup has the gaps listed under [Process-tree cleanup limitations](#process-tree-cleanup-limitations). ## Testing diff --git a/Source/PkChildProcessJob.cs b/Source/PkChildProcessJob.cs index 42ae14a..17ea7f0 100644 --- a/Source/PkChildProcessJob.cs +++ b/Source/PkChildProcessJob.cs @@ -278,7 +278,10 @@ private static void AddTree(Process process, IntPtr treeJob) } // Kills every process in the program's tree job. False if it has none, - // or Windows refused: the caller then uses taskkill. + // or Windows refused: the caller then uses taskkill. The job stays open + // until ReleaseTree (Complete-PkProcess, or the kit's own kill paths) or + // garbage collection, so a second KillTree, as -KillTreeOnExit makes + // after a time-limit kill or a force-stop, ends an empty job and succeeds. public static bool KillTree(Process process) { if (process == null) { return false; } @@ -292,8 +295,6 @@ public static bool KillTree(Process process) } catch (ObjectDisposedException) { return false; } // released meanwhile: taskkill instead finally { if (added) { j.DangerousRelease(); } } - // The tree is gone: its job's handle can go now rather than with the Process. - if (ended) { ReleaseTree(process); } return ended; }