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
130 changes: 129 additions & 1 deletion ParallelKit.Harness.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -3810,7 +3810,7 @@ function Get-HarnessUnguardedCallbacks {
# this list. Invoke-PkRun's `& $ScriptBlock` is the run itself, not called
# from a loop. Returns @{ Calls; Problems }.
param([string]$Source)
$internal = @('$pkNewBatchResult', '$pkGetStartFailureCause', '$pkGetJobTimeLimit', '$pkGetJobMaxOutputChars', '$pkGetJobSwitch', '$pkReportStartFailure', '$pkStartProcessCore', '$pkWriteCallbackLoopWarning')
$internal = @('$pkNewBatchResult', '$pkGetStartFailureCause', '$pkGetJobTimeLimit', '$pkGetJobMaxOutputChars', '$pkGetJobSwitch', '$pkStopExitedJobTree', '$pkReportStartFailure', '$pkStartProcessCore', '$pkWriteCallbackLoopWarning')
$problems = [System.Collections.Generic.List[string]]::new()
$tokens = $null; $errors = $null
$ast = [System.Management.Automation.Language.Parser]::ParseInput($Source, [ref]$tokens, [ref]$errors)
Expand Down Expand Up @@ -5445,6 +5445,134 @@ Reset-Harness
Write-Host ""
}

# ==============================================================================
if (Test-HarnessSection 'BJ' "-KillTreeOnExit: what a program left running goes when it exits") {
# Each program leaves a ping behind (-w 4328, so this section can find and
# kill its own) and exits with code 5 about a second in: by then it's in its
# tree job on both start paths. The ping holds the program's output, except
# where the test says it holds none.
Reset-Harness
function Get-HarnessLeftPingCount { return @(Get-CimInstance Win32_Process -Filter "Name='PING.EXE' AND CommandLine LIKE '%-w 4328 %'").Count }
function Stop-HarnessLeftPings { foreach ($p in @(Get-CimInstance Win32_Process -Filter "Name='PING.EXE' AND CommandLine LIKE '%-w 4328 %'")) { Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue } }
$bjHeld = '/d /c ping -n 2 127.0.0.1 >nul& echo before& start /b ping -n 30 -w 4328 127.0.0.1 >nul& exit 5'
# A start /b child holds the pipes whatever it's redirected to; one started
# through the shell doesn't get them.
$bjLoose = '-NoProfile -Command "Start-Process ping.exe -WindowStyle Hidden -ArgumentList ''-n 30 -w 4328 127.0.0.1''; Start-Sleep -Milliseconds 300; ''before''; exit 5"'
function Test-HarnessKillTree {
# Runs $Run, which returns a result with ExitCode, Stdout and StreamTimedOut
# (or $null), and checks it: the ping gone and the output read to its end at
# once, or ($Left) the ping left running.
param([string]$Name, [scriptblock]$Run, [switch]$Left, [switch]$Loose)
$problem = ''; $r = $null
$sw = [System.Diagnostics.Stopwatch]::StartNew()
try { $r = & $Run } catch { $problem = ', error: ' + $_ }
$sw.Stop()
Start-Sleep -Milliseconds 300
$count = Get-HarnessLeftPingCount
Stop-HarnessLeftPings
$code = $null; $out = $null; $timedOut = $null
if ($null -ne $r) { $code = $r.ExitCode; $out = ([string]$r.Stdout).Trim(); $timedOut = $r.StreamTimedOut }
$secs = [math]::Round($sw.Elapsed.TotalSeconds, 1)
$seen = ' (pings left ' + $count + ', StreamTimedOut=' + $timedOut + ', exit ' + $code + ", output '" + $out + "', " + $secs + ' s' + $problem + ')'
if ($Left) {
Test-Assert ($count -eq 1 -and $code -eq 5 -and $out -eq 'before' -and $timedOut -eq (-not $Loose)) ($Name + ': what it left keeps running' + $seen)
} else {
Test-Assert ($count -eq 0 -and $code -eq 5 -and $out -eq 'before' -and $timedOut -eq $false -and $secs -lt 6) ($Name + ': what it left is killed, and its output ends at once' + $seen)
}
}
function Invoke-HarnessTreeBatch([hashtable]$Extra, [hashtable]$Key, [string]$Arguments) {
$command = @{ FilePath = $cmdExe; Arguments = $Arguments }
foreach ($k in $Key.Keys) { $command[$k] = $Key[$k] }
return (Invoke-PkProcessBatch -Commands @($command) @Extra).Results[0]
}
function Invoke-HarnessTreeDispatch([hashtable]$Extra, [hashtable]$Key, [string]$Arguments) {
$feed = @{ Given = $false }; $got = @{ Result = $null }; $job = @{ FilePath = $cmdExe; Arguments = $Arguments } + $Key
$null = Invoke-PkProcessDispatch -MaxConcurrent 1 @Extra `
-GroupProvider { if ($feed.Given) { return $null }; $feed.Given = $true; return 'g' }.GetNewClosure() `
-JobBuilder { param($g) return @($job) }.GetNewClosure() `
-JobFinalize { param($j, $q) $got.Result = Complete-PkProcess $j }.GetNewClosure()
return $got.Result
}
try {
foreach ($bjPath in 'CreatedInJob', 'Process.Start') {
[PkChildProcessJob]::TestUseProcessStart = ($bjPath -eq 'Process.Start')
Test-HarnessKillTree ('Invoke-PkProcessWithTimeout, ' + $bjPath) { Invoke-PkProcessWithTimeout -FilePath $cmdExe -Arguments $bjHeld -KillTreeOnExit }
Test-HarnessKillTree ('batch, ' + $bjPath) { Invoke-HarnessTreeBatch @{ KillTreeOnExit = $true } @{} $bjHeld }
Test-HarnessKillTree ('dispatcher, ' + $bjPath) { Invoke-HarnessTreeDispatch @{ KillTreeOnExit = $true } @{} $bjHeld }
}
[PkChildProcessJob]::TestUseProcessStart = $false

# Not only when the output is held.
Test-HarnessKillTree 'a leftover that holds no output, one program' { Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments $bjLoose -KillTreeOnExit }
Test-HarnessKillTree 'a leftover that holds no output, batch' { Invoke-HarnessTreeBatch @{ KillTreeOnExit = $true } @{ FilePath = $selfExe } $bjLoose }

# A command's own key, both ways, and off by default.
Test-HarnessKillTree 'batch key' { Invoke-HarnessTreeBatch @{} @{ KillTreeOnExit = $true } $bjHeld }
Test-HarnessKillTree 'dispatcher key' { Invoke-HarnessTreeDispatch @{} @{ KillTreeOnExit = $true } $bjHeld }
Test-HarnessKillTree 'batch, key $false' { Invoke-HarnessTreeBatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{ KillTreeOnExit = $false } $bjHeld } -Left
Test-HarnessKillTree 'dispatcher, key $false' { Invoke-HarnessTreeDispatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{ KillTreeOnExit = $false } $bjHeld } -Left
Test-HarnessKillTree 'batch, no switch' { Invoke-HarnessTreeBatch @{ StreamTimeoutMs = 500 } @{} $bjHeld } -Left
Test-HarnessKillTree 'one program, no switch' { Invoke-PkProcessWithTimeout -FilePath $selfExe -Arguments $bjLoose } -Left -Loose
$bjBad = $null
try { $bjBad = (Invoke-HarnessTreeBatch @{} @{ KillTreeOnExit = 'maybe' } '/d /c exit 0').StartError } catch { $bjBad = [string]$_ }
Test-Assert ([string]$bjBad -like '*KillTreeOnExit must be*maybe*') ("a bad KillTreeOnExit key is that command's StartError (" + $bjBad + ")")
$bjFeed = @{ Given = $false }; $bjStarted = @{ Count = 0 }; $bjDispatch = $null
$script:messages.Clear()
$bjDispatch = Invoke-PkProcessDispatch -MaxConcurrent 1 `
-GroupProvider { if ($bjFeed.Given) { return $null }; $bjFeed.Given = $true; return 'g' }.GetNewClosure() `
-JobBuilder { param($g) return @(@{ FilePath = $cmdExe; Arguments = '/d /c exit 0'; KillTreeOnExit = 'maybe' }) }.GetNewClosure() `
-JobStarter { param($job) $bjStarted.Count++; $s = Start-PkProcess -FilePath $job['FilePath'] -Arguments $job['Arguments']; $job['Proc'] = $s.Proc; return $job }.GetNewClosure() `
-JobFinalize { param($j, $q) }
Test-Assert ($bjDispatch.JobStarterFailedCount -eq 1 -and $bjStarted.Count -eq 0 -and @($script:messages | Where-Object { $_.Message -like "*a job couldn't start: KillTreeOnExit must be*" }).Count -eq 1) ("a bad key on a dispatcher job is refused before its starter runs (failed " + $bjDispatch.JobStarterFailedCount + ", starter calls " + $bjStarted.Count + ")")

# A custom starter's program, and a custom poll: the kill is
# Complete-PkProcess's then.
$bjStarter = { param($job) $s = Start-PkProcess -FilePath $job['FilePath'] -Arguments $job['Arguments']; foreach ($k in 'Proc', 'StdoutTask', 'StderrTask', 'Stopwatch') { $job[$k] = $s[$k] }; return $job }
Test-HarnessKillTree 'a custom starter' { Invoke-HarnessTreeDispatch @{ KillTreeOnExit = $true; JobStarter = $bjStarter } @{} $bjHeld }
Test-HarnessKillTree 'a custom poll' { Invoke-HarnessTreeDispatch @{ KillTreeOnExit = $true; JobPollCompleted = { param($j) return $j['Proc'].HasExited } } @{} $bjHeld }

# A program without a tree job is left alone, with no warning.
Reset-Harness
[PkChildProcessJob]::TestNoTreeJob = $true
try { Test-HarnessKillTree 'no tree job' { Invoke-HarnessTreeBatch @{ KillTreeOnExit = $true; StreamTimeoutMs = 500 } @{} $bjHeld } -Left } finally { [PkChildProcessJob]::TestNoTreeJob = $false }
Test-Assert ($script:messages.Count -eq 0) ("and nothing is said about it (" + $script:messages.Count + " message(s))")

# 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
$bjLeftAt = @{ Count = -1 }
try {
$null = Invoke-HarnessTreeDispatch @{ KillTreeOnExit = $true; AbortTimeoutSeconds = 1; JobPollCompleted = {
param($j)
if ($j['Proc'].HasExited -and $bjLeftAt.Count -lt 0) { $bjLeftAt.Count = Get-HarnessLeftPingCount; Request-PkAbort }
return $false
}.GetNewClosure() } @{} $bjHeld
} catch { Write-Host (" " + $_) }
Reset-PkAbortState
Start-Sleep -Milliseconds 300
$bjNow = Get-HarnessLeftPingCount
Test-Assert ($bjLeftAt.Count -eq 1 -and $bjNow -eq 0) ("a force-stop takes what an exited program left too (pings left before " + $bjLeftAt.Count + ", after " + $bjNow + ")")
Stop-HarnessLeftPings

# Inside a worker.
Reset-Harness
$bjWorker = [System.Collections.Generic.List[object]]::new()
$bjOut = Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @{ Cmd = $cmdExe; Line = $bjHeld } -ResultHandler { param($r) $bjWorker.Add($r) }.GetNewClosure() -WorkerScript {
param([string]$Cmd, [string]$Line)
$one = Invoke-PkProcessWithTimeout -FilePath $Cmd -Arguments $Line -KillTreeOnExit
$batch = (Invoke-PkProcessBatch -Commands @(@{ FilePath = $Cmd; Arguments = $Line }) -KillTreeOnExit).Results[0]
return ([string]$one.StreamTimedOut + ' ' + $batch.StreamTimedOut)
}
$bjNow = Get-HarnessLeftPingCount
Test-Assert ($bjOut.CrashedCount -eq 0 -and $bjWorker.Count -eq 1 -and $bjWorker[0] -eq 'False False' -and $bjNow -eq 0) ("it works inside a worker (crashed " + $bjOut.CrashedCount + ", StreamTimedOut " + ($bjWorker -join ',') + ", pings left " + $bjNow + ")")
} finally {
[PkChildProcessJob]::TestUseProcessStart = $false
Stop-HarnessLeftPings
Reset-Harness
}
Write-Host ""
}

Set-PkMessageHandler -Handler $null
Reset-PkAbortState

Expand Down
Loading
Loading