diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 8bcbfbf..f26c018 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -4858,6 +4858,47 @@ foreach ($rsPath in 'CreatedInJob', 'Process.Start', 'batch') { } } +# The same once the program has exited before the rollback: what it left +# running is still ended, through its tree job (a kill of the program itself +# passes over one that has exited). TestFailRunDelayMs holds the failing Run +# until cmd.exe, which only starts the ping, is gone. +foreach ($rxPath in 'CreatedInJob', 'Process.Start') { + $rsW++ + $rxArgs = '/d /c start "" /b ping -n 30 -w ' + $rsW + ' 127.0.0.1 >nul' + $rxError = $null + [PkChildProcessJob]::TestUseProcessStart = ($rxPath -eq 'Process.Start') + [PkStreamReadTask]::TestFailRunAfter = 1 + [PkStreamReadTask]::TestFailRunDelayMs = 2000 + try { $null = Start-PkProcess -FilePath $cmdExe -Arguments $rxArgs } catch { $rxError = [string]$_ } finally { [PkStreamReadTask]::TestFailRunAfter = -1; [PkStreamReadTask]::TestFailRunDelayMs = 0; [PkChildProcessJob]::TestUseProcessStart = $false } + $rxWait = [System.Diagnostics.Stopwatch]::StartNew() + do { + $rxLeft = @(Get-CimInstance Win32_Process -Filter "Name='PING.EXE'" | Where-Object { [string]$_.CommandLine -like ('*-w ' + $rsW + ' 127.0.0.1*') }) + if ($rxLeft.Count -eq 0) { break } + Start-Sleep -Milliseconds 100 + } while ($rxWait.ElapsedMilliseconds -lt 5000) + foreach ($l in $rxLeft) { Stop-Process -Id $l.ProcessId -Force -ErrorAction SilentlyContinue } + Test-Assert ($rxError -like '*could not start*' -and $rxLeft.Count -eq 0) ("a program that has exited when its reader fails still has what it started ended, " + $rxPath + " (" + $rxLeft.Count + " left running, error: " + $rxError + ")") +} + +# And the dispatcher's own cleanup when a -JobStarter throws after starting a +# program that has since exited. +$rsW++ +$dxArgs = '/d /c start "" /b ping -n 30 -w ' + $rsW + ' 127.0.0.1 >nul' +$dxFeed = @{ Given = $false } +$dx = Invoke-PkProcessDispatch -MaxConcurrent 1 -AbortTimeoutSeconds 5 ` + -GroupProvider { if ($dxFeed.Given) { return $null }; $dxFeed.Given = $true; return 'g' }.GetNewClosure() ` + -JobBuilder { param($g) return @(@{ FilePath = $cmdExe; Arguments = $dxArgs }) }.GetNewClosure() ` + -JobStarter { param($job) $s = Start-PkProcess -FilePath $job['FilePath'] -Arguments $job['Arguments']; $job['Proc'] = $s['Proc']; $null = Wait-PkProcess -Process $s['Proc'] -TimeoutMs 10000; throw "the starter failed after starting its program" }.GetNewClosure() ` + -JobFinalize { param($job, $pending) $null = Complete-PkProcess -Job $job } +$dxWait = [System.Diagnostics.Stopwatch]::StartNew() +do { + $dxLeft = @(Get-CimInstance Win32_Process -Filter "Name='PING.EXE'" | Where-Object { [string]$_.CommandLine -like ('*-w ' + $rsW + ' 127.0.0.1*') }) + if ($dxLeft.Count -eq 0) { break } + Start-Sleep -Milliseconds 100 +} while ($dxWait.ElapsedMilliseconds -lt 5000) +foreach ($l in $dxLeft) { Stop-Process -Id $l.ProcessId -Force -ErrorAction SilentlyContinue } +Test-Assert ($dx.JobStarterFailedCount -eq 1 -and $dxLeft.Count -eq 0) ("dispatch: a -JobStarter that throws after its program exited still has what the program started ended (" + $dxLeft.Count + " left running, " + $dx.JobStarterFailedCount + " start failure(s))") + # Initialize-ParallelKit reports the kit's version and how it starts programs. $ipHeader = [regex]::Match([System.IO.File]::ReadAllText($kitSource), '(?m)^# Version (\d+\.\d+(?:\.\d+)?)\b').Groups[1].Value $ipError = $null; $ip = $null; $ipAdded = $null diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index e03127c..3783a54 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -169,7 +169,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 = 15; + public const int TypesVersion = 16; // Locked: Register-/Unregister-PkCancellationSource are callable from // worker runspaces, and List is not safe for concurrent writers. @@ -404,13 +404,20 @@ public sealed class PkStreamReadTask : Task private PkStreamReadTask(Buffer buffer) : base(new Func(buffer.Pump), TaskCreationOptions.LongRunning) { _buffer = buffer; } // Harness only: n >= 0 makes the Run after the next n throw, as one whose - // thread can't be created would; -1, the default, is off. + // thread can't be created would; -1, the default, is off. With + // TestFailRunDelayMs above 0, that Run waits that long before throwing, so + // a program that ends at once has exited by then. public static int TestFailRunAfter = -1; + public static int TestFailRunDelayMs = 0; // maxChars: 0 for no cap. public static PkStreamReadTask Run(TextReader reader, int maxChars) { - if (TestFailRunAfter >= 0 && Interlocked.Decrement(ref TestFailRunAfter) < 0) { throw new InvalidOperationException("Harness: a reader thread that can't start (TestFailRunAfter)."); } + if (TestFailRunAfter >= 0 && Interlocked.Decrement(ref TestFailRunAfter) < 0) + { + if (TestFailRunDelayMs > 0) { Thread.Sleep(TestFailRunDelayMs); } + throw new InvalidOperationException("Harness: a reader thread that can't start (TestFailRunAfter)."); + } PkStreamReadTask task = new PkStreamReadTask(new Buffer(reader, maxChars)); task.Start(TaskScheduler.Default); return task; @@ -1085,7 +1092,7 @@ public static class PkChildProcessJob # A session that loaded another version keeps that one's 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 15) { +if ((& { try { [PkState]::TypesVersion } catch { 0 } }) -ne 16) { throw "ParallelKit: this PowerShell session already loaded a different version of the kit, and its compiled parts can't be swapped out. Close this window and start a new one." } @@ -1830,7 +1837,12 @@ function Start-PkProcessCore { } catch { $reason = [string]$_ if ($_.Exception -is [System.Management.Automation.MethodInvocationException] -and $null -ne $_.Exception.InnerException) { $reason = $_.Exception.InnerException.Message } - try { $null = Stop-PkProcessTree -Process $proc } catch { } # best effort: the failed start below is what's reported + # Through its tree job first: that reaches what the program started + # even if it has exited already, which Stop-PkProcessTree passes over. + # The same steps as the dispatcher's start-failure catch. + try { if (-not [PkChildProcessJob]::KillTree($proc)) { $null = Stop-PkProcessTree -Process $proc } } catch { } # best effort: the failed start below is what's reported + try { [PkChildProcessJob]::ReleaseTree($proc) } catch { } # its tree job's handle, now rather than at garbage collection; nothing to report + try { $proc.Dispose() } catch { } # the same, for the process handle # A reader whose task started ends when the pipe closes with the # program; one that didn't start is closed here. if ($null -eq $stdoutTask) { try { $stdout.Dispose() } catch { } } # closing an unread pipe: nothing to report if it fails @@ -2858,8 +2870,12 @@ function Invoke-PkProcessDispatchCore { # starter started before throwing is killed first: nothing else # tracks it. $pkStarting is cleared before the release, so the # teardown can't release the slot again. + # Through its tree job first, which reaches what the program + # started even once it has exited (Stop-PkProcessTree passes + # over that). The same steps as Start-PkProcessCore's rollback. if ($pkJob['Proc'] -is [System.Diagnostics.Process]) { - try { $null = Stop-PkProcessTree -Process $pkJob['Proc'] } catch { } # best effort; the failed start is still reported below + try { if (-not [PkChildProcessJob]::KillTree($pkJob['Proc'])) { $null = Stop-PkProcessTree -Process $pkJob['Proc'] } } catch { } # best effort; the failed start is still reported below + try { [PkChildProcessJob]::ReleaseTree($pkJob['Proc']) } catch { } # its tree job's handle, now rather than at garbage collection try { $pkJob['Proc'].Dispose() } catch { } # the failed start is reported either way } $pkStarting = $null diff --git a/Source/PkChildProcessJob.cs b/Source/PkChildProcessJob.cs index 7e2a4a8..4150445 100644 --- a/Source/PkChildProcessJob.cs +++ b/Source/PkChildProcessJob.cs @@ -162,13 +162,20 @@ public string Keep(bool snapshot) private PkStreamReadTask(Buffer buffer) : base(new Func(buffer.Pump), TaskCreationOptions.LongRunning) { _buffer = buffer; } // Harness only: n >= 0 makes the Run after the next n throw, as one whose - // thread can't be created would; -1, the default, is off. + // thread can't be created would; -1, the default, is off. With + // TestFailRunDelayMs above 0, that Run waits that long before throwing, so + // a program that ends at once has exited by then. public static int TestFailRunAfter = -1; + public static int TestFailRunDelayMs = 0; // maxChars: 0 for no cap. public static PkStreamReadTask Run(TextReader reader, int maxChars) { - if (TestFailRunAfter >= 0 && Interlocked.Decrement(ref TestFailRunAfter) < 0) { throw new InvalidOperationException("Harness: a reader thread that can't start (TestFailRunAfter)."); } + if (TestFailRunAfter >= 0 && Interlocked.Decrement(ref TestFailRunAfter) < 0) + { + if (TestFailRunDelayMs > 0) { Thread.Sleep(TestFailRunDelayMs); } + throw new InvalidOperationException("Harness: a reader thread that can't start (TestFailRunAfter)."); + } PkStreamReadTask task = new PkStreamReadTask(new Buffer(reader, maxChars)); task.Start(TaskScheduler.Default); return task; diff --git a/Source/PkConsoleCtrl.cs b/Source/PkConsoleCtrl.cs index e908bcd..912018d 100644 --- a/Source/PkConsoleCtrl.cs +++ b/Source/PkConsoleCtrl.cs @@ -125,7 +125,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 = 15; + public const int TypesVersion = 16; // Locked: Register-/Unregister-PkCancellationSource are callable from // worker runspaces, and List is not safe for concurrent writers.