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
35 changes: 34 additions & 1 deletion IcingaForWindows.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,21 @@ function New-ModuleBaseEnvironment()
'Queue' = (New-Object System.Collections.Concurrent.BlockingCollection[PSObject] -ArgumentList (New-Object System.Collections.Concurrent.ConcurrentQueue[PSObject]));
'Level' = 'Info';
};
'PerformanceCounter' = [PSCustomObject]@{
# Thread-safe transport only. The counter manager class is created lazily
# by the daemon once the kernel (and thus the class type) is dot-sourced.
'RequestQueue' = (New-Object System.Collections.Concurrent.BlockingCollection[PSObject] -ArgumentList (New-Object System.Collections.Concurrent.ConcurrentQueue[PSObject]));
'PendingRequests' = (New-Object 'System.Collections.Concurrent.ConcurrentDictionary[string, System.Collections.Concurrent.BlockingCollection[PSObject]]');
'Registered' = (New-Object 'System.Collections.Concurrent.ConcurrentDictionary[string, datetime]');
'Manager' = $null;
'Heartbeat' = $null;
'LastRefresh' = $null;
'Config' = [PSCustomObject]@{
'WarmupMilliseconds' = 250;
'RefreshIntervalMs' = 1000;
'EvictionMinutes' = 60;
};
};
'External' = $null;
'ReturnCodes' = $null;
}
Expand Down Expand Up @@ -388,6 +403,7 @@ function Use-IcingaForWindows()
New-Thread -Command 'Start-LoggingDaemon' -KeepAlive -WaitForJobs -Start;
New-Thread -Command 'Start-ModuleGarbageCollector' -KeepAlive -Start;
New-Thread -Command 'Start-ThreadHouseKeeper' -Start;
New-Thread -Command 'Start-IcingaPerformanceCounterDaemon' -KeepAlive -WaitForJobs -Start;
New-Thread -Command 'Start-RestApiDaemon' -Start;
New-Thread -Command 'Start-ModuleWebSocketDaemon' -Start;
New-Thread -Command 'Start-IcingaAgent' -Start;
Expand Down Expand Up @@ -430,7 +446,24 @@ All custom declarations must be added above this comment block.
#>
New-ModuleBaseEnvironment;

[string]$KernelPath = Join-Path -Path (Get-ModuleRootDirectory) -ChildPath (Join-Path -Path 'lib' -ChildPath 'IcingaForWindows.Kernel.ps1');
[string]$ClassesPath = Join-Path -Path (Get-ModuleRootDirectory) -ChildPath (Join-Path -Path 'lib' -ChildPath 'IcingaForWindows.Classes.ps1');
[string]$KernelPath = Join-Path -Path (Get-ModuleRootDirectory) -ChildPath (Join-Path -Path 'lib' -ChildPath 'IcingaForWindows.Kernel.ps1');

if (Test-Path -Path $ClassesPath) {
# Windows PowerShell 5.1 reuses the compiled class types when the same class
# content is loaded again by a thread runspace and binds their methods to the
# runspace that loaded it last. Class methods called on the main thread then run
# inside a busy daemon runspace, which hangs or corrupts the call. A unique copy
# of the class content per runspace gives every runspace its own class types.
# In PowerShell Core (PS 7+), class method dispatch is runspace-independent.
if ($PSVersionTable.PSEdition -eq 'Desktop') {
. ([ScriptBlock]::Create([System.IO.File]::ReadAllText($ClassesPath) + [System.Environment]::NewLine + '# ' + [System.Guid]::NewGuid().ToString()));
} else {
. $ClassesPath;
}
} else {
Write-Warning "Icinga for Windows classes file not found at '$ClassesPath'. Run Build-ModuleProject first.";
}

if (Test-Path -Path $KernelPath) {
. $KernelPath;
Expand Down
99 changes: 99 additions & 0 deletions Tests/ClassLiteral.Tests.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1';
if (-not (Get-Module -Name 'IcingaForWindows')) {
Import-Module -Name $ModulePath -Force -Global;
}

Describe 'Class literals in functions' {
BeforeAll {
# Every runspace shares the compiled kernel, so a class literal inside a
# function resolves to the class type of the main runspace. In a thread on
# Windows PowerShell 5.1 every method of such an object waits for the main
# runspace, and type checks no longer match the thread's own objects.
# Functions therefore use New-IcingaPlugin, Test-IcingaError or a runtime
# lookup ('Name' -as [type]); only the class files themselves and enums may
# use literals.
$script:SourceRoot = [System.IO.Path]::GetFullPath((Join-Path -Path $PSScriptRoot -ChildPath '..\src'));
[string[]]$script:ClassNames = @();

foreach ($File in (Get-ChildItem -Path (Join-Path -Path $script:SourceRoot -ChildPath 'Classes') -Filter '*.ps1' -Recurse)) {
$Ast = [System.Management.Automation.Language.Parser]::ParseFile($File.FullName, [ref]$null, [ref]$null);

foreach ($Definition in $Ast.FindAll({ param ($Node) $Node -is [System.Management.Automation.Language.TypeDefinitionAst] -and $Node.IsClass }, $true)) {
$script:ClassNames += $Definition.Name;
}
}
}

It 'reads the class names from the class files' {
$script:ClassNames | Should -Contain 'IcingaPerformanceCounter';
$script:ClassNames | Should -Contain 'IcingaUnit';
}

It 'finds no class literal in a function outside src/Classes' {
[string[]]$Violations = @();
[string[]]$Skipped = @(
(Join-Path -Path $script:SourceRoot -ChildPath 'Classes'),
(Join-Path -Path $script:SourceRoot -ChildPath 'analyze')
);

foreach ($File in (Get-ChildItem -Path $script:SourceRoot -Filter '*.ps1' -Recurse)) {
[bool]$Skip = $false;

foreach ($Folder in $Skipped) {
if ($File.FullName.StartsWith($Folder + [System.IO.Path]::DirectorySeparatorChar, [System.StringComparison]::OrdinalIgnoreCase)) {
$Skip = $true;
}
}

if ($Skip) {
continue;
}

$Ast = [System.Management.Automation.Language.Parser]::ParseFile($File.FullName, [ref]$null, [ref]$null);
$Nodes = $Ast.FindAll({ param ($Node) $Node -is [System.Management.Automation.Language.TypeExpressionAst] -or $Node -is [System.Management.Automation.Language.TypeConstraintAst] }, $true);

foreach ($Node in $Nodes) {
$TypeName = $Node.TypeName;

while ($TypeName -is [System.Management.Automation.Language.ArrayTypeName]) {
$TypeName = $TypeName.ElementType;
}

if ($script:ClassNames -contains $TypeName.Name) {
$Violations += ('{0}:{1} [{2}]' -f $File.FullName.Substring($script:SourceRoot.Length + 1), $Node.Extent.StartLineNumber, $TypeName.Name);
}
}
}

$Violations | Should -BeNullOrEmpty -Because ("functions must not use class literals:`n" + ($Violations -join "`n"));
}

It 'finds no PowerShell class literal inside IcingaPerformanceCounter.ps1' {
[string]$PerfClassFile = Join-Path -Path $script:SourceRoot -ChildPath 'Classes\Icinga\IcingaPerformanceCounter.ps1';
[string[]]$Violations = @();
$Ast = [System.Management.Automation.Language.Parser]::ParseFile($PerfClassFile, [ref]$null, [ref]$null);
$Nodes = $Ast.FindAll({ param ($Node) $Node -is [System.Management.Automation.Language.TypeExpressionAst] -or $Node -is [System.Management.Automation.Language.TypeConstraintAst] }, $true);

foreach ($Node in $Nodes) {
$TypeName = $Node.TypeName;

while ($TypeName -is [System.Management.Automation.Language.ArrayTypeName]) {
$TypeName = $TypeName.ElementType;
}

if ($script:ClassNames -contains $TypeName.Name) {
$Violations += ('IcingaPerformanceCounter.ps1:{0} [{1}]' -f $Node.Extent.StartLineNumber, $TypeName.Name);
}

if ($TypeName -is [System.Management.Automation.Language.GenericTypeName]) {
foreach ($GenArg in $TypeName.GenericArguments) {
if ($script:ClassNames -contains $GenArg.Name) {
$Violations += ('IcingaPerformanceCounter.ps1:{0} [{1}]' -f $Node.Extent.StartLineNumber, $GenArg.Name);
}
}
}
}

$Violations | Should -BeNullOrEmpty -Because ("IcingaPerformanceCounter.ps1 must use runtime lookups ('...' -as [type]) for PS 5.1 runspace isolation:`n" + ($Violations -join "`n"));
}
}
Loading
Loading