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
78 changes: 42 additions & 36 deletions ParallelKit.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -159,16 +159,18 @@ public static class PkSleepBlock
public static bool Unblock() { return SetThreadExecutionState(0x80000000u) != 0; }
}

// Main-thread bookkeeping. Static on purpose: see the note at the top of this
// file.
// Main-thread bookkeeping. Static on purpose, not $script: variables: a
// function called from a .GetNewClosure() block can see an empty $script:
// scope.
public static class PkState
{
public static bool AbortLatched = false;
public static bool CloseAbort = false;
public static object MessageHandler = null; // a PowerShell scriptblock, or null for the default

// Bump this, and the check after the type definitions, whenever any C#
// in this file changes: a session keeps the types it compiled first.
// A session keeps the types it compiled first. Bump this, and the check
// after the type definitions in ParallelKit.ps1, once in a release that
// changes any of the kit's C#.
public const int TypesVersion = 16;

// Locked: Register-/Unregister-PkCancellationSource are callable from
Expand Down Expand Up @@ -524,7 +526,7 @@ 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. The job stays open
// or Windows refused: Stop-PkProcessTree 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.
Expand All @@ -539,7 +541,7 @@ public static class PkChildProcessJob
j.DangerousAddRef(ref added);
ended = !TestFailTerminate && TerminateJobObject(j.DangerousGetHandle(), 1);
}
catch (ObjectDisposedException) { return false; } // released meanwhile: taskkill instead
catch (ObjectDisposedException) { return false; } // released meanwhile: as if it had none
finally { if (added) { j.DangerousRelease(); } }
return ended;
}
Expand Down Expand Up @@ -1902,10 +1904,7 @@ function Start-PkProcessCore {
throw [System.Management.Automation.RuntimeException]::new("Start-PkProcess: could not start '" + $FilePath + "'" + $tried + ": " + $reason, $_.Exception)
}
# The output is read in chunks (PkStreamReadTask), so Complete-PkProcess
# can keep what arrived when a stream times out. The two hashtables below
# have the same four keys, and the dispatcher's default starter and the
# batch's starter copy those keys onto their jobs: a new key goes in all
# four places.
# can keep what arrived when a stream times out.
if ($null -ne $started) {
$proc = $started.Process
$stdout = $started.Stdout
Expand Down Expand Up @@ -1940,6 +1939,8 @@ function Start-PkProcessCore {
if ($treeNote) { $failure = "Start-PkProcess: could not start '" + $FilePath + "': its output couldn't be read (" + $reason + "). " + $treeNote }
throw [System.Management.Automation.RuntimeException]::new($failure, $_.Exception)
}
# The dispatcher's default starter and the batch's starter copy these four
# keys onto their job: a new key goes in all three.
return @{
Proc = $proc
StdoutTask = $stdoutTask
Expand Down Expand Up @@ -2202,9 +2203,9 @@ function Stop-PkFailedStartTree {
# go of its tree job and process handle, and returns '' or a sentence
# for the start's failure report on what may still be running.
param([Parameter(Mandatory)][System.Diagnostics.Process]$Process)
$id = $null
# $null once disposed (a custom starter may have): no number then.
$id = $Process.Id
$stopped = 'Exited'
try { $id = $Process.Id } catch { } # disposed by a custom starter: the sentence then names no process
try { $stopped = Stop-PkProgramTree -Process $Process -Leftovers } catch { } # best effort: the failed start is what's reported
try { [PkChildProcessJob]::ReleaseTree($Process) } catch { } # its tree job's handle, now rather than at garbage collection
try { $Process.Dispose() } catch { } # the same, for the process handle
Expand Down Expand Up @@ -2362,8 +2363,9 @@ function Complete-PkProcess {
param(
[Parameter(Mandatory, Position = 0)]
[hashtable]$Job,
# Invoke-PkProcessDispatch's and Invoke-PkProcessBatch's -StreamTimeoutMs
# default to the same 15000: keep the three in step.
# Invoke-PkProcessWithTimeout's, Invoke-PkProcessDispatch's and
# Invoke-PkProcessBatch's -StreamTimeoutMs default to the same 15000:
# keep the four in step.
[int]$StreamTimeoutMs = 15000,
[switch]$Dispose
)
Expand Down Expand Up @@ -2484,6 +2486,9 @@ function Invoke-PkProcessWithTimeout {
[string]$FilePath,
$Arguments = "",
[int]$TimeoutMs = 60000,
# Complete-PkProcess's, Invoke-PkProcessDispatch's and
# Invoke-PkProcessBatch's -StreamTimeoutMs default to the same 15000:
# keep the four in step.
[int]$StreamTimeoutMs = 15000,
[string]$WorkingDirectory = "",
$OutputEncoding = $null,
Expand Down Expand Up @@ -2525,12 +2530,11 @@ function Invoke-PkProcessWithTimeout {
}
return Complete-PkProcess -Job $job -StreamTimeoutMs $StreamTimeoutMs
} finally {
# Still running here only when PowerShell is stopping the script
# (that skips catch blocks, not finally ones): kill it before the
# process object goes. Best effort, as above.
# The force-stop's steps: the program if it's running, with
# -KillTreeOnExit what it left if it exited before Complete-PkProcess,
# and its tree job's handle (a kill leaves it open).
# The force-stop's steps, before the process object goes: the program
# if it's still running (only when PowerShell is stopping the script,
# which skips catch blocks, not finally ones), what it left if it
# exited before Complete-PkProcess with -KillTreeOnExit, and its tree
# job's handle (a kill leaves it open).
$stopJobs = [System.Collections.Generic.List[hashtable]]::new(); $stopJobs.Add($job)
Stop-PkJobProcess -Jobs $stopJobs
$job['Proc'].Dispose()
Expand Down Expand Up @@ -2628,8 +2632,8 @@ function Invoke-PkProcessDispatch {
# 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; for one without, it warns
# once per session. A job's own KillTreeOnExit
# key overrides it either way. The default -JobPollCompleted does it; with
# once per session. 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
Expand All @@ -2654,8 +2658,9 @@ function Invoke-PkProcessDispatch {
[int]$MaxQueueAhead = 3,
[scriptblock]$GroupReleaseCheck = $null,
[double]$TimeoutSeconds = 0,
# Complete-PkProcess's and Invoke-PkProcessBatch's -StreamTimeoutMs
# default to the same 15000: keep the three in step.
# Complete-PkProcess's, Invoke-PkProcessWithTimeout's and
# Invoke-PkProcessBatch's -StreamTimeoutMs default to the same 15000:
# keep the four in step.
[int]$StreamTimeoutMs = 15000,
[int]$MaxOutputChars = 0,
[switch]$InheritStdin,
Expand Down Expand Up @@ -2717,8 +2722,8 @@ function Invoke-PkProcessDispatch {
$pkJobStarter = {
param($pkJob)
$pkStarted = Start-PkProcessCore -CallerState $pkCallerState -FilePath $pkJob['FilePath'] -Arguments $pkJob['Arguments'] -WorkingDirectory ([string]$pkJob['WorkingDirectory']) -OutputEncoding $pkJob['OutputEncoding'] -MaxOutputChars (Get-PkJobOutputLimit -Job $pkJob -DefaultMaxOutputChars $pkMaxOutputChars) -InheritStdin:(Get-PkJobSwitch -Job $pkJob -Key 'InheritStdin' -Default $pkInheritStdin)
# Start-PkProcessCore's four keys (it builds them in two places); the
# batch's starter copies them too: a new key goes in all four.
# Start-PkProcessCore's four keys; the batch's starter copies them
# too: a new key goes in all three.
$pkJob['Proc'] = $pkStarted.Proc; $pkJob['StdoutTask'] = $pkStarted.StdoutTask; $pkJob['StderrTask'] = $pkStarted.StderrTask
$pkJob['Stopwatch'] = $pkStarted.Stopwatch
return $pkJob
Expand Down Expand Up @@ -3407,8 +3412,8 @@ function Invoke-PkProcessBatch {
# 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; for one without, it warns
# once per session. A command's own
# KillTreeOnExit key overrides it either way.
# once per session. 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,
Expand All @@ -3428,8 +3433,9 @@ function Invoke-PkProcessBatch {
[int]$AbortTimeoutSeconds = 60,
[double]$TimeoutSeconds = 0,
$OutputEncoding = $null,
# Complete-PkProcess's and Invoke-PkProcessDispatch's -StreamTimeoutMs
# default to the same 15000: keep the three in step.
# Complete-PkProcess's, Invoke-PkProcessWithTimeout's and
# Invoke-PkProcessDispatch's -StreamTimeoutMs default to the same
# 15000: keep the four in step.
[int]$StreamTimeoutMs = 15000,
[int]$MaxOutputChars = 0,
[switch]$InheritStdin,
Expand Down Expand Up @@ -3542,8 +3548,8 @@ function Invoke-PkProcessBatch {
& $pkReportStartFailure $pkJob['Command'] $_
throw
}
# Start-PkProcessCore's four keys (it builds them in two places); the
# dispatcher's default starter copies them too: a new key goes in all four.
# Start-PkProcessCore's four keys; the dispatcher's default starter
# copies them too: a new key goes in all three.
$pkJob['Proc'] = $pkStarted.Proc; $pkJob['StdoutTask'] = $pkStarted.StdoutTask; $pkJob['StderrTask'] = $pkStarted.StderrTask
$pkJob['Stopwatch'] = $pkStarted.Stopwatch
return $pkJob
Expand Down Expand Up @@ -3684,7 +3690,7 @@ function Receive-PkCompletedHandle {
$pkCrash = $null
try {
try { $pkWorkerOutput = $h.PS.EndInvoke($h.Handle) } catch { $pkCrash = $_ }
# Same as Invoke-PkRunspaceBatch' main loop: its errors, then the
# Same as Invoke-PkRunspaceBatch's main loop: its errors, then the
# crash, in the order they happened.
Add-PkJobError -PkOutcome $Outcome -PkJob $h['Job'] -PkErrors $h.PS.Streams.Error
if ($null -ne $pkCrash) {
Expand Down Expand Up @@ -3853,7 +3859,7 @@ function Invoke-PkRunspaceBatch {
if ($null -ne $JobParams -and $null -ne $NextJobProvider) {
throw "Invoke-PkRunspaceBatch: supply only one of -JobParams or -NextJobProvider, not both."
}
if ($MaxConcurrent -lt 1) { throw "Invoke-PkRunspaceBatch: -MaxConcurrent must be at least 1." }
if ($MaxConcurrent -lt 1) { throw ("Invoke-PkRunspaceBatch: -MaxConcurrent must be at least 1 (got " + $MaxConcurrent + ").") }
if ($AbortTimeoutSeconds -lt 0) {
throw ("Invoke-PkRunspaceBatch: -AbortTimeoutSeconds must be 0 or more (got " + $AbortTimeoutSeconds + "). It's how long an abort waits for running workers before force-stopping them; 0 doesn't wait.")
}
Expand Down Expand Up @@ -4264,8 +4270,8 @@ function Get-PkCommandKind {
# by path from elsewhere can't. Remembered for the session: on 5.1 each
# lookup searches all of PSModulePath (51 ms with 154 modules on it), for
# every Invoke-PkRunspaceBatch call. So a module installed mid-session is
# missed until a new window, but one put on PSModulePath, as the finding
# suggests, isn't: that's part of the key.
# missed until a new window, but one added to PSModulePath isn't: that's
# part of the key.
$key = $env:PSModulePath + '|' + $Fn.ModuleName
$found = $false
if (-not [PkState]::ModuleFound.TryGetValue($key, [ref]$found)) {
Expand Down
4 changes: 2 additions & 2 deletions Source/PkChildProcessJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ 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. The job stays open
// or Windows refused: Stop-PkProcessTree 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.
Expand All @@ -297,7 +297,7 @@ public static bool KillTree(Process process)
j.DangerousAddRef(ref added);
ended = !TestFailTerminate && TerminateJobObject(j.DangerousGetHandle(), 1);
}
catch (ObjectDisposedException) { return false; } // released meanwhile: taskkill instead
catch (ObjectDisposedException) { return false; } // released meanwhile: as if it had none
finally { if (added) { j.DangerousRelease(); } }
return ended;
}
Expand Down
10 changes: 6 additions & 4 deletions Source/PkConsoleCtrl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,16 +115,18 @@ public static class PkSleepBlock
public static bool Unblock() { return SetThreadExecutionState(0x80000000u) != 0; }
}

// Main-thread bookkeeping. Static on purpose: see the note at the top of this
// file.
// Main-thread bookkeeping. Static on purpose, not $script: variables: a
// function called from a .GetNewClosure() block can see an empty $script:
// scope.
public static class PkState
{
public static bool AbortLatched = false;
public static bool CloseAbort = false;
public static object MessageHandler = null; // a PowerShell scriptblock, or null for the default

// Bump this, and the check after the type definitions, whenever any C#
// in this file changes: a session keeps the types it compiled first.
// A session keeps the types it compiled first. Bump this, and the check
// after the type definitions in ParallelKit.ps1, once in a release that
// changes any of the kit's C#.
public const int TypesVersion = 16;

// Locked: Register-/Unregister-PkCancellationSource are callable from
Expand Down