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
49 changes: 49 additions & 0 deletions ParallelKit.Harness.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -5277,6 +5277,35 @@ Test-Assert ($bcOut.Errors.Count -eq 0) ("a mandatory CancelToken and Mandatory
$bcOut = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams @(@{ A = 1 }) -WorkerScript { param([Parameter(Mandatory, ParameterSetName = 'A')]$A, [Parameter(Mandatory, ParameterSetName = 'B')]$B) $A }
Test-Assert ($bcOut.Errors.Count -eq 0) ("a worker with parameter sets isn't refused for the other set's mandatory parameter (" + $bcOut.Errors.Count + " errors)")

# A function's own scriptblock (${function:Name}) works as -WorkerScript, in
# both forms, function f { param(...) } and function f(...): its parameters
# are read, CancelToken is filled in, a missing mandatory one is refused up
# front, and the function's own top level may use $script:, as a { } block's
# may.
function Get-HarnessFnWorker { param([int]$Id, $CancelToken) return ([string]$Id + ':' + ($CancelToken -is [System.Threading.CancellationToken])) }
function Get-HarnessFnWorkerInline([int]$Id, [Parameter(Mandatory)][string]$Name) { return ([string]$Id + $Name) }
$bcFnResults = [System.Collections.Generic.List[object]]::new()
$bcError = $null
try { $null = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams @(@{ Id = 1 }, @{ Id = 2 }) -WorkerScript ${function:Get-HarnessFnWorker} -ResultHandler { param($r) $bcFnResults.Add($r) }.GetNewClosure() } catch { $bcError = [string]$_ }
$bcFnText = (@($bcFnResults | Sort-Object) -join ',')
Test-Assert ($null -eq $bcError -and $bcFnText -eq '1:True,2:True') ("-WorkerScript `${function:Name} with a param() block: its jobs bind and CancelToken is filled in (" + $bcFnText + ", error: " + $bcError + ")")
$bcFnResults = [System.Collections.Generic.List[object]]::new()
$bcError = $null
try { $null = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams @(@{ Id = 1; Name = 'a' }, @{ Id = 2; Name = 'b' }) -WorkerScript ${function:Get-HarnessFnWorkerInline} -ResultHandler { param($r) $bcFnResults.Add($r) }.GetNewClosure() } catch { $bcError = [string]$_ }
$bcFnText = (@($bcFnResults | Sort-Object) -join ',')
Test-Assert ($null -eq $bcError -and $bcFnText -eq '1a,2b') ("and declared as function f(...) (" + $bcFnText + ", error: " + $bcError + ")")
$bcError = $null
try { $null = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams @(@{ Id = 1; Name = 'a' }, @{ Id = 2 }) -WorkerScript ${function:Get-HarnessFnWorkerInline} } catch { $bcError = [string]$_ }
Test-Assert ($bcError -match "job 1 doesn't supply 'Name'") ("and its missing mandatory parameter is refused before anything starts (" + $bcError + ")")
function Get-HarnessFnScriptVar { param($Id) $script:bcFnCount = $Id; & { $script:bcFnNested } }
function Get-HarnessFnScriptVarInline($Id) { $script:bcFnCount = $Id }
$bcFindings = Test-PkWorkerSafety -WorkerScript ${function:Get-HarnessFnScriptVar}
$bcFindings = @($bcFindings | Where-Object { $_.Rule -eq 'ScriptVariable' })
Test-Assert ($bcFindings.Count -eq 1 -and $bcFindings[0].Text -like '*bcFnNested*') ("`${function:Name}: `$script: at the function's top level isn't flagged, in a nested block it is (" + (@($bcFindings | ForEach-Object { $_.Text }) -join ' | ') + ")")
$bcFindings = Test-PkWorkerSafety -WorkerScript ${function:Get-HarnessFnScriptVarInline}
$bcFindings = @($bcFindings | Where-Object { $_.Rule -eq 'ScriptVariable' })
Test-Assert ($bcFindings.Count -eq 0) ("and the same for function f(...) (" + (@($bcFindings | ForEach-Object { $_.Text }) -join ' | ') + ")")

# A code page read from a CSV or config file is a string.
$bcResolve = { param($e) & (Get-Module ParallelKit) { param($x) try { (Resolve-PkEncoding -Encoding $x).CodePage } catch { 'refused' } } $e }
$bcCodePages = @((& $bcResolve '65001'), (& $bcResolve ' 437 '), (& $bcResolve 65001), (& $bcResolve ([long]65001)))
Expand Down Expand Up @@ -5969,6 +5998,26 @@ try {
try { Test-HarnessKillTree 'no tree job, a second time' { Invoke-HarnessTreeBatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{} $bjHeld } -Left } finally { [PkChildProcessJob]::TestNoTreeJob = $false }
Test-Assert (@($script:messages | Where-Object { $_.Message -like '*-KillTreeOnExit*' }).Count -eq 1) ("and only once per process (" + @($script:messages | Where-Object { $_.Message -like '*-KillTreeOnExit*' }).Count + " warning(s) after a second program)")

# A tree job Windows won't end (TerminateJobObject fails) leaves what the
# program started running too: one warning naming the process, once per
# process, in each engine.
$bjFailTerminate = @(
@{ Name = 'tree job not ended, batch'; Run = { Invoke-HarnessTreeBatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{} $bjHeld } }
@{ Name = 'tree job not ended, dispatcher'; Run = { Invoke-HarnessTreeDispatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{} $bjHeld } }
@{ Name = 'tree job not ended, one program'; Run = { Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments $bjHeld -KillTreeOnExit -StreamTimeoutMs 500 } }
)
foreach ($bjCase in $bjFailTerminate) {
Reset-Harness
[PkChildProcessJob]::TestResetJobWarnings()
[PkChildProcessJob]::TestFailTerminate = $true
try { Test-HarnessKillTree $bjCase.Name $bjCase.Run -Left } finally { [PkChildProcessJob]::TestFailTerminate = $false }
$bjWarned = @($script:messages | Where-Object { $_.Level -eq 'Warn' -and $_.Message -like '*-KillTreeOnExit*process *may still be running*' })
Test-Assert ($script:messages.Count -eq 1 -and $bjWarned.Count -eq 1) ("and says so in one warning naming the process (" + $script:messages.Count + " message(s): " + (@($script:messages | ForEach-Object { $_.Message }) -join ' | ') + ")")
}
[PkChildProcessJob]::TestFailTerminate = $true
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 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
Expand Down
48 changes: 36 additions & 12 deletions ParallelKit.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -507,9 +507,11 @@ public static class PkChildProcessJob

// Harness only: start programs without a tree job, to test the taskkill
// path; or have TryStart's first CreateProcess, with the tree job, count
// as refused, to test its retry without one.
// as refused, to test its retry without one. TestFailTerminate makes
// KillTree's TerminateJobObject count as refused, leaving the tree running.
public static bool TestNoTreeJob = false;
public static bool TestRefuseTreeJob = false;
public static bool TestFailTerminate = false;

private static void AddTree(Process process, IntPtr treeJob)
{
Expand All @@ -528,7 +530,7 @@ public static class PkChildProcessJob
try
{
j.DangerousAddRef(ref added);
ended = TerminateJobObject(j.DangerousGetHandle(), 1);
ended = !TestFailTerminate && TerminateJobObject(j.DangerousGetHandle(), 1);
}
catch (ObjectDisposedException) { return false; } // released meanwhile: taskkill instead
finally { if (added) { j.DangerousRelease(); } }
Expand Down Expand Up @@ -863,12 +865,14 @@ public static class PkChildProcessJob
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, for a running program Windows wouldn't add to it, and for
// -KillTreeOnExit on a program without a tree job.
private static int _initWarned = 0, _assignWarned = 0, _noTreeWarned = 0;
// -KillTreeOnExit on a program without a tree job, or whose tree job
// Windows wouldn't end.
private static int _initWarned = 0, _assignWarned = 0, _noTreeWarned = 0, _killTreeWarned = 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 bool ClaimNoTreeWarning() { return Interlocked.Exchange(ref _noTreeWarned, 1) == 0; }
public static void TestResetJobWarnings() { Interlocked.Exchange(ref _initWarned, 0); Interlocked.Exchange(ref _assignWarned, 0); Interlocked.Exchange(ref _noTreeWarned, 0); }
public static bool ClaimKillTreeWarning() { return Interlocked.Exchange(ref _killTreeWarned, 1) == 0; }
public static void TestResetJobWarnings() { Interlocked.Exchange(ref _initWarned, 0); Interlocked.Exchange(ref _assignWarned, 0); Interlocked.Exchange(ref _noTreeWarned, 0); Interlocked.Exchange(ref _killTreeWarned, 0); }

private static StringBuilder BuildCommandLine(string fileName, string arguments)
{
Expand Down Expand Up @@ -2059,8 +2063,9 @@ function Stop-PkExitedJobTree {
# running, through its tree job. Does nothing while it runs, or for a .Proc
# that isn't a Process. A program without a tree job (Windows wouldn't
# give it one, the kit has no Job Object, or a custom starter started it)
# can't be reached: that warns, once per process. One try only: the
# dispatcher's poll runs this every pass.
# can't be reached: that warns, once per process, and so does a tree job
# Windows won't end. 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 }
Expand All @@ -2071,7 +2076,11 @@ function Stop-PkExitedJobTree {
}
return
}
$null = [PkChildProcessJob]::KillTree($proc)
# Windows refusing to end the tree job has no fallback: with the program
# gone, taskkill /T can't find its children.
if (-not [PkChildProcessJob]::KillTree($proc) -and [PkChildProcessJob]::ClaimKillTreeWarning()) {
Write-PkMessage ("[WARNING] -KillTreeOnExit couldn't stop what process " + $proc.Id + " left running: Windows wouldn't end the program's own Job Object, so anything it started may still be running. It still ends when PowerShell does. Shown once.") -Level Warn
}
}

function Wait-PkProcess {
Expand Down Expand Up @@ -3437,7 +3446,8 @@ function Get-PkWorkerSafeFunctionName {

function Get-PkHandlerParamCount {
# How many parameters a callback declares, or -1 if it has no param()
# block (it takes whatever it's given, in $args).
# block (it takes whatever it's given, in $args). Invoke-PkRunspaceBatch
# reads a -WorkerScript's parameters the same way.
param([Parameter(Mandatory)][scriptblock]$Callback)
$ast = $Callback.Ast
if ($ast -is [System.Management.Automation.Language.FunctionDefinitionAst]) {
Expand Down Expand Up @@ -3725,8 +3735,18 @@ function Invoke-PkRunspaceBatch {
# it out.
$mandatoryParams = [System.Collections.Generic.List[string]]::new()
$hasParameterSets = $false
if ($null -ne $WorkerScript.Ast.ParamBlock) {
foreach ($workerParam in $WorkerScript.Ast.ParamBlock.Parameters) {
# A function's own scriptblock (${function:Name}) has the function as its
# Ast: its parameters are in function f($a) or in its body's param()
# block, as Get-PkHandlerParamCount reads them.
$workerAst = $WorkerScript.Ast
$workerParamList = $null
if ($workerAst -is [System.Management.Automation.Language.FunctionDefinitionAst]) {
if ($null -ne $workerAst.Parameters) { $workerParamList = $workerAst.Parameters }
$workerAst = $workerAst.Body
}
if ($null -eq $workerParamList -and $null -ne $workerAst.ParamBlock) { $workerParamList = $workerAst.ParamBlock.Parameters }
if ($null -ne $workerParamList) {
foreach ($workerParam in $workerParamList) {
$null = $declaredParams.Add($workerParam.Name.VariablePath.UserPath)
$isMandatory = $false
foreach ($paramAttr in $workerParam.Attributes) {
Expand Down Expand Up @@ -4372,7 +4392,11 @@ function Test-PkWorkerSafetyCore {
# A function defined inside the worker script is in the same
# position as a shared one: called from a closure, its $script:
# can read as empty.
foreach ($innerFn in $ast.FindAll({ param($node) $node -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $true)) { $scriptVarScopes.Add($innerFn.Body) }
# Not the worker itself when it's a function (${function:Name}):
# its body is the worker's top level.
foreach ($innerFn in $ast.FindAll({ param($node) $node -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $true)) {
if (-not [object]::ReferenceEquals($innerFn, $ast)) { $scriptVarScopes.Add($innerFn.Body) }
}
} else {
$scriptVarScopes.Add($ast)
}
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,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. `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. `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
14 changes: 9 additions & 5 deletions Source/PkChildProcessJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -265,9 +265,11 @@ private sealed class TreeJob : SafeHandleZeroOrMinusOneIsInvalid

// Harness only: start programs without a tree job, to test the taskkill
// path; or have TryStart's first CreateProcess, with the tree job, count
// as refused, to test its retry without one.
// as refused, to test its retry without one. TestFailTerminate makes
// KillTree's TerminateJobObject count as refused, leaving the tree running.
public static bool TestNoTreeJob = false;
public static bool TestRefuseTreeJob = false;
public static bool TestFailTerminate = false;

private static void AddTree(Process process, IntPtr treeJob)
{
Expand All @@ -286,7 +288,7 @@ public static bool KillTree(Process process)
try
{
j.DangerousAddRef(ref added);
ended = TerminateJobObject(j.DangerousGetHandle(), 1);
ended = !TestFailTerminate && TerminateJobObject(j.DangerousGetHandle(), 1);
}
catch (ObjectDisposedException) { return false; } // released meanwhile: taskkill instead
finally { if (added) { j.DangerousRelease(); } }
Expand Down Expand Up @@ -621,12 +623,14 @@ public static string StartMode
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, for a running program Windows wouldn't add to it, and for
// -KillTreeOnExit on a program without a tree job.
private static int _initWarned = 0, _assignWarned = 0, _noTreeWarned = 0;
// -KillTreeOnExit on a program without a tree job, or whose tree job
// Windows wouldn't end.
private static int _initWarned = 0, _assignWarned = 0, _noTreeWarned = 0, _killTreeWarned = 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 bool ClaimNoTreeWarning() { return Interlocked.Exchange(ref _noTreeWarned, 1) == 0; }
public static void TestResetJobWarnings() { Interlocked.Exchange(ref _initWarned, 0); Interlocked.Exchange(ref _assignWarned, 0); Interlocked.Exchange(ref _noTreeWarned, 0); }
public static bool ClaimKillTreeWarning() { return Interlocked.Exchange(ref _killTreeWarned, 1) == 0; }
public static void TestResetJobWarnings() { Interlocked.Exchange(ref _initWarned, 0); Interlocked.Exchange(ref _assignWarned, 0); Interlocked.Exchange(ref _noTreeWarned, 0); Interlocked.Exchange(ref _killTreeWarned, 0); }

private static StringBuilder BuildCommandLine(string fileName, string arguments)
{
Expand Down