diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 000939c..d6ed009 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -4206,6 +4206,104 @@ try { Test-Assert ($null -eq $tlZero) ("0 is still accepted for -TimeoutMs, -StreamTimeoutMs, -AbortTimeoutSeconds, -DrainTimeoutSeconds and -TimeoutSeconds (error: " + $tlZero + ")") Write-Host "" +Write-Host "=== AV: the tree kill with many programs, or a taskkill that hangs ===" -ForegroundColor Cyan +# One taskkill command line for every program hit Windows' 32,767-character +# limit at roughly 2,500-3,000 programs, so taskkill couldn't start and only +# the programs themselves were killed, not their children. And a taskkill +# still running after its wait was left running. These drive the tree kill's +# core through its test parameters: a shorter argument limit, a shorter wait, +# and a stand-in for taskkill that logs its arguments and can hang. +$tkKit = Get-Module ParallelKit +$tkIds = [int[]](1000000..1002999) +$tkLimit = 32000 - (Join-Path $env:SystemRoot 'System32\taskkill.exe').Length +$tkLists = $null +try { $tkLists = & $tkKit Split-PkTaskkillArguments -Ids $tkIds -MaxLength $tkLimit } catch { $tkLists = @() } # a list returned whole: assigned, not wrapped +$tkSeen = @{} +$tkTooLong = 0 +foreach ($line in $tkLists) { + if ($line.Length -gt $tkLimit -or -not $line.StartsWith('/T /F /PID ')) { $tkTooLong++ } + foreach ($m in [regex]::Matches($line, '/PID (\d+)')) { $tkSeen[$m.Groups[1].Value] = 1 + [int]$tkSeen[$m.Groups[1].Value] } +} +$tkOnce = @($tkIds | Where-Object { $tkSeen[[string]$_] -eq 1 }).Count +Test-Assert ($tkLists.Count -ge 2 -and $tkTooLong -eq 0 -and $tkOnce -eq 3000 -and $tkSeen.Count -eq 3000) ("3,000 programs are split across " + $tkLists.Count + " taskkill command lines, each under the limit, every PID exactly once") + +$tkExe = Join-Path $env:TEMP ("pk-faketaskkill-" + [guid]::NewGuid().ToString("N") + ".exe") +$tkSrc = [System.IO.Path]::ChangeExtension($tkExe, '.cs') +[System.IO.File]::WriteAllText($tkSrc, @' +public static class PkFakeTaskkill { + public static int Main(string[] args) { + string log = System.Environment.GetEnvironmentVariable("PK_FAKE_TASKKILL_LOG"); + if (!string.IsNullOrEmpty(log)) { System.IO.File.AppendAllText(log, string.Join(" ", args) + "\n"); } + if (System.Environment.GetEnvironmentVariable("PK_FAKE_TASKKILL_MODE") == "hang") { System.Threading.Thread.Sleep(60000); } + return 1; + } +} +'@) +$csc = $null +try { $csc = Invoke-PkProcessWithTimeout -FilePath $cscExe -Arguments (ConvertTo-PkArgumentString @('/nologo', ('/out:' + $tkExe), $tkSrc)) } catch { Write-Host " csc.exe failed to run: $_" } +[System.IO.File]::Delete($tkSrc) +$compiled = ($null -ne $csc -and $csc.ExitCode -eq 0 -and [System.IO.File]::Exists($tkExe)) +Test-Assert $compiled "the stand-in taskkill compiles" +if ($compiled) { + $tkLog = [System.IO.Path]::ChangeExtension($tkExe, '.log') + $env:PK_FAKE_TASKKILL_LOG = $tkLog + try { + # Five programs, an argument limit that fits two PIDs: several + # taskkill calls, each under the limit. The stand-in fails, so the + # fallback kills the programs. + $tkProcs = @(1..5 | ForEach-Object { (Start-PkProcess -FilePath $pingExe -Arguments '-n 30 127.0.0.1')['Proc'] }) + $null = & $tkKit Stop-PkProcessTreeCore -Process $tkProcs -TaskkillPath $tkExe -MaxArgumentLength 30 + $tkLines = @() + if ([System.IO.File]::Exists($tkLog)) { $tkLines = @([System.IO.File]::ReadAllLines($tkLog) | Where-Object { $_ }) } + $tkLogged = @($tkProcs | Where-Object { $p = $_; @($tkLines | Where-Object { $_ -match ('/PID ' + $p.Id + '(\s|$)') }).Count -eq 1 }).Count + $tkLongest = 0; foreach ($l in $tkLines) { $tkLongest = [Math]::Max($tkLongest, $l.Length) } + $tkDead = @($tkProcs | Where-Object { $_.WaitForExit(5000) }).Count + Test-Assert ($tkLines.Count -ge 3 -and $tkLongest -le 30 -and $tkLogged -eq 5 -and $tkDead -eq 5) ("past the argument limit the PIDs go to several taskkill calls, each under it (" + $tkLines.Count + " calls, longest " + $tkLongest + " chars, " + $tkLogged + " of 5 PIDs passed once, " + $tkDead + " of 5 killed)") + foreach ($p in $tkProcs) { $p.Dispose() } + + # A taskkill that hangs is killed after its wait, and the fallback runs. + $env:PK_FAKE_TASKKILL_MODE = 'hang' + $tkProcs = @(1..2 | ForEach-Object { (Start-PkProcess -FilePath $pingExe -Arguments '-n 30 127.0.0.1')['Proc'] }) + $sw = [System.Diagnostics.Stopwatch]::StartNew() + $null = & $tkKit Stop-PkProcessTreeCore -Process $tkProcs -TaskkillWaitMs 500 -TaskkillPath $tkExe + $sw.Stop() + $tkHung = @(Get-CimInstance Win32_Process -Filter "Name='$([System.IO.Path]::GetFileName($tkExe))'") + $tkDead = @($tkProcs | Where-Object { $_.WaitForExit(5000) }).Count + Test-Assert ($tkHung.Count -eq 0 -and $tkDead -eq 2 -and $sw.Elapsed.TotalSeconds -lt 5) ("a taskkill still running after its wait is killed, and the programs are killed anyway (" + $tkHung.Count + " stand-in(s) left running, " + $tkDead + " of 2 killed, " + [math]::Round($sw.Elapsed.TotalSeconds, 1) + "s)") + foreach ($h in $tkHung) { Stop-Process -Id $h.ProcessId -Force -ErrorAction SilentlyContinue } + foreach ($p in $tkProcs) { $p.Dispose() } + } finally { + Remove-Item Env:PK_FAKE_TASKKILL_LOG, Env:PK_FAKE_TASKKILL_MODE -ErrorAction SilentlyContinue + try { [System.IO.File]::Delete($tkLog) } catch { } # temp file only; best effort + } + # The stand-in can take a moment to let go of its file after it's killed. + for ($t = 0; $t -lt 20 -and [System.IO.File]::Exists($tkExe); $t++) { + try { [System.IO.File]::Delete($tkExe) } catch { Start-Sleep -Milliseconds 100 } # still held by the process just killed: try again + } +} + +# The real taskkill, one PID per call: each call still kills the whole tree. +$tkStarted = @(1..3 | ForEach-Object { Start-PkProcess -FilePath $cmdExe -Arguments '/d /c ping -n 30 127.0.0.1 >nul' }) +$tkPings = @() +foreach ($s in $tkStarted) { + $p = $null + for ($t = 0; $t -lt 80 -and -not $p; $t++) { + $p = Get-CimInstance Win32_Process -Filter ("ParentProcessId=" + $s['Proc'].Id + " AND Name='PING.EXE'") + if (-not $p) { Start-Sleep -Milliseconds 25 } + } + if ($p) { $tkPings += [int]@($p)[0].ProcessId } +} +$tkKilled = & $tkKit Stop-PkProcessTreeCore -Process @($tkStarted | ForEach-Object { $_['Proc'] }) -MaxArgumentLength 22 +$tkLeft = $tkPings +for ($t = 0; $t -lt 30 -and $tkLeft.Count -gt 0; $t++) { + Start-Sleep -Milliseconds 100 + $tkLeft = @($tkLeft | Where-Object { Get-Process -Id $_ -ErrorAction SilentlyContinue }) +} +foreach ($id in $tkLeft) { Stop-Process -Id $id -Force -ErrorAction SilentlyContinue } +foreach ($s in $tkStarted) { $null = Complete-PkProcess $s -Dispose } +Test-Assert ($tkKilled -and $tkPings.Count -eq 3 -and $tkLeft.Count -eq 0) ("with one PID per taskkill call, every program's children are still killed (" + $tkPings.Count + " children seen, " + $tkLeft.Count + " left running)") +Write-Host "" + Set-PkMessageHandler -Handler $null Reset-PkAbortState diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 546a51c..816c6e3 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -1378,9 +1378,10 @@ function Stop-PkProcessTree { # .SYNOPSIS # Kills one or more programs and every program they started. # .DESCRIPTION - # Uses one taskkill /T call for all of them, so none is left running and - # holding a program's output open; falls back to killing each program - # directly. + # Uses taskkill /T, in as few calls as Windows' command-line limit allows, + # so none is left running and holding a program's output open. If taskkill + # can't start, fails, or is still running after 10 seconds (it's killed + # then), each program is killed directly. # .PARAMETER Process # The program(s), such as the Proc that Start-PkProcess returns. # .OUTPUTS @@ -1392,31 +1393,56 @@ function Stop-PkProcessTree { [AllowEmptyCollection()] [System.Diagnostics.Process[]]$Process ) + return Stop-PkProcessTreeCore -Process $Process +} + +function Stop-PkProcessTreeCore { + # Stop-PkProcessTree's body. The other parameters are for the harness: a + # stand-in for taskkill, a shorter wait for it, and a shorter limit on its + # argument list. + param( + [AllowEmptyCollection()] + [System.Diagnostics.Process[]]$Process, + [string]$TaskkillPath = (Join-Path $env:SystemRoot 'System32\taskkill.exe'), + [int]$TaskkillWaitMs = 10000, + [int]$MaxArgumentLength = 0 + ) $alive = [System.Collections.Generic.List[System.Diagnostics.Process]]::new() # A disposed Process reads $null for HasExited and Id (no throw), and an # empty /PID fails taskkill for the whole list, so it's left out. foreach ($p in $Process) { if ($null -ne $p -and $p.HasExited -eq $false -and $null -ne $p.Id) { $alive.Add($p) } } if ($alive.Count -eq 0) { return $false } $killed = $false - $pidArgs = foreach ($p in $alive) { '/PID ' + $p.Id } - $psi = [System.Diagnostics.ProcessStartInfo]::new((Join-Path $env:SystemRoot 'System32\taskkill.exe'), ('/T /F ' + ($pidArgs -join ' '))) - $psi.UseShellExecute = $false - $psi.CreateNoWindow = $true - $psi.RedirectStandardOutput = $true - $psi.RedirectStandardError = $true - try { - $taskkill = [System.Diagnostics.Process]::Start($psi) + # One command line for every PID passes Windows' 32,767-character limit at + # roughly 2,500-3,000 programs, and then taskkill can't start at all: so as + # many taskkill calls as the limit needs. + if ($MaxArgumentLength -le 0) { $MaxArgumentLength = 32000 - $TaskkillPath.Length } + $ids = [int[]]@(foreach ($p in $alive) { $p.Id }) + foreach ($taskkillArgs in (Split-PkTaskkillArguments -Ids $ids -MaxLength $MaxArgumentLength)) { + $psi = [System.Diagnostics.ProcessStartInfo]::new($TaskkillPath, $taskkillArgs) + $psi.UseShellExecute = $false + $psi.CreateNoWindow = $true + $psi.RedirectStandardOutput = $true + $psi.RedirectStandardError = $true try { - # Read both pipes while taskkill runs: it prints a line per - # process it kills, and on a large kill a full pipe blocks it. - $taskkillOut = $taskkill.StandardOutput.ReadToEndAsync() - $taskkillErr = $taskkill.StandardError.ReadToEndAsync() - if ($taskkill.WaitForExit(10000)) { - $killed = ($taskkill.ExitCode -eq 0) - try { $null = [System.Threading.Tasks.Task]::WaitAll(@($taskkillOut, $taskkillErr), 2000) } catch { } # the reads only keep the pipes drained; their text isn't used - } - } finally { $taskkill.Dispose() } - } catch { } # taskkill missing or blocked: the fallback below still kills each process itself + $taskkill = [System.Diagnostics.Process]::Start($psi) + try { + # Read both pipes while taskkill runs: it prints a line per + # process it kills, and on a large kill a full pipe blocks it. + $taskkillOut = $taskkill.StandardOutput.ReadToEndAsync() + $taskkillErr = $taskkill.StandardError.ReadToEndAsync() + if ($taskkill.WaitForExit($TaskkillWaitMs)) { + if ($taskkill.ExitCode -eq 0) { $killed = $true } + try { $null = [System.Threading.Tasks.Task]::WaitAll(@($taskkillOut, $taskkillErr), 2000) } catch { } # the reads only keep the pipes drained; their text isn't used + } else { + # Still running after its wait (hung, or held up by security + # software): killed, so it isn't left running outside the + # Job Object. The fallback below kills the programs. + try { $taskkill.Kill(); $null = $taskkill.WaitForExit(2000) } catch { } # it exited between the wait and the kill + } + } finally { $taskkill.Dispose() } + } catch { } # taskkill missing or blocked: the fallback below still kills each process itself + } # taskkill fails if any process in the trees couldn't be killed, even when # it killed the program: one already gone (a child in another listed tree, # or a `cmd /c` that ended once taskkill killed its child, which it does @@ -1439,6 +1465,28 @@ function Stop-PkProcessTree { return $killed } +function Split-PkTaskkillArguments { + # taskkill argument lists ('/T /F /PID 1 /PID 2 ...') for these PIDs, as + # few as fit, each at most MaxLength characters (a single PID that doesn't + # fit still gets a list of its own). Returns a list of strings. + param([int[]]$Ids, [int]$MaxLength) + $lists = [System.Collections.Generic.List[string]]::new() + $current = [System.Text.StringBuilder]::new('/T /F') + $count = 0 + foreach ($id in $Ids) { + $part = ' /PID ' + $id + if ($count -gt 0 -and $current.Length + $part.Length -gt $MaxLength) { + $lists.Add($current.ToString()) + $null = $current.Clear().Append('/T /F') + $count = 0 + } + $null = $current.Append($part) + $count++ + } + if ($count -gt 0) { $lists.Add($current.ToString()) } + return ,$lists +} + function Stop-PkJobProcesses { # The dispatcher's force-stop: every running job's tree in one # Stop-PkProcessTree call. A custom starter's .Proc may not be a Process; @@ -2580,7 +2628,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-PkJobProcesses', 'Resolve-PkEncoding', + return @('Write-PkMessage', 'Test-PkAbortSignal', 'Test-PkCancelRequested', 'Initialize-PkThreadPool', 'Stop-PkProcessTree', 'Stop-PkProcessTreeCore', 'Split-PkTaskkillArguments', 'Stop-PkJobProcesses', '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 79d19e3..516134e 100644 --- a/README.md +++ b/README.md @@ -278,7 +278,7 @@ To leave any callback early, use `return`. PowerShell sends a `continue` or `bre | `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. | | `Complete-PkProcess -Job` | Collect exit code and output from a finished one (`-Job` is what `Start-PkProcess` returned). Same result as `Invoke-PkProcessWithTimeout`. | -| `Stop-PkProcessTree -Process` | Kill one or more programs and every program they started, in one `taskkill` call. For one program, returns `$true` if it killed it (even if part of its tree couldn't be) and `$false` if it had already exited. | +| `Stop-PkProcessTree -Process` | Kill one or more programs and every program they started, with `taskkill` (as few calls as Windows' command-line limit allows). For one program, returns `$true` if it killed it (even if part of its tree couldn't be) and `$false` if it had already exited. | `Invoke-PkProcessWithTimeout` and `Start-PkProcess` also take `-WorkingDirectory`.