diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 33798e1..2d95b46 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -1340,9 +1340,9 @@ Reset-Harness function Get-HarnessShape($o) { if ($o -isnot [System.Management.Automation.PSCustomObject]) { return '(not an object)' }; return ($o.PSObject.Properties.Name -join ',') } $shapeBatch = Invoke-PkProcessBatch -Commands @(@{ FilePath = $cmdExe; Arguments = '/c exit 0' }) Test-Assert ((Get-HarnessShape $shapeBatch) -eq 'Results,Aborted,ForceKilledCount') ("a batch returns an object (" + (Get-HarnessShape $shapeBatch) + ")") -Test-Assert ((Get-HarnessShape $shapeBatch.Results[0]) -eq 'Command,ExitCode,Stdout,Stderr,StreamTimedOut,StreamError,StartError,Aborted,TimedOut') ("each batch result is an object, fields in order (" + (Get-HarnessShape $shapeBatch.Results[0]) + ")") +Test-Assert ((Get-HarnessShape $shapeBatch.Results[0]) -eq 'Command,ExitCode,Stdout,Stderr,StreamTimedOut,StreamError,StartError,Aborted,TimedOut,Duration') ("each batch result is an object, fields in order (" + (Get-HarnessShape $shapeBatch.Results[0]) + ")") $shapeOne = Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments '/c exit 0' -Test-Assert ((Get-HarnessShape $shapeOne) -eq 'ExitCode,Stdout,Stderr,StreamTimedOut,StreamError') ("Invoke-PkProcessWithTimeout returns an object (" + (Get-HarnessShape $shapeOne) + ")") +Test-Assert ((Get-HarnessShape $shapeOne) -eq 'ExitCode,Stdout,Stderr,StreamTimedOut,StreamError,Duration') ("Invoke-PkProcessWithTimeout returns an object (" + (Get-HarnessShape $shapeOne) + ")") $shapeDispatch = Invoke-PkProcessDispatch -MaxConcurrent 1 -GroupProvider { return $null } -JobBuilder { param($g) } -JobFinalize { param($j, $p) } Test-Assert ((Get-HarnessShape $shapeDispatch) -eq 'GroupResults,Aborted,ForceKilledCount,JobStarterFailedCount') ("the dispatcher returns an object (" + (Get-HarnessShape $shapeDispatch) + ")") $shapeJobs = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @{ Id = 1 } -WorkerScript { param($Id) } @@ -1352,7 +1352,7 @@ $shapeFinding = $shapeFindings[0] Test-Assert ((Get-HarnessShape $shapeFinding) -eq 'Rule,Where,Line,Text') ("worker-safety findings are objects (" + (Get-HarnessShape $shapeFinding) + ")") Test-Assert ((Get-HarnessShape (Initialize-ParallelKit)) -eq 'AbortHandler,ChildProcessJob,ThreadPool,Version,StartMode') "Initialize-ParallelKit returns an object" -$fields = @('Command', 'ExitCode', 'Stdout', 'Stderr', 'StreamTimedOut', 'StreamError', 'StartError', 'Aborted', 'TimedOut') +$fields = @('Command', 'ExitCode', 'Stdout', 'Stderr', 'StreamTimedOut', 'StreamError', 'StartError', 'Aborted', 'TimedOut', 'Duration') $batch = Invoke-PkProcessBatch -MaxConcurrent 1 -Commands @( @{ FilePath = $cmdExe; Arguments = '/c exit 0' }, @{ FilePath = 'C:\definitely\not\here.exe' }) @@ -4443,6 +4443,51 @@ if ($compiled) { } Write-Host "" +Write-Host "=== AY: Duration: how long each program ran ===" -ForegroundColor Cyan +# From the program's start to its exit or kill: not the time it waited for a +# slot, nor the time spent waiting for its output afterwards. The bounds are +# loose: a busy machine is slow to start programs. +Reset-Harness +function Get-HarnessDuration($r) { + if ($null -eq $r -or $null -eq $r.PSObject.Properties['Duration']) { return 'missing' } + if ($null -eq $r.Duration) { return $null } + if ($r.Duration -isnot [TimeSpan]) { return 'not a TimeSpan' } + return [math]::Round($r.Duration.TotalSeconds, 2) +} +$d = Get-HarnessDuration (Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments '/d /c ping -n 3 127.0.0.1 >nul') +Test-Assert ($d -is [double] -and $d -ge 1.5 -and $d -le 6) ("a program that runs about 2 s has a Duration of about 2 s (" + $d + ")") + +# Output held open for 3 s by a leftover child: the call takes the 1 s stream +# timeout, but the program itself ended at once. +$sw = [System.Diagnostics.Stopwatch]::StartNew() +$d = Get-HarnessDuration (Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments $heldArgs -StreamTimeoutMs 1000) +$sw.Stop() +Test-Assert ($d -is [double] -and $d -lt 0.8 -and $sw.Elapsed.TotalSeconds -ge 0.9) ("time spent waiting for held output isn't counted (Duration " + $d + " s, call " + [math]::Round($sw.Elapsed.TotalSeconds, 1) + " s)") + +# One slot, two 1 s programs: the second waited about 1 s for its turn. +$b = Invoke-PkProcessBatch -MaxConcurrent 1 -Commands @(@{ FilePath = $cmdExe; Arguments = '/d /c ping -n 2 127.0.0.1 >nul'; N = 1 }, @{ FilePath = $cmdExe; Arguments = '/d /c ping -n 2 127.0.0.1 >nul'; N = 2 }) +$dq = @($b.Results | Sort-Object { $_.Command['N'] } | ForEach-Object { Get-HarnessDuration $_ }) +Test-Assert ($dq.Count -eq 2 -and $dq[1] -is [double] -and $dq[1] -ge 0.5 -and $dq[1] -le 1.8) ("time waiting for a slot isn't counted (" + ($dq -join ', ') + ")") + +# Killed by -TimeoutSeconds 1: about 1 s. +$b = Invoke-PkProcessBatch -TimeoutSeconds 1 -Commands @(@{ FilePath = $pingExe; Arguments = '-n 30 127.0.0.1' }) +$d = Get-HarnessDuration $b.Results[0] +Test-Assert ($b.Results[0].TimedOut -and $d -is [double] -and $d -ge 0.8 -and $d -le 5) ("a program killed by its time limit has the time it ran (" + $d + ")") + +# An abort: the running program is force-stopped and gets the time it ran; +# the one still waiting for a slot, and one that couldn't start, get $null. +Reset-Harness +$b = Invoke-PkProcessBatch -MaxConcurrent 2 -AbortTimeoutSeconds 0 -OnComplete { param($c, $r) if ($c['N'] -eq 1) { Request-PkAbort } } -Commands @( + @{ FilePath = 'C:\no\such\program.exe'; N = 0 }, + @{ FilePath = $cmdExe; Arguments = '/d /c ping -n 2 127.0.0.1 >nul'; N = 1 }, + @{ FilePath = $pingExe; Arguments = '-n 30 127.0.0.1'; N = 2 }, + @{ FilePath = $pingExe; Arguments = '-n 30 127.0.0.1'; N = 3 }) +Reset-PkAbortState +$byN = @{}; foreach ($r in $b.Results) { $byN[[int]$r.Command['N']] = $r } +$dStopped = Get-HarnessDuration $byN[2]; $dWaiting = Get-HarnessDuration $byN[3]; $dFailed = Get-HarnessDuration $byN[0] +Test-Assert ($byN.Count -eq 4 -and $byN[2].Aborted -and $dStopped -is [double] -and $dStopped -gt 0 -and $dStopped -le 5 -and $byN[3].Aborted -and $null -eq $dWaiting -and $null -eq $dFailed) ("an abort: the force-stopped program has the time it ran, one never started and one that couldn't start have `$null (" + $dStopped + ", " + $dWaiting + ", " + $dFailed + ")") +Write-Host "" + Set-PkMessageHandler -Handler $null Reset-PkAbortState diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index dc681ac..e6510e7 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -1728,6 +1728,19 @@ function Wait-PkRunningJobs { [System.Threading.Thread]::Sleep($TimeoutMs) } +function Get-PkProcessDuration { + # How long a program ran, from its start to its exit or kill, as a + # [TimeSpan]: not the time it waited for a slot, nor any wait for its + # output afterwards. $null if it isn't a Process (a custom starter's), + # hasn't exited, or was already disposed (Dispose loses the times). + param($Process) + if ($Process -isnot [System.Diagnostics.Process]) { return $null } + try { + if ($Process.HasExited -ne $true) { return $null } + return ($Process.ExitTime - $Process.StartTime) + } catch { return $null } # times not readable: no duration, rather than a throw inside -JobFinalize +} + function Complete-PkProcess { # .SYNOPSIS # Collects the exit code and output of a program that has exited. @@ -1746,7 +1759,8 @@ function Complete-PkProcess { # .PARAMETER Dispose # Dispose the process object afterwards. # .OUTPUTS - # An object with ExitCode, Stdout, Stderr, StreamTimedOut and StreamError. + # An object with ExitCode, Stdout, Stderr, StreamTimedOut, StreamError and + # Duration (how long the program ran, from its start to its exit or kill). # Only -Job by position: otherwise `-Dispose $true` would bind $true to # -StreamTimeoutMs (1 ms) and cut the output off without an error. @@ -1763,7 +1777,7 @@ function Complete-PkProcess { if ($StreamTimeoutMs -lt 0) { throw ("Complete-PkProcess: -StreamTimeoutMs must be 0 or more (got " + $StreamTimeoutMs + "). It's how long to wait for the output after the program exits, in milliseconds; 0 doesn't wait.") } - $result = [ordered]@{ ExitCode = $null; Stdout = $null; Stderr = $null; StreamTimedOut = $false; StreamError = $null } + $result = [ordered]@{ ExitCode = $null; Stdout = $null; Stderr = $null; StreamTimedOut = $false; StreamError = $null; Duration = $null } # 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. @@ -1790,6 +1804,8 @@ function Complete-PkProcess { elseif (-not $task.IsCompleted -and $task -is [PkStreamReadTask]) { $result[$stream] = $task.Snapshot() } } $result.ExitCode = $Job['Proc'].ExitCode + # The program's end, not the output's: before Dispose, which loses it. + $result.Duration = Get-PkProcessDuration -Process $Job['Proc'] if ($Dispose) { $Job['Proc'].Dispose() } return [pscustomobject]$result } @@ -1819,7 +1835,8 @@ function Invoke-PkProcessWithTimeout { # Keep going during an abort, for a cleanup or restore step that has to run # because of it. # .OUTPUTS - # An object with ExitCode, Stdout, Stderr, StreamTimedOut and StreamError. + # An object with ExitCode, Stdout, Stderr, StreamTimedOut, StreamError and + # Duration (how long the program ran, from its start to its exit or kill). # .EXAMPLE # $r = Invoke-PkProcessWithTimeout -FilePath git.exe -Arguments 'rev-parse HEAD' -TimeoutMs 10000 param( @@ -2544,19 +2561,23 @@ function Invoke-PkProcessDispatchCore { function New-PkBatchResult { # One Invoke-PkProcessBatch result, the same shape however the command # ended: ran (-Completed is Complete-PkProcess's object), couldn't start - # (-StartError), or stopped by an abort (-Aborted). + # (-StartError), or stopped by an abort (-Aborted; -Process is its program, + # if it was started, for how long it ran). param( [hashtable]$Command, $Completed = $null, [string]$StartError = $null, [switch]$Aborted, - [bool]$TimedOut = $false + [bool]$TimedOut = $false, + $Process = $null ) $r = [ordered]@{ Command = $Command; ExitCode = $null; Stdout = $null; Stderr = $null; StreamTimedOut = $false; StreamError = $null - StartError = $null; Aborted = [bool]$Aborted; TimedOut = $TimedOut } + StartError = $null; Aborted = [bool]$Aborted; TimedOut = $TimedOut; Duration = $null } if ($null -ne $Completed) { $r.ExitCode = $Completed.ExitCode; $r.Stdout = $Completed.Stdout; $r.Stderr = $Completed.Stderr - $r.StreamTimedOut = $Completed.StreamTimedOut; $r.StreamError = $Completed.StreamError + $r.StreamTimedOut = $Completed.StreamTimedOut; $r.StreamError = $Completed.StreamError; $r.Duration = $Completed.Duration + } elseif ($null -ne $Process) { + $r.Duration = Get-PkProcessDuration -Process $Process } if ($StartError) { $r.StartError = $StartError } return [pscustomobject]$r @@ -2607,8 +2628,8 @@ function Invoke-PkProcessBatch { # or a [System.Text.Encoding]. Default: the console's code page. # .OUTPUTS # An object with Results, Aborted and ForceKilledCount. Each result has Command, - # ExitCode, Stdout, Stderr, StreamTimedOut, StreamError, StartError, Aborted and - # TimedOut, in the order the programs finished. + # ExitCode, Stdout, Stderr, StreamTimedOut, StreamError, StartError, Aborted, + # TimedOut and Duration, in the order the programs finished. # .EXAMPLE # $commands = foreach ($f in Get-ChildItem *.png) { @{ FilePath = 'cjxl.exe'; Arguments = @($f.FullName, "$($f.FullName).jxl") } } # $batch = Invoke-PkRun { Invoke-PkProcessBatch -Commands $commands -MaxConcurrent 6 } @@ -2738,7 +2759,9 @@ function Invoke-PkProcessBatch { $pkJobAbortCleanup = { param($pkJob) - $pkResults.Add((& $pkNewBatchResult -Command $pkJob['Command'] -Aborted)) + # Called after a force-stop's kill and before the program is disposed, + # so a started program's run time can still be read. + $pkResults.Add((& $pkNewBatchResult -Command $pkJob['Command'] -Aborted -Process $pkJob['Proc'])) }.GetNewClosure() $pkDispatchParams = @{ @@ -2765,7 +2788,7 @@ function Invoke-PkProcessBatch { function Get-PkWorkerSafeFunctionNames { # Kit functions every worker runspace gets automatically. - return @('Write-PkMessage', 'Test-PkAbortSignal', 'Test-PkCancelRequested', 'Initialize-PkThreadPool', 'Stop-PkProcessTree', 'Stop-PkProcessTreeCore', 'Split-PkTaskkillArguments', 'Stop-PkJobProcesses', 'Resolve-PkEncoding', + return @('Write-PkMessage', 'Test-PkAbortSignal', 'Test-PkCancelRequested', 'Initialize-PkThreadPool', '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', 'ConvertTo-PkArgumentString', 'Get-PkForceStopReason', 'Resolve-PkFileSystemPath', 'Add-PkDispatchGroupJobs', 'Start-PkProcessCore', 'Get-PkJobTimeLimit', 'Stop-PkTimedOutJob', 'Get-PkStartFailureCause', 'Resolve-PkArguments', 'Invoke-PkCallback', 'Write-PkCallbackLoopWarning', 'ConvertTo-PkArgumentStringCore') diff --git a/README.md b/README.md index f316380..ccee251 100644 --- a/README.md +++ b/README.md @@ -136,13 +136,14 @@ Only the list form gets this quoting. A string, including one built with `Conver Programs run in your current location (`Get-Location`) unless a command says otherwise, and a relative `WorkingDirectory`, or a `FilePath` with a folder in it like `.\tools\cjxl.exe`, is relative to that location too. Drives PowerShell knows, like `~` or one made with `New-PSDrive`, work in both. A bare name like `cjxl.exe` is found the way Windows finds programs, mostly on `PATH`. Only an `.exe` is found without its extension (Windows doesn't use `PATHEXT` here), so a `.cmd` wrapper such as `npm` has to be written out: `npm.cmd`. A `.bat` or `.cmd` program can't run in a network-share (`\\server\share`) folder: `cmd.exe` falls back to `C:\Windows` there, so give such commands a local `WorkingDirectory`. -`Invoke-PkProcessBatch` returns an object with `Results`, `Aborted` and `ForceKilledCount`. Each result is an object with `Command`, `ExitCode`, `Stdout`, `Stderr`, `StreamTimedOut`, `StreamError`, `StartError`, `Aborted` and `TimedOut`, every field always present, so `$batch.Results | Format-Table` reads well: +`Invoke-PkProcessBatch` returns an object with `Results`, `Aborted` and `ForceKilledCount`. Each result is an object with `Command`, `ExitCode`, `Stdout`, `Stderr`, `StreamTimedOut`, `StreamError`, `StartError`, `Aborted`, `TimedOut` and `Duration`, every field always present, so `$batch.Results | Format-Table` reads well: - `Command` is your original command hashtable, so extra keys like `Source` above come back with it. - `ExitCode` is whatever the program returned. The kit doesn't treat a non-zero code as a failure; that's for you to decide. - `StartError` is set when the program couldn't be started (not found, say). Every command is still tried and gets its own result, but repeats of the same failure for the same program print once, with a count at the end. - `Aborted` is `$true` for a command an abort killed or kept from starting. - `TimedOut` is `$true` for a program `-TimeoutSeconds` killed. +- `Duration` is how long the program ran, from its start to its exit or kill, as a `[TimeSpan]`: not the time it waited for a slot, nor any wait for its output afterwards. It's `$null` for a command that never started. Sorting on it finds the slow ones: `$batch.Results | Sort-Object Duration -Descending | Select-Object -First 10`. - `StreamTimedOut` means the output read gave up 15 seconds after the program exited, 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. 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. `StreamError` means a read failed, and that stream comes back `$null`. `Results` is in the order commands finished, not the order you gave them. Use `Command` to match them up, or give each command your own key (`Index = $n`) and sort on it: `$batch.Results | Sort-Object { $_.Command.Index }`. @@ -273,7 +274,7 @@ To leave any callback early, use `return`. PowerShell sends a `continue` or `bre | Function | Use | |---|---| -| `Invoke-PkProcessWithTimeout -FilePath -Arguments -TimeoutMs` | Run one program and wait, with a hard time limit (default 60s). Returns an object with `ExitCode`, `Stdout`, `Stderr`, `StreamTimedOut` and `StreamError`. If it overruns, or the run is aborted, the program is killed and this **throws**; add `-IgnoreAbort` for a cleanup step that must finish anyway. | +| `Invoke-PkProcessWithTimeout -FilePath -Arguments -TimeoutMs` | Run one program and wait, with a hard time limit (default 60s). Returns an object with `ExitCode`, `Stdout`, `Stderr`, `StreamTimedOut`, `StreamError` and `Duration`. If it overruns, or the run is aborted, the program is killed and this **throws**; add `-IgnoreAbort` for a cleanup step that must finish anyway. | | `ConvertTo-PkArgumentString @(args)` | Join a list of arguments into one correctly quoted command line. `-Arguments` / `Arguments` also take the list directly, and then also quote it for `cmd.exe` when the program is a `.bat` or `.cmd`. | | `Start-PkProcess -FilePath -Arguments` | Start one hidden, with output captured in the background. Returns `@{ Proc; StdoutTask; StderrTask; Stopwatch }`; throws if it can't start. | | `Wait-PkProcess -Process -TimeoutMs` | Wait for exit with a timeout that can't overrun. Returns `$true` if it exited. |