diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 3c8d41f..33798e1 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -4354,6 +4354,95 @@ Test-Assert ($ipHeader -ne '' -and $ipVersion -eq $ipHeader) ("Initialize-Parall Test-Assert ($ipMode -eq 'CreatedInJob' -and $ipAdded -eq 'AddedToJob') ("and its StartMode says how programs start: CreatedInJob normally, AddedToJob without the start lock (" + $ipMode + ", " + $ipAdded + ", error: " + $ipError + ")") Write-Host "" +Write-Host "=== AX: output held open by a leftover child is cut short, not lost ===" -ForegroundColor Cyan +# The test program writes "out" and "err", then leaves a copy of itself +# holding one of the two open for 3 s, writing nothing. The copy is started +# with a handle list, so it inherits only that pipe: cmd's `start /b`, and +# even .NET's Process.Start, hand a child both. Modes: stdout / stderr (the +# stream left held), partial (stdout held, ending in half a UTF-8 +# character), split (no copy; a UTF-8 character written in two parts, +# 300 ms apart). +$holdExe = Join-Path $env:TEMP ("pk-hold-" + [guid]::NewGuid().ToString("N") + ".exe") +$holdSrc = [System.IO.Path]::ChangeExtension($holdExe, '.cs') +[System.IO.File]::WriteAllText($holdSrc, @' +using System; using System.IO; using System.Runtime.InteropServices; using System.Text; +public static class PkHold { + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] struct SI { public int cb; public string r, d, t; public int x, y, xs, ys, xc, yc, fill, flags; public short show, r2; public IntPtr r3, hIn, hOut, hErr; } + [StructLayout(LayoutKind.Sequential)] struct SIEX { public SI si; public IntPtr attr; } + [StructLayout(LayoutKind.Sequential)] struct PI { public IntPtr hp, ht; public int pid, tid; } + [DllImport("kernel32.dll")] static extern IntPtr GetStdHandle(int n); + [DllImport("kernel32.dll", SetLastError = true)] static extern bool InitializeProcThreadAttributeList(IntPtr l, int c, int f, ref IntPtr s); + [DllImport("kernel32.dll", SetLastError = true)] static extern bool UpdateProcThreadAttribute(IntPtr l, uint f, IntPtr a, IntPtr v, IntPtr s, IntPtr p, IntPtr r); + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] static extern bool CreateProcess(string app, StringBuilder cmd, IntPtr pa, IntPtr ta, bool inherit, uint flags, IntPtr env, string dir, ref SIEX si, out PI pi); + [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h); + static void Write(Stream s, byte[] b) { s.Write(b, 0, b.Length); s.Flush(); } + public static int Main(string[] args) { + string mode = args[0]; + if (mode == "sleep") { System.Threading.Thread.Sleep(3000); return 0; } + Stream o = Console.OpenStandardOutput(), e = Console.OpenStandardError(); + byte[] text = Encoding.ASCII.GetBytes("out"); + if (mode == "partial" || mode == "split") { text = new byte[] { 0x63, 0x61, 0x66, 0xC3 }; } + Write(o, text); + Write(e, Encoding.ASCII.GetBytes("err")); + if (mode == "split") { System.Threading.Thread.Sleep(300); Write(o, new byte[] { 0xA9, 0x20, 0x6F, 0x6B }); return 0; } + // A copy of this program sleeps 3 s holding exactly one of the two pipes: + // a handle list limits what it inherits to that one. + IntPtr held = GetStdHandle(mode == "stderr" ? -12 : -11); + IntPtr size = IntPtr.Zero; + InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref size); + IntPtr list = Marshal.AllocHGlobal(size); + InitializeProcThreadAttributeList(list, 1, 0, ref size); + IntPtr arr = Marshal.AllocHGlobal(IntPtr.Size); Marshal.WriteIntPtr(arr, held); + if (!UpdateProcThreadAttribute(list, 0, (IntPtr)0x20002, arr, (IntPtr)IntPtr.Size, IntPtr.Zero, IntPtr.Zero)) { return 10; } + SIEX si = new SIEX(); si.si.cb = Marshal.SizeOf(typeof(SIEX)); si.si.flags = 0x100; si.si.hOut = held; si.si.hErr = held; si.attr = list; + PI pi; + string self = System.Reflection.Assembly.GetExecutingAssembly().Location; + if (!CreateProcess(null, new StringBuilder("\"" + self + "\" sleep"), IntPtr.Zero, IntPtr.Zero, true, 0x08080000, IntPtr.Zero, null, ref si, out pi)) { return 11; } + CloseHandle(pi.hp); CloseHandle(pi.ht); + return 0; + } +} +'@) +$csc = $null +try { $csc = Invoke-PkProcessWithTimeout -FilePath $cscExe -Arguments (ConvertTo-PkArgumentString @('/nologo', ('/out:' + $holdExe), $holdSrc)) } catch { Write-Host " csc.exe failed to run: $_" } +[System.IO.File]::Delete($holdSrc) +$compiled = ($null -ne $csc -and $csc.ExitCode -eq 0 -and [System.IO.File]::Exists($holdExe)) +Test-Assert $compiled "the output-holding test program compiles" +if ($compiled) { + $holdCafe = 'caf' + [char]0xE9 + ' ok' + foreach ($holdPath in 'created in the job', 'Process.Start fallback') { + [PkChildProcessJob]::TestUseProcessStart = ($holdPath -eq 'Process.Start fallback') + try { + foreach ($holdMode in 'stdout', 'stderr') { + $s = Start-PkProcess -FilePath $holdExe -Arguments $holdMode + $null = $s['Proc'].WaitForExit(10000) + $r = Complete-PkProcess $s -StreamTimeoutMs 1000 + $heldTask = $s['StdoutTask'] + if ($holdMode -eq 'stderr') { $heldTask = $s['StderrTask'] } + $stillReading = -not $heldTask.IsCompleted + Test-Assert ($r.StreamTimedOut -and $r.Stdout -eq 'out' -and $r.Stderr -eq 'err' -and $null -eq $r.StreamError) ($holdPath + ": with " + $holdMode + " held open past -StreamTimeoutMs, both streams keep their text (Stdout '" + $r.Stdout + "', Stderr '" + $r.Stderr + "', StreamTimedOut " + $r.StreamTimedOut + ")") + # The read carries on until the leftover child lets go of the pipe. + $endedLater = $heldTask.Wait(8000) + Test-Assert ($stillReading -and $endedLater) ($holdPath + ": the held " + $holdMode + " read is still going when the result is handed over, and ends once the child lets go (" + $stillReading + ", " + $endedLater + ")") + $s['Proc'].Dispose() + } + # Half a UTF-8 character at the cut: the text before it, nothing broken. + $s = Start-PkProcess -FilePath $holdExe -Arguments 'partial' -OutputEncoding 'utf-8' + $null = $s['Proc'].WaitForExit(10000) + $r = Complete-PkProcess $s -StreamTimeoutMs 1000 + $null = $s['StdoutTask'].Wait(8000); $s['Proc'].Dispose() + Test-Assert ($r.StreamTimedOut -and $r.Stdout -eq 'caf') ($holdPath + ": output cut off in the middle of a UTF-8 character keeps the whole characters before it ('" + $r.Stdout + "')") + # A character split across two writes comes through whole. + $r = Invoke-PkProcessWithTimeout -FilePath $holdExe -Arguments 'split' -OutputEncoding 'utf-8' + Test-Assert ($r.Stdout -eq $holdCafe -and -not $r.StreamTimedOut) ($holdPath + ": a UTF-8 character written in two parts comes through whole ('" + $r.Stdout + "')") + } finally { [PkChildProcessJob]::TestUseProcessStart = $false } + } + for ($t = 0; $t -lt 20 -and [System.IO.File]::Exists($holdExe); $t++) { + try { [System.IO.File]::Delete($holdExe) } catch { Start-Sleep -Milliseconds 100 } # still held by a process just ended: try again + } +} +Write-Host "" + Set-PkMessageHandler -Handler $null Reset-PkAbortState diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index b292c4a..dc681ac 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -164,7 +164,7 @@ public static class PkState // Bump this, and the check after the type definitions, whenever any C# // in this file changes: a session keeps the types it compiled first. - public const int TypesVersion = 6; + public const int TypesVersion = 7; // Locked: Register-/Unregister-PkCancellationSource are callable from // worker runspaces, and List is not safe for concurrent writers. @@ -235,6 +235,7 @@ using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading; +using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; public sealed class PkStartedProcess @@ -244,6 +245,52 @@ public sealed class PkStartedProcess public StreamReader Stderr; } +// Reads one of a program's output streams to its end, in chunks, so what has +// arrived can be taken at any time (Snapshot): a program the program started +// can hold the stream open long after it exits. The task's result is the +// whole text, at the end of the stream. The reader's decoder carries a +// character split across two reads over to the next, so a snapshot never +// ends in half a character. A read blocks a thread-pool thread, as +// ReadToEndAsync did; it ends when every holder of the stream's write end +// has let go (at the latest when PowerShell exits: they're in the Job Object). +public sealed class PkStreamReadTask : Task +{ + private sealed class Buffer + { + private readonly TextReader _reader; + private StringBuilder _text = new StringBuilder(); + private string _final; + private readonly object _gate = new object(); + public Buffer(TextReader reader) { _reader = reader; } + public string Pump() + { + char[] chunk = new char[4096]; + int n; + while ((n = _reader.Read(chunk, 0, chunk.Length)) > 0) + { + lock (_gate) { _text.Append(chunk, 0, n); } + } + // The builder goes once the text is final, so it isn't held twice. + lock (_gate) { _final = _text.ToString(); _text = null; return _final; } + } + // Locked: the reader may be appending while Complete-PkProcess takes it. + public string Snapshot() { lock (_gate) { return _final != null ? _final : _text.ToString(); } } + } + + private readonly Buffer _buffer; + private PkStreamReadTask(Buffer buffer) : base(new Func(buffer.Pump)) { _buffer = buffer; } + + public static PkStreamReadTask Run(TextReader reader) + { + PkStreamReadTask task = new PkStreamReadTask(new Buffer(reader)); + task.Start(TaskScheduler.Default); + return task; + } + + // The text that has arrived so far; all of it once the task has finished. + public string Snapshot() { return _buffer.Snapshot(); } +} + // A Windows Job Object with KILL_ON_JOB_CLOSE: every child process assigned // to it dies when this process exits for ANY reason, force-kill included. public static class PkChildProcessJob @@ -732,7 +779,7 @@ public static class PkChildProcessJob # A session that loaded an older copy keeps its compiled types. Say so, # rather than fail later with a missing-method error. Keep this number in # sync with [PkState]::TypesVersion. -if ((& { try { [PkState]::TypesVersion } catch { 0 } }) -ne 6) { +if ((& { try { [PkState]::TypesVersion } catch { 0 } }) -ne 7) { throw "ParallelKit: this PowerShell session already loaded an older version of the kit, and its compiled parts can't be swapped out. Close this window and start a new one." } @@ -1427,19 +1474,24 @@ function Start-PkProcessCore { # The original goes along as the inner exception: the batch reads Windows' error code from it. 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. if ($null -ne $started) { return @{ Proc = $started.Process - StdoutTask = $started.Stdout.ReadToEndAsync() - StderrTask = $started.Stderr.ReadToEndAsync() + StdoutTask = [PkStreamReadTask]::Run($started.Stdout) + StderrTask = [PkStreamReadTask]::Run($started.Stderr) Stopwatch = [System.Diagnostics.Stopwatch]::StartNew() } } $null = [PkChildProcessJob]::Assign($proc) return @{ Proc = $proc - StdoutTask = $proc.StandardOutput.ReadToEndAsync() - StderrTask = $proc.StandardError.ReadToEndAsync() + StdoutTask = [PkStreamReadTask]::Run($proc.StandardOutput) + StderrTask = [PkStreamReadTask]::Run($proc.StandardError) Stopwatch = [System.Diagnostics.Stopwatch]::StartNew() } } @@ -1682,8 +1734,10 @@ function Complete-PkProcess { # .DESCRIPTION # A program that exited can still have its output held open by a program it # started, so reading the output is time-limited too; StreamTimedOut says when - # that limit was hit. The stream it gave up on comes back $null: its output - # is missing, not cut short. + # that limit was hit. The stream it gave up on comes back with what arrived + # before then: cut short, not lost. Its read carries on in the background + # until that program lets go of it (it's killed with PowerShell at the + # latest). A stream whose read failed (StreamError) comes back $null. # .PARAMETER Job # What Start-PkProcess returned, or a dispatcher job with the same keys. # .PARAMETER StreamTimeoutMs @@ -1723,9 +1777,18 @@ function Complete-PkProcess { $result.StreamError = [string]$_.Exception.Message } } + # The output's end (both streams closed, or the timeout) is separate from + # the program's end (the exit code, below): a program it started can hold + # a stream open after it exits. A stream still open at the timeout gives + # the text that arrived before it, each stream on its own; its read + # carries on in the background until that program lets go. $ranToCompletion = [System.Threading.Tasks.TaskStatus]::RanToCompletion - if ($null -ne $Job['StdoutTask'] -and $Job['StdoutTask'].Status -eq $ranToCompletion) { $result.Stdout = $Job['StdoutTask'].Result } - if ($null -ne $Job['StderrTask'] -and $Job['StderrTask'].Status -eq $ranToCompletion) { $result.Stderr = $Job['StderrTask'].Result } + foreach ($stream in 'Stdout', 'Stderr') { + $task = $Job[$stream + 'Task'] + if ($null -eq $task) { continue } + if ($task.Status -eq $ranToCompletion) { $result[$stream] = $task.Result } + elseif (-not $task.IsCompleted -and $task -is [PkStreamReadTask]) { $result[$stream] = $task.Snapshot() } + } $result.ExitCode = $Job['Proc'].ExitCode if ($Dispose) { $Job['Proc'].Dispose() } return [pscustomobject]$result @@ -1950,6 +2013,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'] + # 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. $pkJob['Proc'] = $pkStarted.Proc; $pkJob['StdoutTask'] = $pkStarted.StdoutTask; $pkJob['StderrTask'] = $pkStarted.StderrTask $pkJob['Stopwatch'] = $pkStarted.Stopwatch return $pkJob @@ -2651,6 +2716,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. $pkJob['Proc'] = $pkStarted.Proc; $pkJob['StdoutTask'] = $pkStarted.StdoutTask; $pkJob['StderrTask'] = $pkStarted.StderrTask $pkJob['Stopwatch'] = $pkStarted.Stopwatch return $pkJob diff --git a/README.md b/README.md index 5572826..f316380 100644 --- a/README.md +++ b/README.md @@ -143,7 +143,7 @@ Programs run in your current location (`Get-Location`) unless a command says oth - `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. -- `StreamTimedOut` means the output read gave up 15 seconds after the program exited, which only happens when a program it started is still holding the output open. The stream it gave up on comes back `$null`: what the program wrote there is missing, not cut short. `StreamError` means a read failed, and that stream comes back `$null` too. +- `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 }`.