diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index d8107ec..a0cdcbd 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -5573,6 +5573,56 @@ try { Write-Host "" } +# ============================================================================== +if (Test-HarnessSection 'BK' "the worker-safety check looks a module up once") { +# Whether a worker can load the module a command comes from is asked of +# Get-Module -ListAvailable, which searches all of PSModulePath on 5.1. Counted +# with a stand-in Get-Module inside the kit, and two modules of the harness's +# own: one on PSModulePath, one imported by path from elsewhere. +Reset-Harness +$bkRoot = Join-Path $env:TEMP ("pk-bk-" + [guid]::NewGuid().ToString("N")) +$bkTag = [guid]::NewGuid().ToString("N").Substring(0, 8) +foreach ($bkKind in 'On', 'Off') { + $bkDir = Join-Path $bkRoot ($bkKind + '\PkBk' + $bkKind + $bkTag) + $null = [System.IO.Directory]::CreateDirectory($bkDir) + [System.IO.File]::WriteAllText((Join-Path $bkDir ('PkBk' + $bkKind + $bkTag + '.psm1')), ('function Get-PkBk' + $bkKind + $bkTag + ' { 1 }')) +} +$bkOldPath = $env:PSModulePath +$bkKit = Get-Module ParallelKit +$bkLookups = [System.Collections.Generic.List[string]]::new() +& $bkKit { param($log) Set-Item -Path 'Function:script:Get-Module' -Value { $log.Add(($args -join ' ')); Microsoft.PowerShell.Core\Get-Module @args }.GetNewClosure() } $bkLookups +try { + $env:PSModulePath = (Join-Path $bkRoot 'On') + ';' + $bkOldPath + Import-Module ('PkBkOn' + $bkTag) + Import-Module (Join-Path $bkRoot ('Off\PkBkOff' + $bkTag + '\PkBkOff' + $bkTag + '.psm1')) + $bkOnWorker = [scriptblock]::Create('param($Id) Get-PkBkOn' + $bkTag) + $bkOffWorker = [scriptblock]::Create('param($Id) Get-PkBkOff' + $bkTag) + + $bkFindings = foreach ($i in 1..3) { (Test-PkWorkerSafety -WorkerScript $bkOnWorker).Count } + $bkFirst = @($bkLookups | Where-Object { $_ -like '*-ListAvailable*' }).Count + Test-Assert (($bkFindings -join ',') -eq '0,0,0' -and $bkFirst -eq 1) ("three checks of a worker using one module look it up once (findings " + ($bkFindings -join ',') + ", lookups " + $bkFirst + ")") + $bkRun = foreach ($i in 1..2) { (Invoke-PkRunspaceJobs -MaxParallel 1 -JobParams @{ Id = 1 } -WorkerScript $bkOnWorker).CrashedCount } + $bkSecond = @($bkLookups | Where-Object { $_ -like '*-ListAvailable*' }).Count + Test-Assert (($bkRun -join ',') -eq '0,0' -and $bkSecond -eq 1) ("and so do the runs after them (crashes " + ($bkRun -join ',') + ", lookups " + $bkSecond + ")") + + # A module that isn't found is remembered too, until PSModulePath changes: + # the message says to put the module there. + $bkLookups.Clear() + $bkFindings = foreach ($i in 1..2) { $bkFound = Test-PkWorkerSafety -WorkerScript $bkOffWorker; [string]$bkFound.Count + $bkFound[0].Rule } + $bkFirst = @($bkLookups | Where-Object { $_ -like '*-ListAvailable*' }).Count + Test-Assert (($bkFindings -join ',') -eq '1MissingFunction,1MissingFunction' -and $bkFirst -eq 1) ("a module a worker can't load is still found out, and looked up once (" + ($bkFindings -join ',') + ", lookups " + $bkFirst + ")") + $env:PSModulePath = (Join-Path $bkRoot 'Off') + ';' + $env:PSModulePath + $bkFindings = (Test-PkWorkerSafety -WorkerScript $bkOffWorker).Count + Test-Assert ($bkFindings -eq 0) ("a module put on PSModulePath after that is looked up again (findings " + $bkFindings + ")") +} finally { + $env:PSModulePath = $bkOldPath + & $bkKit { Remove-Item -Path 'Function:Get-Module' } + Remove-Module ('PkBkOn' + $bkTag), ('PkBkOff' + $bkTag) -ErrorAction SilentlyContinue + [System.IO.Directory]::Delete($bkRoot, $true) +} +Write-Host "" +} + Set-PkMessageHandler -Handler $null Reset-PkAbortState diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 9202965..904ac1b 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -174,6 +174,11 @@ public static class PkState public static bool RemoveSource(CancellationTokenSource cts) { lock (_sourcesLock) { return _sources.Remove(cts); } } public static CancellationTokenSource[] SnapshotSources() { lock (_sourcesLock) { return _sources.ToArray(); } } public static int SourceCount { get { lock (_sourcesLock) { return _sources.Count; } } } + + // Get-PkCommandKind's answers for this session: whether Get-Module finds a + // module by name, under "|". + public static readonly System.Collections.Concurrent.ConcurrentDictionary ModuleFound = + new System.Collections.Concurrent.ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); } '@ -Language CSharp } @@ -3966,8 +3971,18 @@ function Get-PkCommandKind { if ($Fn.ModuleName -eq 'ParallelKit') { return 'Function' } # A module function (Get-FileHash, say) autoloads in a worker like a # cmdlet does - but only if the module can be found by name. One imported - # by path from elsewhere can't. - if ($null -ne (Get-Module -ListAvailable -Name $Fn.ModuleName -ErrorAction SilentlyContinue | Select-Object -First 1)) { return 'Other' } + # by path from elsewhere can't. Remembered for the session: on 5.1 each + # lookup searches all of PSModulePath (51 ms with 154 modules on it), for + # every Invoke-PkRunspaceJobs call. So a module installed mid-session is + # missed until a new window, but one put on PSModulePath, as the finding + # suggests, isn't: that's part of the key. + $key = $env:PSModulePath + '|' + $Fn.ModuleName + $found = $false + if (-not [PkState]::ModuleFound.TryGetValue($key, [ref]$found)) { + $found = ($null -ne (Get-Module -ListAvailable -Name $Fn.ModuleName -ErrorAction SilentlyContinue | Select-Object -First 1)) + [PkState]::ModuleFound[$key] = $found + } + if ($found) { return 'Other' } return 'UnloadableModuleFunction' } diff --git a/README.md b/README.md index 0abe499..4456982 100644 --- a/README.md +++ b/README.md @@ -378,7 +378,7 @@ Each worker runs in its own runspace: a separate PowerShell session inside the s - Each job hashtable's keys become the worker's parameters. The worker's `param()` block must declare every key, and every job must supply each parameter it makes `[Parameter(Mandatory)]` (`CancelToken` aside, which is filled in). Either mistake is an error; with a fixed `-JobParams` list it's caught before any worker starts, and a `-NextJobProvider` job is checked as it arrives. A worker with parameter sets isn't checked for mandatory ones, since what it needs depends on the set. - If the worker declares a `$CancelToken` parameter, it gets the run's cancellation token. - `-JobParams` takes a list or array of job hashtables. A single hashtable works too, so a list that happens to hold one job is fine. -- A worker runspace starts empty. Name every one of your functions it calls in `-SharedFunctionNames`. The kit's own worker functions are always there, and cmdlets and functions from installed modules load on their own. A module you imported by path isn't installed, so list its functions too (or put it on `$env:PSModulePath`). +- A worker runspace starts empty. Name every one of your functions it calls in `-SharedFunctionNames`. The kit's own worker functions are always there, and cmdlets and functions from installed modules load on their own. A module you imported by path isn't installed, so list its functions too (or put it on `$env:PSModulePath`). The kit looks each module up once per session, so one it didn't find and you then install is only seen in a new window. - Each job starts in your current location (the real folder, if you're on a `New-PSDrive` drive), in a fresh scope. A folder change or a variable one job makes, preference variables like `$ErrorActionPreference` included, doesn't carry over to the next job. Relative paths in .NET calls such as `[System.IO.File]::ReadAllText('x.txt')` still go by the process's working directory, as they do outside workers, so give .NET full paths. - `-MaxParallel` has no default; you choose it. `-DrainTimeoutSeconds` (how long Ctrl+C waits for running workers) defaults to 60. The process engines' names, `-MaxConcurrent` and `-AbortTimeoutSeconds`, work here too.