diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 3bff812..d8107ec 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -3810,7 +3810,7 @@ function Get-HarnessUnguardedCallbacks { # this list. Invoke-PkRun's `& $ScriptBlock` is the run itself, not called # from a loop. Returns @{ Calls; Problems }. param([string]$Source) - $internal = @('$pkNewBatchResult', '$pkGetStartFailureCause', '$pkGetJobTimeLimit', '$pkGetJobMaxOutputChars', '$pkGetJobSwitch', '$pkReportStartFailure', '$pkStartProcessCore', '$pkWriteCallbackLoopWarning') + $internal = @('$pkNewBatchResult', '$pkGetStartFailureCause', '$pkGetJobTimeLimit', '$pkGetJobMaxOutputChars', '$pkGetJobSwitch', '$pkStopExitedJobTree', '$pkReportStartFailure', '$pkStartProcessCore', '$pkWriteCallbackLoopWarning') $problems = [System.Collections.Generic.List[string]]::new() $tokens = $null; $errors = $null $ast = [System.Management.Automation.Language.Parser]::ParseInput($Source, [ref]$tokens, [ref]$errors) @@ -5445,6 +5445,134 @@ Reset-Harness Write-Host "" } +# ============================================================================== +if (Test-HarnessSection 'BJ' "-KillTreeOnExit: what a program left running goes when it exits") { +# Each program leaves a ping behind (-w 4328, so this section can find and +# kill its own) and exits with code 5 about a second in: by then it's in its +# tree job on both start paths. The ping holds the program's output, except +# where the test says it holds none. +Reset-Harness +function Get-HarnessLeftPingCount { return @(Get-CimInstance Win32_Process -Filter "Name='PING.EXE' AND CommandLine LIKE '%-w 4328 %'").Count } +function Stop-HarnessLeftPings { foreach ($p in @(Get-CimInstance Win32_Process -Filter "Name='PING.EXE' AND CommandLine LIKE '%-w 4328 %'")) { Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue } } +$bjHeld = '/d /c ping -n 2 127.0.0.1 >nul& echo before& start /b ping -n 30 -w 4328 127.0.0.1 >nul& exit 5' +# A start /b child holds the pipes whatever it's redirected to; one started +# through the shell doesn't get them. +$bjLoose = '-NoProfile -Command "Start-Process ping.exe -WindowStyle Hidden -ArgumentList ''-n 30 -w 4328 127.0.0.1''; Start-Sleep -Milliseconds 300; ''before''; exit 5"' +function Test-HarnessKillTree { + # Runs $Run, which returns a result with ExitCode, Stdout and StreamTimedOut + # (or $null), and checks it: the ping gone and the output read to its end at + # once, or ($Left) the ping left running. + param([string]$Name, [scriptblock]$Run, [switch]$Left, [switch]$Loose) + $problem = ''; $r = $null + $sw = [System.Diagnostics.Stopwatch]::StartNew() + try { $r = & $Run } catch { $problem = ', error: ' + $_ } + $sw.Stop() + Start-Sleep -Milliseconds 300 + $count = Get-HarnessLeftPingCount + Stop-HarnessLeftPings + $code = $null; $out = $null; $timedOut = $null + if ($null -ne $r) { $code = $r.ExitCode; $out = ([string]$r.Stdout).Trim(); $timedOut = $r.StreamTimedOut } + $secs = [math]::Round($sw.Elapsed.TotalSeconds, 1) + $seen = ' (pings left ' + $count + ', StreamTimedOut=' + $timedOut + ', exit ' + $code + ", output '" + $out + "', " + $secs + ' s' + $problem + ')' + if ($Left) { + Test-Assert ($count -eq 1 -and $code -eq 5 -and $out -eq 'before' -and $timedOut -eq (-not $Loose)) ($Name + ': what it left keeps running' + $seen) + } else { + Test-Assert ($count -eq 0 -and $code -eq 5 -and $out -eq 'before' -and $timedOut -eq $false -and $secs -lt 6) ($Name + ': what it left is killed, and its output ends at once' + $seen) + } +} +function Invoke-HarnessTreeBatch([hashtable]$Extra, [hashtable]$Key, [string]$Arguments) { + $command = @{ FilePath = $cmdExe; Arguments = $Arguments } + foreach ($k in $Key.Keys) { $command[$k] = $Key[$k] } + return (Invoke-PkProcessBatch -Commands @($command) @Extra).Results[0] +} +function Invoke-HarnessTreeDispatch([hashtable]$Extra, [hashtable]$Key, [string]$Arguments) { + $feed = @{ Given = $false }; $got = @{ Result = $null }; $job = @{ FilePath = $cmdExe; Arguments = $Arguments } + $Key + $null = Invoke-PkProcessDispatch -MaxConcurrent 1 @Extra ` + -GroupProvider { if ($feed.Given) { return $null }; $feed.Given = $true; return 'g' }.GetNewClosure() ` + -JobBuilder { param($g) return @($job) }.GetNewClosure() ` + -JobFinalize { param($j, $q) $got.Result = Complete-PkProcess $j }.GetNewClosure() + return $got.Result +} +try { + foreach ($bjPath in 'CreatedInJob', 'Process.Start') { + [PkChildProcessJob]::TestUseProcessStart = ($bjPath -eq 'Process.Start') + Test-HarnessKillTree ('Invoke-PkProcessWithTimeout, ' + $bjPath) { Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments $bjHeld -KillTreeOnExit } + Test-HarnessKillTree ('batch, ' + $bjPath) { Invoke-HarnessTreeBatch @{ KillTreeOnExit = $true } @{} $bjHeld } + Test-HarnessKillTree ('dispatcher, ' + $bjPath) { Invoke-HarnessTreeDispatch @{ KillTreeOnExit = $true } @{} $bjHeld } + } + [PkChildProcessJob]::TestUseProcessStart = $false + + # Not only when the output is held. + Test-HarnessKillTree 'a leftover that holds no output, one program' { Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments $bjLoose -KillTreeOnExit } + Test-HarnessKillTree 'a leftover that holds no output, batch' { Invoke-HarnessTreeBatch @{ KillTreeOnExit = $true } @{ FilePath = $selfExe } $bjLoose } + + # A command's own key, both ways, and off by default. + Test-HarnessKillTree 'batch key' { Invoke-HarnessTreeBatch @{} @{ KillTreeOnExit = $true } $bjHeld } + Test-HarnessKillTree 'dispatcher key' { Invoke-HarnessTreeDispatch @{} @{ KillTreeOnExit = $true } $bjHeld } + Test-HarnessKillTree 'batch, key $false' { Invoke-HarnessTreeBatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{ KillTreeOnExit = $false } $bjHeld } -Left + Test-HarnessKillTree 'dispatcher, key $false' { Invoke-HarnessTreeDispatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{ KillTreeOnExit = $false } $bjHeld } -Left + Test-HarnessKillTree 'batch, no switch' { Invoke-HarnessTreeBatch @{ StreamTimeoutMs = 500 } @{} $bjHeld } -Left + Test-HarnessKillTree 'one program, no switch' { Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments $bjLoose } -Left -Loose + $bjBad = $null + try { $bjBad = (Invoke-HarnessTreeBatch @{} @{ KillTreeOnExit = 'maybe' } '/d /c exit 0').StartError } catch { $bjBad = [string]$_ } + Test-Assert ([string]$bjBad -like '*KillTreeOnExit must be*maybe*') ("a bad KillTreeOnExit key is that command's StartError (" + $bjBad + ")") + $bjFeed = @{ Given = $false }; $bjStarted = @{ Count = 0 }; $bjDispatch = $null + $script:messages.Clear() + $bjDispatch = Invoke-PkProcessDispatch -MaxConcurrent 1 ` + -GroupProvider { if ($bjFeed.Given) { return $null }; $bjFeed.Given = $true; return 'g' }.GetNewClosure() ` + -JobBuilder { param($g) return @(@{ FilePath = $cmdExe; Arguments = '/d /c exit 0'; KillTreeOnExit = 'maybe' }) }.GetNewClosure() ` + -JobStarter { param($job) $bjStarted.Count++; $s = Start-PkProcess -FilePath $job['FilePath'] -Arguments $job['Arguments']; $job['Proc'] = $s.Proc; return $job }.GetNewClosure() ` + -JobFinalize { param($j, $q) } + Test-Assert ($bjDispatch.JobStarterFailedCount -eq 1 -and $bjStarted.Count -eq 0 -and @($script:messages | Where-Object { $_.Message -like "*a job couldn't start: KillTreeOnExit must be*" }).Count -eq 1) ("a bad key on a dispatcher job is refused before its starter runs (failed " + $bjDispatch.JobStarterFailedCount + ", starter calls " + $bjStarted.Count + ")") + + # A custom starter's program, and a custom poll: the kill is + # Complete-PkProcess's then. + $bjStarter = { param($job) $s = Start-PkProcess -FilePath $job['FilePath'] -Arguments $job['Arguments']; foreach ($k in 'Proc', 'StdoutTask', 'StderrTask', 'Stopwatch') { $job[$k] = $s[$k] }; return $job } + Test-HarnessKillTree 'a custom starter' { Invoke-HarnessTreeDispatch @{ KillTreeOnExit = $true; JobStarter = $bjStarter } @{} $bjHeld } + Test-HarnessKillTree 'a custom poll' { Invoke-HarnessTreeDispatch @{ KillTreeOnExit = $true; JobPollCompleted = { param($j) return $j['Proc'].HasExited } } @{} $bjHeld } + + # A program without a tree job is left alone, with no warning. + Reset-Harness + [PkChildProcessJob]::TestNoTreeJob = $true + try { Test-HarnessKillTree 'no tree job' { Invoke-HarnessTreeBatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{} $bjHeld } -Left } finally { [PkChildProcessJob]::TestNoTreeJob = $false } + Test-Assert ($script:messages.Count -eq 0) ("and nothing is said about it (" + $script:messages.Count + " message(s))") + + # 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 + $bjLeftAt = @{ Count = -1 } + try { + $null = Invoke-HarnessTreeDispatch @{ KillTreeOnExit = $true; AbortTimeoutSeconds = 1; JobPollCompleted = { + param($j) + if ($j['Proc'].HasExited -and $bjLeftAt.Count -lt 0) { $bjLeftAt.Count = Get-HarnessLeftPingCount; Request-PkAbort } + return $false + }.GetNewClosure() } @{} $bjHeld + } catch { Write-Host (" " + $_) } + Reset-PkAbortState + Start-Sleep -Milliseconds 300 + $bjNow = Get-HarnessLeftPingCount + Test-Assert ($bjLeftAt.Count -eq 1 -and $bjNow -eq 0) ("a force-stop takes what an exited program left too (pings left before " + $bjLeftAt.Count + ", after " + $bjNow + ")") + Stop-HarnessLeftPings + + # Inside a worker. + Reset-Harness + $bjWorker = [System.Collections.Generic.List[object]]::new() + $bjOut = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @{ Cmd = $cmdExe; Line = $bjHeld } -ResultHandler { param($r) $bjWorker.Add($r) }.GetNewClosure() -WorkerScript { + param([string]$Cmd, [string]$Line) + $one = Invoke-PkProcessWithTimeout -FilePath $Cmd -Arguments $Line -KillTreeOnExit + $batch = (Invoke-PkProcessBatch -Commands @(@{ FilePath = $Cmd; Arguments = $Line }) -KillTreeOnExit).Results[0] + return ([string]$one.StreamTimedOut + ' ' + $batch.StreamTimedOut) + } + $bjNow = Get-HarnessLeftPingCount + Test-Assert ($bjOut.CrashedCount -eq 0 -and $bjWorker.Count -eq 1 -and $bjWorker[0] -eq 'False False' -and $bjNow -eq 0) ("it works inside a worker (crashed " + $bjOut.CrashedCount + ", StreamTimedOut " + ($bjWorker -join ',') + ", pings left " + $bjNow + ")") +} finally { + [PkChildProcessJob]::TestUseProcessStart = $false + Stop-HarnessLeftPings + Reset-Harness +} +Write-Host "" +} + Set-PkMessageHandler -Handler $null Reset-PkAbortState diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 815d7aa..9202965 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -1941,10 +1941,12 @@ function Split-PkTaskkillArguments { function Stop-PkJobProcesses { # The dispatcher's force-stop: every running job's tree in one # Stop-PkProcessTree call. A custom starter's .Proc may not be a Process; - # those are skipped. + # those are skipped. Stop-PkProcessTree passes over a program that has + # exited; with -KillTreeOnExit, what that left running goes as well. param([System.Collections.Generic.List[hashtable]]$Jobs) $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 } function Get-PkJobTimeLimit { @@ -1978,8 +1980,8 @@ function Get-PkJobMaxOutputChars { } function Get-PkJobSwitch { - # A job's own $true/$false key (InheritStdin), else the default: the - # engine's switch of the same name. Throws on anything else, as + # A job's own $true/$false key (InheritStdin, KillTreeOnExit), else the + # default: the engine's switch of the same name. Throws on anything else, as # Get-PkJobTimeLimit does for TimeoutSeconds. Text is taken ('True', as a # CSV gives it), but not a number. param([hashtable]$Job, [string]$Key, [bool]$Default = $false) @@ -2010,6 +2012,18 @@ function Stop-PkTimedOutJob { } } +function Stop-PkExitedJobTree { + # -KillTreeOnExit: once a job's program has exited, kills what it left + # running, through its tree job. Does nothing while it runs, or without a + # tree job (a .Proc that isn't a Process, or a program Windows wouldn't + # give one). One try only: the dispatcher's poll runs this every pass. + param([hashtable]$Job) + $proc = $Job['Proc'] + if ($proc -isnot [System.Diagnostics.Process] -or $proc.HasExited -ne $true) { return } + $Job['KillTree'] = $false + $null = [PkChildProcessJob]::KillTree($proc) +} + function Wait-PkProcess { # .SYNOPSIS # Waits for a program to exit, with a timeout that can't overrun. @@ -2149,6 +2163,10 @@ function Complete-PkProcess { # A custom starter's job may have no read tasks, and a read can fail. # Neither throws: this runs inside JobFinalize, where a throw stops the # whole dispatcher. + # KillTree: -KillTreeOnExit, set by Invoke-PkProcessWithTimeout and the + # dispatcher. The dispatcher's default poll has done this already. Before + # the output wait, since it's what the leftovers hold up. + if ($Job['KillTree']) { Stop-PkExitedJobTree -Job $Job } $tasks = [System.Collections.Generic.List[System.Threading.Tasks.Task]]::new() if ($null -ne $Job['StdoutTask']) { $tasks.Add($Job['StdoutTask']) } if ($null -ne $Job['StderrTask']) { $tasks.Add($Job['StderrTask']) } @@ -2233,6 +2251,10 @@ function Invoke-PkProcessWithTimeout { # .PARAMETER InheritStdin # Give the program PowerShell's own stdin, as for Start-PkProcess. Without # it, the program's input is empty. + # .PARAMETER KillTreeOnExit + # When the program exits, kill whatever it started that's still running, so + # nothing it left behind holds its output open. Only for a program Windows + # gave a Job Object of its own, the normal case. # .PARAMETER IgnoreAbort # Keep going during an abort, for a cleanup or restore step that has to run # because of it. @@ -2252,6 +2274,7 @@ function Invoke-PkProcessWithTimeout { $OutputEncoding = $null, [int]$MaxOutputChars = 0, [switch]$InheritStdin, + [switch]$KillTreeOnExit, [switch]$IgnoreAbort ) # Checked before starting anything: 0 or less would kill the program at once. @@ -2262,6 +2285,7 @@ function Invoke-PkProcessWithTimeout { # same check: keep the four in step. if ($MaxOutputChars -lt 0) { throw ("Invoke-PkProcessWithTimeout: -MaxOutputChars must be 0 (no cap) or more (got " + $MaxOutputChars + "). It's how many characters of each output stream to keep.") } $job = Start-PkProcessCore -FilePath $FilePath -Arguments $Arguments -WorkingDirectory $WorkingDirectory -OutputEncoding $OutputEncoding -MaxOutputChars $MaxOutputChars -InheritStdin:$InheritStdin -CallerState $PSCmdlet.SessionState + $job['KillTree'] = $KillTreeOnExit.IsPresent try { # Short slices, so an abort or cancel is noticed within a moment. $waited = [System.Diagnostics.Stopwatch]::StartNew() @@ -2287,6 +2311,8 @@ function Invoke-PkProcessWithTimeout { # (that skips catch blocks, not finally ones): kill it before the # process object goes. Best effort, as above. 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 { } $job['Proc'].Dispose() } } @@ -2308,14 +2334,14 @@ function Invoke-PkProcessDispatch { # # The dispatcher keeps its own state on each job hashtable. Don't use these keys # for anything else: GroupKey, SlotReleased, Proc, StdoutTask, StderrTask, - # Stopwatch, TimeLimit, TimedOut, StartFailureReported, OutputWait, + # Stopwatch, TimeLimit, TimedOut, KillTree, StartFailureReported, OutputWait, # OutputWaitOver, OutputWaitMs. It also sets Group to # the job's group, unless the job already has a Group of its own. The default # starter reads FilePath, Arguments (a string as written, or a list quoted one # argument per element), WorkingDirectory, OutputEncoding, MaxOutputChars and # InheritStdin from the job. A job's TimeoutSeconds key overrides - # -TimeoutSeconds, its MaxOutputChars key -MaxOutputChars, and its InheritStdin - # key -InheritStdin. + # -TimeoutSeconds, and its MaxOutputChars, InheritStdin and KillTreeOnExit keys + # the parameters of the same names. # .PARAMETER GroupProvider # { } returning the next group, or $null when there are no more, and # outputting nothing else. Return a list as one group with a comma: @@ -2378,6 +2404,12 @@ function Invoke-PkProcessDispatch { # For the default starter: give each job's program PowerShell's own stdin, # as for Start-PkProcess. Without it, its input is empty. A job's own # InheritStdin key overrides it either way. + # .PARAMETER KillTreeOnExit + # When a job's program exits, kill whatever it started that's still running, + # so nothing it left behind holds its output open. Only for a program Windows + # gave a Job Object of its own, the normal case. A job's own KillTreeOnExit + # key overrides it either way. The default -JobPollCompleted does it; with + # your own, Complete-PkProcess does, so it needs -JobFinalize to call that. # .OUTPUTS # An object with GroupResults, Aborted, ForceKilledCount and # JobStarterFailedCount. Each group result has GroupInfo (the group), Completed @@ -2408,7 +2440,8 @@ function Invoke-PkProcessDispatch { # default to the same 15000: keep the three in step. [int]$StreamTimeoutMs = 15000, [int]$MaxOutputChars = 0, - [switch]$InheritStdin + [switch]$InheritStdin, + [switch]$KillTreeOnExit ) # pk-prefixed, parameters included: inside a worker runspace the kit isn't # a module, so a callback without .GetNewClosure() sees this frame's @@ -2430,7 +2463,8 @@ function Invoke-PkProcessDispatch { $pkStreamTimeoutMs = $StreamTimeoutMs $pkMaxOutputChars = $MaxOutputChars $pkInheritStdin = $InheritStdin.IsPresent - Remove-Variable -Name GroupProvider, JobBuilder, JobStarter, JobPollCompleted, JobFinalize, JobAbortCleanup, GroupCompleteCallback, MaxConcurrent, PollCallback, CancelToken, AbortTimeoutSeconds, MaxQueueAhead, GroupReleaseCheck, TimeoutSeconds, StreamTimeoutMs, MaxOutputChars, InheritStdin -Scope Local + $pkKillTreeOnExit = $KillTreeOnExit.IsPresent + Remove-Variable -Name GroupProvider, JobBuilder, JobStarter, JobPollCompleted, JobFinalize, JobAbortCleanup, GroupCompleteCallback, MaxConcurrent, PollCallback, CancelToken, AbortTimeoutSeconds, MaxQueueAhead, GroupReleaseCheck, TimeoutSeconds, StreamTimeoutMs, MaxOutputChars, InheritStdin, KillTreeOnExit -Scope Local # 0 or less would never start a job (or pull a group) and spin forever. if ($pkMaxConcurrent -isnot [System.Threading.SemaphoreSlim]) { @@ -2475,6 +2509,8 @@ function Invoke-PkProcessDispatch { # The default poll reads $pkJob['Proc'], so a started job must have one. $pkRequireProc = ($null -eq $pkJobPollCompleted) if ($null -eq $pkJobPollCompleted) { + # The closure below can't see the module's private functions. + $pkStopExitedJobTree = ${function:Stop-PkExitedJobTree} # Done once the program has exited and its output has been read, so # Complete-PkProcess in -JobFinalize has nothing to wait for: waiting # there would stall the whole loop. A job whose output a leftover @@ -2483,12 +2519,15 @@ function Invoke-PkProcessDispatch { # job as OutputWaitMs, so a Complete-PkProcess given no -StreamTimeoutMs # of its own waits only what's left of it (nothing). After an abort's # wait the final pass sets OutputWaitOver: it takes what has arrived. + # KillTree (-KillTreeOnExit) kills what the program left running first, + # so nothing is left to hold the output. # A closure, so it carries this call's $pkStreamTimeoutMs itself # rather than finding it by dynamic scope (measured: no slower per # job than the plain block on 5.1 or 7). $pkJobPollCompleted = { param($pkJob) if (-not $pkJob['Proc'].HasExited) { return $false } + if ($pkJob['KillTree']) { & $pkStopExitedJobTree -Job $pkJob } $pkOut = $pkJob['StdoutTask']; $pkErr = $pkJob['StderrTask'] if (($pkOut -isnot [System.Threading.Tasks.Task] -or $pkOut.IsCompleted) -and ($pkErr -isnot [System.Threading.Tasks.Task] -or $pkErr.IsCompleted)) { return $true } if ($pkJob['OutputWaitOver']) { return $true } @@ -2527,7 +2566,8 @@ function Invoke-PkProcessDispatch { -JobPollCompleted $pkJobPollCompleted -JobFinalize $pkJobFinalize -JobAbortCleanup $pkJobAbortCleanup ` -GroupCompleteCallback $pkGroupCompleteCallback -MaxConcurrent $pkMaxConcurrent -PollCallback $pkPollCallback ` -CancelToken $pkCancelToken -AbortTimeoutSeconds $pkAbortTimeoutSeconds -MaxQueueAhead $pkMaxQueueAhead ` - -GroupReleaseCheck $pkGroupReleaseCheck -RequireProc $pkRequireProc -TimeoutSeconds $pkTimeoutSeconds + -GroupReleaseCheck $pkGroupReleaseCheck -RequireProc $pkRequireProc -TimeoutSeconds $pkTimeoutSeconds ` + -KillTreeOnExit $pkKillTreeOnExit } finally { if ($null -ne $pkOwnCts) { Unregister-PkCancellationSource -Cts $pkOwnCts @@ -2594,7 +2634,8 @@ function Invoke-PkProcessDispatchCore { [int]$MaxQueueAhead, [scriptblock]$GroupReleaseCheck, [bool]$RequireProc = $false, - [double]$TimeoutSeconds = 0 + [double]$TimeoutSeconds = 0, + [bool]$KillTreeOnExit = $false ) # pk-prefixed, parameters included: inside a worker runspace the kit isn't # a module, so a callback without .GetNewClosure() sees this frame's @@ -2614,7 +2655,8 @@ function Invoke-PkProcessDispatchCore { $pkGroupReleaseCheck = $GroupReleaseCheck $pkRequireProc = $RequireProc $pkTimeoutSeconds = $TimeoutSeconds - Remove-Variable -Name GroupProvider, JobBuilder, JobStarter, JobPollCompleted, JobFinalize, JobAbortCleanup, GroupCompleteCallback, MaxConcurrent, PollCallback, CancelToken, AbortTimeoutSeconds, MaxQueueAhead, GroupReleaseCheck, RequireProc, TimeoutSeconds -Scope Local + $pkKillTreeOnExit = $KillTreeOnExit + Remove-Variable -Name GroupProvider, JobBuilder, JobStarter, JobPollCompleted, JobFinalize, JobAbortCleanup, GroupCompleteCallback, MaxConcurrent, PollCallback, CancelToken, AbortTimeoutSeconds, MaxQueueAhead, GroupReleaseCheck, RequireProc, TimeoutSeconds, KillTreeOnExit -Scope Local $pkIsSharedBudget = ($pkMaxConcurrent -is [System.Threading.SemaphoreSlim]) @@ -2720,6 +2762,9 @@ function Invoke-PkProcessDispatchCore { # Before starting, so a bad key never leaves a program running. $pkStartFailureText = "ProcessDispatch: a job couldn't start: " $pkJob['TimeLimit'] = Get-PkJobTimeLimit -Job $pkJob -DefaultTimeoutSeconds $pkTimeoutSeconds + # The null test saves the call, which runs per job. + $pkJob['KillTree'] = $pkKillTreeOnExit + if ($null -ne $pkJob['KillTreeOnExit']) { $pkJob['KillTree'] = Get-PkJobSwitch -Job $pkJob -Key 'KillTreeOnExit' } $pkStartFailureText = "ProcessDispatch: JobStarter failed to start a job: " $pkCbDone = $false $pkStartedRaw = do { & $pkJobStarter $pkJob; $pkCbDone = $true } while ($false) @@ -3067,9 +3112,9 @@ function Invoke-PkProcessBatch { # .DESCRIPTION # Each command is a hashtable: @{ FilePath = ...; Arguments = ... } plus, # optionally, WorkingDirectory, OutputEncoding (overrides -OutputEncoding), - # TimeoutSeconds (overrides -TimeoutSeconds), MaxOutputChars, InheritStdin - # (which override the parameters of the same names) and any keys of your - # own, which come back on the result's Command. Inside Invoke-PkRun, Ctrl+C + # TimeoutSeconds, MaxOutputChars, InheritStdin and KillTreeOnExit (which + # override the parameters of the same names) and any keys of your own, which + # come back on the result's Command. Inside Invoke-PkRun, Ctrl+C # lets running programs finish (up to -AbortTimeoutSeconds) and starts no new # ones; a second Ctrl+C kills them right away. Every command is tried, and one # that can't start gets a StartError on its result. Repeats of the same failure @@ -3102,6 +3147,11 @@ function Invoke-PkProcessBatch { # Give each program PowerShell's own stdin, as for Start-PkProcess. Without # it, its input is empty. A command's own InheritStdin key overrides it # either way. + # .PARAMETER KillTreeOnExit + # When a program exits, kill whatever it started that's still running, so + # nothing it left behind holds its output open. Only for a program Windows + # gave a Job Object of its own, the normal case. A command's own + # KillTreeOnExit key overrides it either way. # .OUTPUTS # An object with Results, Aborted and ForceKilledCount. Each result has Command, # ExitCode, Stdout, Stderr, StreamTimedOut, StreamError, StartError, Aborted, @@ -3127,7 +3177,8 @@ function Invoke-PkProcessBatch { # default to the same 15000: keep the three in step. [int]$StreamTimeoutMs = 15000, [int]$MaxOutputChars = 0, - [switch]$InheritStdin + [switch]$InheritStdin, + [switch]$KillTreeOnExit ) # pk-prefixed, parameters included: inside a worker runspace the kit isn't # a module, so a callback without .GetNewClosure() sees this frame's @@ -3141,7 +3192,8 @@ function Invoke-PkProcessBatch { $pkStreamTimeoutMs = $StreamTimeoutMs $pkMaxOutputChars = $MaxOutputChars $pkInheritStdin = $InheritStdin.IsPresent - Remove-Variable -Name Commands, MaxConcurrent, OnComplete, AbortTimeoutSeconds, TimeoutSeconds, OutputEncoding, StreamTimeoutMs, MaxOutputChars, InheritStdin -Scope Local + $pkKillTreeOnExit = $KillTreeOnExit.IsPresent + Remove-Variable -Name Commands, MaxConcurrent, OnComplete, AbortTimeoutSeconds, TimeoutSeconds, OutputEncoding, StreamTimeoutMs, MaxOutputChars, InheritStdin, KillTreeOnExit -Scope Local # Checked once here, so a bad name fails the call instead of every command. $null = Resolve-PkEncoding -Encoding $pkOutputEncoding @@ -3214,11 +3266,12 @@ function Invoke-PkProcessBatch { $null = & $pkGetJobTimeLimit -Job $pkC $pkCap = & $pkGetJobMaxOutputChars -Job $pkC -DefaultMaxOutputChars $pkMaxOutputChars $pkStdin = & $pkGetJobSwitch -Job $pkC -Key 'InheritStdin' -Default $pkInheritStdin + $pkKillTree = & $pkGetJobSwitch -Job $pkC -Key 'KillTreeOnExit' -Default $pkKillTreeOnExit } catch { & $pkReportStartFailure $pkC $_ continue } - $pkJobs.Add(@{ FilePath = $pkC['FilePath']; Arguments = $pkC['Arguments']; WorkingDirectory = [string]$pkC['WorkingDirectory']; OutputEncoding = $pkEncoding; TimeoutSeconds = $pkC['TimeoutSeconds']; MaxOutputChars = $pkCap; InheritStdin = $pkStdin; Command = $pkC }) + $pkJobs.Add(@{ FilePath = $pkC['FilePath']; Arguments = $pkC['Arguments']; WorkingDirectory = [string]$pkC['WorkingDirectory']; OutputEncoding = $pkEncoding; TimeoutSeconds = $pkC['TimeoutSeconds']; MaxOutputChars = $pkCap; InheritStdin = $pkStdin; KillTreeOnExit = $pkKillTree; Command = $pkC }) } return $pkJobs }.GetNewClosure() @@ -3287,7 +3340,7 @@ function Get-PkWorkerSafeFunctionNames { 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', 'Get-PkJobSwitch', 'ConvertTo-PkArgumentString', 'Get-PkForceStopReason', 'Resolve-PkFileSystemPath', 'Add-PkDispatchGroupJobs', 'Start-PkProcessCore', 'Get-PkJobTimeLimit', 'Stop-PkTimedOutJob', 'Get-PkStartFailureCause', 'Resolve-PkArguments', 'Invoke-PkCallback', 'Write-PkCallbackLoopWarning', 'ConvertTo-PkArgumentStringCore') + 'Register-PkCancellationSource', 'Unregister-PkCancellationSource', 'New-PkBatchResult', 'Get-PkJobMaxOutputChars', 'Get-PkJobSwitch', 'Stop-PkExitedJobTree', 'ConvertTo-PkArgumentString', 'Get-PkForceStopReason', 'Resolve-PkFileSystemPath', 'Add-PkDispatchGroupJobs', 'Start-PkProcessCore', 'Get-PkJobTimeLimit', 'Stop-PkTimedOutJob', 'Get-PkStartFailureCause', 'Resolve-PkArguments', 'Invoke-PkCallback', 'Write-PkCallbackLoopWarning', 'ConvertTo-PkArgumentStringCore') } function Get-PkHandlerParamCount { diff --git a/README.md b/README.md index a4f82c2..0abe499 100644 --- a/README.md +++ b/README.md @@ -255,6 +255,8 @@ 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 it does nothing, with no warning, for a program without one (`StartMode` `NoJob`, or Windows refused it). In `AddedToJob` mode it can miss a child the program started straight away. +
@@ -328,6 +330,8 @@ During an abort's wait, running programs carry on as normal and end up with norm `StreamTimedOut` means the output read gave up 15 seconds after the program exited (`-StreamTimeoutMs` changes that, in milliseconds; 0 doesn't wait), on stdout, stderr or both, which only happens when a program it started is still holding the output open. Each stream comes back with what arrived before then: one held open is cut short, the other is whole. +`-KillTreeOnExit` avoids the wait: what the program left running is killed when it exits, so nothing is left to hold its output open. + The read of a held stream carries on in the background until that program lets go of it; it's in the kit's Job Object, so that's when PowerShell exits at the latest. Until then that read keeps a thread of its own, one per held stream, so other programs' output isn't held up behind it, and drops what it reads, so a program that keeps writing doesn't fill memory with output nobody can get. What came back is that stream's text from then on, so calling `Complete-PkProcess` again on the same job returns the same text, and so does the read task's `Result` once the stream ends. `StreamError` means a read failed, and that stream comes back `$null`; it can be set alongside `StreamTimedOut` when the other stream was held open. @@ -523,8 +527,8 @@ All of these callbacks run on whichever thread called the dispatcher: the main t - **With your own `-JobPollCompleted`**, none of this applies: `Complete-PkProcess` waits as it does anywhere else. - To retry a job or add follow-up work, enqueue job hashtables onto `$pending` inside `-JobFinalize`. They join the same group, and the group isn't complete until they've all finished. A retry can start within milliseconds of the failure, so cap the number of retries, and don't count on the gap for something like a locked file to clear. - `-JobAbortCleanup { param($job) }` is called for each job an abort killed or kept from starting, to remove its partial output. -- `-TimeoutSeconds 600` kills a job's program, and anything it started, if it's still running after 10 minutes. The default, 0, means no limit, and it can be fractional. A job's own `TimeoutSeconds` key overrides it; 0 opts the job out, and a bad value is a failed start. `-MaxOutputChars` and `-InheritStdin` work the same way, with a job's `MaxOutputChars` and `InheritStdin` keys, for the default starter. The killed job still goes through `-JobFinalize`, where `$job['TimedOut']` is `$true`, and other jobs carry on. The limit stays in force while an abort waits for running jobs. A retry gets a fresh clock. A job whose `.Proc` isn't a process isn't timed: `-JobPollCompleted` is the place for its limit. -- The dispatcher keeps its state on the job hashtables. Don't use these names for your own job fields: `GroupKey`, `SlotReleased`, `Proc`, `StdoutTask`, `StderrTask`, `Stopwatch`, `TimeLimit`, `TimedOut`, `StartFailureReported`, `OutputWait`, `OutputWaitOver`, `OutputWaitMs`. (`Group` is yours if you set it yourself.) +- `-TimeoutSeconds 600` kills a job's program, and anything it started, if it's still running after 10 minutes. The default, 0, means no limit, and it can be fractional. A job's own `TimeoutSeconds` key overrides it; 0 opts the job out, and a bad value is a failed start. `-MaxOutputChars` and `-InheritStdin` work the same way, with a job's `MaxOutputChars` and `InheritStdin` keys, for the default starter. `-KillTreeOnExit` and a job's `KillTreeOnExit` key work with any starter that sets `.Proc` to a program `Start-PkProcess` started. The default `-JobPollCompleted` does the kill; with your own, `Complete-PkProcess` does, so only if `-JobFinalize` calls it. A job killed for its time limit still goes through `-JobFinalize`, where `$job['TimedOut']` is `$true`, and other jobs carry on. The limit stays in force while an abort waits for running jobs. A retry gets a fresh clock. A job whose `.Proc` isn't a process isn't timed: `-JobPollCompleted` is the place for its limit. +- The dispatcher keeps its state on the job hashtables. Don't use these names for your own job fields: `GroupKey`, `SlotReleased`, `Proc`, `StdoutTask`, `StderrTask`, `Stopwatch`, `TimeLimit`, `TimedOut`, `KillTree`, `StartFailureReported`, `OutputWait`, `OutputWaitOver`, `OutputWaitMs`. (`Group` is yours if you set it yourself.)