diff --git a/IcingaForWindows.psm1 b/IcingaForWindows.psm1 index 9a86e2b..62fc3ae 100644 --- a/IcingaForWindows.psm1 +++ b/IcingaForWindows.psm1 @@ -103,7 +103,7 @@ function New-ModuleBaseEnvironment() 'WorkerQueue' = $null; }; 'WebSocket' = [PSCustomObject]@{ - 'Config' = New-Object PSCustomObject; # Global config, containing all endpoints being loaded + 'Config' = New-Object PSCustomObject; # Global config, containing all endpoints being loaded <# WebSocket example structure: $WebSocketName = [PSCustomObject]@{ @@ -193,7 +193,8 @@ function New-ModuleBaseEnvironment() 'CurrentLoggingId' = (New-Guid); }; 'Icinga' = [PSCustomObject]@{ - 'CheckResult' = $null; + 'CheckResult' = $null; + 'ActiveCheckCommand' = $null; }; }; 'Protected' = [PSCustomObject]@{ @@ -233,6 +234,35 @@ function Get-ModuleCertificateDirectory() return (Join-Path -Path $env:ProgramData -ChildPath (Join-Path -Path (Get-ModuleProjectName) -ChildPath 'Certificates')); } +<# +.SYNOPSIS +Return the approved directory path for external check binaries and scripts + +.DESCRIPTION +Get-ModuleBinaryDirectory resolves the dedicated Binaries subdirectory inside +the Icinga for Windows ProgramData root ($env:ProgramData\IcingaForWindows\Binaries +on Windows, or $env:HOME\ProgramData\IcingaForWindows\Binaries on Linux and +macOS). Resolve-IcingaProtocolCommand and Invoke-IcingaProtocolCheckCommand +restrict external binary and .ps1 script execution exclusively to this folder. + +.OUTPUTS +System.String -- Full path to the Icinga for Windows Binaries directory. + +.EXAMPLE +PS> Get-ModuleBinaryDirectory +C:\ProgramData\IcingaForWindows\Binaries + +Returns the approved Icinga for Windows binaries directory path. + +.NOTES +Created automatically during startup by New-ModuleConfigEnvironment and +whitelisted in Get-SecureChildItem. +#> +function Get-ModuleBinaryDirectory() +{ + return (Join-Path -Path $env:ProgramData -ChildPath (Join-Path -Path (Get-ModuleProjectName) -ChildPath 'Binaries')); +} + <# .SYNOPSIS Build and compile the Icinga for Windows module project @@ -277,7 +307,7 @@ function Build-ModuleProject() [switch]$TestDaemonMemoryLeaks = $false ); - & (Join-Path -Path $PSScriptRoot -ChildPath 'build\Build-ModuleProject.ps1') -SkipTests:$SkipTests -GenerateDocs:$GenerateDocs -TestDaemonMemoryLeaks:$TestDaemonMemoryLeaks; + & (Join-Path -Path $PSScriptRoot -ChildPath (Join-Path -Path 'build' -ChildPath 'Build-ModuleProject.ps1')) -SkipTests:$SkipTests -GenerateDocs:$GenerateDocs -TestDaemonMemoryLeaks:$TestDaemonMemoryLeaks; } <# @@ -316,7 +346,7 @@ function Invoke-IcingaModuleTests() [string]$Path = $null ); - & (Join-Path -Path $PSScriptRoot -ChildPath 'build\Invoke-ModuleTests.ps1') -Path $Path; + & (Join-Path -Path $PSScriptRoot -ChildPath (Join-Path -Path 'build' -ChildPath 'Invoke-ModuleTests.ps1')) -Path $Path; } function Get-GlobalRuntimeVariable() diff --git a/Tests/ConvertFrom-IcingaProtocolMacros.Tests.ps1 b/Tests/ConvertFrom-IcingaProtocolMacros.Tests.ps1 new file mode 100644 index 0000000..13560f1 --- /dev/null +++ b/Tests/ConvertFrom-IcingaProtocolMacros.Tests.ps1 @@ -0,0 +1,406 @@ +$ModulePath = Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..') -ChildPath 'IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'ConvertFrom-IcingaProtocolMacros' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + function Invoke-TestMacroParser() + { + param ( + [string]$CommandName = 'Invoke-IcingaCheckDirectory', + [object]$Macros = $null, + [string]$BinaryPath = '' + ); + + return (& $script:IcingaModule { + param ($CmdName, $MacrosArg, $BinPathArg); + + if (-not [string]::IsNullOrEmpty($BinPathArg)) { + [hashtable]$BinResolved = @{ + 'Status' = 'Ok'; + 'Kind' = 'Binary'; + 'CommandName' = [System.IO.Path]::GetFileName($BinPathArg); + 'BinaryPath' = $BinPathArg; + 'Parameters' = $null; + }; + return (ConvertFrom-IcingaProtocolMacros -ResolvedCommand $BinResolved -Macros $MacrosArg); + } + + $CmdInfo = Get-Command -Name $CmdName -CommandType Function, Cmdlet -ErrorAction Stop | Select-Object -First 1; + [hashtable]$PsResolved = @{ + 'Status' = 'Ok'; + 'Kind' = 'PowerShell'; + 'CommandName' = [string]$CmdInfo.Name; + 'BinaryPath' = ''; + 'Parameters' = $CmdInfo.Parameters; + }; + return (ConvertFrom-IcingaProtocolMacros -ResolvedCommand $PsResolved -Macros $MacrosArg); + } $CommandName $Macros $BinaryPath); + } + } + + Context 'Mode A -- Active ifw-api template (PowerShell checks)' { + It 'maps real Icinga 2 ifw_api_arguments payloads and skips unset optional macros' { + [hashtable]$Macros = @{ + 'ifw_api_command' = 'Invoke-IcingaCheckDirectory'; + 'IcingaPowerShellBase_String_ExecutionPolicy' = 'ByPass'; + 'IcingaCheckDirectory_String_Path' = 'C:\Users\cstein'; + 'IcingaCheckDirectory_Array_FileNames' = @( '*.gitconfig' ); + 'IcingaCheckDirectory_String_Critical' = '0'; + 'IcingaCheckDirectory_Switchparameter_ShowFileList' = $true; + 'IcingaCheckDirectory_Switchparameter_Recurse' = 'False'; + 'IcingaCheckDirectory_String_OverrideNotFound' = ''; + 'IcingaCheckDirectory_Int32_Verbosity' = ''; + 'ifw_api_arguments' = @{ + '-Path' = @{ 'value' = '$IcingaCheckDirectory_String_Path$'; }; + '-FileNames' = @{ 'value' = '$IcingaCheckDirectory_Array_FileNames$'; }; + '-Critical' = @{ 'value' = '$IcingaCheckDirectory_String_Critical$'; }; + '-ShowFileList' = @{ 'set_if' = '$IcingaCheckDirectory_Switchparameter_ShowFileList$'; }; + '-Recurse' = @{ 'set_if' = '$IcingaCheckDirectory_Switchparameter_Recurse$'; }; + '-OverrideNotFound' = @{ 'value' = '$IcingaCheckDirectory_String_OverrideNotFound$'; }; + '-Verbosity' = @{ 'value' = '$IcingaCheckDirectory_Int32_Verbosity$'; }; + '-ThresholdInterval' = @{ 'value' = '$IcingaCheckDirectory_String_ThresholdInterval$'; }; + }; + }; + + [hashtable]$Parsed = Invoke-TestMacroParser -CommandName 'Invoke-IcingaCheckDirectory' -Macros $Macros; + + $Parsed['Status'] | Should -Be 'Ok'; + $Parsed['PowerShellArguments']['Path'] | Should -Be 'C:\Users\cstein'; + $Parsed['PowerShellArguments']['FileNames'] | Should -Be @( '*.gitconfig' ); + $Parsed['PowerShellArguments']['Critical'] | Should -Be '0'; + $Parsed['PowerShellArguments']['ShowFileList'] | Should -BeTrue; + $Parsed['PowerShellArguments'].ContainsKey('Recurse') | Should -BeFalse; + $Parsed['PowerShellArguments'].ContainsKey('OverrideNotFound') | Should -BeFalse; + $Parsed['PowerShellArguments'].ContainsKey('Verbosity') | Should -BeFalse; + $Parsed['CommandLine'] | Should -Be "Invoke-IcingaCheckDirectory -Critical '0' -FileNames @('*.gitconfig') -Path 'C:\Users\cstein' -ShowFileList"; + } + + It 'supports Dictionary[string, object] from Windows PowerShell 5.1 and PSCustomObject payloads' { + $Ps51Macros = New-Object 'System.Collections.Generic.Dictionary[string, object]'; + $Ps51Args = New-Object 'System.Collections.Generic.Dictionary[string, object]'; + $Ps51PathSpec = New-Object 'System.Collections.Generic.Dictionary[string, object]'; + $Ps51PathSpec['value'] = '$ICINGACHECKDIRECTORY_STRING_PATH$'; + $Ps51Args['-Path'] = $Ps51PathSpec; + $Ps51Macros['ifw_api_command'] = 'Invoke-IcingaCheckDirectory'; + $Ps51Macros['icingacheckdirectory_string_path'] = $null; + $Ps51Macros['IcingaCheckDirectory_String_Path'] = 'D:\Logs'; + $Ps51Macros['ifw_api_arguments'] = $Ps51Args; + + [hashtable]$Parsed = Invoke-TestMacroParser -CommandName 'Invoke-IcingaCheckDirectory' -Macros $Ps51Macros; + + $PsObjMacros = [PSCustomObject]@{ + 'ifw_api_command' = 'Invoke-IcingaCheckDirectory'; + 'target_path' = 'E:\Data'; + 'ifw_api_arguments' = [PSCustomObject]@{ + '-Path' = [PSCustomObject]@{ 'value' = '$target_path$'; }; + '-ShowFileList' = [PSCustomObject]@{ 'value' = $null; }; + '-Critical' = [PSCustomObject]@{ 'value' = $null; }; + }; + }; + + [hashtable]$ObjParsed = Invoke-TestMacroParser -CommandName 'Invoke-IcingaCheckDirectory' -Macros $PsObjMacros; + + $Parsed['Status'] | Should -Be 'Ok'; + $Parsed['PowerShellArguments']['Path'] | Should -Be 'D:\Logs'; + + $ObjParsed['Status'] | Should -Be 'Ok'; + $ObjParsed['PowerShellArguments']['Path'] | Should -Be 'E:\Data'; + $ObjParsed['PowerShellArguments']['ShowFileList'] | Should -BeTrue; + $ObjParsed['PowerShellArguments'].ContainsKey('Critical') | Should -BeFalse; + } + + It 'skips empty string "", empty [] and empty {} on unknown parameters in ifw_api_arguments and raises IWKB001001 on non-empty values' { + [hashtable]$EmptyUnknown = @{ + 'ifw_api_command' = 'Invoke-IcingaCheckDirectory'; + 'Path' = 'C:\Temp'; + 'ObsoleteEmpty' = ''; + 'ObsoleteList' = @(); + 'ObsoleteDict' = @{ }; + 'EmptyFileNames' = @(); + 'ifw_api_arguments' = @{ + '-Path' = @{ 'value' = '$Path$'; }; + '-FileNames' = @{ 'value' = '$EmptyFileNames$'; }; + '-ThresholdInterval' = @{ 'value' = '$ObsoleteEmpty$'; }; + '-LegacyArrayParam' = @{ 'value' = '$ObsoleteList$'; }; + '-LegacyMapParam' = @{ 'value' = '$ObsoleteDict$'; }; + '-NullRemovedParam' = @{ 'value' = $null; }; + }; + }; + + [hashtable]$PopulatedUnknown = @{ + 'ifw_api_command' = 'Invoke-IcingaCheckDirectory'; + 'ObsoleteValue' = '10s'; + 'ifw_api_arguments' = @{ + '-ThresholdInterval' = @{ 'value' = '$ObsoleteValue$'; }; + }; + }; + + [hashtable]$PopulatedListUnk = @{ + 'ifw_api_command' = 'Invoke-IcingaCheckDirectory'; + 'ObsoleteArr' = @( '10s' ); + 'ifw_api_arguments' = @{ + '-ThresholdInterval' = @{ 'value' = '$ObsoleteArr$'; }; + }; + }; + + [hashtable]$EmptyRes = Invoke-TestMacroParser -CommandName 'Invoke-IcingaCheckDirectory' -Macros $EmptyUnknown; + [hashtable]$PopRes = Invoke-TestMacroParser -CommandName 'Invoke-IcingaCheckDirectory' -Macros $PopulatedUnknown; + [hashtable]$PopListRes = Invoke-TestMacroParser -CommandName 'Invoke-IcingaCheckDirectory' -Macros $PopulatedListUnk; + + $EmptyRes['Status'] | Should -Be 'Ok'; + $EmptyRes['PowerShellArguments']['Path'] | Should -Be 'C:\Temp'; + $EmptyRes['PowerShellArguments'].ContainsKey('FileNames') | Should -BeFalse; + + $PopRes['Status'] | Should -Be 'UnknownParameter'; + $PopRes['KnowledgeBaseId'] | Should -Be 'IWKB001001'; + $PopRes['Message'] | Should -Match 'ThresholdInterval'; + $PopRes['Message'] | Should -Match 'IWKB001001'; + + $PopListRes['Status'] | Should -Be 'UnknownParameter'; + $PopListRes['KnowledgeBaseId'] | Should -Be 'IWKB001001'; + } + + It 'handles Windows dollar-sign paths, escaped $$ literals, single-pass substitution and empty array macros' { + [hashtable]$DollarMacros = @{ + 'ifw_api_command' = 'Invoke-IcingaCheckDirectory'; + 'address' = '10.0.0.5'; + 'first' = 'keep$second$literal'; + 'second' = 'REPLACED'; + 'empty_files' = ''; + 'ifw_api_arguments' = @{ + '-Path' = @{ 'value' = '\\$address$\C$\MSSQL$SQLEXPRESS'; }; + '-ChangeTimeEqual' = @{ 'value' = '\\$address$\D$$'; }; + '-CreationTimeEqual' = @{ 'value' = '$first$/$second$'; }; + '-FileNames' = @{ 'value' = '$empty_files$'; }; + }; + }; + + [hashtable]$DollarParsed = Invoke-TestMacroParser -CommandName 'Invoke-IcingaCheckDirectory' -Macros $DollarMacros; + + $DollarParsed['Status'] | Should -Be 'Ok'; + $DollarParsed['PowerShellArguments']['Path'] | Should -Be '\\10.0.0.5\C$\MSSQL$SQLEXPRESS'; + $DollarParsed['PowerShellArguments']['ChangeTimeEqual'] | Should -Be '\\10.0.0.5\D$'; + $DollarParsed['PowerShellArguments']['CreationTimeEqual'] | Should -Be 'keep$second$literal/REPLACED'; + $DollarParsed['PowerShellArguments'].ContainsKey('FileNames') | Should -BeFalse; + + [hashtable]$SvcParsed = Invoke-TestMacroParser -CommandName 'Invoke-IcingaCheckService' -Macros @{ + 'ifw_api_command' = 'Invoke-IcingaCheckService'; + 'FilterStartupType' = ''; + }; + + $SvcParsed['Status'] | Should -Be 'Ok'; + $SvcParsed['PowerShellArguments'].ContainsKey('FilterStartupType') | Should -BeFalse; + } + + It 'resolves parameter aliases and formats uint32, single and uint64 numeric types unquoted in CommandLine' { + [hashtable]$AliasRes = & $script:IcingaModule { + function Invoke-IcingaCheckMockAliasNumeric() + { + param ( + [Alias('PortNum')] + [uint32]$Port = 443, + [single]$Ratio = 0.5, + [uint64[]]$Sizes = @() + ); + + return 0; + } + + $CmdInfo = Get-Command -Name 'Invoke-IcingaCheckMockAliasNumeric' -CommandType Function; + [hashtable]$Info = @{ + 'Status' = 'Ok'; + 'Kind' = 'PowerShell'; + 'CommandName' = 'Invoke-IcingaCheckMockAliasNumeric'; + 'BinaryPath' = ''; + 'Parameters' = $CmdInfo.Parameters; + }; + [hashtable]$RawMacros = @{ + 'ifw_api_command' = 'Invoke-IcingaCheckMockAliasNumeric'; + 'p' = '8443'; + 'r' = '1.25'; + 's' = @( '1024', '2048' ); + 'ifw_api_arguments' = @{ + '-PortNum' = @{ 'value' = '$p$'; }; + '-Ratio' = @{ 'value' = '$r$'; }; + '-Sizes' = @{ 'value' = '$s$'; }; + }; + }; + + return (ConvertFrom-IcingaProtocolMacros -ResolvedCommand $Info -Macros $RawMacros); + }; + + $AliasRes['Status'] | Should -Be 'Ok'; + $AliasRes['PowerShellArguments']['Port'] | Should -Be ([uint32]8443); + $AliasRes['PowerShellArguments']['Ratio'] | Should -Be ([single]1.25); + $AliasRes['CommandLine'] | Should -Be 'Invoke-IcingaCheckMockAliasNumeric -Port 8443 -Ratio 1.25 -Sizes @(1024, 2048)'; + } + } + + Context 'Mode B -- Fallback without ifw-api (PowerShell checks)' { + It 'maps IcingaCheck[Name]_[Type]_[Param], direct names and ignores empty "" macro keys without IWKB001000' { + $Macros = New-Object 'System.Collections.Generic.Dictionary[string, object]'; + $Macros[''] = '$'; + $Macros[' '] = '$'; + $Macros['ifw_api_command'] = 'Invoke-IcingaCheckDirectory'; + $Macros['IcingaPowerShellBase_String_ExecutionPolicy'] = 'ByPass'; + $Macros['IcingaCheckDirectory_String_Path'] = 'C:\Users\cstein'; + $Macros['IcingaCheckDirectory_Array_FileNames'] = '*.gitconfig'; + $Macros['IcingaCheckDirectory_Switchparameter_ShowFileList'] = 'True'; + $Macros['Verbosity'] = '2'; + + [hashtable]$Parsed = Invoke-TestMacroParser -CommandName 'Invoke-IcingaCheckDirectory' -Macros $Macros; + + $Parsed['Status'] | Should -Be 'Ok'; + $Parsed['PowerShellArguments']['Path'] | Should -Be 'C:\Users\cstein'; + $Parsed['PowerShellArguments']['FileNames'] | Should -Be @( '*.gitconfig' ); + $Parsed['PowerShellArguments']['ShowFileList'] | Should -BeTrue; + $Parsed['PowerShellArguments']['Verbosity'] | Should -Be 2; + } + + It 'returns MappingFailed with exact error message and IWKB001000 on unmapped custom variables' { + [hashtable]$Macros = @{ + 'ifw_api_command' = 'Invoke-IcingaCheckDirectory'; + 'Path' = 'C:\Temp'; + 'foo_bar' = 'unexpected'; + }; + + [hashtable]$Parsed = Invoke-TestMacroParser -CommandName 'Invoke-IcingaCheckDirectory' -Macros $Macros; + + $Parsed['Status'] | Should -Be 'MappingFailed'; + $Parsed['KnowledgeBaseId'] | Should -Be 'IWKB001000'; + $Parsed['Message'] | Should -Match 'Unable to map Custom-Variables to Icinga for Windows Check'; + $Parsed['Message'] | Should -Match 'foo_bar'; + $Parsed['Message'] | Should -Match 'IWKB001000'; + } + } + + Context 'SecureString conversion and CommandLine masking' { + It 'converts plain-text secrets to SecureString and masks them in CommandLine' { + [hashtable]$Parsed = & $script:IcingaModule { + function Invoke-IcingaCheckMockAuth() + { + param ( + [string]$Username = '', + [securestring]$ApiSecret = $null + ); + + return 0; + } + + $CmdInfo = Get-Command -Name 'Invoke-IcingaCheckMockAuth' -CommandType Function; + [hashtable]$Info = @{ + 'Status' = 'Ok'; + 'Kind' = 'PowerShell'; + 'CommandName' = 'Invoke-IcingaCheckMockAuth'; + 'BinaryPath' = ''; + 'Parameters' = $CmdInfo.Parameters; + }; + [hashtable]$RawMacros = @{ + 'ifw_api_command' = 'Invoke-IcingaCheckMockAuth'; + 'Username' = 'icinga'; + 'ApiSecret' = 'TopSecretValue!'; + }; + + return (ConvertFrom-IcingaProtocolMacros -ResolvedCommand $Info -Macros $RawMacros); + }; + + try { + $Parsed['Status'] | Should -Be 'Ok'; + ($Parsed['PowerShellArguments']['ApiSecret'] -is [System.Security.SecureString]) | Should -BeTrue; + $Parsed['AllocatedSecureStrings'].Count | Should -Be 1; + $Parsed['CommandLine'] | Should -Match ([regex]::Escape("-ApiSecret '********'")); + $Parsed['CommandLine'] | Should -Not -Match 'TopSecretValue'; + } finally { + foreach ($Sec in $Parsed['AllocatedSecureStrings']) { + $Sec.Dispose(); + } + } + } + } + + Context 'Binary argument mapping (ifw-api and Fallback)' { + It 'builds ordered CLI arguments with serialized "value": null, skip_key, repeat_key and float order' { + [hashtable]$Macros = @{ + 'ifw_api_command' = 'check_http.exe'; + 'address' = '127.0.0.1'; + 'port' = 8080; + 'headers' = @( 'X-Test: 1', 'X-Env: prod' ); + 'tags' = @( 'web', 'edge' ); + 'pos_items' = @( 'posA', 'posB' ); + 'ssl_enabled' = $true; + 'ifw_api_arguments' = @{ + '-4' = @{ 'order' = -1; 'value' = $null; 'set_if' = $null; 'skip_key' = $false; 'description' = 'IPv4 only'; }; + 'ignored_pos' = @{ 'order' = 0; 'value' = $null; 'skip_key' = $true; }; + 'endpoint' = @{ 'value' = 'http://$address$:$port$/health'; 'skip_key' = $true; 'order' = '1.0'; }; + '-H' = @{ 'value' = '$headers$'; 'repeat_key' = $true; 'order' = 2; }; + '--tags' = @{ 'value' = '$tags$'; 'repeat_key' = $false; 'order' = '2.5'; }; + 'extra_pos' = @{ 'value' = '$pos_items$'; 'skip_key' = $true; 'order' = 3; }; + '--ssl' = @{ 'set_if' = '$ssl_enabled$'; 'order' = 4; }; + }; + }; + + [string]$HttpCheckPath = & $script:IcingaModule { Join-Path -Path (Get-ModuleBinaryDirectory) -ChildPath 'check_http.exe' }; + [hashtable]$Parsed = Invoke-TestMacroParser -BinaryPath $HttpCheckPath -Macros $Macros; + + $Parsed['Status'] | Should -Be 'Ok'; + $Parsed['BinaryArguments'] | Should -Be @( '-4', 'http://127.0.0.1:8080/health', '-H', 'X-Test: 1', '-H', 'X-Env: prod', '--tags', 'web', 'edge', 'posA', 'posB', '--ssl' ); + $Parsed['CommandLine'] | Should -Match 'check_http\.exe'; + $Parsed['CommandLine'] | Should -Match '"X-Test: 1"'; + } + + It 'preserves case-distinct CLI flags (-p vs -P and -c vs -C) in both ifw-api and Fallback modes' { + $CaseApiArgs = New-Object 'System.Collections.Generic.Dictionary[string, object]'; + $CaseApiArgs['-p'] = @{ 'value' = '8080'; 'order' = 1; }; + $CaseApiArgs['-P'] = @{ 'value' = 'payload=ok'; 'order' = 2; }; + $CaseApiArgs['-c'] = @{ 'value' = '5'; 'order' = 3; }; + $CaseApiArgs['-C'] = @{ 'value' = '30,14'; 'order' = 4; }; + + $CaseApiMacros = New-Object 'System.Collections.Generic.Dictionary[string, object]'; + $CaseApiMacros['ifw_api_command'] = 'check_http.exe'; + $CaseApiMacros['ifw_api_arguments'] = $CaseApiArgs; + + $CaseFallbackMacros = New-Object 'System.Collections.Generic.Dictionary[string, object]'; + $CaseFallbackMacros[''] = '$'; + $CaseFallbackMacros['ifw_api_command'] = 'check_http.exe'; + $CaseFallbackMacros['-p'] = '8080'; + $CaseFallbackMacros['-P'] = 'payload=ok'; + $CaseFallbackMacros['-c'] = '5'; + $CaseFallbackMacros['-C'] = '30,14'; + + [string]$HttpBin = & $script:IcingaModule { Join-Path -Path (Get-ModuleBinaryDirectory) -ChildPath 'check_http.exe' }; + [hashtable]$ApiRes = Invoke-TestMacroParser -BinaryPath $HttpBin -Macros $CaseApiMacros; + [hashtable]$FallRes = Invoke-TestMacroParser -BinaryPath $HttpBin -Macros $CaseFallbackMacros; + + $ApiRes['Status'] | Should -Be 'Ok'; + $ApiRes['BinaryArguments'] | Should -Be @( '-p', '8080', '-P', 'payload=ok', '-c', '5', '-C', '30,14' ); + + $FallRes['Status'] | Should -Be 'Ok'; + $FallRes['BinaryArguments'] | Should -Be @( '-p', '8080', '-P', 'payload=ok', '-c', '5', '-C', '30,14' ); + } + + It 'allows zero or flag-prefixed custom variables for binaries in Fallback mode and rejects unprefixed ones with IWKB001002' { + [string]$BinPath = & $script:IcingaModule { Join-Path -Path (Get-ModuleBinaryDirectory) -ChildPath 'check_load.exe' }; + [hashtable]$Empty = Invoke-TestMacroParser -BinaryPath $BinPath -Macros @{ 'ifw_api_command' = 'check_load.exe'; }; + [hashtable]$Flags = Invoke-TestMacroParser -BinaryPath $BinPath -Macros @{ 'ifw_api_command' = 'check_load.exe'; '-w' = '80%'; '/v' = $true; }; + [hashtable]$BadVar = Invoke-TestMacroParser -BinaryPath $BinPath -Macros @{ 'ifw_api_command' = 'check_load.exe'; 'load_win_warn' = '80%'; }; + + $Empty['Status'] | Should -Be 'Ok'; + $Empty['BinaryArguments'].Count | Should -Be 0; + + $Flags['Status'] | Should -Be 'Ok'; + $Flags['BinaryArguments'] | Should -Contain '-w'; + $Flags['BinaryArguments'] | Should -Contain '80%'; + $Flags['BinaryArguments'] | Should -Contain '/v'; + + $BadVar['Status'] | Should -Be 'BinaryMappingFailed'; + $BadVar['KnowledgeBaseId'] | Should -Be 'IWKB001002'; + $BadVar['Message'] | Should -Match 'IWKB001002'; + } + } +} diff --git a/Tests/ConvertFrom-ModuleBoolean.Tests.ps1 b/Tests/ConvertFrom-ModuleBoolean.Tests.ps1 new file mode 100644 index 0000000..198b5b5 --- /dev/null +++ b/Tests/ConvertFrom-ModuleBoolean.Tests.ps1 @@ -0,0 +1,73 @@ +$ModulePath = Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..') -ChildPath 'IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'ConvertFrom-ModuleBoolean' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + function Invoke-TestBoolConversion() + { + param ( + [object]$InputValue = $null + ); + + return (& $script:IcingaModule { + param ($Val); + return (ConvertFrom-ModuleBoolean -Value $Val); + } $InputValue); + } + } + + Context 'Native booleans, switches and null' { + It 'preserves native booleans and evaluates $null to $false' { + (Invoke-TestBoolConversion -InputValue $true) | Should -BeTrue; + (Invoke-TestBoolConversion -InputValue $false) | Should -BeFalse; + (Invoke-TestBoolConversion -InputValue $null) | Should -BeFalse; + } + + It 'converts SwitchParameter values accurately' { + [switch]$PresentSwitch = $true; + [switch]$AbsentSwitch = $false; + + (Invoke-TestBoolConversion -InputValue $PresentSwitch) | Should -BeTrue; + (Invoke-TestBoolConversion -InputValue $AbsentSwitch) | Should -BeFalse; + } + } + + Context 'Numeric and string representations' { + It 'maps numeric 1 and truthy strings case-insensitively to $true' { + (Invoke-TestBoolConversion -InputValue 1) | Should -BeTrue; + (Invoke-TestBoolConversion -InputValue 1.0) | Should -BeTrue; + (Invoke-TestBoolConversion -InputValue 'true') | Should -BeTrue; + (Invoke-TestBoolConversion -InputValue 'TRUE') | Should -BeTrue; + (Invoke-TestBoolConversion -InputValue '1') | Should -BeTrue; + (Invoke-TestBoolConversion -InputValue 'yes') | Should -BeTrue; + (Invoke-TestBoolConversion -InputValue 'YES') | Should -BeTrue; + (Invoke-TestBoolConversion -InputValue '$true') | Should -BeTrue; + } + + It 'maps numeric 0, empty strings and falsy strings to $false without PowerShell string-truthiness bugs' { + (Invoke-TestBoolConversion -InputValue 0) | Should -BeFalse; + (Invoke-TestBoolConversion -InputValue 0.0) | Should -BeFalse; + (Invoke-TestBoolConversion -InputValue 'false') | Should -BeFalse; + (Invoke-TestBoolConversion -InputValue 'False') | Should -BeFalse; + (Invoke-TestBoolConversion -InputValue '0') | Should -BeFalse; + (Invoke-TestBoolConversion -InputValue 'no') | Should -BeFalse; + (Invoke-TestBoolConversion -InputValue '$false') | Should -BeFalse; + (Invoke-TestBoolConversion -InputValue '') | Should -BeFalse; + (Invoke-TestBoolConversion -InputValue ' ') | Should -BeFalse; + } + + It 'returns $false and logs StringToBoolConversionInvalidValue on unrecognized values' { + (Invoke-TestBoolConversion -InputValue 'not-a-bool') | Should -BeFalse; + (Invoke-TestBoolConversion -InputValue 42) | Should -BeFalse; + (Invoke-TestBoolConversion -InputValue -1) | Should -BeFalse; + (Invoke-TestBoolConversion -InputValue ([byte]1)) | Should -BeTrue; + (Invoke-TestBoolConversion -InputValue ([int64]0)) | Should -BeFalse; + } + } +} diff --git a/Tests/ConvertTo-IcingaSortedArray.Tests.ps1 b/Tests/ConvertTo-IcingaSortedArray.Tests.ps1 new file mode 100644 index 0000000..383908f --- /dev/null +++ b/Tests/ConvertTo-IcingaSortedArray.Tests.ps1 @@ -0,0 +1,78 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'ConvertTo-IcingaSortedArray' { + Context 'Natural order' { + It 'sorts processor instances numerically with the totals last' { + $Sorted = ConvertTo-IcingaSortedArray -InputObject @('0,10', '_Total', '1,0', '0,2', '0,_Total', '0,0'); + $Sorted | Should -Be @('0,0', '0,2', '0,10', '0,_Total', '1,0', '_Total'); + } + + It 'compares digit runs by value and text case-insensitively' { + $Sorted = ConvertTo-IcingaSortedArray -InputObject @('core 10', 'Core 9', 'CORE 1', 'Core 01a'); + $Sorted | Should -Be @('CORE 1', 'Core 01a', 'Core 9', 'core 10'); + } + + It 'compares numbers numerically and puts $null first' { + $Sorted = ConvertTo-IcingaSortedArray -InputObject @(10, 9, $null, 100); + $Sorted | Should -Be @($null, 9, 10, 100); + } + + It 'sorts in descending order' { + $Sorted = ConvertTo-IcingaSortedArray -InputObject @('b', 'c', 'a') -Descending; + $Sorted | Should -Be @('c', 'b', 'a'); + } + } + + Context 'Properties' { + It 'sorts objects and hashtables by a property' { + $Objects = @([PSCustomObject]@{ 'Name' = 'Spooler'; }, [PSCustomObject]@{ 'Name' = 'AppInfo'; }); + (ConvertTo-IcingaSortedArray -InputObject $Objects -Property 'Name').Name | Should -Be @('AppInfo', 'Spooler'); + + $Tables = @(@{ 'Name' = 'D:\'; }, @{ 'Name' = 'C:\'; }); + (ConvertTo-IcingaSortedArray -InputObject $Tables -Property 'Name') | ForEach-Object { $_['Name'] } | Should -Be @('C:\', 'D:\'); + } + + It 'breaks ties with the next property' { + $Partitions = @( + @{ 'Disk' = 1; 'Partition' = 1; }, + @{ 'Disk' = 0; 'Partition' = 2; }, + @{ 'Disk' = 0; 'Partition' = 1; } + ); + $Sorted = ConvertTo-IcingaSortedArray -InputObject $Partitions -Property 'Disk', 'Partition'; + ($Sorted | ForEach-Object { '{0}:{1}' -f $_['Disk'], $_['Partition'] }) | Should -Be @('0:1', '0:2', '1:1'); + } + + It 'keeps equal elements in input order' { + $Objects = @( + [PSCustomObject]@{ 'Key' = 'a'; 'Order' = 1; }, + [PSCustomObject]@{ 'Key' = 'b'; 'Order' = 2; }, + [PSCustomObject]@{ 'Key' = 'a'; 'Order' = 3; }, + [PSCustomObject]@{ 'Key' = 'a'; 'Order' = 4; } + ); + (ConvertTo-IcingaSortedArray -InputObject $Objects -Property 'Key').Order | Should -Be @(1, 3, 4, 2); + (ConvertTo-IcingaSortedArray -InputObject $Objects -Property 'Key' -Descending).Order | Should -Be @(2, 1, 3, 4); + } + } + + Context 'Result shape' { + It 'returns a new array and leaves the input unchanged' { + $Input1 = @('b', 'a'); + $Sorted = ConvertTo-IcingaSortedArray -InputObject $Input1; + $Sorted | Should -Be @('a', 'b'); + $Input1 | Should -Be @('b', 'a'); + } + + It 'returns an array for a single element and an empty array for no element' { + $Single = ConvertTo-IcingaSortedArray -InputObject @('a'); + ($Single -is [array]) | Should -BeTrue; + $Single.Count | Should -Be 1; + + $Empty = ConvertTo-IcingaSortedArray -InputObject @(); + ($Empty -is [array]) | Should -BeTrue; + $Empty.Count | Should -Be 0; + } + } +} diff --git a/Tests/ConvertTo-ModuleSecureString.Tests.ps1 b/Tests/ConvertTo-ModuleSecureString.Tests.ps1 new file mode 100644 index 0000000..79da5b5 --- /dev/null +++ b/Tests/ConvertTo-ModuleSecureString.Tests.ps1 @@ -0,0 +1,154 @@ +$ModulePath = Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..') -ChildPath 'IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'ConvertTo-ModuleSecureString and Get-IcingaUnixTime' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + function ConvertFrom-TestSecureString() + { + param ( + [System.Security.SecureString]$Secure = $null + ); + + if ($null -eq $Secure) { + return $null; + } + + [System.IntPtr]$Ptr = [System.IntPtr]::Zero; + try { + $Ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToGlobalAllocUnicode($Secure); + return [System.Runtime.InteropServices.Marshal]::PtrToStringUni($Ptr); + } finally { + if ($Ptr -ne [System.IntPtr]::Zero) { + [System.Runtime.InteropServices.Marshal]::ZeroFreeGlobalAllocUnicode($Ptr); + } + } + } + } + + Context 'ConvertTo-ModuleSecureString' { + It 'returns $null when InputObject is $null' { + $Result = & $script:IcingaModule { ConvertTo-ModuleSecureString -InputObject $null }; + $Result | Should -BeNullOrEmpty; + } + + It 'returns an empty read-only SecureString without throwing on empty string input' { + $Result = & $script:IcingaModule { ConvertTo-ModuleSecureString -InputObject '' }; + ($Result -is [System.Security.SecureString]) | Should -BeTrue; + $Result.IsReadOnly() | Should -BeTrue; + $Result.Length | Should -Be 0; + (ConvertFrom-TestSecureString -Secure $Result) | Should -Be ''; + $Result.Dispose(); + } + + It 'converts plain-text strings and scalar inputs into a read-only SecureString' { + $Result = & $script:IcingaModule { ConvertTo-ModuleSecureString -InputObject 'S3cr3t!Pass#2026' }; + $NumResult = & $script:IcingaModule { ConvertTo-ModuleSecureString -InputObject 98765 }; + try { + ($Result -is [System.Security.SecureString]) | Should -BeTrue; + $Result.IsReadOnly() | Should -BeTrue; + (ConvertFrom-TestSecureString -Secure $Result) | Should -Be 'S3cr3t!Pass#2026'; + (ConvertFrom-TestSecureString -Secure $NumResult) | Should -Be '98765'; + } finally { + $Result.Dispose(); + $NumResult.Dispose(); + } + } + + It 'returns an existing SecureString instance unchanged' { + $Existing = & $script:IcingaModule { ConvertTo-ModuleSecureString -InputObject 'AlreadySecure' }; + try { + $Returned = & $script:IcingaModule { + param ($Sec); + return (ConvertTo-ModuleSecureString -InputObject $Sec); + } $Existing; + + [object]::ReferenceEquals($Existing, $Returned) | Should -BeTrue; + } finally { + $Existing.Dispose(); + } + } + + It 'emits SecureStringConversionFailed via Write-FunctionReturnValue and returns $null without throwing on oversized input' { + [string]$OversizedSecret = ('S' * 65537); + [hashtable]$FailureData = & $script:IcingaModule { + param ($BigInput); + + $script:CapturedCodeKeys = @(); + $RealReturnCmd = Get-Command -Name 'Write-FunctionReturnValue' -CommandType Function; + + function Write-FunctionReturnValue() + { + param ( + [string]$ReturnValue = $null, + [hashtable]$Data = @{ }, + $OverrideReturn = 'Core::IgnoreOverride', + [switch]$AutomationRun = $false + ); + + $script:CapturedCodeKeys += $ReturnValue; + return (& $RealReturnCmd -ReturnValue $ReturnValue -Data $Data -OverrideReturn $OverrideReturn -AutomationRun:$AutomationRun); + } + + $Converted = ConvertTo-ModuleSecureString -InputObject $BigInput; + + function Invoke-IcingaCheckMockOversizedSecret() + { + param ( + [securestring]$Password = $null + ); + + return 0; + } + + $CheckRes = Invoke-IcingaProtocolCheckCommand -Params @{ + 'command' = 'Invoke-IcingaCheckMockOversizedSecret'; + 'macros' = @{ + 'ifw_api_command' = 'Invoke-IcingaCheckMockOversizedSecret'; + 'ifw_api_arguments' = @{ + 'Password' = @{ 'value' = $BigInput; }; + }; + }; + }; + + return @{ + 'Converted' = $Converted; + 'CapturedKeys' = $script:CapturedCodeKeys; + 'CheckExitCode' = $CheckRes['ExitCode']; + 'CheckOutput' = $CheckRes['Output']; + 'CommandLine' = $CheckRes['CommandLine']; + }; + } $OversizedSecret; + + $FailureData['Converted'] | Should -BeNullOrEmpty; + $FailureData['CapturedKeys'] | Should -Contain 'SecureStringConversionFailed'; + $FailureData['CapturedKeys'] | Should -Contain 'IcingaProtocolMacroMappingFailed'; + $FailureData['CheckExitCode'] | Should -Be 3; + $FailureData['CheckOutput'] | Should -Match '\[UNKNOWN\]'; + $FailureData['CommandLine'] | Should -Not -Match 'SSSSSS'; + } + } + + Context 'Get-IcingaUnixTime' { + It 'returns UTC Unix seconds without local timezone drift' { + [int]$Expected = [int][System.DateTimeOffset]::UtcNow.ToUnixTimeSeconds(); + $Actual = Get-IcingaUnixTime; + + ($Actual -is [int]) | Should -BeTrue; + [System.Math]::Abs($Actual - $Expected) | Should -BeLessOrEqual 2; + } + + It 'returns fractional UTC Unix seconds as Double when -Milliseconds is set' { + [double]$Expected = [double]([System.DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() / 1000.0); + $Actual = Get-IcingaUnixTime -Milliseconds; + + ($Actual -is [double]) | Should -BeTrue; + [System.Math]::Abs($Actual - $Expected) | Should -BeLessOrEqual 2.0; + } + } +} diff --git a/Tests/Get-IcingaDirectoryInformation.Tests.ps1 b/Tests/Get-IcingaDirectoryInformation.Tests.ps1 new file mode 100644 index 0000000..315729b --- /dev/null +++ b/Tests/Get-IcingaDirectoryInformation.Tests.ps1 @@ -0,0 +1,234 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Get-IcingaDirectoryInformation' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + # Writes a file of the given size and sets its time stamps. + function New-TestFile() + { + param ( + [string]$Path = '', + [int]$Size = 0, + [datetime]$LastWrite = [datetime]::Now, + [datetime]$Creation = [datetime]::Now, + [datetime]$LastAccess = [datetime]::Now, + [switch]$Hidden = $false + ); + + [System.IO.File]::WriteAllBytes($Path, [byte[]]::new($Size)); + [System.IO.File]::SetCreationTime($Path, $Creation); + [System.IO.File]::SetLastWriteTime($Path, $LastWrite); + [System.IO.File]::SetLastAccessTime($Path, $LastAccess); + + if ($Hidden) { + [System.IO.File]::SetAttributes($Path, [System.IO.FileAttributes]::Hidden); + } + } + + # Calls the provider inside the module scope, where IcingaError is visible. + function Invoke-TestDirectory() + { + param ( + [hashtable]$Arguments = @{ } + ); + + return (& $script:IcingaModule { + param ($Arguments); + + Get-IcingaDirectoryInformation @Arguments; + } $Arguments); + } + + # Layout (sizes in bytes, ages relative to now): + # a.log 100 (written at noon 10 days ago), b.log 2000 (1h), c.txt 50 (40d, + # created 40d ago, last access 40d ago), hidden.log 10 (hidden), + # sub\ (written 3d ago) with d.log 5000 (2d) and deep\e.log 1 (now), + # hidden\ (hidden folder) with f.log 7. + [datetime]$Now = [datetime]::Now; + $script:Root = Join-Path -Path $TestDrive -ChildPath 'scan'; + [string]$Sub = Join-Path -Path $script:Root -ChildPath 'sub'; + [string]$Deep = Join-Path -Path $Sub -ChildPath 'deep'; + [string]$Secret = Join-Path -Path $script:Root -ChildPath 'hidden'; + + New-Item -Path $Deep -ItemType Directory -Force | Out-Null; + New-Item -Path $Secret -ItemType Directory -Force | Out-Null; + + New-TestFile -Path (Join-Path -Path $script:Root -ChildPath 'a.log') -Size 100 -LastWrite $Now.AddDays(-10).Date.AddHours(12); + New-TestFile -Path (Join-Path -Path $script:Root -ChildPath 'b.log') -Size 2000 -LastWrite $Now.AddHours(-1); + New-TestFile -Path (Join-Path -Path $script:Root -ChildPath 'c.txt') -Size 50 -LastWrite $Now.AddDays(-40) -Creation $Now.AddDays(-40) -LastAccess $Now.AddDays(-40); + New-TestFile -Path (Join-Path -Path $script:Root -ChildPath 'hidden.log') -Size 10 -Hidden; + New-TestFile -Path (Join-Path -Path $Sub -ChildPath 'd.log') -Size 5000 -LastWrite $Now.AddDays(-2); + New-TestFile -Path (Join-Path -Path $Deep -ChildPath 'e.log') -Size 1; + New-TestFile -Path (Join-Path -Path $Secret -ChildPath 'f.log') -Size 7; + + [System.IO.Directory]::SetLastWriteTime($Sub, $Now.AddDays(-3)); + [System.IO.Directory]::SetLastWriteTime($Deep, $Now.AddDays(-3)); + $SecretInfo = [System.IO.DirectoryInfo]::new($Secret); + $SecretInfo.Attributes = $SecretInfo.Attributes -bor [System.IO.FileAttributes]::Hidden; + } + + It 'collects the statistics of the top level and skips hidden entries' { + $Result = Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; }; + + $Result.Exists | Should -BeTrue; + $Result.FileCount | Should -Be 3; + $Result.FolderCount | Should -Be 1; + $Result.TotalCount | Should -Be 4; + $Result.TotalSize | Should -Be 2150; + $Result.SmallestFile | Should -Be 50; + $Result.LargestFile | Should -Be 2000; + $Result.AverageSize | Should -Be 716.67; + @($Result.FileList).Count | Should -Be 0; + } + + It 'descends into every subdirectory with Recurse, but not into hidden ones' { + $Result = Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'Recurse' = $true; }; + + $Result.FileCount | Should -Be 5; + $Result.FolderCount | Should -Be 2; + $Result.TotalSize | Should -Be 7151; + $Result.SmallestFile | Should -Be 1; + $Result.LargestFile | Should -Be 5000; + } + + It 'matches the file names case-insensitively and still scans non-matching folders' { + $Result = Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'Recurse' = $true; 'FileNames' = @('*.LOG'); }; + + $Result.FileCount | Should -Be 4; + $Result.FolderCount | Should -Be 0; + } + + It 'keeps entries matching any of several name patterns' { + $Result = Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'FileNames' = @('a.*', '*.txt'); }; + + $Result.FileCount | Should -Be 2; + } + + It 'filters by the last write time' { + (Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'ChangeOlderThan' = '5d'; }).FileCount | Should -Be 2; + (Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'ChangeOlderThan' = '5d'; }).FolderCount | Should -Be 0; + (Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'ChangeYoungerThan' = '1d'; }).FileCount | Should -Be 1; + (Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'ChangeYoungerThan' = '4d'; }).FolderCount | Should -Be 1; + (Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'ChangeTimeEqual' = '10d'; }).FileCount | Should -Be 1; + } + + It 'filters by the creation and the last access time' { + (Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'CreationOlderThan' = '20d'; }).FileCount | Should -Be 1; + (Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'CreationYoungerThan' = '20d'; }).FileCount | Should -Be 2; + (Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'AccessOlderThan' = '20d'; }).FileCount | Should -Be 1; + } + + It 'filters files by size, accepts plain numbers as bytes and never keeps folders' { + $Larger = Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'Recurse' = $true; 'FileSizeGreaterThan' = '1KB'; }; + $Larger.FileCount | Should -Be 2; + $Larger.FolderCount | Should -Be 0; + + (Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'FileSizeSmallerThan' = '100'; }).FileCount | Should -Be 1; + } + + It 'combines every given filter with AND' { + $Result = Invoke-TestDirectory -Arguments @{ + 'Path' = $script:Root; + 'Recurse' = $true; + 'FileNames' = @('*.log'); + 'ChangeYoungerThan' = '3d'; + 'FileSizeGreaterThan' = '1KB'; + }; + + $Result.FileCount | Should -Be 2; + $Result.TotalSize | Should -Be 7000; + } + + It 'returns the kept entries with IncludeFileList' { + $Result = Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'IncludeFileList' = $true; }; + + [array]$Names = @($Result.FileList | ForEach-Object { $_.Name } | Sort-Object); + $Names | Should -Be @('a.log', 'b.log', 'c.txt', 'sub'); + } + + It 'resolves a relative path against the current location' { + $Result = & $script:IcingaModule { + param ($Root); + + Push-Location -Path $Root; + try { + Get-IcingaDirectoryInformation -Path 'sub'; + } finally { + Pop-Location; + } + } $script:Root; + + $Result.FileCount | Should -Be 1; + $Result.FolderCount | Should -Be 1; + } + + It 'rejects an invalid filter value with DirectoryFilterInvalid' { + $Result = Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'ChangeOlderThan' = '20MB'; }; + $Result.GetType().Name | Should -Be 'IcingaError'; + $Result.ReturnCode | Should -Be 'DirectoryFilterInvalid'; + $Result.Message | Should -Be 'The value "20MB" of -ChangeOlderThan is not a valid duration such as 20d, 12h or 30m'; + + (Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'FileSizeGreaterThan' = 'abc'; }).ReturnCode | Should -Be 'DirectoryFilterInvalid'; + (Invoke-TestDirectory -Arguments @{ 'Path' = $script:Root; 'FileNames' = @( '[unclosed' ); }).ReturnCode | Should -Be 'DirectoryFilterInvalid'; + } + + It 'reports a missing path, or an empty result with IgnoreMissingPath' { + [string]$Missing = Join-Path -Path $TestDrive -ChildPath 'missing'; + + $Result = Invoke-TestDirectory -Arguments @{ 'Path' = $Missing; }; + $Result.ReturnCode | Should -Be 'DirectoryPathNotFound'; + $Result.Message | Should -Be ([string]::Format('The directory "{0}" does not exist on this system', $Missing)); + + $Empty = Invoke-TestDirectory -Arguments @{ 'Path' = $Missing; 'IgnoreMissingPath' = $true; }; + $Empty.Exists | Should -BeFalse; + $Empty.FileCount | Should -Be 0; + + (Invoke-TestDirectory -Arguments @{ 'Path' = ''; }).ReturnCode | Should -Be 'DirectoryPathMissing'; + } + + It 'reports a directory that cannot be listed with DirectoryAccessDenied' { + [string]$Locked = Join-Path -Path $TestDrive -ChildPath 'locked'; + New-Item -Path $Locked -ItemType Directory -Force | Out-Null; + + $Rule = New-Object System.Security.AccessControl.FileSystemAccessRule( + [System.Security.Principal.WindowsIdentity]::GetCurrent().Name, + [System.Security.AccessControl.FileSystemRights]::ListDirectory, + [System.Security.AccessControl.AccessControlType]::Deny + ); + $Acl = Get-Acl -Path $Locked; + $Acl.AddAccessRule($Rule); + Set-Acl -Path $Locked -AclObject $Acl; + + try { + $Result = Invoke-TestDirectory -Arguments @{ 'Path' = $Locked; }; + $Result.ReturnCode | Should -Be 'DirectoryAccessDenied'; + $Result.Message | Should -Be ([string]::Format('Access to the directory "{0}" was denied', $Locked)); + } finally { + $Acl = Get-Acl -Path $Locked; + [void]$Acl.RemoveAccessRule($Rule); + Set-Acl -Path $Locked -AclObject $Acl; + } + } + + It 'scans 5000 files with filters in one pass within the time budget' { + [string]$Large = Join-Path -Path $TestDrive -ChildPath 'large'; + New-Item -Path $Large -ItemType Directory -Force | Out-Null; + + for ($i = 0; $i -lt 5000; $i++) { + [System.IO.File]::WriteAllBytes((Join-Path -Path $Large -ChildPath ([string]::Format('file{0}.log', $i))), [byte[]]::new($i % 10)); + } + + $Watch = [System.Diagnostics.Stopwatch]::StartNew(); + $Result = Invoke-TestDirectory -Arguments @{ 'Path' = $Large; 'FileNames' = @('*.log'); 'ChangeYoungerThan' = '1h'; 'FileSizeGreaterThan' = '4'; }; + $Watch.Stop(); + + $Result.FileCount | Should -Be 2500; + $Watch.ElapsedMilliseconds | Should -BeLessThan 5000; + } +} diff --git a/Tests/Get-IcingaDiskInformation.Tests.ps1 b/Tests/Get-IcingaDiskInformation.Tests.ps1 new file mode 100644 index 0000000..b8a9ab1 --- /dev/null +++ b/Tests/Get-IcingaDiskInformation.Tests.ps1 @@ -0,0 +1,211 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Get-IcingaDiskInformation' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + # Runs the provider inside the module scope with Get-IcingaWindowsInformation + # shadowed by a function that serves the stub instances per class, or an + # IcingaError for every class listed in FailingClasses. + function Invoke-TestDiskInformation() + { + param ( + [string]$Entrypoint = 'PhysicalDisk', + [hashtable]$StubData = @{ }, + [array]$FailingClasses = @() + ); + + return (& $script:IcingaModule { + param ($Entrypoint, $StubData, $FailingClasses); + + function Get-IcingaWindowsInformation() + { + param ( + [string]$ClassName = '', + [string]$Namespace = '', + [string]$Filter = '', + [array]$Property = @() + ); + + if ($FailingClasses -contains $ClassName) { + return [IcingaError]::new('WindowsInformationClassUnknown', [string]::Format('Simulated failure of {0}', $ClassName), @{ }); + } + + if ($StubData.ContainsKey($ClassName)) { + return ,@($StubData[$ClassName]); + } + + return ,@(); + } + + $Value = Get-IcingaDiskInformation -Entrypoint $Entrypoint; + + return @{ + 'Value' = $Value; + 'IsError' = ($Value -is [IcingaError]); + }; + } $Entrypoint $StubData $FailingClasses); + } + + $script:StubData = @{ + 'Win32_Volume' = @( + [PSCustomObject]@{ 'DeviceID' = '\\?\Volume{c}\'; 'Name' = 'C:\'; 'DriveLetter' = 'C:'; 'Label' = 'System'; 'FileSystem' = 'NTFS'; 'Capacity' = [uint64]500000000000; 'FreeSpace' = [uint64]100000000000; }, + [PSCustomObject]@{ 'DeviceID' = '\\?\Volume{r}\'; 'Name' = '\\?\Volume{r}\'; 'DriveLetter' = $null; 'Label' = 'Recovery'; 'FileSystem' = 'NTFS'; 'Capacity' = [uint64]1000000000; 'FreeSpace' = [uint64]100000000; }, + [PSCustomObject]@{ 'DeviceID' = '\\?\Volume{x}\'; 'Name' = '\\?\Volume{x}\'; 'DriveLetter' = $null; 'Label' = $null; 'FileSystem' = 'RAW'; 'Capacity' = $null; 'FreeSpace' = $null; } + ); + 'MSFT_Partition' = @( + [PSCustomObject]@{ 'DiskNumber' = [uint32]0; 'PartitionNumber' = [uint32]1; 'DriveLetter' = [char]0; 'AccessPaths' = @('\\?\Volume{e}\'); 'Size' = [uint64]200000000; 'Offset' = [uint64]1048576; 'GptType' = '{c12a7328-f81f-11d2-ba4b-00a0c93ec93b}'; 'MbrType' = $null; 'IsBoot' = $false; 'IsSystem' = $true; 'IsActive' = $false; 'IsHidden' = $true; }, + [PSCustomObject]@{ 'DiskNumber' = [uint32]0; 'PartitionNumber' = [uint32]3; 'DriveLetter' = [char]'C'; 'AccessPaths' = @('C:\', '\\?\Volume{c}\'); 'Size' = [uint64]500000000000; 'Offset' = [uint64]227540992; 'GptType' = '{ebd0a0a2-b9e5-4433-87c0-68b6b72699c7}'; 'MbrType' = $null; 'IsBoot' = $true; 'IsSystem' = $false; 'IsActive' = $false; 'IsHidden' = $false; }, + [PSCustomObject]@{ 'DiskNumber' = [uint32]0; 'PartitionNumber' = [uint32]4; 'DriveLetter' = [char]0; 'AccessPaths' = @('\\?\Volume{r}\'); 'Size' = [uint64]1000000000; 'Offset' = [uint64]500300000000; 'GptType' = '{de94bba4-06d1-4d40-a16a-bfd50179d6ac}'; 'MbrType' = $null; 'IsBoot' = $false; 'IsSystem' = $false; 'IsActive' = $false; 'IsHidden' = $true; }, + [PSCustomObject]@{ 'DiskNumber' = [uint32]1; 'PartitionNumber' = [uint32]1; 'DriveLetter' = [char]'E'; 'AccessPaths' = @('E:\'); 'Size' = [uint64]100000000000; 'Offset' = [uint64]1048576; 'GptType' = $null; 'MbrType' = [uint16]7; 'IsBoot' = $false; 'IsSystem' = $false; 'IsActive' = $true; 'IsHidden' = $false; } + ); + 'MSFT_Disk' = @( + [PSCustomObject]@{ 'Number' = [uint32]0; 'FriendlyName' = 'NVMe Disk'; 'Model' = 'NVMe Disk'; 'Manufacturer' = 'Vendor'; 'SerialNumber' = 'SERIAL0 '; 'UniqueId' = 'eui.0000'; 'Size' = [uint64]512000000000; 'BusType' = [uint16]17; 'HealthStatus' = [uint16]0; 'OperationalStatus' = @([uint16]53264); 'IsOffline' = $false; 'OfflineReason' = [uint16]0; 'IsReadOnly' = $false; 'IsBoot' = $true; 'IsSystem' = $true; 'IsClustered' = $false; 'PartitionStyle' = [uint16]2; 'Location' = 'PCI Slot 8'; }, + [PSCustomObject]@{ 'Number' = [uint32]1; 'FriendlyName' = 'SAN LUN'; 'Model' = 'LUN'; 'Manufacturer' = 'SAN'; 'SerialNumber' = 'SAN-SERIAL'; 'UniqueId' = '600A0B80'; 'Size' = [uint64]100000000000; 'BusType' = [uint16]6; 'HealthStatus' = [uint16]0; 'OperationalStatus' = @([uint16]53264); 'IsOffline' = $false; 'OfflineReason' = [uint16]0; 'IsReadOnly' = $true; 'IsBoot' = $false; 'IsSystem' = $false; 'IsClustered' = $true; 'PartitionStyle' = [uint16]1; 'Location' = 'Fibre Channel'; } + ); + 'MSFT_PhysicalDisk' = @( + [PSCustomObject]@{ 'DeviceId' = '0'; 'MediaType' = [uint16]4; 'SpindleSpeed' = [uint32]0; } + ); + 'MPIO_DISK_INFO' = @( + [PSCustomObject]@{ 'InstanceName' = 'ROOT\MPIO\0000_0'; 'DriveInfo' = @([PSCustomObject]@{ 'Name' = 'MPIO Disk1'; 'NumberPaths' = [uint32]4; 'SerialNumber' = '600A0B80'; }); } + ); + }; + } + + Context 'Volume entrypoint' { + It 'returns every volume keyed by its volume path with sizes in bytes' { + $Volumes = (Invoke-TestDiskInformation -Entrypoint 'Volume' -StubData $script:StubData).Value; + $Volumes.Count | Should -Be 3; + $Volumes['\\?\Volume{c}\'].Name | Should -Be 'C:\'; + $Volumes['\\?\Volume{c}\'].DriveLetter | Should -Be 'C:'; + $Volumes['\\?\Volume{c}\'].Size | Should -Be 500000000000; + $Volumes['\\?\Volume{c}\'].FreeSpace | Should -Be 100000000000; + $Volumes['\\?\Volume{c}\'].UsedSpace | Should -Be 400000000000; + $Volumes['\\?\Volume{r}\'].Label | Should -Be 'Recovery'; + } + + It 'links each volume to its disk and partition through the access paths' { + $Volumes = (Invoke-TestDiskInformation -Entrypoint 'Volume' -StubData $script:StubData).Value; + $Volumes['\\?\Volume{c}\'].DiskNumber | Should -Be 0; + $Volumes['\\?\Volume{c}\'].PartitionNumber | Should -Be 3; + $Volumes['\\?\Volume{c}\'].PartitionId | Should -Be 'Disk #0, Partition #3'; + $Volumes['\\?\Volume{x}\'].DiskNumber | Should -BeNullOrEmpty; + } + + It 'reports unknown sizes as $null' { + $Volume = (Invoke-TestDiskInformation -Entrypoint 'Volume' -StubData $script:StubData).Value['\\?\Volume{x}\']; + $Volume.Size | Should -BeNullOrEmpty; + $Volume.UsedSpace | Should -BeNullOrEmpty; + } + + It 'still returns the volumes when the partition data is unavailable' { + $Result = Invoke-TestDiskInformation -Entrypoint 'Volume' -StubData $script:StubData -FailingClasses 'MSFT_Partition'; + $Result.IsError | Should -BeFalse; + $Result.Value['\\?\Volume{c}\'].Size | Should -Be 500000000000; + $Result.Value['\\?\Volume{c}\'].DiskNumber | Should -BeNullOrEmpty; + } + + It 'returns the IcingaError when the volumes cannot be read' { + $Result = Invoke-TestDiskInformation -Entrypoint 'Volume' -StubData $script:StubData -FailingClasses 'Win32_Volume'; + $Result.IsError | Should -BeTrue; + $Result.Value.Message | Should -Be 'Simulated failure of Win32_Volume'; + } + + It 'skips querying MSFT_Partition when SkipPartitionMapping is enabled on Volume entrypoint' { + $Outcome = & $script:IcingaModule { + param ($StubData); + + $script:QueriedClasses = @(); + + function Get-IcingaWindowsInformation() + { + param ( + [string]$ClassName = '', + [string]$Namespace = '', + [string]$Filter = '', + [array]$Property = @() + ); + + $script:QueriedClasses += $ClassName; + return ,@($StubData[$ClassName]); + } + + $Vols = Get-IcingaDiskInformation -Entrypoint 'Volume' -SkipPartitionMapping; + + return @{ + 'Queried' = $script:QueriedClasses; + 'Volumes' = $Vols; + }; + } $script:StubData; + + $Outcome['Queried'] | Should -Be @( 'Win32_Volume' ); + $Outcome['Volumes'].Count | Should -Be 3; + $Outcome['Volumes']['\\?\Volume{c}\'].DiskNumber | Should -BeNullOrEmpty; + } + } + + Context 'Partition entrypoint' { + It 'returns every partition with drive letter and linked volume' { + $Partitions = (Invoke-TestDiskInformation -Entrypoint 'Partition' -StubData $script:StubData).Value; + $Partitions.Count | Should -Be 4; + $Partitions['Disk #0, Partition #3'].DriveLetter | Should -Be 'C:'; + $Partitions['Disk #0, Partition #3'].VolumeId | Should -Be '\\?\Volume{c}\'; + $Partitions['Disk #0, Partition #3'].Volume.Name | Should -Be 'C:\'; + $Partitions['Disk #0, Partition #3'].IsBoot | Should -BeTrue; + $Partitions['Disk #0, Partition #1'].DriveLetter | Should -Be ''; + $Partitions['Disk #0, Partition #1'].Volume | Should -BeNullOrEmpty; + $Partitions['Disk #1, Partition #1'].MbrType | Should -Be 7; + } + + It 'returns the IcingaError when the partitions cannot be read' { + (Invoke-TestDiskInformation -Entrypoint 'Partition' -StubData $script:StubData -FailingClasses 'MSFT_Partition').IsError | Should -BeTrue; + } + } + + Context 'PhysicalDisk entrypoint' { + It 'returns every disk keyed by its number with media type and status' { + $Disks = (Invoke-TestDiskInformation -StubData $script:StubData).Value; + $Disks.Count | Should -Be 2; + $Disks['0'].FriendlyName | Should -Be 'NVMe Disk'; + $Disks['0'].SerialNumber | Should -Be 'SERIAL0'; + $Disks['0'].MediaType | Should -Be 4; + $Disks['0'].BusType | Should -Be 17; + $Disks['0'].OperationalStatus | Should -Be @(53264); + $Disks['0'].IsBoot | Should -BeTrue; + $Disks['1'].IsReadOnly | Should -BeTrue; + $Disks['1'].MediaType | Should -BeNullOrEmpty; + } + + It 'attaches partitions, volumes and drive letters to their disk' { + $Disks = (Invoke-TestDiskInformation -StubData $script:StubData).Value; + @($Disks['0'].Partitions.Keys | Sort-Object) | Should -Be @('1', '3', '4'); + $Disks['0'].DriveLetters | Should -Be @('C:'); + @($Disks['0'].Volumes | ForEach-Object { $_.Name }) | Should -Be @('C:\', '\\?\Volume{r}\'); + $Disks['1'].DriveLetters | Should -Be @('E:'); + } + + It 'matches the MPIO information by unique id' { + $Disks = (Invoke-TestDiskInformation -StubData $script:StubData).Value; + $Disks['1'].MPIO.Name | Should -Be 'MPIO Disk1'; + $Disks['1'].MPIO.NumberPaths | Should -Be 4; + $Disks['1'].MPIO.InstanceName | Should -Be 'ROOT\MPIO\0000_0'; + $Disks['0'].MPIO | Should -BeNullOrEmpty; + } + + It 'leaves MPIO and media type empty when their classes are unavailable' { + $Result = Invoke-TestDiskInformation -StubData $script:StubData -FailingClasses 'MPIO_DISK_INFO', 'MSFT_PhysicalDisk'; + $Result.IsError | Should -BeFalse; + $Result.Value['1'].MPIO | Should -BeNullOrEmpty; + $Result.Value['0'].MediaType | Should -BeNullOrEmpty; + } + + It 'returns the IcingaError when the disks cannot be read' { + (Invoke-TestDiskInformation -StubData $script:StubData -FailingClasses 'MSFT_Disk').IsError | Should -BeTrue; + } + } +} diff --git a/Tests/Get-IcingaPerformanceCounter.Tests.ps1 b/Tests/Get-IcingaPerformanceCounter.Tests.ps1 index 9322eb5..5390d50 100644 --- a/Tests/Get-IcingaPerformanceCounter.Tests.ps1 +++ b/Tests/Get-IcingaPerformanceCounter.Tests.ps1 @@ -267,5 +267,71 @@ Describe 'Get-IcingaPerformanceCounter' { }; $err | Should -Not -BeNullOrEmpty; } + + It 'skips registering malformed counter paths, writes BOM-less UTF-8 cache files, and survives daemon timeout disposal races' { + $MockCacheDir = Join-Path -Path $TestDrive -ChildPath ('PerfCache_' + [System.Guid]::NewGuid().ToString('N')); + New-Item -Path $MockCacheDir -ItemType Directory -Force | Out-Null; + + [hashtable]$DaemonSafety = & $script:IcingaModule { + param ($CacheDir); + + $Store = (Get-GlobalRuntimeVariable).Public.PerformanceCounter; + [datetime]$RemovedAt = [datetime]::MinValue; + [void]$Store.Registered.TryRemove('not_a_valid_counter', [ref]$RemovedAt); + Get-IcingaPerformanceCounter -Counter 'not_a_valid_counter' | Out-Null; + [bool]$InvalidRegistered = $Store.Registered.ContainsKey('not_a_valid_counter'); + + $Store.Registered['\Memory\Available Bytes'] = (Get-Date); + + function Get-ModuleCacheDirectory() + { + return $CacheDir; + } + + Write-IcingaPerformanceCounterCache; + [string]$CacheFile = Join-Path -Path $CacheDir -ChildPath 'PerformanceCounter.json'; + [byte[]]$RawBytes = [System.IO.File]::ReadAllBytes($CacheFile); + [bool]$HasUtf8Bom = ($RawBytes.Length -ge 3 -and $RawBytes[0] -eq 0xEF -and $RawBytes[1] -eq 0xBB -and $RawBytes[2] -eq 0xBF); + + # Simulate a timed-out caller whose response BlockingCollection was already disposed + [string]$StaleId = [System.Guid]::NewGuid().ToString(); + $DisposedQueue = [System.Collections.Concurrent.BlockingCollection[PSObject]]::new(1); + $DisposedQueue.Dispose(); + $Store.PendingRequests[$StaleId] = $DisposedQueue; + $Store.RequestQueue.Add([PSCustomObject]@{ + 'RequestId' = $StaleId; + 'Counter' = [string[]]@( '\Memory\Available Bytes' ); + }); + + $script:LoopCount = 0; + function Test-ThreadRunning() + { + $script:LoopCount++; + return ($script:LoopCount -le 1); + } + function Set-ThreadProcessing() + { + } + function Update-IcingaPerformanceCounterState() + { + param ($Store = $null); + } + + Start-IcingaPerformanceCounterDaemon; + [bool]$StaleRemoved = (-not $Store.PendingRequests.ContainsKey($StaleId)); + + return @{ + 'InvalidRegistered' = $InvalidRegistered; + 'CacheExists' = (Test-Path -Path $CacheFile); + 'HasUtf8Bom' = $HasUtf8Bom; + 'StaleRemoved' = $StaleRemoved; + }; + } $MockCacheDir; + + $DaemonSafety['InvalidRegistered'] | Should -BeFalse; + $DaemonSafety['CacheExists'] | Should -BeTrue; + $DaemonSafety['HasUtf8Bom'] | Should -BeFalse; + $DaemonSafety['StaleRemoved'] | Should -BeTrue; + } } } diff --git a/Tests/Get-IcingaProcessInformation.Tests.ps1 b/Tests/Get-IcingaProcessInformation.Tests.ps1 new file mode 100644 index 0000000..7d03b28 --- /dev/null +++ b/Tests/Get-IcingaProcessInformation.Tests.ps1 @@ -0,0 +1,191 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Get-IcingaProcessInformation' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + # Builds the -StructureByInstance result of the process counters. Every + # process is @(instance, id, cpu, memory, pagefile, threads); a string id + # becomes the counter error of an instance that ended between the reads. + function New-TestProcessCounter() + { + param ( + [array]$Processes = @( + @('powershell', 100, 50, 104857600, 52428800, 10), + @('powershell#1', 200, 30, 209715200, 62914560, 20), + @('svchost', 300, 8, 10485760, 5242880, 5), + @('_Total', 0, 400, 1073741824, 1073741824, 900), + @('Idle', 0, 300, 8192, 0, 8), + @('gone', 'The instance "gone" does not exist in the category "Process"', 0, 0, 0, 0) + ) + ); + + [hashtable]$Result = @{ }; + + foreach ($Process in $Processes) { + [hashtable]$Values = @{ }; + [array]$Counters = @( + @('ID Process', $Process[1]), + @('% Processor Time', $Process[2]), + @('Working Set - Private', $Process[3]), + @('Page File Bytes', $Process[4]), + @('Thread Count', $Process[5]) + ); + + foreach ($Counter in $Counters) { + $Leaf = @{ 'value' = [decimal]0; 'sample' = $null; 'help' = ''; 'type' = ''; 'error' = $null; }; + + if ($Counter[1] -is [string]) { + $Leaf['error'] = $Counter[1]; + } else { + $Leaf['value'] = [decimal]$Counter[1]; + } + + $Values[$Counter[0]] = $Leaf; + } + + $Result[$Process[0]] = @{ 'Process' = $Values; }; + } + + return $Result; + } + + # Runs the provider inside the module scope with the CIM and performance counter + # functions shadowed. 16GiB installed memory, 4 logical processors, 20GiB commit limit. + function Invoke-TestProcessInformation() + { + param ( + $Counters = (New-TestProcessCounter), + $CommitLimit = [decimal]21474836480, + [hashtable]$Arguments = @{ }, + [string]$FailClass = '' + ); + + return (& $script:IcingaModule { + param ($Counters, $CommitLimit, $Arguments, $FailClass); + + function New-IcingaPerformanceCounter() + { + param ( + [array]$Counter = @() + ); + } + + function Get-IcingaPerformanceCounter() + { + param ( + [array]$Counter = @(), + [int]$TimeoutMs = 5000, + [switch]$StructureByInstance = $false + ); + + if ($StructureByInstance) { + return $Counters; + } + + $Leaf = @{ 'value' = [decimal]0; 'sample' = $null; 'help' = ''; 'type' = ''; 'error' = $null; }; + + if ($CommitLimit -is [string]) { + $Leaf['error'] = $CommitLimit; + } else { + $Leaf['value'] = [decimal]$CommitLimit; + } + + return @{ '\Memory\Commit Limit' = $Leaf; }; + } + + function Get-IcingaWindowsInformation() + { + param ( + [string]$ClassName = '', + [string]$Namespace = 'root/cimv2', + [string]$Filter = '', + [array]$Property = @() + ); + + if ($ClassName -eq $FailClass) { + return [IcingaError]::new('WindowsInformationAccessDenied', 'Simulated failure of ' + $ClassName, @{ }); + } + + return ,@([PSCustomObject]@{ 'TotalPhysicalMemory' = [uint64]17179869184; 'NumberOfLogicalProcessors' = [uint32]4; }); + } + + Get-IcingaProcessInformation @Arguments; + } $Counters $CommitLimit $Arguments $FailClass); + } + } + + It 'groups the processes by name and keys every process by its id' { + $Data = Invoke-TestProcessInformation; + + @($Data.Processes.Keys | Sort-Object) | Should -Be @('powershell', 'svchost'); + @($Data.Processes['powershell'].Instances.Keys | Sort-Object) | Should -Be @('100', '200'); + $Data.Processes['powershell'].Instances['200'].Memory | Should -Be 209715200; + $Data.Processes['powershell'].Instances['200'].PageFile | Should -Be 62914560; + $Data.Processes['powershell'].Instances['200'].Threads | Should -Be 20; + } + + It 'divides the CPU usage by the number of logical processors' { + $Data = Invoke-TestProcessInformation; + + $Data.Processes['powershell'].Instances['100'].Cpu | Should -Be 12.5; + $Data.Processes['powershell'].Instances['200'].Cpu | Should -Be 7.5; + $Data.Processes['svchost'].Instances['300'].Cpu | Should -Be 2; + $Data.LogicalProcessors | Should -Be 4; + } + + It 'sums every process of a name' { + $Total = (Invoke-TestProcessInformation).Processes['powershell'].Total; + + $Total.Cpu | Should -Be 20; + $Total.Memory | Should -Be 314572800; + $Total.PageFile | Should -Be 115343360; + $Total.Threads | Should -Be 30; + $Total.Count | Should -Be 2; + } + + It 'leaves out _Total, Idle and processes that ended between the reads' { + $Data = Invoke-TestProcessInformation; + + $Data.Processes.ContainsKey('_Total') | Should -BeFalse; + $Data.Processes.ContainsKey('Idle') | Should -BeFalse; + $Data.Processes.ContainsKey('gone') | Should -BeFalse; + } + + It 'returns the installed memory and the commit limit' { + $Data = Invoke-TestProcessInformation; + + $Data.MemoryTotal | Should -Be 17179869184; + $Data.CommitLimit | Should -Be 21474836480; + } + + It 'filters the processes by name' { + @((Invoke-TestProcessInformation -Arguments @{ 'Include' = @('power*'); }).Processes.Keys) | Should -Be @('powershell'); + @((Invoke-TestProcessInformation -Arguments @{ 'Exclude' = @('POWERSHELL'); }).Processes.Keys) | Should -Be @('svchost'); + } + + It 'returns the IcingaError of a failed CIM query' { + $Data = Invoke-TestProcessInformation -FailClass 'Win32_ComputerSystem'; + + (Test-IcingaError -InputObject $Data) | Should -BeTrue; + $Data.Message | Should -Be 'Simulated failure of Win32_ComputerSystem'; + } + + It 'returns an IcingaError when the counters cannot be read' { + $Data = Invoke-TestProcessInformation -Counters $null; + (Test-IcingaError -InputObject $Data) | Should -BeTrue; + $Data.ReturnCode | Should -Be 'ProcessCounterReadFailed'; + + $Data = Invoke-TestProcessInformation -Counters @{ }; + (Test-IcingaError -InputObject $Data) | Should -BeTrue; + + $Data = Invoke-TestProcessInformation -CommitLimit 'Counter not initialized'; + (Test-IcingaError -InputObject $Data) | Should -BeTrue; + $Data.Message | Should -Match 'Commit Limit'; + } +} diff --git a/Tests/Get-IcingaScheduledTask.Tests.ps1 b/Tests/Get-IcingaScheduledTask.Tests.ps1 new file mode 100644 index 0000000..f0cae5d --- /dev/null +++ b/Tests/Get-IcingaScheduledTask.Tests.ps1 @@ -0,0 +1,121 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Get-IcingaScheduledTask' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + function Invoke-TestGetScheduledTask() + { + param ( + [array]$Tasks = @(), + [hashtable]$Infos = @{ }, + [hashtable]$Arguments = @{ }, + [switch]$Fail = $false + ); + + return (& $script:IcingaModule { + param ($Tasks, $Infos, $Arguments, $Fail); + + function Get-ScheduledTask() + { + param ( + [string]$TaskName = '*', + [string]$ErrorAction = 'Continue' + ); + + if ($Fail) { + throw 'Access is denied'; + } + + return $Tasks; + } + + function Get-ScheduledTaskInfo() + { + param ( + [string]$TaskName = '', + [string]$TaskPath = '', + [string]$ErrorAction = 'Continue' + ); + + [string]$Key = '{0}{1}' -f $TaskPath, $TaskName; + if ($Infos.ContainsKey($Key)) { + return $Infos[$Key]; + } + + return $null; + } + + return (Get-IcingaScheduledTask @Arguments); + } $Tasks $Infos $Arguments $Fail); + } + } + + Context 'Task collection and filtering' { + It 'groups tasks by TaskPath and resolves runtime info' { + [datetime]$Past = [datetime]::Now.AddHours(-2); + [datetime]$Future = [datetime]::Now.AddHours(1); + + $Tasks = @( + [PSCustomObject]@{ 'TaskName' = 'Renew Certificate'; 'TaskPath' = '\Icinga\'; 'State' = 'Ready' }, + [PSCustomObject]@{ 'TaskName' = 'Backup'; 'TaskPath' = '\Microsoft\'; 'State' = 'Disabled' } + ); + $Infos = @{ + '\Icinga\Renew Certificate' = [PSCustomObject]@{ + 'LastRunTime' = $Past; + 'NextRunTime' = $Future; + 'NumberOfMissedRuns' = 1; + 'LastTaskResult' = 0; + }; + '\Microsoft\Backup' = [PSCustomObject]@{ + 'LastRunTime' = [datetime]::new(1999, 11, 30, 0, 0, 0); + 'NextRunTime' = $null; + 'NumberOfMissedRuns' = 0; + 'LastTaskResult' = 267011; + }; + }; + + $Result = Invoke-TestGetScheduledTask -Tasks $Tasks -Infos $Infos; + $Result.Tasks.Count | Should -Be 2; + $Result.Tasks['\Icinga\'][0].TaskName | Should -Be 'Renew Certificate'; + [string]$Result.Tasks['\Icinga\'][0].State | Should -Be 'Ready'; + $Result.Tasks['\Icinga\'][0].MissedRuns | Should -Be 1; + $Result.Tasks['\Icinga\'][0].LastRunOffset | Should -BeGreaterThan 7000; + $Result.Tasks['\Icinga\'][0].NextRunOffset | Should -BeGreaterThan 3000; + + # 1999-11-30 with 267011 (SCHED_S_TASK_HAS_NOT_RUN) is treated as never run. + $Result.Tasks['\Microsoft\'][0].LastRunTime | Should -Be ''; + $Result.Tasks['\Microsoft\'][0].LastRunOffset | Should -Be 0; + $Result.Tasks['\Microsoft\'][0].NextRunTime | Should -Be ''; + $Result.Tasks['\Microsoft\'][0].NextRunOffset | Should -Be 0; + } + + It 'filters by TaskName, ExcludeTaskName, TaskPath and ExcludeTaskPath' { + $Tasks = @( + [PSCustomObject]@{ 'TaskName' = 'TaskA'; 'TaskPath' = '\Icinga\'; 'State' = 'Ready' }, + [PSCustomObject]@{ 'TaskName' = 'TaskB'; 'TaskPath' = '\Icinga\'; 'State' = 'Ready' }, + [PSCustomObject]@{ 'TaskName' = 'TaskC'; 'TaskPath' = '\Other\'; 'State' = 'Ready' } + ); + + $Result = Invoke-TestGetScheduledTask -Tasks $Tasks -Arguments @{ + 'TaskPath' = '\Icinga\*'; + 'ExcludeTaskName' = 'TaskB'; + }; + + $Result.Tasks.Count | Should -Be 1; + $Result.Tasks['\Icinga\'].Count | Should -Be 1; + $Result.Tasks['\Icinga\'][0].TaskName | Should -Be 'TaskA'; + $Result.TaskNames | Should -Be @('TaskA'); + } + + It 'returns an IcingaError when Get-ScheduledTask fails' { + $Result = Invoke-TestGetScheduledTask -Fail; + (Test-IcingaError -InputObject $Result) | Should -BeTrue; + } + } +} diff --git a/Tests/Get-IcingaWindowsInformation.Tests.ps1 b/Tests/Get-IcingaWindowsInformation.Tests.ps1 new file mode 100644 index 0000000..c6d9919 --- /dev/null +++ b/Tests/Get-IcingaWindowsInformation.Tests.ps1 @@ -0,0 +1,130 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Get-IcingaWindowsInformation' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + # Runs the query inside the module scope with Get-CimInstance shadowed by a + # function. The result is wrapped in a hashtable so its type survives the + # pipeline, and IcingaError is only resolvable inside the module scope. + function Invoke-TestWindowsInformation() + { + param ( + [hashtable]$Arguments = @{ }, + [array]$StubData = @(), + [string]$FailCode = '', + [switch]$EchoArguments + ); + + return (& $script:IcingaModule { + param ($Arguments, $StubData, $FailCode, $EchoArguments); + + class FakeCimException : System.Exception + { + [string]$NativeErrorCode = ''; + + FakeCimException([string]$Message, [string]$Code) : base($Message) + { + $this.NativeErrorCode = $Code; + } + } + + function Get-CimInstance() + { + [CmdletBinding()] + param ( + [string]$ClassName = '', + [string]$Namespace = '', + [string]$Filter = '', + [string[]]$Property = @() + ); + + if (-not [string]::IsNullOrEmpty($FailCode)) { + throw [FakeCimException]::new('Simulated CIM failure', $FailCode); + } + + if ($EchoArguments) { + return [PSCustomObject]@{ + 'Bound' = @($PSBoundParameters.Keys); + 'ClassName' = $ClassName; + 'Namespace' = $Namespace; + 'Filter' = $Filter; + 'Property' = $Property; + }; + } + + return $StubData; + } + + $Value = Get-IcingaWindowsInformation @Arguments; + + return @{ + 'Value' = $Value; + 'IsArray' = ($Value -is [array]); + 'IsError' = ($Value -is [IcingaError]); + }; + } $Arguments $StubData $FailCode $EchoArguments); + } + } + + Context 'Successful queries' { + It 'returns the instances as an array, even a single one' { + $Result = Invoke-TestWindowsInformation -Arguments @{ 'ClassName' = 'Win32_Service'; } -StubData @([PSCustomObject]@{ 'Name' = 'Spooler'; }); + $Result.IsArray | Should -BeTrue; + $Result.Value.Count | Should -Be 1; + $Result.Value[0].Name | Should -Be 'Spooler'; + } + + It 'returns an empty array when nothing matches' { + $Result = Invoke-TestWindowsInformation -Arguments @{ 'ClassName' = 'Win32_Service'; }; + $Result.IsArray | Should -BeTrue; + $Result.Value.Count | Should -Be 0; + } + + It 'uses root/cimv2 and passes filter and properties only when given' { + $Plain = Invoke-TestWindowsInformation -Arguments @{ 'ClassName' = 'Win32_Volume'; } -EchoArguments; + $Plain.Value[0].Namespace | Should -Be 'root/cimv2'; + $Plain.Value[0].Bound | Should -Not -Contain 'Filter'; + $Plain.Value[0].Bound | Should -Not -Contain 'Property'; + + $Full = Invoke-TestWindowsInformation -Arguments @{ 'ClassName' = 'MSFT_Disk'; 'Namespace' = 'root/Microsoft/Windows/Storage'; 'Filter' = 'Number = 0'; 'Property' = @('Number', 'Size'); } -EchoArguments; + $Full.Value[0].Namespace | Should -Be 'root/Microsoft/Windows/Storage'; + $Full.Value[0].Filter | Should -Be 'Number = 0'; + $Full.Value[0].Property | Should -Be @('Number', 'Size'); + } + } + + Context 'Failed queries' { + It 'maps the CIM error to ' -ForEach @( + @{ 'Code' = 'InvalidClass'; 'ReturnCode' = 'WindowsInformationClassUnknown'; }, + @{ 'Code' = 'InvalidNamespace'; 'ReturnCode' = 'WindowsInformationNamespaceInvalid'; }, + @{ 'Code' = 'AccessDenied'; 'ReturnCode' = 'WindowsInformationAccessDenied'; }, + @{ 'Code' = 'InvalidQuery'; 'ReturnCode' = 'WindowsInformationInvalidQuery'; }, + @{ 'Code' = 'NoSuchProperty'; 'ReturnCode' = 'WindowsInformationInvalidQuery'; }, + @{ 'Code' = 'Failed'; 'ReturnCode' = 'WindowsInformationQueryFailed'; } + ) { + $Result = Invoke-TestWindowsInformation -Arguments @{ 'ClassName' = 'Win32_Foo'; 'Namespace' = 'root/test'; } -FailCode $Code; + $Result.IsError | Should -BeTrue; + $Result.Value.ReturnCode | Should -Be $ReturnCode; + } + + It 'names class, namespace and reason in the error message and data' { + $Result = Invoke-TestWindowsInformation -Arguments @{ 'ClassName' = 'MPIO_DISK_INFO'; 'Namespace' = 'root/wmi'; } -FailCode 'InvalidClass'; + $Result.Value.Message | Should -Be 'The requested CIM class does not exist on this system: Class "MPIO_DISK_INFO", Namespace "root/wmi": Simulated CIM failure'; + $Result.Value.Data['ClassName'] | Should -Be 'MPIO_DISK_INFO'; + $Result.Value.Data['Namespace'] | Should -Be 'root/wmi'; + } + + It 'returns an IcingaError instead of throwing for a missing class name' { + $Result = Invoke-TestWindowsInformation -Arguments @{ }; + $Result.IsError | Should -BeTrue; + $Result.Value.ReturnCode | Should -Be 'WindowsInformationClassNameMissing'; + $Result.Value.Message | Should -Be 'No CIM class name was provided for the query'; + } + } +} diff --git a/Tests/IcingaPlugin.Tests.ps1 b/Tests/IcingaPlugin.Tests.ps1 index a4fdb6e..8d2c0b0 100644 --- a/Tests/IcingaPlugin.Tests.ps1 +++ b/Tests/IcingaPlugin.Tests.ps1 @@ -948,5 +948,64 @@ Describe 'IcingaPlugin' { $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match '^\[WARNING\] Duration: 45m is greater than threshold 30m'; $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData[0] | Should -Be 'default::ifw_check::duration=2700s;1800;3600;;'; } + + It 'caches Get-PSCallStack in O(1) via ActiveCheckCommand across pre-constructed and child nodes and resets on Compile' { + [hashtable]$ScaleOutcome = & $script:IcingaModule { + $script:StackLookups = 0; + $RealGetCallStack = Get-Command -Name 'Get-PSCallStack' -CommandType Cmdlet; + + function Get-PSCallStack() + { + $script:StackLookups++; + return (& $RealGetCallStack); + } + + function Invoke-IcingaCheckCachedScale() + { + $PreBuiltLeaf = (New-IcingaPlugin 'PreBuilt' 10 '%').MetricIndex('pre').MetricLabel('load').CheckRange(); + $RootPkg = New-IcingaPlugin 'Scale Root'; + $RootPkg.AddCheck($PreBuiltLeaf).Commit(); + + for ($idx = 0; $idx -lt 25; $idx++) { + $RootPkg.AddCheck((New-IcingaPlugin "Item $idx" $idx '%').MetricIndex("i$idx").MetricLabel('load').CheckRange()).Commit(); + } + + return $RootPkg.Compile(); + } + + # Standalone check outside any Invoke-IcingaCheck* must not populate ActiveCheckCommand + [void](New-IcingaPlugin 'ScratchDangling' 42 '%').Warning('80').Critical('90').CheckRange(); + $SlotBeforeScale = (Get-GlobalRuntimeVariable).Private.Icinga.ActiveCheckCommand; + $script:StackLookups = 0; + + [int]$ExitScale = Invoke-IcingaCheckCachedScale; + [int]$CallsDuringPlugin = $script:StackLookups; + [array]$ScalePerf = @((Get-GlobalRuntimeVariable).Private.Icinga.CheckResult.PerformanceData); + $ActiveSlotAfterCompile = (Get-GlobalRuntimeVariable).Private.Icinga.ActiveCheckCommand; + + [int]$ExitStandalone = (New-IcingaPlugin 'Standalone' 5 '%').CheckRange().Compile(); + [string]$StandalonePerf = [string]((Get-GlobalRuntimeVariable).Private.Icinga.CheckResult.PerformanceData[0]); + + return @{ + 'SlotBeforeScale' = $SlotBeforeScale; + 'ExitScale' = $ExitScale; + 'CallsDuringPlugin' = $CallsDuringPlugin; + 'FirstPerf' = [string]$ScalePerf[0]; + 'LastPerf' = [string]$ScalePerf[$ScalePerf.Count - 1]; + 'ActiveSlotAfterCompile' = $ActiveSlotAfterCompile; + 'ExitStandalone' = $ExitStandalone; + 'StandalonePerf' = $StandalonePerf; + }; + }; + + $ScaleOutcome['SlotBeforeScale'] | Should -BeNullOrEmpty; + $ScaleOutcome['ExitScale'] | Should -Be 0; + $ScaleOutcome['CallsDuringPlugin'] | Should -Be 1; + $ScaleOutcome['FirstPerf'] | Should -Be 'pre::ifw_cachedscale::load=10%;;;;'; + $ScaleOutcome['LastPerf'] | Should -Be 'i24::ifw_cachedscale::load=24%;;;;'; + $ScaleOutcome['ActiveSlotAfterCompile'] | Should -BeNullOrEmpty; + $ScaleOutcome['ExitStandalone'] | Should -Be 0; + $ScaleOutcome['StandalonePerf'] | Should -Be 'default::ifw_check::standalone=5%;;;;'; + } } } diff --git a/Tests/IcingaScheduledTaskStatus.Tests.ps1 b/Tests/IcingaScheduledTaskStatus.Tests.ps1 new file mode 100644 index 0000000..ac0b29a --- /dev/null +++ b/Tests/IcingaScheduledTaskStatus.Tests.ps1 @@ -0,0 +1,90 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'IcingaScheduledTaskStatus' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + } + + Context 'Enum values' { + It 'keeps the Task Scheduler state codes used by the state perfdata' { + $Codes = & $script:IcingaModule { + return @( + [int][IcingaScheduledTaskStatus]::Unknown, + [int][IcingaScheduledTaskStatus]::Disabled, + [int][IcingaScheduledTaskStatus]::Queued, + [int][IcingaScheduledTaskStatus]::Ready, + [int][IcingaScheduledTaskStatus]::Running + ); + }; + $Codes | Should -Be @(0, 1, 2, 3, 4); + } + + It 'converts names in any casing and codes as a parameter type' { + $Converted = & $script:IcingaModule { + function Test-IcingaScheduledTaskStatusParameter() + { + param ( + [IcingaScheduledTaskStatus]$State = 'Ready' + ); + + return [string]$State; + } + + return @( + (Test-IcingaScheduledTaskStatusParameter), + (Test-IcingaScheduledTaskStatusParameter -State 'disabled'), + (Test-IcingaScheduledTaskStatusParameter -State 4) + ); + }; + $Converted | Should -Be @('Ready', 'Disabled', 'Running'); + } + + It 'rejects an unknown name as a parameter value' { + { + & $script:IcingaModule { + function Test-IcingaScheduledTaskStatusParameter() + { + param ( + [IcingaScheduledTaskStatus]$State = 'Ready' + ); + + return $State; + } + + Test-IcingaScheduledTaskStatusParameter -State 'Sleeping'; + }; + } | Should -Throw; + } + } + + Context 'IcingaScheduledTaskStatusMap' { + It 'resolves names in any casing and numeric codes' { + $Resolved = & $script:IcingaModule { + return @( + [string][IcingaScheduledTaskStatusMap]::Resolve('Ready'), + [string][IcingaScheduledTaskStatusMap]::Resolve('running'), + [string][IcingaScheduledTaskStatusMap]::Resolve(1), + [string][IcingaScheduledTaskStatusMap]::Resolve('2') + ); + }; + $Resolved | Should -Be @('Ready', 'Running', 'Disabled', 'Queued'); + } + + It 'resolves unmappable values to Unknown' { + $Resolved = & $script:IcingaModule { + return @( + [string][IcingaScheduledTaskStatusMap]::Resolve($null), + [string][IcingaScheduledTaskStatusMap]::Resolve(''), + [string][IcingaScheduledTaskStatusMap]::Resolve('InvalidState'), + [string][IcingaScheduledTaskStatusMap]::Resolve(99) + ); + }; + $Resolved | Should -Be @('Unknown', 'Unknown', 'Unknown', 'Unknown'); + } + } +} diff --git a/Tests/IcingaServiceStartupType.Tests.ps1 b/Tests/IcingaServiceStartupType.Tests.ps1 new file mode 100644 index 0000000..a5f1a14 --- /dev/null +++ b/Tests/IcingaServiceStartupType.Tests.ps1 @@ -0,0 +1,83 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'IcingaServiceStartupType' { + BeforeAll { + # The data types live in the dot-sourced kernel and are only visible inside + # the script module scope. + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + } + + Context 'Enum values' { + It 'keeps the ServiceStartMode codes' { + $Codes = & $script:IcingaModule { + return @( + [int][IcingaServiceStartupType]::Boot, + [int][IcingaServiceStartupType]::System, + [int][IcingaServiceStartupType]::Automatic, + [int][IcingaServiceStartupType]::Manual, + [int][IcingaServiceStartupType]::Disabled, + [int][IcingaServiceStartupType]::Unknown + ); + }; + $Codes | Should -Be @(0, 1, 2, 3, 4, 5); + } + + It 'converts an array of names as a parameter type' { + $Converted = & $script:IcingaModule { + function Test-IcingaServiceStartupTypeParameter() + { + param ( + [IcingaServiceStartupType[]]$StartupType = @() + ); + + return ($StartupType -join ','); + } + + return (Test-IcingaServiceStartupTypeParameter -StartupType 'automatic', 'Disabled'); + }; + $Converted | Should -Be 'Automatic,Disabled'; + } + } + + Context 'IcingaServiceStartupTypeMap' { + It 'resolves the Win32_Service start modes' { + $Resolved = & $script:IcingaModule { + return @( + [string][IcingaServiceStartupTypeMap]::Resolve('Boot'), + [string][IcingaServiceStartupTypeMap]::Resolve('System'), + [string][IcingaServiceStartupTypeMap]::Resolve('Auto'), + [string][IcingaServiceStartupTypeMap]::Resolve('Manual'), + [string][IcingaServiceStartupTypeMap]::Resolve('Disabled') + ); + }; + $Resolved | Should -Be @('Boot', 'System', 'Automatic', 'Manual', 'Disabled'); + } + + It 'resolves names in any casing and numeric codes' { + $Resolved = & $script:IcingaModule { + return @( + [string][IcingaServiceStartupTypeMap]::Resolve('automatic'), + [string][IcingaServiceStartupTypeMap]::Resolve(3) + ); + }; + $Resolved | Should -Be @('Automatic', 'Manual'); + } + + It 'resolves unmappable values to Unknown' { + $Resolved = & $script:IcingaModule { + return @( + [string][IcingaServiceStartupTypeMap]::Resolve($null), + [string][IcingaServiceStartupTypeMap]::Resolve(''), + [string][IcingaServiceStartupTypeMap]::Resolve('Delayed'), + [string][IcingaServiceStartupTypeMap]::Resolve(42) + ); + }; + $Resolved | Should -Be @('Unknown', 'Unknown', 'Unknown', 'Unknown'); + } + } +} diff --git a/Tests/IcingaServiceStatus.Tests.ps1 b/Tests/IcingaServiceStatus.Tests.ps1 new file mode 100644 index 0000000..d5d560b --- /dev/null +++ b/Tests/IcingaServiceStatus.Tests.ps1 @@ -0,0 +1,106 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'IcingaServiceStatus' { + BeforeAll { + # The data types live in the dot-sourced kernel and are only visible inside + # the script module scope. + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + } + + Context 'Enum values' { + It 'keeps the ServiceControllerStatus codes used by the state perfdata' { + $Codes = & $script:IcingaModule { + return @( + [int][IcingaServiceStatus]::Unknown, + [int][IcingaServiceStatus]::Stopped, + [int][IcingaServiceStatus]::StartPending, + [int][IcingaServiceStatus]::StopPending, + [int][IcingaServiceStatus]::Running, + [int][IcingaServiceStatus]::ContinuePending, + [int][IcingaServiceStatus]::PausePending, + [int][IcingaServiceStatus]::Paused + ); + }; + $Codes | Should -Be @(0, 1, 2, 3, 4, 5, 6, 7); + } + + It 'converts names in any casing and codes as a parameter type' { + $Converted = & $script:IcingaModule { + function Test-IcingaServiceStatusParameter() + { + param ( + [IcingaServiceStatus]$Status = 'Running' + ); + + return [string]$Status; + } + + return @( + (Test-IcingaServiceStatusParameter), + (Test-IcingaServiceStatusParameter -Status 'stoppending'), + (Test-IcingaServiceStatusParameter -Status 7) + ); + }; + $Converted | Should -Be @('Running', 'StopPending', 'Paused'); + } + + It 'rejects an unknown name as a parameter value' { + { + & $script:IcingaModule { + function Test-IcingaServiceStatusParameter() + { + param ( + [IcingaServiceStatus]$Status = 'Running' + ); + + return $Status; + } + + Test-IcingaServiceStatusParameter -Status 'Sleeping'; + }; + } | Should -Throw; + } + } + + Context 'IcingaServiceStatusMap' { + It 'resolves Win32_Service states with blanks' { + $Resolved = & $script:IcingaModule { + return @( + [string][IcingaServiceStatusMap]::Resolve('Running'), + [string][IcingaServiceStatusMap]::Resolve('Start Pending'), + [string][IcingaServiceStatusMap]::Resolve('Continue Pending'), + [string][IcingaServiceStatusMap]::Resolve('Unknown') + ); + }; + $Resolved | Should -Be @('Running', 'StartPending', 'ContinuePending', 'Unknown'); + } + + It 'resolves names in any casing and numeric codes' { + $Resolved = & $script:IcingaModule { + return @( + [string][IcingaServiceStatusMap]::Resolve('paused'), + [string][IcingaServiceStatusMap]::Resolve(1), + [string][IcingaServiceStatusMap]::Resolve('4') + ); + }; + $Resolved | Should -Be @('Paused', 'Stopped', 'Running'); + } + + It 'resolves unmappable values to Unknown' { + $Resolved = & $script:IcingaModule { + return @( + [string][IcingaServiceStatusMap]::Resolve($null), + [string][IcingaServiceStatusMap]::Resolve(''), + [string][IcingaServiceStatusMap]::Resolve('Sleeping'), + [string][IcingaServiceStatusMap]::Resolve(99) + ); + }; + $Resolved | Should -Be @('Unknown', 'Unknown', 'Unknown', 'Unknown'); + } + } +} diff --git a/Tests/Invoke-IcingaCheckCPU.Tests.ps1 b/Tests/Invoke-IcingaCheckCPU.Tests.ps1 new file mode 100644 index 0000000..1dc76d4 --- /dev/null +++ b/Tests/Invoke-IcingaCheckCPU.Tests.ps1 @@ -0,0 +1,209 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Invoke-IcingaCheckCPU' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + $script:OriginalDaemonFlag = $Global:IcingaForWindows.Protected.IsBackgroundDaemon; + + # Builds the -StructureByInstance result of Get-IcingaPerformanceCounter for + # '\Processor Information(*)\% Processor Time'. A string value becomes the + # counter error of that instance. + function New-TestCpuCounter() + { + param ( + [hashtable]$Instances = @{ } + ); + + [hashtable]$Result = @{ }; + + foreach ($Instance in $Instances.Keys) { + $Leaf = @{ 'value' = [decimal]0; 'sample' = $null; 'help' = ''; 'type' = ''; 'error' = $null; }; + + if ($Instances[$Instance] -is [string]) { + $Leaf['error'] = $Instances[$Instance]; + } else { + $Leaf['value'] = [decimal]$Instances[$Instance]; + } + + $Result[$Instance] = @{ 'Processor Information' = @{ '% Processor Time' = $Leaf; }; }; + } + + return $Result; + } + + # Runs the plugin inside the module scope with the performance counter + # functions shadowed, so the check works on the given counter values. + function Invoke-TestCpuCheck() + { + param ( + $StubData = $null, + [hashtable]$Arguments = @{ } + ); + + return (& $script:IcingaModule { + param ($StubData, $Arguments); + + function New-IcingaPerformanceCounter() + { + param ( + [array]$Counter = @() + ); + } + + function Get-IcingaPerformanceCounter() + { + param ( + [array]$Counter = @(), + [int]$TimeoutMs = 5000, + [switch]$StructureByInstance = $false + ); + + return $StubData; + } + + Invoke-IcingaCheckCPU @Arguments; + } $StubData $Arguments); + } + + # Windows' own totals carry wrong values on purpose: the plugin must average the + # cores instead of reading these instances. + $script:TwoNodes = New-TestCpuCounter -Instances @{ + '0,1' = 95; + '0,0' = 5; + '0,_Total' = 77; + '1,0' = 10; + '1,_Total' = 99; + '_Total' = 1; + }; + } + + AfterAll { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $script:OriginalDaemonFlag; + } + + BeforeEach { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $true; + } + + It 'writes the perfdata per core, per NUMA node and in total in natural order' { + Invoke-TestCpuCheck -StubData $script:TwoNodes -Arguments @{ 'Warning' = '80'; 'Critical' = '90'; } | Out-Null; + + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Be @( + '0_0::ifw_cpu::load=5%;80;90;0;100', + '0_1::ifw_cpu::load=95%;80;90;0;100', + '0_total::ifw_cpu::load=50%;80;90;0;100', + '1_2::ifw_cpu::load=10%;80;90;0;100', + '1_total::ifw_cpu::load=10%;80;90;0;100', + 'totalload::ifw_cpu::load=36.67%;80;90;0;100' + ); + } + + It 'groups the cores into one container per NUMA node and numbers them across all nodes' { + Invoke-TestCpuCheck -StubData $script:TwoNodes -Arguments @{ 'Verbosity' = 2; } | Should -Be 0; + + [array]$Lines = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output -split "`n"; + $Lines[0] | Should -Be '[OK] CPU Load: 6 Ok'; + $Lines[1] | Should -Be '\_ [OK] NUMA Node #0'; + $Lines[2] | Should -Match '^ \\_ \[OK\] Core #0: '; + $Lines[4] | Should -Match '^ \\_ \[OK\] Node Total: '; + $Lines[5] | Should -Be '\_ [OK] NUMA Node #1'; + $Lines[6] | Should -Be ' \_ [OK] Core #2: 10% is ok'; + $Lines[8] | Should -Match '^\\_ \[OK\] Overall Load: '; + } + + It 'reports the same node total and overall load on a single NUMA node' { + $Counters = New-TestCpuCounter -Instances @{ '0,0' = 13.18; '0,1' = 9.67; '0,2' = 6.52; '0,3' = 1.13; '0,_Total' = 7.44; '_Total' = 7.57; }; + + Invoke-TestCpuCheck -StubData $Counters | Should -Be 0; + + [array]$Perf = $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData; + $Perf[4] | Should -Be '0_total::ifw_cpu::load=7.62%;;;0;100'; + $Perf[5] | Should -Be 'totalload::ifw_cpu::load=7.62%;;;0;100'; + } + + It 'raises CRITICAL when a single core breaches the critical threshold' { + Invoke-TestCpuCheck -StubData $script:TwoNodes -Arguments @{ 'Warning' = '80'; 'Critical' = '90'; } | Should -Be 2; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result.Output | Should -Match '^\[CRITICAL\] CPU Load: 1 Critical 5 Ok'; + $Result.Output | Should -Match ([regex]::Escape('[CRITICAL] Core #1: 95% is greater than threshold 90%')); + } + + It 'reports a core whose counter failed as UNKNOWN and averages the readable cores' { + $Counters = New-TestCpuCounter -Instances @{ '0,0' = 5; '0,1' = 'Counter not initialized'; '0,_Total' = 50; '_Total' = 50; }; + + Invoke-TestCpuCheck -StubData $Counters -Arguments @{ 'Warning' = '80'; } | Should -Be 3; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result.Output | Should -Match ([regex]::Escape('[UNKNOWN] Core #1: Failed to read the performance counter: Counter not initialized')); + $Result.PerformanceData | Should -Contain '0_total::ifw_cpu::load=5%;80;;0;100'; + $Result.PerformanceData | Should -Contain 'totalload::ifw_cpu::load=5%;80;;0;100'; + } + + It 'reports the node total as UNKNOWN when no core of the node could be read' { + $Counters = New-TestCpuCounter -Instances @{ '0,0' = 5; '1,0' = 'Counter not initialized'; }; + + Invoke-TestCpuCheck -StubData $Counters -Arguments @{ 'Verbosity' = 2; } | Should -Be 3; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result.Output | Should -Match ([regex]::Escape('[UNKNOWN] Node Total: Failed to read the performance counter: no core of this NUMA node could be read')); + $Result.PerformanceData | Should -Contain 'totalload::ifw_cpu::load=5%;;;0;100'; + } + + It 'returns UNKNOWN when no processor instance could be read' { + Invoke-TestCpuCheck -StubData $null | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] CPU Load: Failed to read the performance counter \Processor Information(*)\% Processor Time: no processor instance available'; + + Invoke-TestCpuCheck -StubData @{ } | Should -Be 3; + Invoke-TestCpuCheck -StubData (New-TestCpuCounter -Instances @{ '_Total' = 5; '0,_Total' = 5; }) | Should -Be 3; + } + + It 'suppresses the performance data with NoPerfData' { + Invoke-TestCpuCheck -StubData $script:TwoNodes -Arguments @{ 'NoPerfData' = $true; } | Should -Be 0; + @($Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData).Count | Should -Be 0; + } + + It 'evaluates thresholds exclusively on Overall Load when OverallOnly is enabled while keeping all core perfdata' { + Invoke-TestCpuCheck -StubData $script:TwoNodes -Arguments @{ 'Warning' = '80'; 'Critical' = '90'; 'OverallOnly' = $true; } | Should -Be 0; + + $OkResult = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $OkResult.PerformanceData | Should -Be @( + '0_0::ifw_cpu::load=5%;;;0;100', + '0_1::ifw_cpu::load=95%;;;0;100', + '0_total::ifw_cpu::load=50%;;;0;100', + '1_2::ifw_cpu::load=10%;;;0;100', + '1_total::ifw_cpu::load=10%;;;0;100', + 'totalload::ifw_cpu::load=36.67%;80;90;0;100' + ); + + Invoke-TestCpuCheck -StubData $script:TwoNodes -Arguments @{ 'Warning' = '20'; 'Critical' = '30'; 'OverallOnly' = $true; } | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('[CRITICAL] Overall Load: 36.67% is greater than threshold 30%')); + } + + It 'supports Core "_Total", "Total" and specific core numbers as well as NodeFilter / SocketFilter' { + Invoke-TestCpuCheck -StubData $script:TwoNodes -Arguments @{ 'Core' = '_Total'; 'Warning' = '80'; 'Critical' = '90'; } | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Be @( 'totalload::ifw_cpu::load=36.67%;80;90;0;100' ); + + Invoke-TestCpuCheck -StubData $script:TwoNodes -Arguments @{ 'Core' = '1'; 'Warning' = '80'; 'Critical' = '90'; } | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Be @( '0_1::ifw_cpu::load=95%;80;90;0;100' ); + + Invoke-TestCpuCheck -StubData $script:TwoNodes -Arguments @{ 'Core' = '1'; 'OverallOnly' = $true; 'Warning' = '80'; 'Critical' = '90'; } | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Be @( '0_1::ifw_cpu::load=95%;80;90;0;100' ); + + Invoke-TestCpuCheck -StubData $script:TwoNodes -Arguments @{ 'SocketFilter' = @( '1' ); 'Warning' = '80'; 'Critical' = '90'; } | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Be @( + '1_2::ifw_cpu::load=10%;80;90;0;100', + '1_total::ifw_cpu::load=10%;80;90;0;100', + 'totalload::ifw_cpu::load=10%;80;90;0;100' + ); + + Invoke-TestCpuCheck -StubData $script:TwoNodes -Arguments @{ 'Core' = '99'; } | Should -Be 3; + Invoke-TestCpuCheck -StubData $script:TwoNodes -Arguments @{ 'NodeFilter' = @( '9' ); } | Should -Be 3; + } +} diff --git a/Tests/Invoke-IcingaCheckDirectory.Tests.ps1 b/Tests/Invoke-IcingaCheckDirectory.Tests.ps1 new file mode 100644 index 0000000..b9e4808 --- /dev/null +++ b/Tests/Invoke-IcingaCheckDirectory.Tests.ps1 @@ -0,0 +1,207 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Invoke-IcingaCheckDirectory' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + $script:OriginalDaemonFlag = $Global:IcingaForWindows.Protected.IsBackgroundDaemon; + + # Builds a result in the shape of Get-IcingaDirectoryInformation. + function New-TestDirectoryData() + { + param ( + [int]$FileCount = 0, + [int]$FolderCount = 0, + [long]$TotalSize = 0, + [long]$SmallestFile = 0, + [long]$LargestFile = 0, + [array]$FileList = @() + ); + + [double]$Average = 0; + + if ($FileCount -ne 0) { + $Average = [System.Math]::Round($TotalSize / $FileCount, 2); + } + + return @{ + 'Path' = 'C:\Backup'; + 'Exists' = $true; + 'FileCount' = $FileCount; + 'FolderCount' = $FolderCount; + 'TotalCount' = $FileCount + $FolderCount; + 'TotalSize' = $TotalSize; + 'LargestFile' = $LargestFile; + 'SmallestFile' = $SmallestFile; + 'AverageSize' = $Average; + 'FileList' = $FileList; + }; + } + + # Runs the plugin inside the module scope with Get-IcingaDirectoryInformation + # shadowed by a function, which records the arguments it was called with. + function Invoke-TestDirectoryCheck() + { + param ( + $StubData = $null, + [hashtable]$Arguments = @{ }, + [switch]$Fail = $false + ); + + return (& $script:IcingaModule { + param ($StubData, $Arguments, $Fail); + + function Get-IcingaDirectoryInformation() + { + param ( + [string]$Path = '', + [array]$FileNames = @( '*' ), + [switch]$Recurse = $false, + [string]$ChangeTimeEqual = '', + [string]$ChangeYoungerThan = '', + [string]$ChangeOlderThan = '', + [string]$CreationTimeEqual = '', + [string]$CreationYoungerThan = '', + [string]$CreationOlderThan = '', + [string]$AccessYoungerThan = '', + [string]$AccessOlderThan = '', + [string]$FileSizeGreaterThan = '', + [string]$FileSizeSmallerThan = '', + [switch]$IncludeFileList = $false, + [switch]$IgnoreMissingPath = $false + ); + + $Global:IcingaTestDirectoryCall = $PSBoundParameters; + + if ($Fail) { + return [IcingaError]::new('DirectoryAccessDenied', 'Access to the directory "C:\Backup" was denied', @{ }); + } + + return $StubData; + } + + Invoke-IcingaCheckDirectory @Arguments; + } $StubData $Arguments $Fail); + } + + # 3 files of 1KiB, 2KiB and 3KiB, one folder. + $script:Backup = New-TestDirectoryData -FileCount 3 -FolderCount 1 -TotalSize 6144 -SmallestFile 1024 -LargestFile 3072; + } + + AfterAll { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $script:OriginalDaemonFlag; + Remove-Variable -Name 'IcingaTestDirectoryCall' -Scope Global -ErrorAction Ignore; + } + + BeforeEach { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $true; + } + + It 'writes one metric per statistic with the path as index' { + Invoke-TestDirectoryCheck -StubData $script:Backup -Arguments @{ 'Path' = 'C:\Backup'; 'Warning' = '5'; 'Critical' = '10'; } | Should -Be 0; + + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Be @( + 'cbackup::ifw_directory::files=3;5;10;;', + 'cbackup::ifw_directory::folders=1;;;;', + 'cbackup::ifw_directory::totalsize=6144B;;;;', + 'cbackup::ifw_directory::smallestfile=1024B;;;;', + 'cbackup::ifw_directory::largestfile=3072B;;;;', + 'cbackup::ifw_directory::averagefile=2048B;;;;' + ); + } + + It 'lists every statistic and the informational file found entry' { + Invoke-TestDirectoryCheck -StubData $script:Backup -Arguments @{ 'Path' = 'C:\Backup'; 'Verbosity' = 2; } | Should -Be 0; + + [array]$Lines = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output -split "`n"; + $Lines[0] | Should -Be '[OK] Directory Check: "C:\Backup": 6 Ok'; + $Lines[1] | Should -Be '\_ [OK] File Count: 3 is ok'; + $Lines[3] | Should -Be '\_ [OK] Total Size: 6KiB is ok'; + $Lines[6] | Should -Be '\_ [OK] Average File Size: 2KiB is ok'; + $Lines[7] | Should -Be '\_ [INFO] File Found: Yes'; + } + + It 'raises the state when the file count or a size breaches its threshold' { + Invoke-TestDirectoryCheck -StubData $script:Backup -Arguments @{ 'Path' = 'C:\Backup'; 'Critical' = '2'; 'WarningTotalSize' = '5KiB'; } | Should -Be 2; + + $Output = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output; + $Output | Should -Match ([regex]::Escape('[CRITICAL] Directory Check: "C:\Backup": 1 Critical 1 Warning 4 Ok')); + $Output | Should -Match ([regex]::Escape('[CRITICAL] File Count: 3 is greater than threshold 2')); + $Output | Should -Match ([regex]::Escape('[WARNING] Total Size: 6KiB is greater than threshold 5KiB')); + } + + It 'adds the folders to the file count with CountFolderAsFile' { + Invoke-TestDirectoryCheck -StubData $script:Backup -Arguments @{ 'Path' = 'C:\Backup'; 'Critical' = '3'; 'CountFolderAsFile' = $true; } | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData[0] | Should -Be 'cbackup::ifw_directory::files=4;;3;;'; + } + + It 'passes the filters to the provider and treats a missing path as empty only with OverrideNotFound' { + Invoke-TestDirectoryCheck -StubData $script:Backup -Arguments @{ 'Path' = 'C:\Backup'; 'Recurse' = $true; 'FileNames' = @('*.bak'); 'ChangeOlderThan' = '1d'; 'FileSizeGreaterThan' = '1MB'; } | Out-Null; + + $Global:IcingaTestDirectoryCall['Recurse'] | Should -BeTrue; + $Global:IcingaTestDirectoryCall['FileNames'] | Should -Be @('*.bak'); + $Global:IcingaTestDirectoryCall['ChangeOlderThan'] | Should -Be '1d'; + $Global:IcingaTestDirectoryCall['FileSizeGreaterThan'] | Should -Be '1MB'; + $Global:IcingaTestDirectoryCall['IgnoreMissingPath'] | Should -BeFalse; + $Global:IcingaTestDirectoryCall['IncludeFileList'] | Should -BeFalse; + + Invoke-TestDirectoryCheck -StubData $script:Backup -Arguments @{ 'Path' = 'C:\Backup'; 'OverrideNotFound' = 'Critical'; } | Out-Null; + $Global:IcingaTestDirectoryCall['IgnoreMissingPath'] | Should -BeTrue; + } + + It 'reports the OverrideNotFound state when nothing matches' { + $Empty = New-TestDirectoryData; + + Invoke-TestDirectoryCheck -StubData $Empty -Arguments @{ 'Path' = 'C:\Backup'; 'OverrideNotFound' = 'Critical'; } | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be "[CRITICAL] Directory Check: `"C:\Backup`": 1 Critical 6 Ok [CRITICAL] File Found`n\_ [CRITICAL] File Found: No"; + + Invoke-TestDirectoryCheck -StubData $Empty -Arguments @{ 'Path' = 'C:\Backup'; 'OverrideNotFound' = 'Warning'; } | Should -Be 1; + Invoke-TestDirectoryCheck -StubData $Empty -Arguments @{ 'Path' = 'C:\Backup'; 'OverrideNotFound' = 'Ok'; } | Should -Be 0; + Invoke-TestDirectoryCheck -StubData $Empty -Arguments @{ 'Path' = 'C:\Backup'; } | Should -Be 0; + } + + It 'reports OK for found files even with OverrideNotFound' { + Invoke-TestDirectoryCheck -StubData $script:Backup -Arguments @{ 'Path' = 'C:\Backup'; 'OverrideNotFound' = 'Critical'; 'Verbosity' = 2; } | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('[OK] File Found: Yes')); + } + + It 'reports a provider failure as UNKNOWN with its reason' { + Invoke-TestDirectoryCheck -Fail -Arguments @{ 'Path' = 'C:\Backup'; } | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Directory Check: "C:\Backup": Access to the directory "C:\Backup" was denied'; + } + + It 'lists the files sorted by path with ShowFileList without counting them' { + [string]$ListRoot = Join-Path -Path $TestDrive -ChildPath 'list'; + New-Item -Path (Join-Path -Path $ListRoot -ChildPath 'folder') -ItemType Directory -Force | Out-Null; + [System.IO.File]::WriteAllBytes((Join-Path -Path $ListRoot -ChildPath 'b.bak'), [byte[]]::new(2048)); + [System.IO.File]::WriteAllBytes((Join-Path -Path $ListRoot -ChildPath 'a.bak'), [byte[]]::new(1024)); + + [array]$Entries = @( + [System.IO.FileInfo]::new((Join-Path -Path $ListRoot -ChildPath 'b.bak')), + [System.IO.DirectoryInfo]::new((Join-Path -Path $ListRoot -ChildPath 'folder')), + [System.IO.FileInfo]::new((Join-Path -Path $ListRoot -ChildPath 'a.bak')) + ); + $Data = New-TestDirectoryData -FileCount 2 -FolderCount 1 -TotalSize 3072 -SmallestFile 1024 -LargestFile 2048 -FileList $Entries; + + Invoke-TestDirectoryCheck -StubData $Data -Arguments @{ 'Path' = 'C:\Backup'; 'ShowFileList' = $true; } | Should -Be 0; + + $Global:IcingaTestDirectoryCall['IncludeFileList'] | Should -BeTrue; + + [array]$Lines = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output -split "`n"; + $Lines[0] | Should -Be '[OK] Directory Check: "C:\Backup": 6 Ok'; + $Lines[8] | Should -Be '\_ [INFO] File List'; + $Lines[9] | Should -Be ([string]::Format(' \_ [INFO] {0}: 1KiB', (Join-Path -Path $ListRoot -ChildPath 'a.bak'))); + $Lines[10] | Should -Be ([string]::Format(' \_ [INFO] {0}: 2KiB', (Join-Path -Path $ListRoot -ChildPath 'b.bak'))); + $Lines[11] | Should -Be ([string]::Format(' \_ [INFO] {0}: Folder', (Join-Path -Path $ListRoot -ChildPath 'folder'))); + } + + It 'suppresses the performance data with NoPerfData' { + Invoke-TestDirectoryCheck -StubData $script:Backup -Arguments @{ 'Path' = 'C:\Backup'; 'NoPerfData' = $true; } | Should -Be 0; + @($Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData).Count | Should -Be 0; + } +} diff --git a/Tests/Invoke-IcingaCheckMemory.Tests.ps1 b/Tests/Invoke-IcingaCheckMemory.Tests.ps1 new file mode 100644 index 0000000..34ccbc2 --- /dev/null +++ b/Tests/Invoke-IcingaCheckMemory.Tests.ps1 @@ -0,0 +1,205 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Invoke-IcingaCheckMemory' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + $script:OriginalDaemonFlag = $Global:IcingaForWindows.Protected.IsBackgroundDaemon; + + # Builds the -StructureByInstance result of the two memory counters. A string + # value becomes the counter error. + function New-TestMemoryCounter() + { + param ( + $Available = [decimal]4294967296, + $PagesSec = [decimal]12.5 + ); + + [hashtable]$Memory = @{ }; + + foreach ($Counter in @(@('Available Bytes', $Available), @('Pages/sec', $PagesSec))) { + $Leaf = @{ 'value' = [decimal]0; 'sample' = $null; 'help' = ''; 'type' = ''; 'error' = $null; }; + + if ($Counter[1] -is [string]) { + $Leaf['error'] = $Counter[1]; + } else { + $Leaf['value'] = [decimal]$Counter[1]; + } + + $Memory[$Counter[0]] = $Leaf; + } + + return @{ 'Memory' = $Memory; }; + } + + # 16GiB installed, two page files of 2048MB (512MB used) and 1024MB (1000MB used). + function New-TestCimData() + { + param ( + [bool]$AutomaticManagedPagefile = $true, + [array]$PageFileSettings = @() + ); + + return @{ + 'Win32_ComputerSystem' = @([PSCustomObject]@{ 'TotalPhysicalMemory' = [uint64]17179869184; 'AutomaticManagedPagefile' = $AutomaticManagedPagefile; }); + 'Win32_PageFileUsage' = @( + [PSCustomObject]@{ 'Name' = 'D:\pagefile.sys'; 'AllocatedBaseSize' = [uint32]1024; 'CurrentUsage' = [uint32]1000; }, + [PSCustomObject]@{ 'Name' = 'C:\pagefile.sys'; 'AllocatedBaseSize' = [uint32]2048; 'CurrentUsage' = [uint32]512; } + ); + 'Win32_PageFileSetting' = $PageFileSettings; + }; + } + + # Runs the plugin inside the module scope with the CIM and performance counter + # functions shadowed, so the check works on the given data. + function Invoke-TestMemoryCheck() + { + param ( + [hashtable]$CimData = (New-TestCimData), + $Counters = (New-TestMemoryCounter), + [hashtable]$Arguments = @{ }, + [string]$FailClass = '' + ); + + return (& $script:IcingaModule { + param ($CimData, $Counters, $Arguments, $FailClass); + + function New-IcingaPerformanceCounter() + { + param ( + [array]$Counter = @() + ); + } + + function Get-IcingaPerformanceCounter() + { + param ( + [array]$Counter = @(), + [int]$TimeoutMs = 5000, + [switch]$StructureByInstance = $false + ); + + return $Counters; + } + + function Get-IcingaWindowsInformation() + { + param ( + [string]$ClassName = '', + [string]$Namespace = 'root/cimv2', + [string]$Filter = '', + [array]$Property = @() + ); + + if ($ClassName -eq $FailClass) { + return [IcingaError]::new('WindowsInformationAccessDenied', 'Simulated failure of ' + $ClassName, @{ }); + } + + return ,@($CimData[$ClassName]); + } + + Invoke-IcingaCheckMemory @Arguments; + } $CimData $Counters $Arguments $FailClass); + } + } + + AfterAll { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $script:OriginalDaemonFlag; + } + + BeforeEach { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $true; + } + + It 'writes the used memory, the paging rate and every page file as perfdata' { + Invoke-TestMemoryCheck -Arguments @{ 'Warning' = '80%'; 'Critical' = '90%'; } | Should -Be 0; + + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Be @( + 'memory::ifw_memory::used=12884901888B;13743895347;15461882266;0;17179869184', + 'memory::ifw_memory::pagessec=12.5;;;;', + 'cpagefilesys::ifw_pagefile::used=536870912B;;;0;2147483648', + 'dpagefilesys::ifw_pagefile::used=1048576000B;;;0;1073741824' + ); + } + + It 'renders the used memory with its share of the installed memory' { + Invoke-TestMemoryCheck -Arguments @{ 'Warning' = '70%'; } | Should -Be 1; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('[WARNING] Used Memory: 12GiB (75%) is greater than threshold 11.2GiB (70%)')); + } + + It 'checks the page files and the paging rate against their own thresholds' { + Invoke-TestMemoryCheck -Arguments @{ 'PageFileWarning' = '90%'; 'MemoryPagesSecCritical' = '10'; 'Verbosity' = 2; } | Should -Be 2; + + $Output = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output; + $Output | Should -Match ([regex]::Escape('[CRITICAL] Memory pages/sec: 12.5 is greater than threshold 10')); + $Output | Should -Match ([regex]::Escape('[OK] C:\pagefile.sys: 512MiB (25%) is ok')); + $Output | Should -Match ([regex]::Escape('[WARNING] D:\pagefile.sys: 1000MiB (97.66%) is greater than threshold 921.6MiB (90%)')); + } + + It 'measures a page file with a configured maximum against that maximum' { + $CimData = New-TestCimData -AutomaticManagedPagefile $false -PageFileSettings @( + [PSCustomObject]@{ 'Name' = 'C:\pagefile.sys'; 'MaximumSize' = [uint32]4096; }, + [PSCustomObject]@{ 'Name' = 'D:\pagefile.sys'; 'MaximumSize' = [uint32]0; } + ); + + Invoke-TestMemoryCheck -CimData $CimData | Should -Be 0; + + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Contain 'cpagefilesys::ifw_pagefile::used=536870912B;;;0;4294967296'; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Contain 'dpagefilesys::ifw_pagefile::used=1048576000B;;;0;1073741824'; + } + + It 'filters the page files and leaves the package out when none remains' { + Invoke-TestMemoryCheck -Arguments @{ 'ExcludePageFile' = @('D:*'); 'Verbosity' = 2; } | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Not -Match 'D:\\pagefile'; + + Invoke-TestMemoryCheck -Arguments @{ 'IncludePageFile' = @('X:*'); 'Verbosity' = 2; } | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Not -Match 'PageFile Usage'; + } + + It 'reports a failed CIM query as UNKNOWN with its reason' { + Invoke-TestMemoryCheck -FailClass 'Win32_ComputerSystem' | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Memory Usage: Simulated failure of Win32_ComputerSystem'; + + Invoke-TestMemoryCheck -FailClass 'Win32_PageFileUsage' | Should -Be 3; + } + + It 'keeps the page files on their allocated size when the settings cannot be read' { + Invoke-TestMemoryCheck -CimData (New-TestCimData -AutomaticManagedPagefile $false) -FailClass 'Win32_PageFileSetting' | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Contain 'cpagefilesys::ifw_pagefile::used=536870912B;;;0;2147483648'; + } + + It 'reports unreadable performance counters as UNKNOWN' { + Invoke-TestMemoryCheck -Counters $null | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Memory Usage: Failed to read the performance counters of the category Memory'; + + Invoke-TestMemoryCheck -Counters (New-TestMemoryCounter -Available 'Counter not initialized') | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('[UNKNOWN] Used Memory: Failed to read the performance counter \Memory\Available Bytes: Counter not initialized')); + } + + It 'suppresses the performance data with NoPerfData' { + Invoke-TestMemoryCheck -Arguments @{ 'NoPerfData' = $true; } | Should -Be 0; + @($Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData).Count | Should -Be 0; + } + + It 'guards empty Win32_ComputerSystem results and skips 0-byte pagefiles cleanly' { + [hashtable]$EmptyComp = @{ + 'Win32_ComputerSystem' = @(); + 'Win32_PageFileUsage' = @(); + }; + Invoke-TestMemoryCheck -CimData $EmptyComp | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match 'Failed to read installed physical memory'; + + [hashtable]$ZeroPageData = @{ + 'Win32_ComputerSystem' = @([PSCustomObject]@{ 'TotalPhysicalMemory' = [uint64]17179869184; 'AutomaticManagedPagefile' = $true; }); + 'Win32_PageFileUsage' = @( + [PSCustomObject]@{ 'Name' = 'C:\pagefile.sys'; 'AllocatedBaseSize' = [uint32]0; 'CurrentUsage' = [uint32]0; } + ); + }; + Invoke-TestMemoryCheck -CimData $ZeroPageData -Arguments @{ 'PageFileWarning' = '80%'; 'PageFileCritical' = '90%'; } | Should -Be 0; + } +} diff --git a/Tests/Invoke-IcingaCheckPartitionSpace.Tests.ps1 b/Tests/Invoke-IcingaCheckPartitionSpace.Tests.ps1 new file mode 100644 index 0000000..c04afdd --- /dev/null +++ b/Tests/Invoke-IcingaCheckPartitionSpace.Tests.ps1 @@ -0,0 +1,207 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Invoke-IcingaCheckPartitionSpace' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + $script:OriginalDaemonFlag = $Global:IcingaForWindows.Protected.IsBackgroundDaemon; + + # Builds a volume entry in the shape of Get-IcingaDiskInformation -Entrypoint 'Volume'. + function New-TestVolume() + { + param ( + [string]$Name = '', + [string]$DriveLetter = '', + [string]$Label = '', + $Capacity = $null, + $FreeSpace = $null + ); + + $UsedSpace = $null; + + if ($null -ne $Capacity -and $null -ne $FreeSpace) { + $UsedSpace = [uint64]$Capacity - [uint64]$FreeSpace; + } + + return @{ + 'DeviceId' = $Name; + 'Name' = $Name; + 'DriveLetter' = $DriveLetter; + 'Label' = $Label; + 'FileSystem' = 'NTFS'; + 'Size' = $Capacity; + 'FreeSpace' = $FreeSpace; + 'UsedSpace' = $UsedSpace; + }; + } + + # Runs the plugin inside the module scope with Get-IcingaDiskInformation + # shadowed by a function, so the check works on the given volume entries. + function Invoke-TestPartitionCheck() + { + param ( + [array]$StubData = @(), + [hashtable]$Arguments = @{ }, + [switch]$Fail = $false + ); + + return (& $script:IcingaModule { + param ($StubData, $Arguments, $Fail); + + function Get-IcingaDiskInformation() + { + param ( + [string]$Entrypoint = 'PhysicalDisk', + [switch]$SkipPartitionMapping = $false + ); + + if ($Fail) { + return [IcingaError]::new('Simulated volume failure'); + } + + [hashtable]$Volumes = @{ }; + + foreach ($Volume in $StubData) { + $Volumes[$Volume.DeviceId] = $Volume; + } + + return $Volumes; + } + + Invoke-IcingaCheckPartitionSpace @Arguments; + } $StubData $Arguments $Fail); + } + + # 512GB volume with 442.692GB used (86.46%). + $script:DriveC = New-TestVolume -Name 'C:\' -DriveLetter 'C:' -Label 'System' -Capacity ([uint64]512000000000) -FreeSpace ([uint64]69308000000); + # 100GB volume with 10GB used (10%). + $script:DriveD = New-TestVolume -Name 'D:\' -DriveLetter 'D:' -Label 'Data' -Capacity ([uint64]100000000000) -FreeSpace ([uint64]90000000000); + } + + AfterAll { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $script:OriginalDaemonFlag; + } + + BeforeEach { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $true; + } + + Context 'Used space' { + It 'evaluates the used space against percent thresholds' { + Invoke-TestPartitionCheck -StubData @($script:DriveC, $script:DriveD) -Arguments @{ 'Warning' = '80%'; 'Critical' = '90%'; } | Should -Be 1; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result.Output | Should -Match '^\[WARNING\] Used Partition Space: 1 Warning 1 Ok'; + $Result.Output | Should -Match ([regex]::Escape('[WARNING] Partition C: 412.29GiB (86.46%) is greater than threshold 381.47GiB (80%)')); + } + + It 'writes the used space and resolved thresholds in bytes into the perfdata' { + Invoke-TestPartitionCheck -StubData @($script:DriveC, $script:DriveD) -Arguments @{ 'Warning' = '80%'; 'Critical' = '90%'; } | Out-Null; + + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Be @( + 'c::ifw_partitionspace::used=442692000000B;409600000000;460800000000;0;512000000000', + 'd::ifw_partitionspace::used=10000000000B;80000000000;90000000000;0;100000000000' + ); + } + + It 'accepts absolute size thresholds' { + Invoke-TestPartitionCheck -StubData @($script:DriveC) -Arguments @{ 'Warning' = '400GB'; 'Critical' = '450GB'; 'Verbosity' = 2; } | Should -Be 1; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('Partition C: 412.29GiB is greater than threshold 400GB')); + } + } + + Context 'Free space' { + It 'evaluates the free space against a percent range with CheckFreeSpace' { + Invoke-TestPartitionCheck -StubData @($script:DriveC) -Arguments @{ 'CheckFreeSpace' = $true; 'Warning' = '15%:'; 'Critical' = '5%:'; } | Should -Be 1; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result.Output | Should -Match '^\[WARNING\] Free Partition Space'; + $Result.Output | Should -Match ([regex]::Escape('Partition C: 64.55GiB (13.54%) is lower than threshold 71.53GiB (15%)')); + $Result.PerformanceData | Should -Be @('c::ifw_partitionspace::free=69308000000B;76800000000:;25600000000:;0;512000000000'); + } + } + + Context 'Partition selection' { + It 'only checks included partitions, ignoring the drive letter colon' { + Invoke-TestPartitionCheck -StubData @($script:DriveC, $script:DriveD) -Arguments @{ 'Include' = 'D:'; 'Warning' = '80%'; } | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Be @('d::ifw_partitionspace::used=10000000000B;80000000000;;0;100000000000'); + } + + It 'skips excluded partitions' { + Invoke-TestPartitionCheck -StubData @($script:DriveC, $script:DriveD) -Arguments @{ 'Exclude' = 'C:\'; 'Warning' = '80%'; } | Should -Be 0; + @($Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData).Count | Should -Be 1; + } + + It 'names a volume without drive letter after its label, or its path without a label' { + $Labeled = New-TestVolume -Name '\\?\Volume{1}\' -Label 'Recovery' -Capacity ([uint64]1000000000) -FreeSpace ([uint64]500000000); + $Unlabeled = New-TestVolume -Name '\\?\Volume{2}\' -Capacity ([uint64]1000000000) -FreeSpace ([uint64]500000000); + + Invoke-TestPartitionCheck -StubData @($Labeled, $Unlabeled) -Arguments @{ 'Verbosity' = 2; } | Should -Be 0; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result.Output | Should -Match ([regex]::Escape('[OK] Partition Recovery: ')); + $Result.Output | Should -Match ([regex]::Escape('[OK] Partition \\?\Volume{2}\: ')); + $Result.PerformanceData | Should -Contain 'recovery::ifw_partitionspace::used=500000000B;;;0;1000000000'; + $Result.PerformanceData | Should -Contain 'volume2::ifw_partitionspace::used=500000000B;;;0;1000000000'; + } + + It 'reports a missing required partition as CRITICAL' { + Invoke-TestPartitionCheck -StubData @($script:DriveD) -Arguments @{ 'RequiredPartition' = 'D:', 'E:'; } | Should -Be 2; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result.Output | Should -Match ([regex]::Escape('[CRITICAL] Partition E: Mandatory partition not found on host')); + $Result.Output | Should -Not -Match 'Partition D: Mandatory'; + } + + It 'returns UNKNOWN when no partition matches, OK with IgnoreEmptyChecks or MitigateUnknown' { + Invoke-TestPartitionCheck -StubData @($script:DriveC) -Arguments @{ 'Include' = 'Q'; } | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Used Partition Space: No partition matches the given filter'; + + Invoke-TestPartitionCheck -StubData @($script:DriveC) -Arguments @{ 'Include' = @( '' ); } | Should -Be 3; + Invoke-TestPartitionCheck -StubData @($script:DriveC) -Arguments @{ 'Include' = 'Q'; 'IgnoreEmptyChecks' = $true; } | Should -Be 0; + Invoke-TestPartitionCheck -StubData @($script:DriveC) -Arguments @{ 'Include' = 'Q'; 'MitigateUnknown' = $true; } | Should -Be 0; + } + + It 'matches folder mount points with or without a trailing backslash in Include, Exclude and RequiredPartition' { + $MountVol = New-TestVolume -Name 'C:\ClusterStorage\Volume1\' -Capacity ([uint64]100000000000) -FreeSpace ([uint64]80000000000); + + Invoke-TestPartitionCheck -StubData @($script:DriveC, $MountVol) -Arguments @{ 'Include' = 'C:\ClusterStorage\Volume1'; 'RequiredPartition' = 'C:\ClusterStorage\Volume1'; } | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData.Count | Should -Be 1; + + Invoke-TestPartitionCheck -StubData @($script:DriveC, $MountVol) -Arguments @{ 'Exclude' = 'C:\ClusterStorage\Volume1'; } | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData.Count | Should -Be 1; + + Invoke-TestPartitionCheck -StubData @($script:DriveC, $MountVol) -Arguments @{ 'Include' = 'C:/ClusterStorage/Volume1/'; 'RequiredPartition' = 'C:/ClusterStorage/Volume1/'; } | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData.Count | Should -Be 1; + + Invoke-TestPartitionCheck -StubData @($script:DriveC, $MountVol) -Arguments @{ 'Exclude' = 'C:/ClusterStorage/Volume1/'; } | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData.Count | Should -Be 1; + } + } + + Context 'Missing size data and errors' { + It 'reports a volume without size as UNKNOWN, OK with SkipUnknown' { + $NoSize = New-TestVolume -Name 'F:\' -DriveLetter 'F:'; + + Invoke-TestPartitionCheck -StubData @($NoSize) -Arguments @{ 'Warning' = '80%'; } | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('[UNKNOWN] Partition F: No partition size available')); + + Invoke-TestPartitionCheck -StubData @($NoSize) -Arguments @{ 'Warning' = '80%'; 'SkipUnknown' = $true; } | Should -Be 0; + } + + It 'suppresses the performance data with NoPerfData' { + Invoke-TestPartitionCheck -StubData @($script:DriveC) -Arguments @{ 'Warning' = '80%'; 'NoPerfData' = $true; } | Should -Be 1; + @($Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData).Count | Should -Be 0; + } + + It 'returns UNKNOWN when the volume query fails' { + Invoke-TestPartitionCheck -Fail | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Used Partition Space: Simulated volume failure'; + } + } +} diff --git a/Tests/Invoke-IcingaCheckPerfCounter.Tests.ps1 b/Tests/Invoke-IcingaCheckPerfCounter.Tests.ps1 new file mode 100644 index 0000000..4e17865 --- /dev/null +++ b/Tests/Invoke-IcingaCheckPerfCounter.Tests.ps1 @@ -0,0 +1,198 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Invoke-IcingaCheckPerfCounter' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + $script:OriginalDaemonFlag = $Global:IcingaForWindows.Protected.IsBackgroundDaemon; + + # Builds one counter result in the shape of Get-IcingaPerformanceCounter. A + # string value becomes the counter error. + function New-TestLeaf() + { + param ( + $Value = [decimal]0, + [string]$Type = '' + ); + + $Leaf = @{ 'value' = [decimal]0; 'sample' = $null; 'help' = ''; 'type' = $Type; 'error' = $null; }; + + if ($Value -is [string]) { + $Leaf['error'] = $Value; + } else { + $Leaf['value'] = [decimal]$Value; + } + + return $Leaf; + } + + # Runs the plugin inside the module scope with Get-IcingaPerformanceCounter + # shadowed, so the check works on the given counter results. + function Invoke-TestPerfCounterCheck() + { + param ( + $StubData = $null, + [hashtable]$Arguments = @{ } + ); + + return (& $script:IcingaModule { + param ($StubData, $Arguments); + + function Get-IcingaPerformanceCounter() + { + param ( + [array]$Counter = @(), + [int]$TimeoutMs = 5000, + [switch]$StructureByInstance = $false + ); + + return $StubData; + } + + Invoke-IcingaCheckPerfCounter @Arguments; + } $StubData $Arguments); + } + + $script:Counters = @{ + '\Processor(*)\% Processor Time' = @{ + '\Processor(1)\% Processor Time' = (New-TestLeaf -Value 95 -Type 'Timer100NsInverse'); + '\Processor(0)\% Processor Time' = (New-TestLeaf -Value 10 -Type 'Timer100NsInverse'); + '\Processor(_Total)\% Processor Time' = (New-TestLeaf -Value 52.5 -Type 'Timer100NsInverse'); + }; + '\Memory\Available Bytes' = (New-TestLeaf -Value 50 -Type 'NumberOfItems64'); + '\Nope\Nothing' = (New-TestLeaf -Value "Category 'Nope' does not exist."); + '\Disk(*)\Reads' = @{ }; + '\Broken(*)\Value' = @{ + '\Broken(a)\Value' = (New-TestLeaf -Value 'Counter not initialized'); + '\Broken(b)\Value' = (New-TestLeaf -Value 'Instance vanished'); + }; + }; + } + + AfterAll { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $script:OriginalDaemonFlag; + } + + BeforeEach { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $true; + } + + It 'writes one metric per instance with the category as index' { + Invoke-TestPerfCounterCheck -StubData $script:Counters -Arguments @{ 'PerfCounter' = @('\Processor(*)\% Processor Time', '\Memory\Available Bytes'); 'Warning' = '80'; 'Critical' = '90'; } | Should -Be 2; + + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Be @( + 'processor::ifw_perfcounter::percentprocessortime0=10%;80;90;;', + 'processor::ifw_perfcounter::percentprocessortime1=95%;80;90;;', + 'processor::ifw_perfcounter::percentprocessortime_total=52.5%;80;90;;', + 'memory::ifw_perfcounter::availablebytes=50B;80;90;;' + ); + } + + It 'groups the instances into one package per requested counter' { + Invoke-TestPerfCounterCheck -StubData $script:Counters -Arguments @{ 'PerfCounter' = @('\Processor(*)\% Processor Time', '\Memory\Available Bytes'); 'Critical' = '90'; 'Verbosity' = 2; } | Should -Be 2; + + [array]$Lines = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output -split "`n"; + $Lines[0] | Should -Be '[CRITICAL] Performance Counter: 1 Critical 3 Ok [CRITICAL] \Processor(1)\% Processor Time'; + $Lines[1] | Should -Be '\_ [CRITICAL] \Processor(*)\% Processor Time'; + $Lines[3] | Should -Be ' \_ [CRITICAL] \Processor(1)\% Processor Time: 95% is greater than threshold 90%'; + $Lines[5] | Should -Be '\_ [OK] \Memory\Available Bytes'; + } + + It 'filters the instances with ExcludeCounter and IncludeCounter' { + Invoke-TestPerfCounterCheck -StubData $script:Counters -Arguments @{ 'PerfCounter' = @('\Processor(*)\% Processor Time'); 'ExcludeCounter' = @('*_Total*'); } | Should -Be 0; + @($Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData).Count | Should -Be 2; + + Invoke-TestPerfCounterCheck -StubData $script:Counters -Arguments @{ 'PerfCounter' = @('\Processor(*)\% Processor Time'); 'IncludeCounter' = @('*(0)*'); } | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Be @('processor::ifw_perfcounter::percentprocessortime0=10%;;;;'); + } + + It 'derives the unit of every value from the counter type and name' { + $Units = @{ + '\Memory\Available MBytes' = (New-TestLeaf -Value 2 -Type 'NumberOfItems64'); + '\PhysicalDisk(_Total)\Avg. Disk sec/Read' = (New-TestLeaf -Value 0.004 -Type 'AverageTimer32'); + '\System\System Up Time' = (New-TestLeaf -Value 93784.33 -Type 'ElapsedTime'); + '\Memory\Pages/sec' = (New-TestLeaf -Value 12.5 -Type 'RateOfCountsPerSecond32'); + '\PhysicalDisk(_Total)\% Disk Time' = (New-TestLeaf -Value 7.456789 -Type '542573824'); + '\PhysicalDisk(_Total)\Disk Bytes/sec' = (New-TestLeaf -Value 1048576.4 -Type 'RateOfCountsPerSecond64'); + }; + + Invoke-TestPerfCounterCheck -StubData $Units -Arguments @{ 'PerfCounter' = @($Units.Keys); 'Verbosity' = 2; } | Should -Be 0; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result.Output | Should -Match ([regex]::Escape('\Memory\Available MBytes: 2MiB is ok')); + $Result.Output | Should -Match ([regex]::Escape('\Avg. Disk sec/Read: 4ms is ok')); + $Result.Output | Should -Match ([regex]::Escape('\System\System Up Time: 1d 2h 3m 4s is ok')); + $Result.Output | Should -Match ([regex]::Escape('\Memory\Pages/sec: 12.5 is ok')); + $Result.Output | Should -Match ([regex]::Escape('\% Disk Time: 7.46% is ok')); + $Result.Output | Should -Match ([regex]::Escape('\Disk Bytes/sec: 1MiB is ok')); + $Result.PerformanceData | Should -Contain 'memory::ifw_perfcounter::availablembytes=2097152B;;;;'; + $Result.PerformanceData | Should -Contain 'system::ifw_perfcounter::systemuptime=93784s;;;;'; + $Result.PerformanceData | Should -Contain 'memory::ifw_perfcounter::pagessec=12.5;;;;'; + + # Three counters of the same category and instance keep distinct labels. + $Result.PerformanceData | Should -Contain 'physicaldisk::ifw_perfcounter::avgdisksecread_total=0.004s;;;;'; + $Result.PerformanceData | Should -Contain 'physicaldisk::ifw_perfcounter::percentdisktime_total=7.46%;;;;'; + $Result.PerformanceData | Should -Contain 'physicaldisk::ifw_perfcounter::diskbytessec_total=1048576B;;;;'; + } + + It 'compares sizes and durations against thresholds with units' { + $Units = @{ + '\Memory\Available MBytes' = (New-TestLeaf -Value 2 -Type 'NumberOfItems64'); + '\System\System Up Time' = (New-TestLeaf -Value 93784 -Type 'ElapsedTime'); + }; + + Invoke-TestPerfCounterCheck -StubData $Units -Arguments @{ 'PerfCounter' = @('\Memory\Available MBytes'); 'Warning' = '1MB'; } | Should -Be 1; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('2MiB is greater than threshold 1MB')); + + Invoke-TestPerfCounterCheck -StubData $Units -Arguments @{ 'PerfCounter' = @('\System\System Up Time'); 'Critical' = '1d'; } | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('1d 2h 3m 4s is greater than threshold 1d')); + } + + It 'reports a failed concrete counter as UNKNOWN with its error' { + Invoke-TestPerfCounterCheck -StubData $script:Counters -Arguments @{ 'PerfCounter' = @('\Memory\Available Bytes', '\Nope\Nothing'); } | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape("[UNKNOWN] \Nope\Nothing: Failed to read the performance counter: Category 'Nope' does not exist.")); + } + + It 'reports a wildcard counter without readable instances as UNKNOWN with the first error' { + Invoke-TestPerfCounterCheck -StubData $script:Counters -Arguments @{ 'PerfCounter' = @('\Disk(*)\Reads', '\Broken(*)\Value'); } | Should -Be 3; + + $Output = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output; + $Output | Should -Match ([regex]::Escape('[UNKNOWN] \Disk(*)\Reads: Failed to read the performance counter: no instance of this counter exists')); + $Output | Should -Match ([regex]::Escape('[UNKNOWN] \Broken(*)\Value: Failed to read the performance counter: Counter not initialized')); + } + + It 'reports an empty result as UNKNOWN, or OK with IgnoreEmptyChecks' { + [hashtable]$Arguments = @{ 'PerfCounter' = @('\Processor(*)\% Processor Time'); 'IncludeCounter' = @('*(9)*'); }; + + Invoke-TestPerfCounterCheck -StubData $script:Counters -Arguments $Arguments | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Performance Counter: No performance counter matches the given filter'; + + $Arguments['IgnoreEmptyChecks'] = $true; + Invoke-TestPerfCounterCheck -StubData $script:Counters -Arguments $Arguments | Should -Be 0; + + $Arguments.Remove('IgnoreEmptyChecks'); + $Arguments['MitigateUnknown'] = $true; + Invoke-TestPerfCounterCheck -StubData $script:Counters -Arguments $Arguments | Should -Be 0; + } + + It 'rejects a missing or invalid counter path and a timed out read' { + Invoke-TestPerfCounterCheck -StubData $script:Counters | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Performance Counter: No performance counter was provided'; + + Invoke-TestPerfCounterCheck -StubData $script:Counters -Arguments @{ 'PerfCounter' = @('Memory'); } | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('[UNKNOWN] Memory: Invalid performance counter path')); + + Invoke-TestPerfCounterCheck -StubData $null -Arguments @{ 'PerfCounter' = @('\Memory\Available Bytes'); } | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Performance Counter: Failed to read the performance counters \Memory\Available Bytes'; + } + + It 'suppresses the performance data with NoPerfData' { + Invoke-TestPerfCounterCheck -StubData $script:Counters -Arguments @{ 'PerfCounter' = @('\Memory\Available Bytes'); 'NoPerfData' = $true; } | Should -Be 0; + @($Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData).Count | Should -Be 0; + } +} diff --git a/Tests/Invoke-IcingaCheckProcess.Tests.ps1 b/Tests/Invoke-IcingaCheckProcess.Tests.ps1 new file mode 100644 index 0000000..3e331f5 --- /dev/null +++ b/Tests/Invoke-IcingaCheckProcess.Tests.ps1 @@ -0,0 +1,152 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Invoke-IcingaCheckProcess' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + $script:OriginalDaemonFlag = $Global:IcingaForWindows.Protected.IsBackgroundDaemon; + + # Two PowerShell processes on a host with 16GiB memory and a 4GiB commit limit. + function New-TestProcessData() + { + param ( + [uint64]$CommitLimit = 4294967296 + ); + + return @{ + 'MemoryTotal' = [uint64]17179869184; + 'CommitLimit' = $CommitLimit; + 'LogicalProcessors' = 4; + 'Processes' = @{ + 'powershell' = @{ + 'Name' = 'powershell'; + 'Instances' = @{ + '200' = @{ 'Id' = 200; 'Cpu' = [double]7.5; 'Memory' = [uint64]209715200; 'PageFile' = [uint64]62914560; 'Threads' = 20; }; + '100' = @{ 'Id' = 100; 'Cpu' = [double]12.5; 'Memory' = [uint64]104857600; 'PageFile' = [uint64]52428800; 'Threads' = 10; }; + }; + 'Total' = @{ 'Cpu' = [double]20; 'Memory' = [uint64]314572800; 'PageFile' = [uint64]115343360; 'Threads' = 30; 'Count' = 2; }; + }; + }; + }; + } + + # Runs the plugin inside the module scope with the provider shadowed. + function Invoke-TestProcessCheck() + { + param ( + $Data = (New-TestProcessData), + [hashtable]$Arguments = @{ } + ); + + return (& $script:IcingaModule { + param ($Data, $Arguments); + + function Get-IcingaProcessInformation() + { + param ( + [array]$Include = @(), + [array]$Exclude = @() + ); + + if ($Data -is [string]) { + return [IcingaError]::new('ProcessCounterReadFailed', $Data, @{ }); + } + + return $Data; + } + + Invoke-IcingaCheckProcess @Arguments; + } $Data $Arguments); + } + } + + AfterAll { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $script:OriginalDaemonFlag; + } + + BeforeEach { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $true; + } + + It 'checks every process and the summary of every name' { + Invoke-TestProcessCheck -Arguments @{ 'Verbosity' = 2; } | Should -Be 0; + + $Output = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output; + $Output | Should -Match ([regex]::Escape('[OK] Process Overview: 13 Ok')); + $Output | Should -Match ([regex]::Escape('\_ [OK] powershell [100]')); + $Output | Should -Match ([regex]::Escape('\_ [OK] CPU Usage: 12.5% is ok')); + $Output | Should -Match ([regex]::Escape('\_ [OK] Page File Usage: 50MiB is ok')); + $Output | Should -Match ([regex]::Escape('\_ [OK] powershell Summary')); + $Output | Should -Match ([regex]::Escape('\_ [OK] Process Count: 2 is ok')); + } + + It 'lists the single processes in the order of their ids' { + Invoke-TestProcessCheck -Arguments @{ 'Verbosity' = 2; } | Should -Be 0; + + $Output = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output; + $Output.IndexOf('powershell [100]') | Should -BeLessThan $Output.IndexOf('powershell [200]'); + } + + It 'writes performance data for the summary only' { + Invoke-TestProcessCheck | Should -Be 0; + + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Be @( + 'powershell::ifw_process::pagefile=115343360B;;;0;4294967296', + 'powershell::ifw_process::memory=314572800B;;;0;17179869184', + 'powershell::ifw_process::cpu=20%;;;0;100', + 'powershell::ifw_process::threads=30;;;;', + 'powershell::ifw_process::count=2;;;;' + ); + } + + It 'applies the single thresholds to every process and the total thresholds to the summary' { + Invoke-TestProcessCheck -Arguments @{ 'CPUWarning' = '10'; 'TotalMemoryCritical' = '1%'; 'TotalProcessCountCritical' = '3:'; } | Should -Be 2; + + $Output = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output; + $Output | Should -Match ([regex]::Escape('\_ [WARNING] powershell [100]')); + $Output | Should -Match ([regex]::Escape('[WARNING] CPU Usage: 12.5% is greater than threshold 10%')); + $Output | Should -Match ([regex]::Escape('[CRITICAL] Memory Usage: 300MiB (1.83%) is greater than threshold 163.84MiB (1%)')); + $Output | Should -Match ([regex]::Escape('[CRITICAL] Process Count: 2 is lower than threshold 3')); + $Output | Should -Not -Match ([regex]::Escape('powershell [200]')); + } + + It 'measures the page file usage against the commit limit' { + Invoke-TestProcessCheck -Arguments @{ 'TotalPageFileWarning' = '2%'; } | Should -Be 1; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('[WARNING] Page File Usage: 110MiB (2.69%) is greater than threshold 81.92MiB (2%)')); + } + + It 'reports every requested process without a match with the OverrideNotFound state' { + Invoke-TestProcessCheck -Arguments @{ 'Process' = @('powershell', 'notepad', 'note*'); } | Should -Be 3; + + $Output = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output; + $Output | Should -Match ([regex]::Escape('[UNKNOWN] notepad: Process not found')); + $Output | Should -Match ([regex]::Escape('[UNKNOWN] note*: Process not found')); + $Output | Should -Not -Match ([regex]::Escape('powershell: Process not found')); + + Invoke-TestProcessCheck -Arguments @{ 'Process' = @('notepad'); 'OverrideNotFound' = 'Critical'; } | Should -Be 2; + Invoke-TestProcessCheck -Arguments @{ 'Process' = @('notepad'); 'OverrideNotFound' = 'Ok'; } | Should -Be 0; + } + + It 'reports a provider error as UNKNOWN with its reason' { + Invoke-TestProcessCheck -Data 'Simulated counter failure' | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Process Overview: Simulated counter failure'; + } + + It 'reports UNKNOWN when no process matches' { + $Data = New-TestProcessData; + $Data['Processes'] = @{ }; + + Invoke-TestProcessCheck -Data $Data | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Process Overview: No process matches the given filter'; + } + + It 'suppresses the performance data with NoPerfData' { + Invoke-TestProcessCheck -Arguments @{ 'NoPerfData' = $true; } | Should -Be 0; + @($Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData).Count | Should -Be 0; + } +} diff --git a/Tests/Invoke-IcingaCheckScheduledTask.Tests.ps1 b/Tests/Invoke-IcingaCheckScheduledTask.Tests.ps1 new file mode 100644 index 0000000..fa44c2e --- /dev/null +++ b/Tests/Invoke-IcingaCheckScheduledTask.Tests.ps1 @@ -0,0 +1,219 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Invoke-IcingaCheckScheduledTask' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + $script:OriginalDaemonFlag = $Global:IcingaForWindows.Protected.IsBackgroundDaemon; + + function Invoke-TestScheduledTaskCheck() + { + param ( + [array]$Tasks = @(), + [hashtable]$Infos = @{ }, + [hashtable]$Arguments = @{ }, + [switch]$Fail = $false + ); + + return (& $script:IcingaModule { + param ($Tasks, $Infos, $Arguments, $Fail); + + function Get-ScheduledTask() + { + param ( + [string]$TaskName = '*', + [string]$ErrorAction = 'Continue' + ); + + if ($Fail) { + throw 'Access is denied'; + } + + return $Tasks; + } + + function Get-ScheduledTaskInfo() + { + param ( + [string]$TaskName = '', + [string]$TaskPath = '', + [string]$ErrorAction = 'Continue' + ); + + [string]$Key = '{0}{1}' -f $TaskPath, $TaskName; + if ($Infos.ContainsKey($Key)) { + return $Infos[$Key]; + } + + return $null; + } + + return (Invoke-IcingaCheckScheduledTask @Arguments); + } $Tasks $Infos $Arguments $Fail); + } + + $script:DefaultTask = [PSCustomObject]@{ + 'TaskName' = 'Renew Certificate'; + 'TaskPath' = '\Icinga\Icinga for Windows\'; + 'State' = 'Ready'; + }; + $script:DefaultInfo = @{ + '\Icinga\Icinga for Windows\Renew Certificate' = [PSCustomObject]@{ + 'LastRunTime' = [datetime]::Now.AddHours(-1); + 'NextRunTime' = [datetime]::Now.AddHours(2); + 'NumberOfMissedRuns' = 0; + 'LastTaskResult' = 0; + }; + }; + } + + AfterAll { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $script:OriginalDaemonFlag; + } + + BeforeEach { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $true; + } + + Context 'State checks and multi-value State arrays' { + It 'returns OK when task state matches a single or multi-value State list and emits perfdata' { + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $script:DefaultInfo -Arguments @{ 'State' = @('Ready', 'Running'); 'Verbosity' = 2; } | Should -Be 0; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result.Output | Should -Match ([regex]::Escape("[OK] State: 'Ready' is ok")); + $Result.PerformanceData | Should -Contain 'icinga_icingaforwindows_renewcertificate::ifw_scheduledtask::state=3;;;;'; + $Result.PerformanceData | Should -Contain 'icinga_icingaforwindows_renewcertificate::ifw_scheduledtask::missedruns=0;;;;'; + $Result.PerformanceData | Should -Contain 'icinga_icingaforwindows_renewcertificate::ifw_scheduledtask::lasttaskresult=0;;;;'; + } + + It 'returns CRITICAL when task state does not match the required State list' { + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $script:DefaultInfo -Arguments @{ 'State' = @('Disabled'); 'Verbosity' = 2; } | Should -Be 2; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result.Output | Should -Match ([regex]::Escape("[CRITICAL] State: 'Ready' does not equal pattern 'Disabled'")); + } + } + + Context 'Exit codes, Missed Runs and Run Time thresholds' { + It 'raises CRITICAL on a non-zero LastTaskResult unless ignored via IgnoreLastRunTime or IgnoreExitCodes' { + $FailedInfo = @{ + '\Icinga\Icinga for Windows\Renew Certificate' = [PSCustomObject]@{ + 'LastRunTime' = [datetime]::Now.AddHours(-1); + 'NextRunTime' = $null; + 'NumberOfMissedRuns' = 0; + 'LastTaskResult' = 267009; + }; + }; + + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $FailedInfo | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match 'Task exited with code 267009'; + + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $FailedInfo -Arguments @{ 'IgnoreLastRunTime' = $true; } | Should -Be 0; + + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $FailedInfo -Arguments @{ 'IgnoreExitCodes' = @('0x41301'); } | Should -Be 0; + } + + It 'treats 267009 on Running tasks and 267011 as OK, masks 32-bit HRESULT hex codes, and supports legacy aliases' { + $RunningTask = [PSCustomObject]@{ + 'TaskName' = 'Active Job'; + 'TaskPath' = '\Icinga\'; + 'State' = 'Running'; + }; + $RunningInfo = @{ + '\Icinga\Active Job' = [PSCustomObject]@{ + 'LastRunTime' = [datetime]::Now.AddMinutes(-2); + 'NextRunTime' = $null; + 'NumberOfMissedRuns' = 0; + 'LastTaskResult' = 267009; + }; + }; + $NeverRunInfo = @{ + '\Icinga\Icinga for Windows\Renew Certificate' = [PSCustomObject]@{ + 'LastRunTime' = [datetime]::new(1999, 11, 30, 0, 0, 0); + 'NextRunTime' = $null; + 'NumberOfMissedRuns' = 0; + 'LastTaskResult' = 267011; + }; + }; + $HresultInfo = @{ + '\Icinga\Icinga for Windows\Renew Certificate' = [PSCustomObject]@{ + 'LastRunTime' = [datetime]::Now.AddMinutes(-10); + 'NextRunTime' = $null; + 'NumberOfMissedRuns' = 0; + 'LastTaskResult' = -2147024891; + }; + }; + + Invoke-TestScheduledTaskCheck -Tasks @($RunningTask) -Infos $RunningInfo | Should -Be 0; + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $NeverRunInfo | Should -Be 0; + + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $HresultInfo | Should -Be 2; + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $HresultInfo -Arguments @{ 'IgnoreExitCodes' = @('0x80070005'); } | Should -Be 0; + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $HresultInfo -Arguments @{ 'IgnoreLastResult' = $true; } | Should -Be 0; + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $HresultInfo -Arguments @{ 'IgnoreExitCode' = $true; } | Should -Be 0; + } + + It 'evaluates WarningMissedRuns and WarningLastRunTime thresholds' { + $Info = @{ + '\Icinga\Icinga for Windows\Renew Certificate' = [PSCustomObject]@{ + 'LastRunTime' = [datetime]::Now.AddHours(-5); + 'NextRunTime' = $null; + 'NumberOfMissedRuns' = 3; + 'LastTaskResult' = 0; + }; + }; + + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $Info -Arguments @{ 'WarningMissedRuns' = '2'; } | Should -Be 1; + + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $Info -Arguments @{ 'CriticalLastRunTime' = '2h'; } | Should -Be 2; + } + + It 'renders unset run times as [Never]: Never with 0s perfdata' { + $NeverInfo = @{ + '\Icinga\Icinga for Windows\Renew Certificate' = [PSCustomObject]@{ + 'LastRunTime' = $null; + 'NextRunTime' = $null; + 'NumberOfMissedRuns' = 0; + 'LastTaskResult' = 0; + }; + }; + + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $NeverInfo -Arguments @{ 'Verbosity' = 3; } | Should -Be 0; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result.Output | Should -Match ([regex]::Escape('[INFO] Last Run Time [Never]: Never')); + $Result.Output | Should -Match ([regex]::Escape('[INFO] Next Run Time [Never]: Never')); + $Result.PerformanceData | Should -Contain 'icinga_icingaforwindows_renewcertificate::ifw_scheduledtask::lastruntime=0s;;;;'; + $Result.PerformanceData | Should -Contain 'icinga_icingaforwindows_renewcertificate::ifw_scheduledtask::nextruntime=0s;;;;'; + } + } + + Context 'Missing tasks and empty filter handling' { + It 'reports a missing required task with OverrideNotFound (UNKNOWN by default)' { + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $script:DefaultInfo -Arguments @{ 'TaskName' = @('Renew Certificate', 'MissingTask'); } | Should -Be 3; + + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('[UNKNOWN] MissingTask: Task not found')); + + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $script:DefaultInfo -Arguments @{ 'TaskName' = @('MissingTask'); 'OverrideNotFound' = 'Critical'; } | Should -Be 2; + } + + It 'returns UNKNOWN when no task matches a wildcard filter, or OK with MitigateUnknown' { + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $script:DefaultInfo -Arguments @{ 'TaskPath' = '\DoesNotExist\*'; } | Should -Be 3; + + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Scheduled Tasks: No scheduled task matches the given filter'; + + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $script:DefaultInfo -Arguments @{ 'TaskPath' = '\DoesNotExist\*'; 'MitigateUnknown' = $true; } | Should -Be 0; + Invoke-TestScheduledTaskCheck -Tasks @($script:DefaultTask) -Infos $script:DefaultInfo -Arguments @{ 'TaskPath' = '\DoesNotExist\*'; 'IgnoreEmptyChecks' = $true; } | Should -Be 0; + } + + It 'returns UNKNOWN when querying scheduled tasks fails' { + Invoke-TestScheduledTaskCheck -Fail | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match '^\[UNKNOWN\] Scheduled Tasks: Failed to query scheduled tasks: Access is denied'; + } + } +} diff --git a/Tests/Invoke-IcingaCheckService.Tests.ps1 b/Tests/Invoke-IcingaCheckService.Tests.ps1 new file mode 100644 index 0000000..18d4c40 --- /dev/null +++ b/Tests/Invoke-IcingaCheckService.Tests.ps1 @@ -0,0 +1,218 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Invoke-IcingaCheckService' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + $script:OriginalDaemonFlag = $Global:IcingaForWindows.Protected.IsBackgroundDaemon; + + function New-TestService() + { + param ( + [string]$Name = '', + [string]$DisplayName = '', + [string]$State = 'Running', + [string]$StartMode = 'Auto', + [int]$ExitCode = 0 + ); + + return [PSCustomObject]@{ + 'Name' = $Name; + 'DisplayName' = $DisplayName; + 'State' = $State; + 'StartMode' = $StartMode; + 'ExitCode' = $ExitCode; + }; + } + + # Runs the plugin inside the module scope with Get-CimInstance shadowed by a + # function, so the check works on the given service objects instead of CIM. + function Invoke-TestServiceCheck() + { + param ( + [array]$StubData = @(), + [hashtable]$Arguments = @{ }, + [switch]$Fail = $false + ); + + return (& $script:IcingaModule { + param ($StubData, $Arguments, $Fail); + + function Get-CimInstance() + { + [CmdletBinding()] + param ( + [string]$ClassName = '', + [string]$Namespace = '', + [string]$Filter = '', + [string[]]$Property = @() + ); + + if ($Fail) { + throw 'Access is denied'; + } + + return $StubData; + } + + Invoke-IcingaCheckService @Arguments; + } $StubData $Arguments $Fail); + } + + $script:Spooler = New-TestService -Name 'Spooler' -DisplayName 'Print Spooler'; + } + + AfterAll { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $script:OriginalDaemonFlag; + } + + BeforeEach { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $true; + } + + Context 'Explicit services' { + It 'reports a running service as OK with state and summary perfdata' { + Invoke-TestServiceCheck -StubData @($script:Spooler) -Arguments @{ 'Service' = 'Spooler'; 'Verbosity' = 2; } | Should -Be 0; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result.Output | Should -Match ([regex]::Escape('[OK] Service "Print Spooler (Spooler)": ''Running'' is ok')); + $Result.PerformanceData | Should -Contain 'spooler::ifw_service::state=4;;;;'; + $Result.PerformanceData | Should -Contain 'summary::ifw_service::running=1;;;;'; + $Result.PerformanceData | Should -Contain 'summary::ifw_service::count=1;;;;'; + } + + It 'reports a stopped service as CRITICAL by default' { + $Stopped = New-TestService -Name 'Spooler' -DisplayName 'Print Spooler' -State 'Stopped'; + + Invoke-TestServiceCheck -StubData @($Stopped) -Arguments @{ 'Service' = 'Spooler'; } | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('[CRITICAL] Service "Print Spooler (Spooler)": ''Stopped'' does not equal pattern ''Running''')); + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Contain 'spooler::ifw_service::state=1;;;;'; + } + + It 'applies OverrideNotOk to a service in the wrong state' { + $Stopped = New-TestService -Name 'Spooler' -DisplayName 'Print Spooler' -State 'Stopped'; + + Invoke-TestServiceCheck -StubData @($Stopped) -Arguments @{ 'Service' = 'Spooler'; 'OverrideNotOk' = 'Warning'; } | Should -Be 1; + Invoke-TestServiceCheck -StubData @($Stopped) -Arguments @{ 'Service' = 'Spooler'; 'OverrideNotOk' = 'Unknown'; } | Should -Be 3; + Invoke-TestServiceCheck -StubData @($Stopped) -Arguments @{ 'Service' = 'Spooler'; 'OverrideNotOk' = 'Ok'; } | Should -Be 0; + } + + It 'compares against the expected Status, including multi-status arrays and empty @()' { + $Stopped = New-TestService -Name 'Spooler' -DisplayName 'Print Spooler' -State 'Stopped'; + $Paused = New-TestService -Name 'Spooler' -DisplayName 'Print Spooler' -State 'Paused'; + + Invoke-TestServiceCheck -StubData @($Stopped) -Arguments @{ 'Service' = 'Spooler'; 'Status' = 'Stopped'; } | Should -Be 0; + Invoke-TestServiceCheck -StubData @($script:Spooler) -Arguments @{ 'Service' = 'Spooler'; 'Status' = 'Stopped'; } | Should -Be 2; + Invoke-TestServiceCheck -StubData @($Stopped) -Arguments @{ 'Service' = 'Spooler'; 'Status' = @('Running', 'Stopped'); } | Should -Be 0; + Invoke-TestServiceCheck -StubData @($script:Spooler) -Arguments @{ 'Service' = 'Spooler'; 'Status' = @('Running', 'Stopped'); } | Should -Be 0; + Invoke-TestServiceCheck -StubData @($Paused) -Arguments @{ 'Service' = 'Spooler'; 'Status' = @('Running', 'Stopped'); } | Should -Be 2; + Invoke-TestServiceCheck -StubData @($script:Spooler) -Arguments @{ 'Service' = 'Spooler'; 'Status' = @(); } | Should -Be 0; + } + + It 'maps pending states to their status code and summary counter' { + $Pending = New-TestService -Name 'Spooler' -DisplayName 'Print Spooler' -State 'Start Pending'; + + Invoke-TestServiceCheck -StubData @($Pending) -Arguments @{ 'Service' = 'Spooler'; } | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Contain 'spooler::ifw_service::state=2;;;;'; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Contain 'summary::ifw_service::pendingstarted=1;;;;'; + } + + It 'reports a service in the Unknown state with state code 0' { + $Unknown = New-TestService -Name 'Spooler' -DisplayName 'Print Spooler' -State 'Unknown'; + + Invoke-TestServiceCheck -StubData @($Unknown) -Arguments @{ 'Service' = 'Spooler'; } | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Contain 'spooler::ifw_service::state=0;;;;'; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Contain 'summary::ifw_service::count=1;;;;'; + } + + It 'rejects a Status that is no IcingaServiceStatus' { + { Invoke-TestServiceCheck -StubData @($script:Spooler) -Arguments @{ 'Service' = 'Spooler'; 'Status' = 'Sleeping'; } } | Should -Throw; + } + + It 'selects services by wildcard and honours Exclude' { + $Services = @( + (New-TestService -Name 'WinRM' -DisplayName 'Windows Remote Management'), + (New-TestService -Name 'WinDefend' -DisplayName 'Microsoft Defender Antivirus Service'), + $script:Spooler + ); + + Invoke-TestServiceCheck -StubData $Services -Arguments @{ 'Service' = 'Win*'; 'Exclude' = 'WinDefend'; } | Should -Be 0; + + [array]$StateMetrics = @($Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Where-Object { $_ -like '*::state=*' }); + $StateMetrics | Should -Be @('winrm::ifw_service::state=4;;;;'); + } + + It 'matches services by display name' { + Invoke-TestServiceCheck -StubData @($script:Spooler) -Arguments @{ 'Service' = 'Print Spooler'; 'Verbosity' = 2; } | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Not -Match 'Service not found'; + } + + It 'only checks services with a matching startup type' { + $Services = @( + (New-TestService -Name 'Manual1' -DisplayName 'Manual One' -State 'Stopped' -StartMode 'Manual'), + (New-TestService -Name 'Auto1' -DisplayName 'Auto One' -State 'Running' -StartMode 'Auto') + ); + + Invoke-TestServiceCheck -StubData $Services -Arguments @{ 'Service' = '*'; 'Status' = 'Stopped'; 'FilterStartupType' = 'Manual'; } | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData | Should -Contain 'summary::ifw_service::count=1;;;;'; + } + } + + Context 'Missing services' { + It 'reports a service that does not exist as UNKNOWN' { + Invoke-TestServiceCheck -StubData @($script:Spooler) -Arguments @{ 'Service' = 'Spooler', 'DoesNotExist'; } | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('[UNKNOWN] DoesNotExist: Service not found')); + } + + It 'applies OverrideNotFound to a service that does not exist' { + Invoke-TestServiceCheck -StubData @($script:Spooler) -Arguments @{ 'Service' = 'DoesNotExist'; 'OverrideNotFound' = 'Critical'; } | Should -Be 2; + Invoke-TestServiceCheck -StubData @($script:Spooler) -Arguments @{ 'Service' = 'DoesNotExist'; 'OverrideNotFound' = 'Ok'; } | Should -Be 0; + } + + It 'returns UNKNOWN when a wildcard matches nothing, OK with MitigateUnknown' { + Invoke-TestServiceCheck -StubData @($script:Spooler) -Arguments @{ 'Service' = 'Nope*'; } | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Services: No service matches the given filter'; + + Invoke-TestServiceCheck -StubData @($script:Spooler) -Arguments @{ 'Service' = 'Nope*'; 'MitigateUnknown' = $true; } | Should -Be 0; + Invoke-TestServiceCheck -StubData @($script:Spooler) -Arguments @{ 'Service' = 'Nope*'; 'IgnoreEmptyChecks' = $true; } | Should -Be 0; + } + } + + Context 'Automatic services' { + It 'checks only automatic services and accepts a clean exit' { + $Services = @( + (New-TestService -Name 'AutoRunning' -DisplayName 'Auto Running'), + (New-TestService -Name 'AutoDone' -DisplayName 'Auto Done' -State 'Stopped' -ExitCode 0), + (New-TestService -Name 'AutoFailed' -DisplayName 'Auto Failed' -State 'Stopped' -ExitCode 1067), + (New-TestService -Name 'ManualStopped' -DisplayName 'Manual Stopped' -State 'Stopped' -StartMode 'Manual' -ExitCode 1) + ); + + Invoke-TestServiceCheck -StubData $Services | Should -Be 2; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result.Output | Should -Match '^\[CRITICAL\] Services: 1 Critical 2 Ok'; + $Result.Output | Should -Match ([regex]::Escape('Service "Auto Failed (AutoFailed)"')); + $Result.Output | Should -Not -Match 'ManualStopped'; + $Result.PerformanceData | Should -Contain 'summary::ifw_service::count=3;;;;'; + $Result.PerformanceData | Should -Contain 'summary::ifw_service::stopped=2;;;;'; + @($Result.PerformanceData | Where-Object { $_ -like '*::state=*' }).Count | Should -Be 0; + } + } + + Context 'Errors and perfdata switches' { + It 'suppresses all performance data with NoPerfData' { + Invoke-TestServiceCheck -StubData @($script:Spooler) -Arguments @{ 'Service' = 'Spooler'; 'NoPerfData' = $true; } | Should -Be 0; + @($Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData).Count | Should -Be 0; + } + + It 'returns UNKNOWN when the service query fails' { + Invoke-TestServiceCheck -Fail -Arguments @{ 'Service' = 'Spooler'; } | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Services: The CIM query failed with an unhandled error: Class "Win32_Service", Namespace "root/cimv2": Access is denied'; + } + } +} diff --git a/Tests/Invoke-IcingaCheckUptime.Tests.ps1 b/Tests/Invoke-IcingaCheckUptime.Tests.ps1 new file mode 100644 index 0000000..77e465f --- /dev/null +++ b/Tests/Invoke-IcingaCheckUptime.Tests.ps1 @@ -0,0 +1,108 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Invoke-IcingaCheckUptime' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + $script:OriginalDaemonFlag = $Global:IcingaForWindows.Protected.IsBackgroundDaemon; + + # Builds the -StructureByInstance result of '\System\System Up Time'. A string + # value becomes the counter error. + function New-TestUptimeCounter() + { + param ( + $Value = [decimal]0 + ); + + $Leaf = @{ 'value' = [decimal]0; 'sample' = $null; 'help' = ''; 'type' = ''; 'error' = $null; }; + + if ($Value -is [string]) { + $Leaf['error'] = $Value; + } else { + $Leaf['value'] = [decimal]$Value; + } + + return @{ 'System' = @{ 'System Up Time' = $Leaf; }; }; + } + + # Runs the plugin inside the module scope with the performance counter + # functions shadowed, so the check works on the given counter value. + function Invoke-TestUptimeCheck() + { + param ( + $StubData = $null, + [hashtable]$Arguments = @{ } + ); + + return (& $script:IcingaModule { + param ($StubData, $Arguments); + + function New-IcingaPerformanceCounter() + { + param ( + [array]$Counter = @() + ); + } + + function Get-IcingaPerformanceCounter() + { + param ( + [array]$Counter = @(), + [int]$TimeoutMs = 5000, + [switch]$StructureByInstance = $false + ); + + return $StubData; + } + + Invoke-IcingaCheckUptime @Arguments; + } $StubData $Arguments); + } + } + + AfterAll { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $script:OriginalDaemonFlag; + } + + BeforeEach { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $true; + } + + It 'shows the uptime as duration and writes it in whole seconds' { + Invoke-TestUptimeCheck -StubData (New-TestUptimeCounter -Value 93784.4) -Arguments @{ 'Warning' = '1d:'; 'Verbosity' = 2; } | Should -Be 0; + + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + [array]$Lines = $Result.Output -split "`n"; + $Lines[0] | Should -Be '[OK] System Uptime: 1d 2h 3m 4s: 1 Ok'; + $Lines[1] | Should -Be '\_ [OK] System Uptime: 1d 2h 3m 4s is ok'; + $Lines[2] | Should -Match '^\\_ \[INFO\] Last Boot: \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$'; + $Result.PerformanceData | Should -Be @('windows::ifw_uptime::uptime=93784s;86400:;;;'); + } + + It 'raises the state after a recent restart' { + Invoke-TestUptimeCheck -StubData (New-TestUptimeCounter -Value 3600) -Arguments @{ 'Warning' = '1d:'; 'Critical' = '30m:'; } | Should -Be 1; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('[WARNING] System Uptime: 1h is lower than threshold 1d')); + } + + It 'raises the state when the system runs longer than allowed' { + Invoke-TestUptimeCheck -StubData (New-TestUptimeCounter -Value 5184000) -Arguments @{ 'Critical' = '30d'; } | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('[CRITICAL] System Uptime: 2M is greater than threshold 30d')); + } + + It 'reports a failed counter read as UNKNOWN' { + Invoke-TestUptimeCheck -StubData (New-TestUptimeCounter -Value 'Counter not initialized') | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] System Uptime: Failed to read the performance counter \System\System Up Time: Counter not initialized'; + + Invoke-TestUptimeCheck -StubData $null | Should -Be 3; + } + + It 'suppresses the performance data with NoPerfData' { + Invoke-TestUptimeCheck -StubData (New-TestUptimeCounter -Value 3600) -Arguments @{ 'NoPerfData' = $true; } | Should -Be 0; + @($Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData).Count | Should -Be 0; + } +} diff --git a/Tests/Invoke-IcingaProtocolCheckCommand.Tests.ps1 b/Tests/Invoke-IcingaProtocolCheckCommand.Tests.ps1 new file mode 100644 index 0000000..c103ca0 --- /dev/null +++ b/Tests/Invoke-IcingaProtocolCheckCommand.Tests.ps1 @@ -0,0 +1,940 @@ +$ModulePath = Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..') -ChildPath 'IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Invoke-IcingaProtocolCheckCommand and Split-IcingaBinaryPluginOutput' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + } + + BeforeEach { + $script:TestBinDir = Join-Path -Path $TestDrive -ChildPath ('Bin_' + [System.Guid]::NewGuid().ToString('N')); + $script:TestDataDir = Join-Path -Path $TestDrive -ChildPath ('Data_' + [System.Guid]::NewGuid().ToString('N')); + New-Item -Path $script:TestBinDir -ItemType Directory -Force | Out-Null; + New-Item -Path $script:TestDataDir -ItemType Directory -Force | Out-Null; + } + + Context 'Split-IcingaBinaryPluginOutput' { + It 'splits single-line, multi-line, quoted, scoped and doubled-quote performance data accurately' { + [string]$Sample = "DISK WARNING - free space low | 'C:\ Free Space'=12GB;20;10;0;100 check_disk::'E:\ Free Space'=18GB;20;10;0;100 'Label''s Space'=10% inode=44%`nDetail line 1`nDetail line 2 | `"D:\ Free Space`"=80GB;20;10;0;100`nextra_metric=5s"; + + [hashtable]$Split = & $script:IcingaModule { + param ($Raw); + return (Split-IcingaBinaryPluginOutput -RawOutput $Raw); + } $Sample; + + $Split['Output'] | Should -Be "DISK WARNING - free space low`nDetail line 1`nDetail line 2"; + $Split['PerformanceData'].Count | Should -Be 6; + $Split['PerformanceData'][0] | Should -Be "'C:\ Free Space'=12GB;20;10;0;100"; + $Split['PerformanceData'][1] | Should -Be "check_disk::'E:\ Free Space'=18GB;20;10;0;100"; + $Split['PerformanceData'][2] | Should -Be "'Label''s Space'=10%"; + $Split['PerformanceData'][3] | Should -Be 'inode=44%'; + $Split['PerformanceData'][4] | Should -Be '"D:\ Free Space"=80GB;20;10;0;100'; + $Split['PerformanceData'][5] | Should -Be 'extra_metric=5s'; + } + } + + Context 'End-to-end PowerShell plugin execution and SecureString disposal' { + It 'executes Invoke-IcingaCheckDirectory via shorthand and returns compiled output and perfdata' { + Set-Content -Path (Join-Path -Path $script:TestDataDir -ChildPath 'a.gitconfig') -Value 'test' -Encoding UTF8; + Set-Content -Path (Join-Path -Path $script:TestDataDir -ChildPath 'b.gitconfig') -Value 'test' -Encoding UTF8; + + [hashtable]$Params = @{ + 'command' = 'Invoke-IcingaCheckDirectory'; + 'macros' = @{ + 'ifw_api_command' = 'directory'; + 'Path' = $script:TestDataDir; + 'FileNames' = @( '*.gitconfig' ); + 'Critical' = '1'; + 'ShowFileList' = $true; + 'ifw_api_arguments' = @{ + '-Path' = @{ 'value' = '$Path$'; }; + '-FileNames' = @{ 'value' = '$FileNames$'; }; + '-Critical' = @{ 'value' = '$Critical$'; }; + '-ShowFileList' = @{ 'set_if' = '$ShowFileList$'; }; + }; + }; + }; + + [hashtable]$ExecResult = & $script:IcingaModule { + param ($RpcParams, $BinDir); + function Get-ModuleBinaryDirectory() + { + return $BinDir; + } + return (Invoke-IcingaProtocolCheckCommand -Params $RpcParams); + } $Params $script:TestBinDir; + + $ExecResult['ExitCode'] | Should -Be 2; + $ExecResult['Output'] | Should -Match '\[CRITICAL\]'; + $ExecResult['PerformanceData'].Count | Should -BeGreaterThan 0; + $ExecResult['CommandLine'] | Should -Match '^Invoke-IcingaCheckDirectory '; + } + + It 'converts plain-text SecureString arguments, masks CommandLine and disposes the SecureString after execution' { + [hashtable]$Outcome = & $script:IcingaModule { + param ($BinDir); + + function Get-ModuleBinaryDirectory() + { + return $BinDir; + } + + $script:CapturedSecureRef = $null; + $script:CapturedPlainText = ''; + + function Invoke-IcingaCheckSecretProbe() + { + param ( + [securestring]$Token = $null + ); + + $script:CapturedSecureRef = $Token; + [System.IntPtr]$Ptr = [System.IntPtr]::Zero; + try { + $Ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToGlobalAllocUnicode($Token); + $script:CapturedPlainText = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($Ptr); + } finally { + if ($Ptr -ne [System.IntPtr]::Zero) { + [System.Runtime.InteropServices.Marshal]::ZeroFreeGlobalAllocUnicode($Ptr); + } + } + + $Pkg = New-IcingaPlugin 'Secret Probe'; + $Pkg.AddCheck((New-IcingaPlugin 'Auth' 1).CheckRange()) | Out-Null; + return $Pkg.Compile(); + } + + [hashtable]$RpcParams = @{ + 'command' = 'Invoke-IcingaCheckSecretProbe'; + 'macros' = @{ + 'ifw_api_command' = 'Invoke-IcingaCheckSecretProbe'; + 'Token' = 'SuperSecretToken99!'; + }; + }; + + [hashtable]$Res = Invoke-IcingaProtocolCheckCommand -Params $RpcParams; + [bool]$WasDisposed = $false; + + try { + [void][System.Runtime.InteropServices.Marshal]::SecureStringToGlobalAllocUnicode($script:CapturedSecureRef); + } catch [System.ObjectDisposedException] { + $WasDisposed = $true; + } + + return @{ + 'Result' = $Res; + 'Decrypted' = $script:CapturedPlainText; + 'WasDisposed' = $WasDisposed; + }; + } $script:TestBinDir; + + $Outcome['Decrypted'] | Should -Be 'SuperSecretToken99!'; + $Outcome['WasDisposed'] | Should -BeTrue; + $Outcome['Result']['ExitCode'] | Should -Be 0; + $Outcome['Result']['CommandLine'] | Should -Match ([regex]::Escape("-Token '********'")); + $Outcome['Result']['CommandLine'] | Should -Not -Match 'SuperSecretToken99!'; + } + + It 'catches unhandled exceptions from faulty PowerShell checks and returns UNKNOWN (3)' { + [hashtable]$CrashRes = & $script:IcingaModule { + param ($BinDir); + + function Get-ModuleBinaryDirectory() + { + return $BinDir; + } + + function Invoke-IcingaCheckBoom() + { + throw 'Simulated plugin crash'; + } + + return (Invoke-IcingaProtocolCheckCommand -Params @{ + 'command' = 'Invoke-IcingaCheckBoom'; + 'macros' = @{ 'ifw_api_command' = 'Invoke-IcingaCheckBoom'; }; + }); + } $script:TestBinDir; + + $CrashRes['ExitCode'] | Should -Be 3; + $CrashRes['Output'] | Should -Match '\[UNKNOWN\]'; + $CrashRes['Output'] | Should -Match 'Simulated plugin crash'; + } + } + + Context 'End-to-end External Script and Native Process execution in Binaries' { + It 'executes .ps1 scripts inside Binaries, splits perfdata and normalizes out-of-range exit codes to 3' { + [string]$ScriptPath = Join-Path -Path $script:TestBinDir -ChildPath 'check_custom.ps1'; + [string]$ScriptBody = @( + 'param([int]$ExitWith = 0, [string]$Label = "disk")', + 'Write-Output ("CUSTOM STATE | ''" + $Label + "''=75%;80;90;0;100")', + 'exit $ExitWith' + ) -join "`n"; + Set-Content -Path $ScriptPath -Value $ScriptBody -Encoding UTF8; + + [hashtable]$WarnParams = @{ + 'command' = 'check_custom'; + 'macros' = @{ + 'ifw_api_command' = 'check_custom.ps1'; + 'exit_code' = 1; + 'metric_label' = 'C:\ Data'; + 'ifw_api_arguments' = @{ + '-ExitWith' = @{ 'value' = '$exit_code$'; 'order' = 1; }; + '-Label' = @{ 'value' = '$metric_label$'; 'order' = 2; }; + }; + }; + }; + + [hashtable]$OutOfRangeParams = @{ + 'command' = 'check_custom'; + 'macros' = @{ + 'ifw_api_command' = 'check_custom.ps1'; + '-ExitWith' = 255; + }; + }; + + [hashtable]$WarnRes = & $script:IcingaModule { + param ($P, $B); + function Get-ModuleBinaryDirectory() + { + return $B; + } + return (Invoke-IcingaProtocolCheckCommand -Params $P); + } $WarnParams $script:TestBinDir; + + [hashtable]$OutRes = & $script:IcingaModule { + param ($P, $B); + function Get-ModuleBinaryDirectory() + { + return $B; + } + return (Invoke-IcingaProtocolCheckCommand -Params $P); + } $OutOfRangeParams $script:TestBinDir; + + $WarnRes['ExitCode'] | Should -Be 1; + $WarnRes['Output'] | Should -Be 'CUSTOM STATE'; + $WarnRes['PerformanceData'] | Should -Be @( "'C:\ Data'=75%;80;90;0;100" ); + + $OutRes['ExitCode'] | Should -Be 3; + } + + It 'binds array, boolean and SecureString parameters on external .ps1 scripts and masks secrets in CommandLine' { + [string]$AdvScriptPath = Join-Path -Path $script:TestBinDir -ChildPath 'check_typed.ps1'; + [string]$AdvScriptBody = @( + 'param([string[]]$Targets = @(), [bool]$UseSsl = $true, [switch]$ForceCheck = $false, [securestring]$Secret = $null, [Parameter(ValueFromRemainingArguments = $true)][string[]]$Rest = @())', + '$hasSec = ($null -ne $Secret -and $Secret.Length -gt 0)', + 'Write-Output ("Targets=" + ($Targets -join ",") + " Ssl=" + $UseSsl + " Force=" + [bool]$ForceCheck + " Rest=" + $Rest.Count + " Secret=" + $hasSec + " | count=" + $Targets.Count)', + 'exit 0' + ) -join "`n"; + Set-Content -Path $AdvScriptPath -Value $AdvScriptBody -Encoding UTF8; + + [hashtable]$AdvParams = @{ + 'command' = 'check_typed'; + 'macros' = @{ + 'ifw_api_command' = 'check_typed.ps1'; + 'targets' = @( 'node1', 'node2' ); + 'ssl_flag' = 'False'; + 'force_flag' = 'False'; + 'api_key' = ' MySecret123 '; + 'ifw_api_arguments' = @{ + '-Targets' = @{ 'value' = '$targets$'; 'order' = 1; }; + '-UseSsl' = @{ 'value' = '$ssl_flag$'; 'order' = 2; }; + '-ForceCheck' = @{ 'value' = '$force_flag$'; 'order' = 3; }; + '-Secret' = @{ 'value' = '$api_key$'; 'order' = 4; }; + }; + }; + }; + + [hashtable]$EmptyArrParams = @{ + 'command' = 'check_typed'; + 'macros' = @{ + 'ifw_api_command' = 'check_typed.ps1'; + 'ifw_api_arguments' = @{ + '-Targets' = @{ 'order' = 1; 'value' = $null; }; + '-UseSsl' = @{ 'value' = 'False'; 'order' = 2; }; + }; + }; + }; + + [hashtable]$TrailingParams = @{ + 'command' = 'check_typed'; + 'macros' = @{ + 'ifw_api_command' = 'check_typed.ps1'; + 'ifw_api_arguments' = @{ + '-UseSsl' = @{ 'order' = 1; 'value' = $null; }; + }; + }; + }; + + [hashtable]$MidFlagParams = @{ + 'command' = 'check_typed'; + 'macros' = @{ + 'ifw_api_command' = 'check_typed.ps1'; + 'ifw_api_arguments' = @{ + '-UseSsl' = @{ 'order' = 1; 'value' = $null; }; + '-ForceCheck' = @{ 'order' = 2; 'value' = $null; }; + }; + }; + }; + + [hashtable]$ColonSecParams = @{ + 'command' = 'check_typed'; + 'macros' = @{ + 'ifw_api_command' = 'check_typed.ps1'; + '-Secret:ColonSecret99!' = $true; + '-UseSsl:False' = $true; + '-ForceCheck:True' = $true; + }; + }; + + [hashtable]$PosSecParams = @{ + 'command' = 'check_typed'; + 'macros' = @{ + 'ifw_api_command' = 'check_typed.ps1'; + 'ifw_api_arguments' = @{ + 'targets_pos' = @{ 'order' = 1; 'skip_key' = $true; 'value' = 'nodePos'; }; + 'ssl_pos' = @{ 'order' = 2; 'skip_key' = $true; 'value' = 'False'; }; + 'sec_pos' = @{ 'order' = 3; 'skip_key' = $true; 'value' = 'PosSecret77!'; }; + }; + }; + }; + + [hashtable]$AdvRes = & $script:IcingaModule { + param ($P, $B); + function Get-ModuleBinaryDirectory() + { + return $B; + } + return (Invoke-IcingaProtocolCheckCommand -Params $P); + } $AdvParams $script:TestBinDir; + + [hashtable]$EmptyArrRes = & $script:IcingaModule { + param ($P, $B); + function Get-ModuleBinaryDirectory() + { + return $B; + } + return (Invoke-IcingaProtocolCheckCommand -Params $P); + } $EmptyArrParams $script:TestBinDir; + + [hashtable]$TrailingRes = & $script:IcingaModule { + param ($P, $B); + function Get-ModuleBinaryDirectory() + { + return $B; + } + return (Invoke-IcingaProtocolCheckCommand -Params $P); + } $TrailingParams $script:TestBinDir; + + [hashtable]$MidFlagRes = & $script:IcingaModule { + param ($P, $B); + function Get-ModuleBinaryDirectory() + { + return $B; + } + return (Invoke-IcingaProtocolCheckCommand -Params $P); + } $MidFlagParams $script:TestBinDir; + + [hashtable]$ColonSecRes = & $script:IcingaModule { + param ($P, $B); + function Get-ModuleBinaryDirectory() + { + return $B; + } + return (Invoke-IcingaProtocolCheckCommand -Params $P); + } $ColonSecParams $script:TestBinDir; + + [hashtable]$PosSecRes = & $script:IcingaModule { + param ($P, $B); + function Get-ModuleBinaryDirectory() + { + return $B; + } + return (Invoke-IcingaProtocolCheckCommand -Params $P); + } $PosSecParams $script:TestBinDir; + + $AdvRes['ExitCode'] | Should -Be 0; + $AdvRes['Output'] | Should -Be 'Targets=node1,node2 Ssl=False Force=False Rest=0 Secret=True'; + $AdvRes['PerformanceData'] | Should -Be @( 'count=2' ); + $AdvRes['CommandLine'] | Should -Match '\*{8}'; + $AdvRes['CommandLine'] | Should -Not -Match 'MySecret123'; + + $EmptyArrRes['ExitCode'] | Should -Be 0; + $EmptyArrRes['Output'] | Should -Be 'Targets= Ssl=False Force=False Rest=0 Secret=False'; + $EmptyArrRes['PerformanceData'] | Should -Be @( 'count=0' ); + + $TrailingRes['ExitCode'] | Should -Be 3; + $TrailingRes['Output'] | Should -Match '\[UNKNOWN\]'; + + $MidFlagRes['ExitCode'] | Should -Be 3; + $MidFlagRes['Output'] | Should -Match '\[UNKNOWN\]'; + + $ColonSecRes['ExitCode'] | Should -Be 0; + $ColonSecRes['Output'] | Should -Be 'Targets= Ssl=False Force=True Rest=0 Secret=True'; + $ColonSecRes['CommandLine'] | Should -Match ([regex]::Escape('-Secret:********')); + $ColonSecRes['CommandLine'] | Should -Not -Match 'ColonSecret99!'; + + $PosSecRes['ExitCode'] | Should -Be 0; + $PosSecRes['Output'] | Should -Be 'Targets=nodePos Ssl=False Force=False Rest=0 Secret=True'; + $PosSecRes['CommandLine'] | Should -Match '\*{8}'; + $PosSecRes['CommandLine'] | Should -Not -Match 'PosSecret77!'; + } + + It 'supports external .ps1 scripts in Binaries that build results with New-IcingaPlugin' { + [string]$PluginScriptPath = Join-Path -Path $script:TestBinDir -ChildPath 'check_ifw_plugin.ps1'; + [string]$PluginScriptBody = @( + 'param([int]$Val = 85)', + '$global:LASTEXITCODE = 0', + '$Pkg = New-IcingaPlugin ''External Script Package''', + '$Chk = New-IcingaPlugin ''Load'' $Val ''%''', + '[void]$Chk.Warning(''80'').Critical(''90'').CheckRange()', + '[void]$Pkg.AddCheck($Chk)', + '[void]$Pkg.Compile()' + ) -join "`n"; + Set-Content -Path $PluginScriptPath -Value $PluginScriptBody -Encoding UTF8; + + [hashtable]$PluginScriptRes = & $script:IcingaModule { + param ($B); + function Get-ModuleBinaryDirectory() + { + return $B; + } + return (Invoke-IcingaProtocolCheckCommand -Params @{ + 'command' = 'check_ifw_plugin'; + 'macros' = @{ + 'ifw_api_command' = 'check_ifw_plugin.ps1'; + 'ifw_api_arguments' = @{ + '-Val' = @{ 'value' = '85'; 'order' = 1; }; + }; + }; + }); + } $script:TestBinDir; + + $PluginScriptRes['ExitCode'] | Should -Be 1; + $PluginScriptRes['Output'] | Should -Match '\[WARNING\]'; + $PluginScriptRes['Output'] | Should -Match 'External Script Package'; + $PluginScriptRes['PerformanceData'].Count | Should -BeGreaterThan 0; + } + + It 'enforces check_timeout and kills descendant processes when a binary hangs or spawns a background pipe holder' { + [bool]$IsWindowsHost = ($env:OS -eq 'Windows_NT'); + [string]$HangFile = ''; + [string]$BgPipeFile = ''; + + if ($IsWindowsHost) { + $HangFile = Join-Path -Path $script:TestBinDir -ChildPath 'check_hang.cmd'; + Set-Content -Path $HangFile -Value "@echo off`r`nping -n 15 127.0.0.1 >nul`r`nexit /b 0`r`n" -Encoding ASCII; + + $BgPipeFile = Join-Path -Path $script:TestBinDir -ChildPath 'check_bgpipe.cmd'; + Set-Content -Path $BgPipeFile -Value "@echo off`r`necho OK ^| m=1`r`nstart `"`" /b ping -n 15 127.0.0.1`r`nexit /b 0`r`n" -Encoding ASCII; + } else { + $HangFile = Join-Path -Path $script:TestBinDir -ChildPath 'check_hang'; + [System.IO.File]::WriteAllText($HangFile, "#!/bin/sh`nsleep 10`nexit 0`n", (New-Object System.Text.UTF8Encoding $false)); + & /bin/chmod +x $HangFile; + + $BgPipeFile = Join-Path -Path $script:TestBinDir -ChildPath 'check_bgpipe'; + [System.IO.File]::WriteAllText($BgPipeFile, "#!/bin/sh`necho `"OK | m=1`"`nsleep 10 &`nexit 0`n", (New-Object System.Text.UTF8Encoding $false)); + & /bin/chmod +x $BgPipeFile; + } + + $Timer = [System.Diagnostics.Stopwatch]::StartNew(); + [hashtable]$HangRes = & $script:IcingaModule { + param ($B, $CmdName); + function Get-ModuleBinaryDirectory() + { + return $B; + } + return (Invoke-IcingaProtocolCheckCommand -Params @{ + 'command' = 'hang-test'; + 'check_timeout' = 0.5; + 'macros' = @{ 'ifw_api_command' = $CmdName; }; + }); + } $script:TestBinDir ([System.IO.Path]::GetFileName($HangFile)); + $Timer.Stop(); + + $HangRes['ExitCode'] | Should -Be 3; + $HangRes['Output'] | Should -Match 'timed out'; + $Timer.Elapsed.TotalSeconds | Should -BeLessThan 5.0; + + $BgTimer = [System.Diagnostics.Stopwatch]::StartNew(); + [hashtable]$BgPipeRes = & $script:IcingaModule { + param ($B, $CmdName); + function Get-ModuleBinaryDirectory() + { + return $B; + } + return (Invoke-IcingaProtocolCheckCommand -Params @{ + 'command' = 'bgpipe-test'; + 'check_timeout' = 0.5; + 'macros' = @{ 'ifw_api_command' = $CmdName; }; + }); + } $script:TestBinDir ([System.IO.Path]::GetFileName($BgPipeFile)); + $BgTimer.Stop(); + + $BgPipeRes['ExitCode'] | Should -Be 3; + $BgPipeRes['Output'] | Should -Match 'timed out'; + $BgTimer.Elapsed.TotalSeconds | Should -BeLessThan 5.0; + } + + It 'executes native OS processes by full path, falls back to stderr when stdout is empty, and guards .cmd/.bat metacharacters' { + [bool]$IsWindowsHost = ($env:OS -eq 'Windows_NT'); + [string]$NativeFile = ''; + [string]$StderrFile = ''; + [string]$BatchFile = Join-Path -Path $script:TestBinDir -ChildPath 'check_meta.cmd'; + + if ($IsWindowsHost) { + $NativeFile = Join-Path -Path $script:TestBinDir -ChildPath 'check_native.cmd'; + [string]$CmdBody = "@echo off`r`necho NATIVE CRITICAL %~1 %~2 ^| 'load avg'=2.50;1.50;2.00;0;`r`nexit /b 2`r`n"; + Set-Content -Path $NativeFile -Value $CmdBody -Encoding ASCII; + + $StderrFile = Join-Path -Path $script:TestBinDir -ChildPath 'check_stderr.cmd'; + [string]$ErrBody = "@echo off`r`necho STDERR WARNING ^| err_count=1 >&2`r`nexit /b 1`r`n"; + Set-Content -Path $StderrFile -Value $ErrBody -Encoding ASCII; + + Set-Content -Path $BatchFile -Value "@echo off`r`necho THRESH %~1 %~2 %~3 %~4`r`nexit /b 0`r`n" -Encoding ASCII; + } else { + $NativeFile = Join-Path -Path $script:TestBinDir -ChildPath 'check_native'; + [string]$ShBody = "#!/bin/sh`necho `"NATIVE CRITICAL `$1 `$2 | 'load avg'=2.50;1.50;2.00;0;`"`nexit 2`n"; + [System.IO.File]::WriteAllText($NativeFile, $ShBody, (New-Object System.Text.UTF8Encoding $false)); + & /bin/chmod +x $NativeFile; + + $StderrFile = Join-Path -Path $script:TestBinDir -ChildPath 'check_stderr'; + [string]$ErrBody = "#!/bin/sh`necho `"STDERR WARNING | err_count=1`" >&2`nexit 1`n"; + [System.IO.File]::WriteAllText($StderrFile, $ErrBody, (New-Object System.Text.UTF8Encoding $false)); + & /bin/chmod +x $StderrFile; + + [System.IO.File]::WriteAllText($BatchFile, "#!/bin/sh`necho `"THRESH `$1 `$2 `$3 `$4`"`nexit 0`n", (New-Object System.Text.UTF8Encoding $false)); + & /bin/chmod +x $BatchFile; + } + + [hashtable]$NativeParams = @{ + 'command' = 'ifw-native'; + 'check_timeout' = 10; + 'macros' = @{ + 'ifw_api_command' = [System.IO.Path]::GetFileName($NativeFile); + 'msg' = 'hello world'; + 'ifw_api_arguments' = @{ + '-m' = @{ 'value' = '$msg$'; 'order' = 1; }; + }; + }; + }; + + [hashtable]$StderrParams = @{ + 'command' = 'ifw-stderr'; + 'check_timeout' = 99999999; + 'macros' = @{ + 'ifw_api_command' = [System.IO.Path]::GetFileName($StderrFile); + }; + }; + + [hashtable]$InjectedBatch = @{ + 'command' = 'ifw-batch-inject'; + 'macros' = @{ + 'ifw_api_command' = 'check_meta.cmd'; + 'ifw_api_arguments' = @{ + '-w' = @{ 'value' = '80%&whoami'; 'order' = 1; }; + }; + }; + }; + + [hashtable]$EnvExpandBatch = @{ + 'command' = 'ifw-batch-env'; + 'macros' = @{ + 'ifw_api_command' = 'check_meta.cmd'; + 'ifw_api_arguments' = @{ + '-w' = @{ 'value' = '%TEMP%'; 'order' = 1; }; + }; + }; + }; + + [hashtable]$SpaceSubstBatch = @{ + 'command' = 'ifw-batch-subst'; + 'macros' = @{ + 'ifw_api_command' = 'check_meta.cmd'; + 'ifw_api_arguments' = @{ + '-w' = @{ 'value' = '%COMSPEC: =%'; 'order' = 1; }; + }; + }; + }; + + [hashtable]$SafePercentBatch = @{ + 'command' = 'ifw-batch-safe'; + 'macros' = @{ + 'ifw_api_command' = 'check_meta.cmd'; + 'ifw_api_arguments' = @{ + '-w' = @{ 'value' = '80%'; 'order' = 1; }; + '-c' = @{ 'value' = '90%'; 'order' = 2; }; + }; + }; + }; + + [hashtable]$NativeRes = & $script:IcingaModule { + param ($P, $B); + function Get-ModuleBinaryDirectory() + { + return $B; + } + return (Invoke-IcingaProtocolCheckCommand -Params $P); + } $NativeParams $script:TestBinDir; + + [hashtable]$StderrRes = & $script:IcingaModule { + param ($P, $B); + function Get-ModuleBinaryDirectory() + { + return $B; + } + return (Invoke-IcingaProtocolCheckCommand -Params $P); + } $StderrParams $script:TestBinDir; + + [hashtable]$InjectedRes = & $script:IcingaModule { + param ($P, $B); + function Get-ModuleBinaryDirectory() + { + return $B; + } + return (Invoke-IcingaProtocolCheckCommand -Params $P); + } $InjectedBatch $script:TestBinDir; + + [hashtable]$EnvExpandRes = & $script:IcingaModule { + param ($P, $B); + function Get-ModuleBinaryDirectory() + { + return $B; + } + return (Invoke-IcingaProtocolCheckCommand -Params $P); + } $EnvExpandBatch $script:TestBinDir; + + [hashtable]$SpaceSubstRes = & $script:IcingaModule { + param ($P, $B); + function Get-ModuleBinaryDirectory() + { + return $B; + } + return (Invoke-IcingaProtocolCheckCommand -Params $P); + } $SpaceSubstBatch $script:TestBinDir; + + [hashtable]$SafePercentRes = & $script:IcingaModule { + param ($P, $B); + function Get-ModuleBinaryDirectory() + { + return $B; + } + return (Invoke-IcingaProtocolCheckCommand -Params $P); + } $SafePercentBatch $script:TestBinDir; + + $NativeRes['ExitCode'] | Should -Be 2; + $NativeRes['Output'] | Should -Be 'NATIVE CRITICAL -m hello world'; + $NativeRes['PerformanceData'] | Should -Be @( "'load avg'=2.50;1.50;2.00;0;" ); + $NativeRes['CommandLine'] | Should -Match '"hello world"'; + + $StderrRes['ExitCode'] | Should -Be 1; + $StderrRes['Output'] | Should -Be 'STDERR WARNING'; + $StderrRes['PerformanceData'] | Should -Be @( 'err_count=1' ); + + $InjectedRes['ExitCode'] | Should -Be 3; + $InjectedRes['Output'] | Should -Match 'metacharacters'; + + $EnvExpandRes['ExitCode'] | Should -Be 3; + $EnvExpandRes['Output'] | Should -Match 'metacharacters'; + + $SpaceSubstRes['ExitCode'] | Should -Be 3; + $SpaceSubstRes['Output'] | Should -Match 'metacharacters'; + + $SafePercentRes['ExitCode'] | Should -Be 0; + $SafePercentRes['Output'] | Should -Be 'THRESH -w 80% -c 90%'; + } + } + + Context 'UNKNOWN error handling with IWKB001000..IWKB001003' { + It 'returns ExitCode 3 and IWKB001003 for unmodified ITL load-windows without ifw_api_command' { + [hashtable]$Res = & $script:IcingaModule { + param ($B); + function Get-ModuleBinaryDirectory() + { + return $B; + } + return (Invoke-IcingaProtocolCheckCommand -Params @{ 'command' = 'load-windows'; 'macros' = @{ }; }); + } $script:TestBinDir; + + $Res['ExitCode'] | Should -Be 3; + $Res['Output'] | Should -Match 'IWKB001003'; + $Res['Output'] | Should -Match 'load-windows'; + } + } + + Context 'Start-IcingaProtocolWorker ExecuteCommand dispatch and timing' { + It 'measures execution_start/execution_end and dispatches CheckResult via Send-IcingaProtocolCheckResult' { + Set-Content -Path (Join-Path -Path $script:TestDataDir -ChildPath 'item.log') -Value 'ok' -Encoding UTF8; + + [hashtable]$Dispatched = & $script:IcingaModule { + param ($DataDir, $BinDir); + + $GlobalVar = Get-GlobalRuntimeVariable; + $PrevQueue = $GlobalVar.Public.IcingaProtocol.WorkerQueue; + $PrevHost = $GlobalVar.Public.IcingaProtocol.Config.Hostname; + $script:WorkerLoopCalls = 0; + $script:SentCheckResult = $null; + + function Get-ModuleBinaryDirectory() + { + return $BinDir; + } + + function Test-ThreadRunning() + { + param ( + [switch]$NoSleep = $false + ); + + $script:WorkerLoopCalls++; + return ($script:WorkerLoopCalls -le 1); + } + + function Set-ThreadProcessing() + { + } + + function Set-TCPClientAndStream() + { + param ( + $TcpClient = $null, + $SslStream = $null + ); + } + + function Send-IcingaProtocolCheckResult() + { + param ( + [hashtable]$CheckResult = @{ } + ); + + $script:SentCheckResult = $CheckResult; + } + + try { + $QueueList = New-Object System.Collections.ArrayList; + $Queue = New-Object 'System.Collections.Concurrent.BlockingCollection[PSObject]' -ArgumentList (New-Object 'System.Collections.Concurrent.ConcurrentQueue[PSObject]'); + [void]$QueueList.Add($Queue); + + $GlobalVar.Public.IcingaProtocol.WorkerQueue = $QueueList; + $GlobalVar.Public.IcingaProtocol.Config.Hostname = 'win-agent-01.local'; + + $Queue.Add([PSCustomObject]@{ + 'Message' = @{ + 'method' = 'event::ExecuteCommand'; + 'params' = @{ + 'host' = 'win-agent-01.local'; + 'service' = 'Logs Check'; + 'command' = 'Invoke-IcingaCheckDirectory'; + 'macros' = @{ + 'ifw_api_command' = 'Invoke-IcingaCheckDirectory'; + 'Path' = $DataDir; + 'FileNames' = @( '*.log' ); + }; + }; + }; + 'Client' = $null; + 'Stream' = $null; + }); + + Start-IcingaProtocolWorker -WorkerId 0; + return $script:SentCheckResult; + } finally { + $GlobalVar.Public.IcingaProtocol.WorkerQueue = $PrevQueue; + $GlobalVar.Public.IcingaProtocol.Config.Hostname = $PrevHost; + } + } $script:TestDataDir $script:TestBinDir; + + $Dispatched | Should -Not -BeNullOrEmpty; + $Dispatched['host'] | Should -Be 'win-agent-01.local'; + $Dispatched['service'] | Should -Be 'Logs Check'; + $Dispatched['cr']['check_source'] | Should -Be 'win-agent-01.local'; + $Dispatched['cr']['exit_status'] | Should -Be 0; + $Dispatched['cr']['state'] | Should -Be 0; + $Dispatched['cr']['type'] | Should -Be 'CheckResult'; + $Dispatched['cr']['command'] | Should -Match '^Invoke-IcingaCheckDirectory '; + ($Dispatched['cr']['execution_end'] -ge $Dispatched['cr']['execution_start']) | Should -BeTrue; + } + + It 'omits the service key for Icinga 2 Host checks and falls back check_source to host when Config.Hostname is unset' { + Set-Content -Path (Join-Path -Path $script:TestDataDir -ChildPath 'host.log') -Value 'ok' -Encoding UTF8; + + [hashtable]$HostDispatched = & $script:IcingaModule { + param ($DataDir, $BinDir); + + $GlobalVar = Get-GlobalRuntimeVariable; + $PrevQueue = $GlobalVar.Public.IcingaProtocol.WorkerQueue; + $PrevHost = $GlobalVar.Public.IcingaProtocol.Config.Hostname; + $script:HostLoopCalls = 0; + $script:HostSentResult = $null; + + function Get-ModuleBinaryDirectory() + { + return $BinDir; + } + + function Test-ThreadRunning() + { + param ( + [switch]$NoSleep = $false + ); + + $script:HostLoopCalls++; + return ($script:HostLoopCalls -le 1); + } + + function Set-ThreadProcessing() + { + } + + function Set-TCPClientAndStream() + { + param ( + $TcpClient = $null, + $SslStream = $null + ); + } + + function Send-IcingaProtocolCheckResult() + { + param ( + [hashtable]$CheckResult = @{ } + ); + + $script:HostSentResult = $CheckResult; + } + + try { + $QueueList = New-Object System.Collections.ArrayList; + $Queue = New-Object 'System.Collections.Concurrent.BlockingCollection[PSObject]' -ArgumentList (New-Object 'System.Collections.Concurrent.ConcurrentQueue[PSObject]'); + [void]$QueueList.Add($Queue); + + $GlobalVar.Public.IcingaProtocol.WorkerQueue = $QueueList; + $GlobalVar.Public.IcingaProtocol.Config.Hostname = ''; + + $Queue.Add([PSCustomObject]@{ + 'Message' = @{ + 'method' = 'event::ExecuteCommand'; + 'params' = @{ + 'host' = 'win-hostcheck.local'; + 'command' = 'Invoke-IcingaCheckDirectory'; + 'macros' = @{ + 'ifw_api_command' = 'Invoke-IcingaCheckDirectory'; + 'Path' = $DataDir; + 'FileNames' = @( '*.log' ); + }; + }; + }; + 'Client' = $null; + 'Stream' = $null; + }); + + Start-IcingaProtocolWorker -WorkerId 0; + return $script:HostSentResult; + } finally { + $GlobalVar.Public.IcingaProtocol.WorkerQueue = $PrevQueue; + $GlobalVar.Public.IcingaProtocol.Config.Hostname = $PrevHost; + } + } $script:TestDataDir $script:TestBinDir; + + $HostDispatched | Should -Not -BeNullOrEmpty; + $HostDispatched['host'] | Should -Be 'win-hostcheck.local'; + $HostDispatched.ContainsKey('service') | Should -BeFalse; + $HostDispatched['cr']['check_source'] | Should -Be 'win-hostcheck.local'; + $HostDispatched['cr']['exit_status'] | Should -Be 0; + } + + It 'dispatches ExecuteCommand payloads deserialized as Dictionary[string, object] on Windows PowerShell 5.1' { + Set-Content -Path (Join-Path -Path $script:TestDataDir -ChildPath 'ps51.log') -Value 'ok' -Encoding UTF8; + + [hashtable]$Ps51Dispatched = & $script:IcingaModule { + param ($DataDir, $BinDir); + + $GlobalVar = Get-GlobalRuntimeVariable; + $PrevQueue = $GlobalVar.Public.IcingaProtocol.WorkerQueue; + $PrevHost = $GlobalVar.Public.IcingaProtocol.Config.Hostname; + $script:Ps51LoopCalls = 0; + $script:Ps51SentResult = $null; + + function Get-ModuleBinaryDirectory() + { + return $BinDir; + } + + function Test-ThreadRunning() + { + param ( + [switch]$NoSleep = $false + ); + + $script:Ps51LoopCalls++; + return ($script:Ps51LoopCalls -le 1); + } + + function Set-ThreadProcessing() + { + } + + function Set-TCPClientAndStream() + { + param ( + $TcpClient = $null, + $SslStream = $null + ); + } + + function Send-IcingaProtocolCheckResult() + { + param ( + [hashtable]$CheckResult = @{ } + ); + + $script:Ps51SentResult = $CheckResult; + } + + try { + $QueueList = New-Object System.Collections.ArrayList; + $Queue = New-Object 'System.Collections.Concurrent.BlockingCollection[PSObject]' -ArgumentList (New-Object 'System.Collections.Concurrent.ConcurrentQueue[PSObject]'); + [void]$QueueList.Add($Queue); + + $GlobalVar.Public.IcingaProtocol.WorkerQueue = $QueueList; + $GlobalVar.Public.IcingaProtocol.Config.Hostname = 'win-ps51-agent.local'; + + $MsgDict = New-Object 'System.Collections.Generic.Dictionary[string, object]'; + $ParamsDict = New-Object 'System.Collections.Generic.Dictionary[string, object]'; + $MacrosDict = New-Object 'System.Collections.Generic.Dictionary[string, object]'; + $MacrosDict['ifw_api_command'] = 'Invoke-IcingaCheckDirectory'; + $MacrosDict['Path'] = $DataDir; + $MacrosDict['FileNames'] = [object[]]@( '*.log' ); + $ParamsDict['host'] = 'win-ps51-agent.local'; + $ParamsDict['service'] = 'PS51 Logs Check'; + $ParamsDict['command'] = 'Invoke-IcingaCheckDirectory'; + $ParamsDict['macros'] = $MacrosDict; + $MsgDict['method'] = 'event::ExecuteCommand'; + $MsgDict['params'] = $ParamsDict; + + $Queue.Add([PSCustomObject]@{ + 'Message' = $MsgDict; + 'Client' = $null; + 'Stream' = $null; + }); + + Start-IcingaProtocolWorker -WorkerId 0; + return $script:Ps51SentResult; + } finally { + $GlobalVar.Public.IcingaProtocol.WorkerQueue = $PrevQueue; + $GlobalVar.Public.IcingaProtocol.Config.Hostname = $PrevHost; + } + } $script:TestDataDir $script:TestBinDir; + + $Ps51Dispatched | Should -Not -BeNullOrEmpty; + $Ps51Dispatched['host'] | Should -Be 'win-ps51-agent.local'; + $Ps51Dispatched['service'] | Should -Be 'PS51 Logs Check'; + $Ps51Dispatched['cr']['check_source'] | Should -Be 'win-ps51-agent.local'; + $Ps51Dispatched['cr']['exit_status'] | Should -Be 0; + } + } +} diff --git a/Tests/ModuleToolsHelpers.Tests.ps1 b/Tests/ModuleToolsHelpers.Tests.ps1 new file mode 100644 index 0000000..47f2fd7 --- /dev/null +++ b/Tests/ModuleToolsHelpers.Tests.ps1 @@ -0,0 +1,246 @@ +$ModulePath = Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..') -ChildPath 'IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Shared Module Tools and Protocol Helpers' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + } + + Context 'Get-ModuleObjectValue' { + It 'reads keys case-insensitively across Hashtable, Dictionary[string, object], OrderedDictionary and PSCustomObject' { + [hashtable]$Outcome = & $script:IcingaModule { + $Ht = @{ 'Check_Timeout' = 45; }; + $Dict = New-Object 'System.Collections.Generic.Dictionary[string, object]'; + $Dict['check_timeout'] = 10; + $Dict['CHECK_TIMEOUT'] = 25; + $Ord = New-Object System.Collections.Specialized.OrderedDictionary([System.StringComparer]::Ordinal); + $Ord['-p'] = 'lower'; + $Ord['-P'] = 'upper'; + $Obj = [PSCustomObject]@{ 'Service' = 'CPU Load'; }; + + $EmptyArrSource = @{ 'Items' = @(); 'Single' = @( 'only' ); }; + $EmptyArrVal = Get-ModuleObjectValue -InputObject $EmptyArrSource -Name 'items'; + $SingleArrVal = Get-ModuleObjectValue -InputObject $EmptyArrSource -Name 'single'; + + return @{ + 'HtVal' = (Get-ModuleObjectValue -InputObject $Ht -Name 'check_timeout' -DefaultValue 60); + 'ExactDictVal' = (Get-ModuleObjectValue -InputObject $Dict -Name 'CHECK_TIMEOUT' -DefaultValue 60); + 'CiDictVal' = (Get-ModuleObjectValue -InputObject $Dict -Name 'Check_Timeout' -DefaultValue 60); + 'OrdLower' = (Get-ModuleObjectValue -InputObject $Ord -Name '-p'); + 'OrdUpper' = (Get-ModuleObjectValue -InputObject $Ord -Name '-P'); + 'ObjVal' = (Get-ModuleObjectValue -InputObject $Obj -Name 'service'); + 'MissingVal' = (Get-ModuleObjectValue -InputObject $Obj -Name 'missing' -DefaultValue 'fallback'); + 'NullObjVal' = (Get-ModuleObjectValue -InputObject $null -Name 'any' -DefaultValue 99); + 'EmptyArrIsArr' = ($EmptyArrVal -is [array] -and $EmptyArrVal.Count -eq 0); + 'SingleIsArr' = ($SingleArrVal -is [array] -and $SingleArrVal.Count -eq 1); + }; + }; + + $Outcome['HtVal'] | Should -Be 45; + $Outcome['ExactDictVal'] | Should -Be 25; + $Outcome['CiDictVal'] | Should -Be 10; + $Outcome['OrdLower'] | Should -Be 'lower'; + $Outcome['OrdUpper'] | Should -Be 'upper'; + $Outcome['ObjVal'] | Should -Be 'CPU Load'; + $Outcome['MissingVal'] | Should -Be 'fallback'; + $Outcome['NullObjVal'] | Should -Be 99; + $Outcome['EmptyArrIsArr'] | Should -BeTrue; + $Outcome['SingleIsArr'] | Should -BeTrue; + } + } + + Context 'ConvertTo-ModuleOrderedDictionary' { + It 'converts dictionaries and PSCustomObjects with ordinal key comparison and optional empty-key skipping' { + [hashtable]$Outcome = & $script:IcingaModule { + $Src = New-Object 'System.Collections.Generic.Dictionary[string, object]'; + $Src[''] = '$'; + $Src[' '] = '$'; + $Src['-p'] = '80'; + $Src['-P'] = '443'; + + $Kept = ConvertTo-ModuleOrderedDictionary -InputObject $Src; + $Skipped = ConvertTo-ModuleOrderedDictionary -InputObject $Src -SkipEmptyKeys; + $FromObj = ConvertTo-ModuleOrderedDictionary -InputObject ([PSCustomObject]@{ 'Alpha' = 1; 'Beta' = 2; }); + + return @{ + 'KeptCount' = $Kept.Count; + 'SkippedCount' = $Skipped.Count; + 'LowerP' = $Skipped['-p']; + 'UpperP' = $Skipped['-P']; + 'ObjKeys' = (@($FromObj.Keys) -join ','); + }; + }; + + $Outcome['KeptCount'] | Should -Be 4; + $Outcome['SkippedCount'] | Should -Be 2; + $Outcome['LowerP'] | Should -Be '80'; + $Outcome['UpperP'] | Should -Be '443'; + $Outcome['ObjKeys'] | Should -Be 'Alpha,Beta'; + } + } + + Context 'Format-ModuleCommandLineArguments' { + It 'escapes empty strings, spaces, trailing backslashes and embedded quotes per CommandLineToArgvW' { + [hashtable]$Outcome = & $script:IcingaModule { + return @{ + 'Empty' = (Format-ModuleCommandLineArguments -Arguments @()); + 'Complex' = (Format-ModuleCommandLineArguments -Arguments @( 'simple', '', 'has space', 'C:\Dir\', 'C:\My Dir\', 'say "hi"', 'C:\Path\"quoted"' )); + }; + }; + + $Outcome['Empty'] | Should -Be ''; + $Outcome['Complex'] | Should -Be 'simple "" "has space" C:\Dir\ "C:\My Dir\\" "say \"hi\"" "C:\Path\\\"quoted\""'; + } + } + + Context 'Get-ModuleCommandParameterMap and ConvertTo-ModuleParameterValue' { + It 'filters CommonParameters, resolves aliases, orders positional parameters and coerces edge-case values' { + [hashtable]$Outcome = & $script:IcingaModule { + function Test-SampleTargetCmd() + { + [CmdletBinding(SupportsShouldProcess = $true)] + param ( + [Parameter(Position = 1)] + [Alias('SecondAlias')] + [int]$SecondParam = 5, + [Parameter(Position = 0)] + [string[]]$FirstList = @( '*' ), + [ValidateSet('Ok', 'Critical')] + [string]$Mode = 'Ok', + [securestring]$SecretVal = $null, + [Parameter(ValueFromRemainingArguments = $true)] + [string[]]$RemainingItems = @() + ); + + return 0; + } + + $CmdMeta = Get-Command -Name 'Test-SampleTargetCmd' -CommandType Function; + [hashtable]$Map = Get-ModuleCommandParameterMap -Parameters $CmdMeta.Parameters; + [hashtable]$Lookup = $Map['Lookup']; + [array]$Positional = $Map['Positional']; + + [hashtable]$SkipEmptyList = ConvertTo-ModuleParameterValue -ParameterMetadata $Lookup['FirstList'] -RawValue @(); + [hashtable]$BoundList = ConvertTo-ModuleParameterValue -ParameterMetadata $Lookup['FirstList'] -RawValue @( '*.log', '*.json' ); + [hashtable]$SkipEmptyNum = ConvertTo-ModuleParameterValue -ParameterMetadata $Lookup['SecondAlias'] -RawValue @( ); + [hashtable]$BoundNum = ConvertTo-ModuleParameterValue -ParameterMetadata $Lookup['SecondAlias'] -RawValue '42'; + [hashtable]$SkipBlankSet = ConvertTo-ModuleParameterValue -ParameterMetadata $Lookup['Mode'] -RawValue ' '; + [hashtable]$BoundSecret = ConvertTo-ModuleParameterValue -ParameterMetadata $Lookup['SecretVal'] -RawValue 'MyToken!'; + + try { + return @{ + 'HasVerbose' = $Lookup.ContainsKey('Verbose'); + 'HasWhatIf' = $Lookup.ContainsKey('WhatIf'); + 'HasAlias' = $Lookup.ContainsKey('SecondAlias'); + 'PosOrder' = ((@($Positional) | ForEach-Object { [string]$_.Name }) -join ','); + 'SkipEmptyList' = $SkipEmptyList['Status']; + 'BoundListVal' = ($BoundList['Value'] -join ','); + 'SkipEmptyNum' = $SkipEmptyNum['Status']; + 'BoundNumVal' = $BoundNum['Value']; + 'SkipBlankSet' = $SkipBlankSet['Status']; + 'SecretIsSecure' = ($BoundSecret['Value'] -is [System.Security.SecureString]); + }; + } finally { + if ($null -ne $BoundSecret['AllocatedSecret']) { + $BoundSecret['AllocatedSecret'].Dispose(); + } + } + }; + + $Outcome['HasVerbose'] | Should -BeFalse; + $Outcome['HasWhatIf'] | Should -BeFalse; + $Outcome['HasAlias'] | Should -BeTrue; + $Outcome['PosOrder'] | Should -Be 'FirstList,SecondParam,Mode,SecretVal'; + $Outcome['SkipEmptyList'] | Should -Be 'Skipped'; + $Outcome['BoundListVal'] | Should -Be '*.log,*.json'; + $Outcome['SkipEmptyNum'] | Should -Be 'Skipped'; + $Outcome['BoundNumVal'] | Should -Be 42; + $Outcome['SkipBlankSet'] | Should -Be 'Skipped'; + $Outcome['SecretIsSecure'] | Should -BeTrue; + } + } + + Context 'Invoke-ModulePowerShellCommand and Add-IcingaRPCMessageToWorker' { + It 'resets ActiveCheckCommand in finally even when a check throws before Compile' { + [hashtable]$Outcome = & $script:IcingaModule { + function Invoke-IcingaCheckAbortMidway() + { + [void](New-IcingaPlugin 'Partial' 10 '%').CheckRange(); + throw 'Aborted before Compile'; + } + + [hashtable]$Res = Invoke-ModulePowerShellCommand -Command 'Invoke-IcingaCheckAbortMidway'; + $GlobalVar = Get-GlobalRuntimeVariable; + + return @{ + 'ExitCode' = $Res['ExitCode']; + 'Output' = $Res['Output']; + 'ActiveAfterFailure' = $GlobalVar.Private.Icinga.ActiveCheckCommand; + 'ResultAfterFailure' = $GlobalVar.Private.Icinga.CheckResult; + }; + }; + + $Outcome['ExitCode'] | Should -Be 3; + $Outcome['Output'] | Should -Match 'Aborted before Compile'; + $Outcome['ActiveAfterFailure'] | Should -BeNullOrEmpty; + $Outcome['ResultAfterFailure'] | Should -BeNullOrEmpty; + } + + It 'drops malformed JSON cleanly in Add-IcingaRPCMessageToWorker and preserves empty-key stripping' { + [hashtable]$Outcome = & $script:IcingaModule { + $GlobalVar = Get-GlobalRuntimeVariable; + $PrevQueue = $GlobalVar.Public.IcingaProtocol.WorkerQueue; + $PrevCount = $GlobalVar.Public.IcingaProtocol.Config.WorkerCount; + $PrevLastWorker = $GlobalVar.Private.TCP.LastWorkerId; + $TestQueue = New-Object 'System.Collections.Concurrent.BlockingCollection[PSObject]'; + $QueueList = [System.Collections.ArrayList]::new(); + [void]$QueueList.Add($TestQueue); + + try { + $GlobalVar.Public.IcingaProtocol.Config.WorkerCount = 1; + $GlobalVar.Public.IcingaProtocol.WorkerQueue = $QueueList; + $GlobalVar.Private.TCP.LastWorkerId = -1; + + [void](Add-IcingaRPCMessageToWorker -Message '{invalid-json'); + [int]$AfterInvalid = $TestQueue.Count; + + [void](Add-IcingaRPCMessageToWorker -Message '{"jsonrpc":"2.0","method":"event::ExecuteCommand","params":{"macros":{"":"$","ifw_api_command":"uptime"}}}'); + [int]$AfterValid = $TestQueue.Count; + $QueuedItem = $TestQueue.Take(); + + return @{ + 'AfterInvalid' = $AfterInvalid; + 'AfterValid' = $AfterValid; + 'QueuedMethod' = (Get-ModuleObjectValue -InputObject $QueuedItem.Message -Name 'method'); + }; + } finally { + $TestQueue.Dispose(); + $GlobalVar.Public.IcingaProtocol.WorkerQueue = $PrevQueue; + $GlobalVar.Public.IcingaProtocol.Config.WorkerCount = $PrevCount; + $GlobalVar.Private.TCP.LastWorkerId = $PrevLastWorker; + } + }; + + $Outcome['AfterInvalid'] | Should -Be 0; + $Outcome['AfterValid'] | Should -Be 1; + $Outcome['QueuedMethod'] | Should -Be 'event::ExecuteCommand'; + } + + It 'accumulates repeated -Param:Value colon arguments on array parameters in Invoke-IcingaProtocolExternalScript' { + [string]$ColonScript = Join-Path -Path $TestDrive -ChildPath 'check_colon_array.ps1'; + [System.IO.File]::WriteAllText($ColonScript, "param([string[]]`$Tags = @()); Write-Output (`$Tags -join ','); exit 0;`n", (New-Object System.Text.UTF8Encoding($false))); + + [hashtable]$ScriptRes = & $script:IcingaModule { + param ($Path); + return (Invoke-IcingaProtocolExternalScript -ScriptPath $Path -CommandName 'check_colon_array.ps1' -BinaryArguments @( '-Tags:alpha', '-Tags:beta' )); + } $ColonScript; + + $ScriptRes['ExitCode'] | Should -Be 0; + $ScriptRes['Output'] | Should -Be 'alpha,beta'; + } + } +} diff --git a/Tests/New-IcingaPlugin.Tests.ps1 b/Tests/New-IcingaPlugin.Tests.ps1 index 5dffde2..41400e6 100644 --- a/Tests/New-IcingaPlugin.Tests.ps1 +++ b/Tests/New-IcingaPlugin.Tests.ps1 @@ -12,6 +12,13 @@ Describe 'New-IcingaPlugin' { # Daemon mode keeps Compile from writing to the console; the result is still # stored in Private.Icinga.CheckResult. $script:OriginalDaemonFlag = $Global:IcingaForWindows.Protected.IsBackgroundDaemon; + + function Invoke-TestNewPlugin() + { + return (& $script:IcingaModule { + New-IcingaPlugin @args; + } @args); + } } AfterAll { @@ -24,13 +31,13 @@ Describe 'New-IcingaPlugin' { It 'creates an instance of the IcingaPlugin type loaded by the current runspace' { $PluginType = & $script:IcingaModule { 'IcingaPlugin' -as [type] }; - $Plugin = New-IcingaPlugin 'Disks'; + $Plugin = Invoke-TestNewPlugin 'Disks'; ($Plugin.GetType() -eq $PluginType) | Should -BeTrue; } It 'creates a container from a name only' { - $Plugin = New-IcingaPlugin -Name 'Disks'; + $Plugin = & $script:IcingaModule { New-IcingaPlugin -Name 'Disks' }; $Plugin.Name | Should -Be 'Disks'; $Plugin.Value | Should -BeNullOrEmpty; @@ -38,21 +45,21 @@ Describe 'New-IcingaPlugin' { } It 'creates a check from a name and a value' { - $Plugin = New-IcingaPlugin -Name 'Load' -Value 95; + $Plugin = & $script:IcingaModule { New-IcingaPlugin -Name 'Load' -Value 95 }; $Plugin.Value | Should -Be 95; $Plugin.Unit | Should -Be ''; } It 'passes the unit to the check' { - $Plugin = New-IcingaPlugin -Name 'Load' -Value 95 -Unit '%'; + $Plugin = & $script:IcingaModule { New-IcingaPlugin -Name 'Load' -Value 95 -Unit '%' }; $Plugin.Value | Should -Be 95; $Plugin.Unit | Should -Be '%'; } It 'binds name, value and unit by position' { - $Plugin = New-IcingaPlugin 'C:' 55 '%'; + $Plugin = Invoke-TestNewPlugin 'C:' 55 '%'; $Plugin.Name | Should -Be 'C:'; $Plugin.Value | Should -Be 55; @@ -60,17 +67,31 @@ Describe 'New-IcingaPlugin' { } It 'returns a node whose fluent chain evaluates and compiles the check' { - $ExitCode = (New-IcingaPlugin 'Load' 95 '%').Warning('80').Critical('90').CheckRange().Compile(); + $ExitCode = (Invoke-TestNewPlugin 'Load' 95 '%').Warning('80').Critical('90').CheckRange().Compile(); $ExitCode | Should -Be 2; $Global:IcingaForWindows.Private.Icinga.CheckResult.ToString() | Should -Match '^\[CRITICAL\] Load'; } It 'aggregates the checks added to a container' { - $CheckPackage = New-IcingaPlugin 'Disks'; - $CheckPackage.AddCheck((New-IcingaPlugin 'C:' 55 '%').Warning('80').CheckRange()).Commit(); - $CheckPackage.AddCheck((New-IcingaPlugin 'D:' 85 '%').Warning('80').CheckRange()).Commit(); + $CheckPackage = Invoke-TestNewPlugin 'Disks'; + $CheckPackage.AddCheck((Invoke-TestNewPlugin 'C:' 55 '%').Warning('80').CheckRange()).Commit(); + $CheckPackage.AddCheck((Invoke-TestNewPlugin 'D:' 85 '%').Warning('80').CheckRange()).Commit(); $CheckPackage.Compile() | Should -Be 1; } + + It 'is publicly exported for external SDK plugins outside module scope' { + $ExportedCmd = Get-Command -Name 'New-IcingaPlugin' -Module 'IcingaForWindows' -ErrorAction Stop; + $SdkContainer = New-IcingaPlugin 'Custom SDK Package'; + $SdkLeaf = (New-IcingaPlugin 'Queue Depth' 12).MetricIndex('queue0').MetricName('customsdk').Warning('10').Critical('20').CheckRange(); + $SdkContainer.AddCheck($SdkLeaf).Commit(); + + [int]$SdkExit = $SdkContainer.Compile(); + + $ExportedCmd.Name | Should -Be 'New-IcingaPlugin'; + $SdkExit | Should -Be 1; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match '^\[WARNING\] Custom SDK Package'; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData[0] | Should -Be 'queue0::ifw_customsdk::queuedepth=12;10;20;;'; + } } diff --git a/Tests/Resolve-IcingaProtocolCommand.Tests.ps1 b/Tests/Resolve-IcingaProtocolCommand.Tests.ps1 new file mode 100644 index 0000000..ac3e83a --- /dev/null +++ b/Tests/Resolve-IcingaProtocolCommand.Tests.ps1 @@ -0,0 +1,265 @@ +$ModulePath = Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..') -ChildPath 'IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Resolve-IcingaProtocolCommand' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + function Invoke-TestCommandResolution() + { + param ( + [object]$Macros = $null, + [string]$CheckCommand = '', + [string]$BinaryDir = '' + ); + + return (& $script:IcingaModule { + param ($MacrosArg, $CheckCmdArg, $BinDirArg); + + function Get-ModuleBinaryDirectory() + { + return $BinDirArg; + } + + return (Resolve-IcingaProtocolCommand -Macros $MacrosArg -CheckCommand $CheckCmdArg); + } $Macros $CheckCommand $BinaryDir); + } + } + + BeforeEach { + $script:TestBinDir = Join-Path -Path $TestDrive -ChildPath ('Binaries_' + [System.Guid]::NewGuid().ToString('N')); + New-Item -Path $script:TestBinDir -ItemType Directory -Force | Out-Null; + } + + Context 'Mandatory ifw_api_command enforcement (IWKB001003)' { + It 'returns CommandMissing with IWKB001003 when macros are empty (unmodified ITL load-windows)' { + [hashtable]$Result = Invoke-TestCommandResolution -Macros @{ } -CheckCommand 'load-windows' -BinaryDir $script:TestBinDir; + + $Result['Status'] | Should -Be 'CommandMissing'; + $Result['KnowledgeBaseId'] | Should -Be 'IWKB001003'; + $Result['ReturnCodeKey'] | Should -Be 'IcingaProtocolCommandMissing'; + $Result['Message'] | Should -Match 'load-windows'; + $Result['Message'] | Should -Match 'IWKB001003'; + } + + It 'returns CommandMissing when Macros is $null or ifw_api_command is whitespace' { + [hashtable]$NullResult = Invoke-TestCommandResolution -Macros $null -BinaryDir $script:TestBinDir; + [hashtable]$BlankResult = Invoke-TestCommandResolution -Macros @{ 'ifw_api_command' = ' '; } -BinaryDir $script:TestBinDir; + + $NullResult['Status'] | Should -Be 'CommandMissing'; + $BlankResult['Status'] | Should -Be 'CommandMissing'; + } + } + + Context 'PowerShell check plugin resolution and shorthand expansion' { + It 'resolves an explicit Invoke-IcingaCheck* function with parameter metadata' { + [hashtable]$Result = Invoke-TestCommandResolution -Macros @{ 'ifw_api_command' = 'Invoke-IcingaCheckDirectory'; } -BinaryDir $script:TestBinDir; + + $Result['Status'] | Should -Be 'Ok'; + $Result['Kind'] | Should -Be 'PowerShell'; + $Result['CommandName'] | Should -Be 'Invoke-IcingaCheckDirectory'; + $Result['Parameters'].ContainsKey('Path') | Should -BeTrue; + } + + It 'expands shorthand names from Hashtable and PSCustomObject macros when no binary exists in Binaries' { + [hashtable]$CpuResult = Invoke-TestCommandResolution -Macros @{ 'ifw_api_command' = 'cpu'; } -BinaryDir $script:TestBinDir; + [hashtable]$DirResult = Invoke-TestCommandResolution -Macros ([PSCustomObject]@{ 'ifw_api_command' = 'IcingaCheckDirectory'; }) -BinaryDir $script:TestBinDir; + + $CpuResult['Status'] | Should -Be 'Ok'; + $CpuResult['Kind'] | Should -Be 'PowerShell'; + $CpuResult['CommandName'] | Should -Be 'Invoke-IcingaCheckCPU'; + + $DirResult['Status'] | Should -Be 'Ok'; + $DirResult['Kind'] | Should -Be 'PowerShell'; + $DirResult['CommandName'] | Should -Be 'Invoke-IcingaCheckDirectory'; + } + + It 'rejects non-check PowerShell cmdlets and wildcard patterns with IWKB001003' { + [hashtable]$RemoveResult = Invoke-TestCommandResolution -Macros @{ 'ifw_api_command' = 'Remove-Item'; } -BinaryDir $script:TestBinDir; + [hashtable]$ProcResult = Invoke-TestCommandResolution -Macros @{ 'ifw_api_command' = 'Get-Process'; } -BinaryDir $script:TestBinDir; + [hashtable]$WildResult = Invoke-TestCommandResolution -Macros @{ 'ifw_api_command' = 'Invoke-IcingaCheck*'; } -BinaryDir $script:TestBinDir; + + $RemoveResult['Status'] | Should -Be 'CommandNotFound'; + $RemoveResult['KnowledgeBaseId'] | Should -Be 'IWKB001003'; + $ProcResult['Status'] | Should -Be 'CommandNotFound'; + $WildResult['Status'] | Should -Be 'CommandNotFound'; + } + } + + Context 'Strict full-path Binary lookup and Path-Traversal rejection' { + It 'resolves binaries inside Get-ModuleBinaryDirectory with explicit or probed extensions' { + [string]$ExeFile = Join-Path -Path $script:TestBinDir -ChildPath 'check_load.exe'; + [string]$CmdFile = Join-Path -Path $script:TestBinDir -ChildPath 'check_load.cmd'; + [string]$DottedFile = Join-Path -Path $script:TestBinDir -ChildPath 'check_app_v1.2.exe'; + Set-Content -Path $ExeFile -Value 'stub' -Encoding UTF8; + Set-Content -Path $CmdFile -Value 'stub' -Encoding UTF8; + Set-Content -Path $DottedFile -Value 'stub' -Encoding UTF8; + + [hashtable]$Explicit = Invoke-TestCommandResolution -Macros @{ 'ifw_api_command' = 'check_load.cmd'; } -BinaryDir $script:TestBinDir; + [hashtable]$Probed = Invoke-TestCommandResolution -Macros @{ 'ifw_api_command' = 'check_load'; } -BinaryDir $script:TestBinDir; + [hashtable]$Dotted = Invoke-TestCommandResolution -Macros @{ 'ifw_api_command' = 'check_app_v1.2'; } -BinaryDir $script:TestBinDir; + + $Explicit['Status'] | Should -Be 'Ok'; + $Explicit['Kind'] | Should -Be 'Binary'; + $Explicit['BinaryPath'] | Should -Be ([System.IO.Path]::GetFullPath($CmdFile)); + + $Probed['Status'] | Should -Be 'Ok'; + $Probed['Kind'] | Should -Be 'Binary'; + $Probed['CommandName'] | Should -Be 'check_load.exe'; + $Probed['BinaryPath'] | Should -Be ([System.IO.Path]::GetFullPath($ExeFile)); + + $Dotted['Status'] | Should -Be 'Ok'; + $Dotted['Kind'] | Should -Be 'Binary'; + $Dotted['CommandName'] | Should -Be 'check_app_v1.2.exe'; + $Dotted['BinaryPath'] | Should -Be ([System.IO.Path]::GetFullPath($DottedFile)); + } + + It 'gives files inside Get-ModuleBinaryDirectory precedence over shorthand expansion' { + [string]$CustomCpuScript = Join-Path -Path $script:TestBinDir -ChildPath 'cpu.ps1'; + Set-Content -Path $CustomCpuScript -Value 'exit 0' -Encoding UTF8; + + [hashtable]$Result = Invoke-TestCommandResolution -Macros @{ 'ifw_api_command' = 'cpu'; } -BinaryDir $script:TestBinDir; + + $Result['Status'] | Should -Be 'Ok'; + $Result['Kind'] | Should -Be 'Binary'; + $Result['CommandName'] | Should -Be 'cpu.ps1'; + $Result['BinaryPath'] | Should -Be ([System.IO.Path]::GetFullPath($CustomCpuScript)); + } + + It 'rejects path traversal, sibling-prefix tricks and system paths outside Binaries with IWKB001003' { + [string]$SiblingDir = $script:TestBinDir + 'Evil'; + New-Item -Path $SiblingDir -ItemType Directory -Force | Out-Null; + [string]$SiblingFile = Join-Path -Path $SiblingDir -ChildPath 'evil.exe'; + Set-Content -Path $SiblingFile -Value 'stub' -Encoding UTF8; + + [hashtable]$Traversal = Invoke-TestCommandResolution -Macros @{ 'ifw_api_command' = '..\evil.exe'; } -BinaryDir $script:TestBinDir; + [hashtable]$Sibling = Invoke-TestCommandResolution -Macros @{ 'ifw_api_command' = $SiblingFile; } -BinaryDir $script:TestBinDir; + [hashtable]$WinSys = Invoke-TestCommandResolution -Macros @{ 'ifw_api_command' = 'C:\Windows\System32\cmd.exe'; } -BinaryDir $script:TestBinDir; + [hashtable]$UnixSys = Invoke-TestCommandResolution -Macros @{ 'ifw_api_command' = '/bin/sh'; } -BinaryDir $script:TestBinDir; + [hashtable]$UncPath = Invoke-TestCommandResolution -Macros @{ 'ifw_api_command' = '\\attacker\share\tool.exe'; } -BinaryDir $script:TestBinDir; + + $Traversal['Status'] | Should -Be 'BinaryPathRejected'; + $Traversal['KnowledgeBaseId'] | Should -Be 'IWKB001003'; + $Sibling['Status'] | Should -Be 'BinaryPathRejected'; + $WinSys['Status'] | Should -Be 'BinaryPathRejected'; + $UnixSys['Status'] | Should -Be 'BinaryPathRejected'; + $UncPath['Status'] | Should -Be 'BinaryPathRejected'; + } + + It 'rejects NTFS Alternate Data Stream colons, drive-relative colons and ASCII control characters' { + [string]$ValidBin = Join-Path -Path $script:TestBinDir -ChildPath 'check_load.exe'; + Set-Content -Path $ValidBin -Value 'stub' -Encoding UTF8; + + [hashtable]$AdsRel = Invoke-TestCommandResolution -Macros @{ 'ifw_api_command' = 'check_load.exe:stream'; } -BinaryDir $script:TestBinDir; + [hashtable]$AdsFull = Invoke-TestCommandResolution -Macros @{ 'ifw_api_command' = ($ValidBin + ':stream'); } -BinaryDir $script:TestBinDir; + [hashtable]$DriveRel = Invoke-TestCommandResolution -Macros @{ 'ifw_api_command' = 'C:evil.exe'; } -BinaryDir $script:TestBinDir; + [hashtable]$CtrlNewline = Invoke-TestCommandResolution -Macros @{ 'ifw_api_command' = "check_load.exe`nwhoami"; } -BinaryDir $script:TestBinDir; + [hashtable]$CtrlNull = Invoke-TestCommandResolution -Macros @{ 'ifw_api_command' = ("check_load.exe" + [char]0 + '.txt'); } -BinaryDir $script:TestBinDir; + [hashtable]$PathWild = Invoke-TestCommandResolution -Macros @{ 'ifw_api_command' = '..\*.exe'; } -BinaryDir $script:TestBinDir; + [hashtable]$PipeInvalid = Invoke-TestCommandResolution -Macros @{ 'ifw_api_command' = 'check_load|evil.exe'; } -BinaryDir $script:TestBinDir; + + $AdsRel['Status'] | Should -Be 'BinaryPathRejected'; + $AdsRel['KnowledgeBaseId'] | Should -Be 'IWKB001003'; + $AdsFull['Status'] | Should -Be 'BinaryPathRejected'; + $DriveRel['Status'] | Should -Be 'BinaryPathRejected'; + $CtrlNewline['Status'] | Should -Be 'BinaryPathRejected'; + $CtrlNull['Status'] | Should -Be 'BinaryPathRejected'; + $PathWild['Status'] | Should -Be 'BinaryPathRejected'; + $PipeInvalid['Status'] | Should -Be 'BinaryPathRejected'; + } + } + + Context 'Binary directory environment and secure child enumeration' { + It 'resolves Get-ModuleBinaryDirectory and creates Config and Binaries via New-ModuleConfigEnvironment' { + [string]$MockProgramData = Join-Path -Path $TestDrive -ChildPath ('ProgData_' + [System.Guid]::NewGuid().ToString('N')); + New-Item -Path $MockProgramData -ItemType Directory -Force | Out-Null; + + [hashtable]$EnvOutcome = & $script:IcingaModule { + param ($TempProgData); + + [string]$PrevProgramData = $env:ProgramData; + try { + $env:ProgramData = $TempProgData; + [string]$BinDir = Get-ModuleBinaryDirectory; + [string]$CfgDir = Get-ModuleConfigDirectory; + $FirstCode = New-ModuleConfigEnvironment; + $SecondCode = New-ModuleConfigEnvironment; + + return @{ + 'BinDir' = $BinDir; + 'CfgDir' = $CfgDir; + 'BinExists' = (Test-Path -Path $BinDir -PathType Container); + 'CfgExists' = (Test-Path -Path $CfgDir -PathType Container); + 'FirstCode' = $FirstCode; + 'SecondCode' = $SecondCode; + }; + } finally { + $env:ProgramData = $PrevProgramData; + } + } $MockProgramData; + + [string]$ExpectedBin = Join-Path -Path $MockProgramData -ChildPath (Join-Path -Path 'IcingaForWindows' -ChildPath 'Binaries'); + $EnvOutcome['BinDir'] | Should -Be $ExpectedBin; + $EnvOutcome['BinExists'] | Should -BeTrue; + $EnvOutcome['CfgExists'] | Should -BeTrue; + ($EnvOutcome['FirstCode'] -is [int]) | Should -BeTrue; + $EnvOutcome['FirstCode'] | Should -Be 0; + $EnvOutcome['SecondCode'] | Should -Be 0; + } + + It 'allows Get-SecureChildItem inside Get-ModuleBinaryDirectory and rejects unapproved paths once' { + [string]$MockProgramData = Join-Path -Path $TestDrive -ChildPath ('SecProg_' + [System.Guid]::NewGuid().ToString('N')); + [string]$OutsideDir = Join-Path -Path $TestDrive -ChildPath ('Outside_' + [System.Guid]::NewGuid().ToString('N')); + New-Item -Path $MockProgramData -ItemType Directory -Force | Out-Null; + New-Item -Path $OutsideDir -ItemType Directory -Force | Out-Null; + Set-Content -Path (Join-Path -Path $OutsideDir -ChildPath 'secret.txt') -Value 'nope' -Encoding UTF8; + + [hashtable]$SecOutcome = & $script:IcingaModule { + param ($TempProgData, $UnapprovedPath); + + [string]$PrevProgramData = $env:ProgramData; + try { + $env:ProgramData = $TempProgData; + [void](New-ModuleConfigEnvironment); + [string]$BinDir = Get-ModuleBinaryDirectory; + Set-Content -Path (Join-Path -Path $BinDir -ChildPath 'check_demo.exe') -Value 'bin' -Encoding UTF8; + + $ApprovedItems = @(Get-SecureChildItem -Path $BinDir -File); + $script:ApproveChecks = 0; + $RealApproveCmd = Get-Command -Name 'Test-SecureApprovedPath' -CommandType Function; + + function Test-SecureApprovedPath() + { + param ( + [string]$Path = '', + [array]$ApprovedPath = @() + ); + + $script:ApproveChecks++; + return (& $RealApproveCmd -Path $Path -ApprovedPath $ApprovedPath); + } + + $DeniedResult = Get-SecureChildItem -Path $UnapprovedPath -File; + + return @{ + 'ApprovedCount' = $ApprovedItems.Count; + 'ApprovedName' = [string]$ApprovedItems[0].Name; + 'DeniedResult' = $DeniedResult; + 'ApproveChecks' = $script:ApproveChecks; + }; + } finally { + $env:ProgramData = $PrevProgramData; + } + } $MockProgramData $OutsideDir; + + $SecOutcome['ApprovedCount'] | Should -Be 1; + $SecOutcome['ApprovedName'] | Should -Be 'check_demo.exe'; + $SecOutcome['DeniedResult'] | Should -BeNullOrEmpty; + $SecOutcome['ApproveChecks'] | Should -Be 1; + } + } +} diff --git a/Tests/Test-IcingaArrayFilter.Tests.ps1 b/Tests/Test-IcingaArrayFilter.Tests.ps1 new file mode 100644 index 0000000..8e9ed6a --- /dev/null +++ b/Tests/Test-IcingaArrayFilter.Tests.ps1 @@ -0,0 +1,58 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Test-IcingaArrayFilter' { + Context 'Single values' { + It 'passes every value without filters' { + Test-IcingaArrayFilter -InputObject 'Spooler' | Should -BeTrue; + } + + It 'requires an include match when an include list is given' { + Test-IcingaArrayFilter -InputObject 'Spooler' -Include 'Spo*' | Should -BeTrue; + Test-IcingaArrayFilter -InputObject 'Spooler' -Include 'WinRM', 'W*' | Should -BeFalse; + } + + It 'matches case-insensitively with ? and [] wildcards' { + Test-IcingaArrayFilter -InputObject 'SPOOLER' -Include 'spo?ler' | Should -BeTrue; + Test-IcingaArrayFilter -InputObject 'D' -Include '[c-e]' | Should -BeTrue; + } + + It 'lets an exclude match win over an include match' { + Test-IcingaArrayFilter -InputObject 'Spooler' -Include '*' -Exclude 'Spooler' | Should -BeFalse; + Test-IcingaArrayFilter -InputObject 'WinRM' -Exclude 'Spooler' | Should -BeTrue; + } + + It 'compares non-string values by their string form' { + Test-IcingaArrayFilter -InputObject 4 -Include '4' | Should -BeTrue; + } + + It 'never passes $null' { + Test-IcingaArrayFilter -InputObject $null | Should -BeFalse; + } + + It 'treats an invalid wildcard pattern as no match instead of throwing' { + Test-IcingaArrayFilter -InputObject 'abc' -Include '[abc' | Should -BeFalse; + Test-IcingaArrayFilter -InputObject 'abc' -Exclude '[abc' | Should -BeTrue; + } + } + + Context 'Arrays' { + It 'returns the passing elements as an array' { + $Result = Test-IcingaArrayFilter -InputObject @('C', 'D', 'E') -Exclude 'D'; + ($Result -is [array]) | Should -BeTrue; + $Result | Should -Be @('C', 'E'); + } + + It 'returns an array for a single passing element and an empty array for none' { + $Single = Test-IcingaArrayFilter -InputObject @('C', 'D') -Include 'C'; + ($Single -is [array]) | Should -BeTrue; + $Single.Count | Should -Be 1; + + $None = Test-IcingaArrayFilter -InputObject @('C', 'D') -Include 'Q'; + ($None -is [array]) | Should -BeTrue; + $None.Count | Should -Be 0; + } + } +} diff --git a/build/Build-ModuleProject.ps1 b/build/Build-ModuleProject.ps1 index 374ef4c..c7a1d7d 100644 --- a/build/Build-ModuleProject.ps1 +++ b/build/Build-ModuleProject.ps1 @@ -192,6 +192,13 @@ if (Test-Path $OutputPath) { Write-Host " * Output directory ready: $OutputPath" -ForegroundColor Green; +# TODO: Compile native helpers into signed DLLs here instead of generating them at runtime. +# Keep their C# sources as .cs files in the repository (e.g. the DeviceIoControl based +# volume/disk-extent and NTFS volume data reader for Get-IcingaDiskInformation), build +# them into lib/ during this step, sign them together with the module and load them at +# import time only when the type is not present yet. Nothing may call Add-Type with a +# type definition at runtime anymore. + # Build consolidated classes and kernel files Write-Host "`n[3/4] Building consolidated classes and kernel modules..." -ForegroundColor Yellow; diff --git a/docs/Agents/tasks/plugins-cpu-service-partition/implementation_plan.md b/docs/Agents/tasks/plugins-cpu-service-partition/implementation_plan.md new file mode 100644 index 0000000..f4f24aa --- /dev/null +++ b/docs/Agents/tasks/plugins-cpu-service-partition/implementation_plan.md @@ -0,0 +1,67 @@ +# Implementation Plan — Icinga Protocol Check-Command Execution, Shared Helpers & Core Plugins (`plugins-cpu-service-partition`) + +## 1. Problem Statement & Objectives + +This branch delivers a modular, zero-duplication command execution pipeline for `event::ExecuteCommand` RPC frames alongside the public `New-IcingaPlugin` SDK, `O(1)` call-stack caching in `IcingaPlugin`, hardened `PerformanceCounter` daemon concurrency, and legacy-compatible monitoring plugins (`Invoke-IcingaCheckCPU`, `Invoke-IcingaCheckDirectory`, `Invoke-IcingaCheckMemory`, `Invoke-IcingaCheckPartitionSpace`, `Invoke-IcingaCheckPerfCounter`, `Invoke-IcingaCheckProcess`, `Invoke-IcingaCheckScheduledTask`, `Invoke-IcingaCheckService`, `Invoke-IcingaCheckUptime`): + +1. **Shared Module Helpers (`src/Tools/Private/` — Zero Duplication):** + - `Get-ModuleObjectValue`: Null-safe, case-insensitive lookup across `Hashtable`, PS 5.1 `Dictionary[string, object]`, `OrderedDictionary`, and `PSCustomObject` without array unrolling. + - `ConvertTo-ModuleOrderedDictionary`: Ordinal `OrderedDictionary` normalizer with optional `-SkipEmptyKeys`. + - `Format-ModuleCommandLineArguments`: Windows `CommandLineToArgvW` argument token quoter. + - `Get-ModuleCommandParameterMap` & `ConvertTo-ModuleParameterValue`: Shared PowerShell parameter introspection (filtering `CommonParameters` / `ShouldProcess`), type coercion (`[bool]`, `[switch]`, numeric, enum, arrays, `[ValidateSet]` / `[ValidatePattern]` blank-skip), and `[securestring]` conversion/tracking. + - `Invoke-ModulePowerShellCommand`: Unified in-process `&` runner reading `Private.Icinga.CheckResult`, supporting `-UseLastExitCode` and Nagios `|` fallback for `.ps1` scripts, and resetting `CheckResult` + `ActiveCheckCommand` in `finally`. +2. **Modular IcingaProtocol Execution Pipeline (`src/IcingaProtocol/Private/`):** + - `Expand-IcingaProtocolMacroValue`, `Invoke-IcingaProtocolExternalScript`, `Stop-IcingaProtocolProcessTree`, and `Invoke-IcingaProtocolBinaryProcess` decompose `ConvertFrom-IcingaProtocolMacros` and `Invoke-IcingaProtocolCheckCommand` into focused single-responsibility functions. + - Skips unset, `$null`, `""`, empty `IList` (`[]`), and empty `IDictionary`/`PSCustomObject` (`{}`) placeholders on unknown `ifw_api_arguments` parameters (`IWKB001001`). + - Preserves PS 5.1 empty-key `"": "$"` stripping and adds a `$null -eq $RPCMessage` guard in `Add-IcingaRPCMessageToWorker`. +3. **Plugin SDK, `IcingaPlugin` `O(1)` CallStack Caching, Plugin Parity & `PerformanceCounter` Daemon Safety:** + - Promotes `New-IcingaPlugin` to `src/Plugins/Lib/Public/New-IcingaPlugin.ps1` as the public SDK factory for custom/external plugin repositories (keeping `Get-Icinga*` providers in `Private/`). + - Caches `Get-PSCallStack` command detection in `$GlobalVariable.Private.Icinga.ActiveCheckCommand` (`O(1)` per check execution regardless of node count or creation order, cleared in `Compile()`, `Invoke-ModulePowerShellCommand`, and `Start-IcingaProtocolWorker`). + - Full legacy parity on `Invoke-IcingaCheckCPU` (`-Core`, `-OverallOnly`, `-NodeFilter` with `[Alias('SocketFilter')]`), `Invoke-IcingaCheckScheduledTask` (`267009` on `Running` tasks & `267011` treated as `OK`, 32-bit `0xFFFFFFFFL` HRESULT hex masking for `-IgnoreExitCodes`, `[Alias('IgnoreLastResult', 'IgnoreExitCode')]`), and `Invoke-IcingaCheckService` (`[IcingaServiceStatus[]]$Status` multi-status array + single-string compatibility). + - Mutual `-IgnoreEmptyChecks` <-> `-MitigateUnknown` aliases, `Get-IcingaDirectoryInformation` `[WildcardPattern]` validation, `Invoke-IcingaCheckMemory` empty-CIM & 0-byte pagefile guards, `Get-IcingaDiskInformation -SkipPartitionMapping` + `Invoke-IcingaCheckPartitionSpace` trailing `\` mount-point matching, and `InvariantCulture` formatting in `Invoke-IcingaCheckUptime`. + - `PerformanceCounter` daemon loop `try / catch / finally` resilience, atomic `PendingRequests.TryRemove` timeout disposal protection, `ParsePath` check before `Registered` insertion, and BOM-less UTF-8 `try / catch` cache persistence. + +--- + +## 2. Proposed File Changes + +### Shared Tools & Runtime State +- **[MODIFY]** `IcingaForWindows.psm1` (`Get-ModuleBinaryDirectory` & `Private.Icinga.ActiveCheckCommand`) +- **[MODIFY]** `src/Classes/Icinga/IcingaPlugin.ps1` (`O(1)` `ActiveCheckCommand` caching & `Compile()` reset) +- **[NEW]** `src/Tools/Private/Get-ModuleObjectValue.ps1` +- **[NEW]** `src/Tools/Private/ConvertTo-ModuleOrderedDictionary.ps1` +- **[NEW]** `src/Tools/Private/Format-ModuleCommandLineArguments.ps1` +- **[NEW]** `src/Tools/Private/Get-ModuleCommandParameterMap.ps1` +- **[NEW]** `src/Tools/Private/ConvertTo-ModuleParameterValue.ps1` +- **[NEW]** `src/Tools/Private/Invoke-ModulePowerShellCommand.ps1` +- **[NEW]** `src/Tools/Private/ConvertTo-ModuleSecureString.ps1` & `ConvertFrom-ModuleBoolean.ps1` +- **[MODIFY]** `src/Tools/Public/Get-IcingaUnixTime.ps1` + +### IcingaProtocol Execution Pipeline +- **[NEW]** `src/IcingaProtocol/Private/Resolve-IcingaProtocolCommand.ps1` +- **[NEW]** `src/IcingaProtocol/Private/Expand-IcingaProtocolMacroValue.ps1` +- **[NEW]** `src/IcingaProtocol/Private/ConvertFrom-IcingaProtocolMacros.ps1` +- **[NEW]** `src/IcingaProtocol/Private/Split-IcingaBinaryPluginOutput.ps1` +- **[NEW]** `src/IcingaProtocol/Private/Invoke-IcingaProtocolExternalScript.ps1` +- **[NEW]** `src/IcingaProtocol/Private/Stop-IcingaProtocolProcessTree.ps1` +- **[NEW]** `src/IcingaProtocol/Private/Invoke-IcingaProtocolBinaryProcess.ps1` +- **[NEW]** `src/IcingaProtocol/Private/Invoke-IcingaProtocolCheckCommand.ps1` +- **[MODIFY]** `src/IcingaProtocol/Private/Start-IcingaProtocolWorker.ps1` & `Add-IcingaRPCMessageToWorker.ps1` + +### Plugins, Providers & PerformanceCounter +- **[MOVE]** `src/Plugins/Lib/Private/New-IcingaPlugin.ps1` -> `src/Plugins/Lib/Public/New-IcingaPlugin.ps1` +- **[MODIFY]** `src/Plugins/Provider/Disk/Private/Get-IcingaDiskInformation.ps1` & `src/Plugins/Provider/FileSystem/Private/Get-IcingaDirectoryInformation.ps1` +- **[MODIFY]** `src/Plugins/Checks/Public/Invoke-IcingaCheck{CPU,Memory,PartitionSpace,PerfCounter,ScheduledTask,Service,Uptime}.ps1` +- **[MODIFY]** `src/PerformanceCounter/Private/{Start-IcingaPerformanceCounterDaemon,Write-IcingaPerformanceCounterCache}.ps1` & `src/PerformanceCounter/Public/Get-IcingaPerformanceCounter.ps1` + +### Deferred Follow-Up Branch Plans (Unmodified Source on This Branch) +- **[NEW]** `docs/Agents/tasks/fix-restapi-and-security/{implementation_plan,todo}.md` +- **[NEW]** `docs/Agents/tasks/fix-icingaprotocol-transport/{implementation_plan,todo}.md` + +--- + +## 3. Verification Plan + +1. Compile `lib/` with daemon memory-leak checks (`.\build\Build-ModuleProject.ps1 -SkipTests -TestDaemonMemoryLeaks`) and regenerate docs (`.\build\Build-ModuleDocs.ps1 -Strict $true`). +2. Validate code styling (`.\build\Test-ModuleCodeStyling.ps1`), class-literal rules (`Tests/ClassLiteral.Tests.ps1`), and `Invoke-ScriptAnalyzer` (`0` violations). +3. Run all Pester 6.1.0 unit test suites across helpers, protocol execution, plugins, providers, and `PerformanceCounter`. diff --git a/docs/Agents/tasks/plugins-cpu-service-partition/todo.md b/docs/Agents/tasks/plugins-cpu-service-partition/todo.md new file mode 100644 index 0000000..45ae4a4 --- /dev/null +++ b/docs/Agents/tasks/plugins-cpu-service-partition/todo.md @@ -0,0 +1,34 @@ +# Task Checklist — `plugins-cpu-service-partition` + +## Completed Tasks + +- [x] **Shared Module Helpers (`src/Tools/Private/`)** + - Created `Get-ModuleObjectValue.ps1`, `ConvertTo-ModuleOrderedDictionary.ps1`, `Format-ModuleCommandLineArguments.ps1`, `Get-ModuleCommandParameterMap.ps1`, `ConvertTo-ModuleParameterValue.ps1`, `Invoke-ModulePowerShellCommand.ps1`, `ConvertTo-ModuleSecureString.ps1`, and `ConvertFrom-ModuleBoolean.ps1`. +- [x] **Modular IcingaProtocol Execution Pipeline (`src/IcingaProtocol/Private/`)** + - Created `Resolve-IcingaProtocolCommand.ps1`, `Expand-IcingaProtocolMacroValue.ps1`, `ConvertFrom-IcingaProtocolMacros.ps1`, `Split-IcingaBinaryPluginOutput.ps1`, `Invoke-IcingaProtocolExternalScript.ps1`, `Stop-IcingaProtocolProcessTree.ps1`, `Invoke-IcingaProtocolBinaryProcess.ps1`, and `Invoke-IcingaProtocolCheckCommand.ps1`. + - Updated `Start-IcingaProtocolWorker.ps1` (`Get-ModuleObjectValue`, monotonic `Stopwatch` timing, `ActiveCheckCommand` reset in `finally`) and `Add-IcingaRPCMessageToWorker.ps1` (retained PS 5.1 empty-key `"": "$"` stripping + added `$null -eq $RPCMessage` guard). + - Updated `ConvertFrom-IcingaProtocolMacros.ps1` to skip empty `IList` (`[]`) and empty `IDictionary`/`PSCustomObject` (`{}`) alongside `""` on unknown `ifw_api_arguments` parameters (`IWKB001001`). +- [x] **Plugin SDK, `O(1)` CallStack Caching & Core Plugin Parity** + - Promoted `src/Plugins/Lib/Private/New-IcingaPlugin.ps1` -> `src/Plugins/Lib/Public/New-IcingaPlugin.ps1` (keeping `Get-Icinga*` providers in `Private/`). + - Implemented `O(1)` `Get-PSCallStack` caching in `IcingaPlugin.ps1` via `$GlobalVariable.Private.Icinga.ActiveCheckCommand` with deterministic reset in `Compile()` `finally`, `Invoke-ModulePowerShellCommand`, and `Start-IcingaProtocolWorker`. + - Added legacy parity to `Invoke-IcingaCheckCPU.ps1` (`-Core`, `-OverallOnly`, `[Alias('SocketFilter')] -NodeFilter`), `Invoke-IcingaCheckScheduledTask.ps1` (`267009` on `Running` tasks & `267011` as `OK`, `0xFFFFFFFFL` HRESULT hex masking, `[Alias('IgnoreLastResult', 'IgnoreExitCode')]`), and `Invoke-IcingaCheckService.ps1` (`[IcingaServiceStatus[]]$Status` multi-status array + single-string compatibility). + - Hardened `Get-IcingaDirectoryInformation.ps1`, `Get-IcingaDiskInformation.ps1` (`-SkipPartitionMapping`), `Invoke-IcingaCheckMemory.ps1`, `Invoke-IcingaCheckPartitionSpace.ps1`, `Invoke-IcingaCheckPerfCounter.ps1`, and `Invoke-IcingaCheckUptime.ps1`. +- [x] **`PerformanceCounter` Daemon Concurrency & Cache Safety** + - Wrapped `Start-IcingaPerformanceCounterDaemon.ps1` loop in `try / catch / finally` and coordinated `PendingRequests` handoff via atomic `TryRemove` + `ObjectDisposedException` safety. + - Validated counter paths via `ParsePath` before adding to `Store.Registered` in `Get-IcingaPerformanceCounter.ps1`. + - Guarded `Write-IcingaPerformanceCounterCache.ps1` with `try / catch` and BOM-less UTF-8 `[System.IO.File]::WriteAllText`. +- [x] **Documentation, Tests & Follow-Up Task Tracking** + - Regenerated `docs/Icinga.*.md` (`198` functions, `0` violations) and updated `docs/Developer/Plugins/{02-IcingaPlugin-Reference,04-Custom-Plugin-Developer-Guide}.md` + `docs/Developer/IcingaProtocol/01-Check-and-Binary-Execution.md`. + - Added `Tests/ModuleToolsHelpers.Tests.ps1` and expanded `15` existing Pester test suites; validated `0` violations in `Test-ModuleCodeStyling.ps1`, `Invoke-ScriptAnalyzer`, `ClassLiteral.Tests.ps1`, and `Test-ModuleDaemonMemoryLeak.ps1`. + - Created persistent follow-up plans under `docs/Agents/tasks/fix-restapi-and-security/` and `docs/Agents/tasks/fix-icingaprotocol-transport/`. +- [x] **Live Windows PowerShell 5.1 Daemon & Icinga 2 End-to-End Verification** + - Verified live daemon and check execution under Windows PowerShell 5.1 against Icinga 2 (`event::ExecuteCommand` checks running cleanly end-to-end). + +--- + +## Follow-Up Branches After Merge to `main` + +- [ ] **RestApi, Security & Manifest Follow-Up (`docs/Agents/tasks/fix-restapi-and-security/`):** + Implement shared helper integration in `RestApi`, boundary normalization in `Test-SecureApprovedPath.ps1`, certificate disposal fix in `Get-TlsCertificate.ps1`, and optional static `FunctionsToExport` sync in `IcingaForWindows.psd1`. +- [ ] **IcingaProtocol Socket & Netstring Transport Follow-Up (`docs/Agents/tasks/fix-icingaprotocol-transport/`):** + Implement UTF-8 byte-accurate netstring framing, `WriterQueue` startup synchronization, thread-safe `Connections` tracking, and cluster lifecycle handlers in a dedicated branch. diff --git a/docs/Agents/tasks/plugins-cpu-service-partition/walkthrough.md b/docs/Agents/tasks/plugins-cpu-service-partition/walkthrough.md new file mode 100644 index 0000000..195caac --- /dev/null +++ b/docs/Agents/tasks/plugins-cpu-service-partition/walkthrough.md @@ -0,0 +1,49 @@ +# Implementation Walkthrough — Shared Helpers, IcingaProtocol Decomposition, Plugin SDK & Parity (`plugins-cpu-service-partition`) + +## 1. Executive Summary + +Delivered the modular decomposition of the Icinga 2 `event::ExecuteCommand` pipeline (`src/Tools/Private/` + `src/IcingaProtocol/Private/`), promoted `New-IcingaPlugin` to a public Plugin SDK cmdlet (`src/Plugins/Lib/Public/New-IcingaPlugin.ps1`), reduced `IcingaPlugin` `Get-PSCallStack` overhead from `O(N)` per node to `O(1)` per check execution via `Private.Icinga.ActiveCheckCommand`, hardened `PerformanceCounter` daemon concurrency and cache writes, and brought all nine core monitoring plugins to full legacy parity and edge-case safety. Deferred `RestApi`, `Test-SecureApprovedPath`, `Get-TlsCertificate`, `IcingaForWindows.psd1` static export sync, and `IcingaProtocol` socket/netstring transport items were documented in persistent task folders (`docs/Agents/tasks/fix-restapi-and-security/` and `docs/Agents/tasks/fix-icingaprotocol-transport/`) without touching any deferred source files. + +--- + +## 2. Under-the-Hood Deep Dive + +### 2.1 Zero-Duplication Shared Module Helpers (`src/Tools/Private/`) +- **`Get-ModuleObjectValue`:** Uniform, null-safe lookup across `Hashtable`, Windows PowerShell 5.1 `Dictionary[string, object]`, `OrderedDictionary`, and `PSCustomObject` with exact-key `O(1)` lookup first (`Contains` / `ContainsKey`) and `OrdinalIgnoreCase` fallback, preserving empty and single-element arrays via unary comma return. +- **`ConvertTo-ModuleOrderedDictionary`:** Normalizes dictionary and `PSCustomObject` payloads into an ordinal `OrderedDictionary` (`-SkipEmptyKeys` supported). +- **`Format-ModuleCommandLineArguments`:** Pure Windows `CommandLineToArgvW` argument quoter for CLI command rendering and `ProcessStartInfo.Arguments`. +- **`Get-ModuleCommandParameterMap` & `ConvertTo-ModuleParameterValue`:** Centralizes PowerShell parameter metadata lookup (excluding `CommonParameters` / `ShouldProcess`), alias resolution, positional ordering, typed coercion (`[bool]`, `[switch]`, numeric, enum, arrays, blank-skip on `[ValidateSet]` / `[ValidatePattern]`), and `[securestring]` conversion/tracking. +- **`Invoke-ModulePowerShellCommand`:** Unified `&` execution helper supporting both native `Invoke-IcingaCheck*` functions (`Private.Icinga.CheckResult`) and external `.ps1` scripts (`-UseLastExitCode` + Nagios `|` fallback) while deterministically resetting `Private.Icinga.CheckResult` and `Private.Icinga.ActiveCheckCommand` in `finally`. + +### 2.2 Modular IcingaProtocol Execution Pipeline (`src/IcingaProtocol/Private/`) +- Extracted `Expand-IcingaProtocolMacroValue`, `Invoke-IcingaProtocolExternalScript`, `Stop-IcingaProtocolProcessTree`, and `Invoke-IcingaProtocolBinaryProcess`, reducing `ConvertFrom-IcingaProtocolMacros.ps1` and `Invoke-IcingaProtocolCheckCommand.ps1` to clean, single-responsibility orchestrators with 100% identical external behavior. +- `ConvertFrom-IcingaProtocolMacros` now skips empty `IList` (`[]`) and empty `IDictionary`/`PSCustomObject` (`{}`) alongside `""` and `$null` on unknown `ifw_api_arguments` parameters (`IWKB001001`). +- `Add-IcingaRPCMessageToWorker` retains `.Replace('"":"$",', '').Replace(',"":"$"', '')` for Windows PowerShell 5.1 `JavaScriptSerializer` safety and guards `if ($null -eq $RPCMessage)` after `ConvertFrom-ModuleJson`. + +### 2.3 Public `New-IcingaPlugin` SDK, `O(1)` CallStack Caching & Plugin Parity +- **SDK Visibility:** Moved `New-IcingaPlugin.ps1` from `src/Plugins/Lib/Private/` to `src/Plugins/Lib/Public/` (`42` exported public functions) while keeping `Get-Icinga*` providers private. +- **`O(1)` CallStack Caching (`IcingaPlugin`):** `DetectCheckCommand()` checks `$GlobalVariable.Private.Icinga.ActiveCheckCommand` first and walks `Get-PSCallStack` only once when the first node of an `Invoke-IcingaCheck*` plugin is constructed, caching the resolved command name for all subsequent child/metric nodes (leaving `ActiveCheckCommand` untouched when called standalone outside a check command). `Compile()` resets `$GlobalVariable.Private.Icinga.ActiveCheckCommand = $null` in `finally` (backed up by `Invoke-ModulePowerShellCommand` and `Start-IcingaProtocolWorker`). +- **`Invoke-IcingaCheckCPU`:** Added `-Core` (`'*'`, `'_Total'`/`'Total'`, or core pattern), `-OverallOnly` (evaluates `-Warning`/`-Critical` only on `Overall Load` when `Overall Load` is present while preserving threshold evaluation on explicit single-core selectors), and `[Alias('SocketFilter')] -NodeFilter`. +- **`Invoke-IcingaCheckScheduledTask`:** Treats `LastTaskResult = 267009` (`0x41301`, when task `State` is `Running`) and `267011` (`0x41303`, `SCHED_S_TASK_HAS_NOT_RUN`) as `OK` by default, masks 32-bit HRESULTs with `0xFFFFFFFFL` (`0x80070005`) for `-IgnoreExitCodes`, and adds `[Alias('IgnoreLastResult', 'IgnoreExitCode')]` on `-IgnoreLastRunTime`. +- **`Invoke-IcingaCheckService`:** Changed `-Status` to `[IcingaServiceStatus[]]$Status = @( [IcingaServiceStatus]::Running )`, supporting single string `'Running'`, multi-status arrays `@('Running', 'Paused')` via `.CheckNotIn()`, and empty `@()` fallback without bitwise-OR enum corruption. +- **Additional Plugin & Provider Hardening:** Mutual `-IgnoreEmptyChecks` <-> `-MitigateUnknown` aliases (while keeping `[ValidateSet('Ok', 'Warning', 'Critical', 'Unknown')]` on `OverrideNotFound`/`OverrideNotOk` for Icinga Director dropdown DataLists and PowerShell auto-completion); `[WildcardPattern]` pre-validation (`DirectoryFilterInvalid`) in `Get-IcingaDirectoryInformation` (`-FileNames`); empty `Win32_ComputerSystem` and 0-byte pagefile guards in `Invoke-IcingaCheckMemory`; `-SkipPartitionMapping` on `Get-IcingaDiskInformation` (used by `Invoke-IcingaCheckPartitionSpace` while preserving `Get-IcingaDiskInformation -Entrypoint 'Volume'` standalone contract) and folder mount-point slash + trailing `\` normalization in `Invoke-IcingaCheckPartitionSpace` (keeping `@('')` fail-closed); and `InvariantCulture` formatting in `Invoke-IcingaCheckUptime`. + +### 2.4 `PerformanceCounter` Daemon & Cache Safety +- `Start-IcingaPerformanceCounterDaemon` wraps each iteration in `try / catch / finally` and claims caller response queues atomically via `PendingRequests.TryRemove` with inner `try / catch` around `TryAdd` (while timed-out callers synchronize any in-flight `TryAdd` before calling `Dispose()`), preventing `BlockingCollection` disposal races. +- `Get-IcingaPerformanceCounter` validates paths via `IcingaPerformanceCounter::ParsePath` before recording timestamps in `Store.Registered`. +- `Write-IcingaPerformanceCounterCache` writes BOM-less UTF-8 (`[System.Text.UTF8Encoding]::new($false)`) inside `try / catch` logging warnings on I/O locks instead of throwing. + +--- + +## 3. Verification Results + +- **Module Build & Daemon Memory Leak Analysis (`.\build\Build-ModuleProject.ps1 -SkipTests -TestDaemonMemoryLeaks`):** + - Compiled `42` public functions, `156` private functions, and `10` classes into `lib/IcingaForWindows.Classes.ps1` and `lib/IcingaForWindows.Kernel.ps1` with **`0` daemon memory leaks**. +- **Strict API Documentation (`.\build\Build-ModuleDocs.ps1 -Strict $true`):** + - Parsed `198` functions across `20` Markdown files with **`0` documentation violations** (untouched CRLF-only `docs/Icinga.Core.*.md` files reset cleanly). +- **Code Styling, Class-Literal & Static Analysis:** + - `Tests/CodeStyling.Tests.ps1` (`.\build\Test-ModuleCodeStyling.ps1`): **`0` violations** across all `99` target paths/directories. + - `Tests/ClassLiteral.Tests.ps1`: **`3 / 3` passed** (`0` PowerShell class literals in functions). + - `Invoke-ScriptAnalyzer -Settings .\PSScriptAnalyzerSettings.psd1` across all `33` new/modified `.ps1`/`.psm1` files: **`0` Error or Warning findings**. +- **Pester Test Suite (`.\Tests`):** + - **`484 / 501` passed** (`100%` of cross-platform tests across `37` test files, including `17` new test blocks; the remaining `17` are pre-existing Windows-only OS calls on macOS: `WindowsIdentity::GetCurrent`, `System.Diagnostics.PerformanceCounter`, and `New-SelfSignedCertificate`). diff --git a/docs/Developer/IcingaProtocol/01-Check-and-Binary-Execution.md b/docs/Developer/IcingaProtocol/01-Check-and-Binary-Execution.md new file mode 100644 index 0000000..a165ead --- /dev/null +++ b/docs/Developer/IcingaProtocol/01-Check-and-Binary-Execution.md @@ -0,0 +1,188 @@ +# Icinga Protocol Check and Binary Execution + +This guide explains how Icinga for Windows receives, validates, and executes monitoring checks delivered by Icinga 2 over the native JSON-RPC cluster protocol (`event::ExecuteCommand`), covering both native PowerShell check plugins (`Invoke-IcingaCheck*`) and external binaries or scripts located in the approved `Binaries` directory. + +--- + +## 1. Architectural Background: How Icinga 2 Transmits Commands + +Unlike legacy Icinga 2 Agent setups that synchronize local Icinga 2 DSL configuration files to the endpoint, Icinga for Windows operates directly as an Icinga 2 JSON-RPC endpoint without requiring local `.conf` check definitions on the Windows host. + +When Icinga 2 schedules a check on an Icinga for Windows node, the payload sent inside `event::ExecuteCommand` depends on the `execute` method configured on the **CheckCommand** object on the Icinga 2 master/satellite: + +1. **Standard ITL `plugin-check-command` (`methods_execute = PluginCheck`):** + Icinga 2 assumes the remote agent already possesses the local `CheckCommand` definition (such as the ITL `load-windows` command) and therefore transmits **only** the Icinga `CheckCommand` object name (`"command": "load-windows"`) and custom variables explicitly referenced by remote macro list rules — often resulting in an **empty `"macros": {}` payload**. +2. **Icinga for Windows `ifw-api` CheckCommand Template (`methods_execute = IfwApiCheck`):** + Importing `ifw-api` on the **CheckCommand** instructs Icinga 2 to serialize and transmit: + - `macros.ifw_api_command`: The exact PowerShell check command or binary filename to execute on the Windows host. + - `macros.ifw_api_arguments`: The structured argument dictionary (`value`, `set_if`, `order`, `skip_key`, `repeat_key`) derived from the `CheckCommand`'s `arguments` block. + - All resolved host, service, and command macro values referenced by those arguments. + +> **Important:** `ifw-api` is a **CheckCommand template**, not a Service template. Importing `ifw-api` on a `Service` object has no effect on `methods_execute`; it **must** be imported on the `CheckCommand` definition itself. + +--- + +## 2. Command Resolution Rules & Security Boundaries + +Every incoming `event::ExecuteCommand` request is resolved by `Resolve-IcingaProtocolCommand` using strict, deterministic rules: + +1. **`macros.ifw_api_command` is mandatory:** + Icinga for Windows never guesses an executable or cmdlet name from `params.command`. If `macros.ifw_api_command` is missing or empty (for example when using an unmodified ITL command such as `load-windows`), execution is rejected immediately with `[UNKNOWN]` and knowledge base reference **[IWKB001003](../../Knowledgebase/IWKB001003.md)**. +2. **Path traversal, NTFS ADS & boundary enforcement:** + ASCII control characters (`0x00..0x1F`), invalid path characters, drive-relative colons (`C:evil.exe`), and NTFS Alternate Data Stream colons (`check_load.exe:stream`) are rejected immediately. Any value containing path separators (`\`, `/`), rooted drive prefixes, UNC prefixes, or `..` segments is normalized via `[System.IO.Path]::GetFullPath(...)` and verified against `Get-ModuleBinaryDirectory()` (`C:\ProgramData\IcingaForWindows\Binaries`). Any path outside that directory is rejected with **[IWKB001003](../../Knowledgebase/IWKB001003.md)**. +3. **Explicit PowerShell check plugins (`Invoke-IcingaCheck*`):** + Names starting with `Invoke-IcingaCheck` (without wildcards or path separators) are resolved against loaded module functions and cmdlets via `(Get-Command).Parameters` metadata introspection (no slow `Get-Help` calls and no Windows PowerShell 5.1 ETS memory leaks). Arbitrary PowerShell cmdlets such as `Remove-Item`, `Get-Process`, or `Invoke-Expression` are never accepted. +4. **Approved external binaries and scripts (`Get-ModuleBinaryDirectory()`):** + External executables and scripts are looked up **exclusively** inside `C:\ProgramData\IcingaForWindows\Binaries` using full canonical file paths (`[System.IO.File]::Exists(...)`). `$env:PATH` and system directories (`System32`) are **never** searched. When `ifw_api_command` is specified without a file extension (or with a non-executable dotted suffix such as `check_app_v1.2`), extensions are probed deterministically in the order `.exe`, `.cmd`, `.bat`, `.com`, `.ps1`. +5. **PowerShell shorthand names:** + If no matching file exists inside `C:\ProgramData\IcingaForWindows\Binaries` and `ifw_api_command` has neither path separators nor a file extension, Icinga for Windows expands shorthand names automatically: + - `"cpu"` -> `Invoke-IcingaCheckCPU` + - `"directory"` -> `Invoke-IcingaCheckDirectory` + - `"IcingaCheckService"` -> `Invoke-IcingaCheckService` + +--- + +## 3. Configuring PowerShell Check Plugins + +### 3.1 Recommended Mode: Active `ifw-api` Template + +When using the Icinga for Windows Director Basket or DSL CheckCommand definitions, each `CheckCommand` imports `PowerShell Base` and `ifw-api`: + +```icinga2 +object CheckCommand "Invoke-IcingaCheckDirectory" { + import "PowerShell Base" + import "ifw-api" + + vars.ifw_api_command = "Invoke-IcingaCheckDirectory" + + arguments += { + "-Path" = { + value = "$IcingaCheckDirectory_String_Path$" + order = 1 + } + "-FileNames" = { + value = "$IcingaCheckDirectory_Array_FileNames$" + order = 2 + } + "-Critical" = { + value = "$IcingaCheckDirectory_String_Critical$" + order = 3 + } + "-ShowFileList" = { + set_if = "$IcingaCheckDirectory_Switchparameter_ShowFileList$" + order = 4 + } + } +} +``` + +In this mode, `ConvertFrom-IcingaProtocolMacros` delegates token expansion to `Expand-IcingaProtocolMacroValue` and parameter coercion to `Get-ModuleCommandParameterMap` and `ConvertTo-ModuleParameterValue`, preserving native JSON types (arrays, numbers, booleans), handling Icinga 2 serialized valueless flags (`"value": null` on `[switch]` parameters), evaluating `set_if` switches safely via `ConvertFrom-ModuleBoolean`, and validating that every parameter supplied with a **non-empty** value exists on the target PowerShell check plugin (otherwise returning `[UNKNOWN]` with **[IWKB001001](../../Knowledgebase/IWKB001001.md)**). Unpopulated optional template macros (`null`, empty string `""`, empty JSON array `[]`, or empty JSON dictionary/object `{}`) are automatically skipped. + +### 3.2 Fallback Mode: Without `ifw-api` + +If `ifw_api_command` is provided in `macros` without `ifw_api_arguments`, `ConvertFrom-IcingaProtocolMacros` falls back to convention-based custom variable mapping: + +- Internal transport variables (`ifw_api_*`, `IcingaPowerShellBase_*`) and empty `""` placeholder keys are ignored. +- Custom variables matching an exact plugin parameter or alias name (for example `vars.Path = "C:\\Logs"`) are bound directly. +- Custom variables following the Icinga for Windows naming convention `IcingaCheck__` (for example `vars.IcingaCheckDirectory_String_Path = "C:\\Logs"`) are mapped to `-`. +- If one or more custom variables (including inherited Host `vars.*` forwarded when `ifw-api` is inactive) cannot be mapped to any parameter of the check plugin, execution aborts with `[UNKNOWN]` and **[IWKB001000](../../Knowledgebase/IWKB001000.md)**. + +--- + +## 4. Configuring External Binaries and Scripts + +External Nagios/Icinga plugins (`.exe`, `.cmd`, `.bat`, `.com`) and custom PowerShell scripts (`.ps1`) are restricted exclusively to `Get-ModuleBinaryDirectory()` without exposing `$env:PATH`. Icinga for Windows applies two distinct execution and timeout models depending on whether the target is PowerShell or a non-PowerShell OS binary: + +1. **PowerShell Check Plugins (`Invoke-IcingaCheck*`) and `.ps1` Scripts in `Binaries`:** + Executed natively in-process using PowerShell's `&` call operator (never dot-sourced `.`) via `Invoke-ModulePowerShellCommand` (for check plugins) and `Invoke-IcingaProtocolExternalScript` (for `.ps1` scripts in `Binaries`) with `Protected.IsBackgroundDaemon = $true` and **no** custom process timeout wrapper. Hung PowerShell threads are governed centrally by `Start-ThreadHouseKeeper` (`FROZEN` -> `ZOMBIE` + automatic `-KeepAlive` worker thread replacement) and the Icinga 2 master's check timeout. External `.ps1` scripts support typed parameter coercion (`[bool]`, `[switch]`, arrays, `[securestring]`), `New-IcingaPlugin` `.Compile()` results via `Private.Icinga.CheckResult`, and standard Nagios/Icinga `|` stdout + `exit` code handling. +2. **Native Executables (`.exe`, `.com`) and Batch Scripts (`.cmd`, `.bat`) in `Binaries`:** + Executed as isolated OS processes via `Invoke-IcingaProtocolBinaryProcess` (`System.Diagnostics.Process` with `UseShellExecute = $false` and `Format-ModuleCommandLineArguments` quoting) and enforced against `params.check_timeout` (`60s` default) with full descendant process-tree termination via `Stop-IcingaProtocolProcessTree` on timeout so hung third-party binaries cannot accumulate in memory on the Windows host. + +### Step 1: Place the Binary in the Approved Directory + +Copy the executable or script into: + +```text +C:\ProgramData\IcingaForWindows\Binaries\ +``` + +For example: `C:\ProgramData\IcingaForWindows\Binaries\check_load.exe`. + +### Step 2: Configure the `CheckCommand` in Icinga 2 DSL + +Do **not** use an unmodified ITL command such as `load-windows` directly, because `load-windows` uses `PluginCheck` and does not define `ifw_api_command`. Instead, define a `CheckCommand` that imports `ifw-api` and explicitly sets `vars.ifw_api_command`: + +```icinga2 +object CheckCommand "ifw-check-load" { + import "ifw-api" + + vars.ifw_api_command = "check_load.exe" + + arguments = { + "-w" = { + value = "$load_win_warn$" + description = "Warning threshold" + order = 1 + } + "-c" = { + value = "$load_win_crit$" + description = "Critical threshold" + order = 2 + } + } +} + +apply Service "Windows Load (Binary)" { + check_command = "ifw-check-load" + vars.load_win_warn = "80%" + vars.load_win_crit = "90%" + assign where host.vars.os == "Windows" +} +``` + +### Step 3: Equivalent Configuration in Icinga Director + +1. Navigate to **Icinga Director -> Commands -> Commands** and create a new Command (or clone the desired command). +2. Under **Imports**, import the **`ifw-api`** CheckCommand template. +3. On the **Arguments** tab, configure the CLI flags expected by the binary (such as `-w` and `-c` with `value`, `set_if`, `order`, `skip_key`, `repeat_key`). +4. On the **Custom properties** (`Fields` / `Vars`) tab of the Command, set: + - `ifw_api_command` = `check_load.exe` *(overrides any `$command.name$` default when the Icinga Command object name differs from the executable filename)*. +5. Deploy the configuration through Icinga Director. + +### Output, Performance Data, Timeout & Exit Code Handling for Binaries + +- **Full-path execution, argument escaping & `.cmd`/`.bat` metacharacter protection:** Native `.exe`/`.com` executables are started directly via `System.Diagnostics.Process` with `UseShellExecute = $false` and `FileName` set to the full canonical path in `C:\ProgramData\IcingaForWindows\Binaries\...`, preserving case-distinct CLI flags (`-p` vs `-P`, `-c` vs `-C`) and Icinga 2 serialized valueless flags (`"value": null`) with Windows `CommandLineToArgvW` quoting. Because Windows `CreateProcess` invokes `.cmd` and `.bat` files through `cmd.exe /c`, arguments passed to `.cmd`/`.bat` scripts are validated beforehand and rejected with `[UNKNOWN]` (`3`) if they contain `cmd.exe` command, redirection, or variable-expansion metacharacters (`&`, `|`, `<`, `>`, `^`, `\r`, `\n`, `"`, `!`, or paired `%VAR%` patterns), while standalone percent thresholds (`80%`, `90%`) remain permitted. +- **OS process timeout & descendant tree termination:** Non-PowerShell binaries enforce `params.check_timeout` (`60s` default, clamped safely to `Int32.MaxValue` ms) across both process execution and asynchronous `stdout`/`stderr` pipe closure. When a binary times out or leaves a background child holding `stdout`/`stderr` open, Icinga for Windows terminates the root process and every descendant process (`Win32_Process` `ParentProcessId` walk + handle `WaitForExit` rundown on Windows; `Process.Kill($true)` + `pgrep -P` walk on Unix) before returning `[UNKNOWN]` (`3`). +- **Nagios/Icinga pipe splitting & `stderr` fallback:** Standard output (falling back to `stderr` when `stdout` is blank) is split at `|` via `Split-IcingaBinaryPluginOutput` into human-readable check output and individual performance-data metric strings, preserving quoted, Icinga 2 scoped, and doubled-quote metric labels containing spaces (such as `'C:\ Free Space'=50GB;20;10;0;100` or `check_disk::'C:\ Free Space'=12GB`). +- **Exit code normalization:** Exit codes `0` (`OK`), `1` (`WARNING`), `2` (`CRITICAL`), and `3` (`UNKNOWN`) are preserved; any exit code outside `0..3` is normalized to `3` (`UNKNOWN`). +- **Fallback without `ifw-api`:** If a binary is invoked without `ifw_api_arguments`, execution succeeds when no custom variables are passed or when every custom variable starts with `-` or `/`. Unprefixed custom variables trigger `[UNKNOWN]` with **[IWKB001002](../../Knowledgebase/IWKB001002.md)**. + +--- + +## 5. SecureString Parameters & Secret Masking + +When a PowerShell check plugin (`Invoke-IcingaCheck*`) or an external `.ps1` script in `Binaries` declares a parameter of type `[System.Security.SecureString]`: + +1. Plain-text secret strings transmitted in Icinga 2 macros are automatically converted into read-only `[System.Security.SecureString]` instances via `ConvertTo-ModuleSecureString` (`AppendChar` + `MakeReadOnly`, safely supporting empty strings on Windows PowerShell 5.1 and PowerShell 7+). +2. In the rendered command string (`cr.command` returned to Icinga Web 2 and debug logs), the parameter value is always masked as `'********'`. +3. Immediately after plugin or `.ps1` execution finishes, `Invoke-IcingaProtocolCheckCommand` calls `.Dispose()` on every allocated `SecureString` inside a `finally` block. + +--- + +## 6. Execution Timing & Host/Service Result Dispatch + +Inside `Start-IcingaProtocolWorker`, execution timing for `event::ExecuteCommand` measures the complete local check processing window without including idle queue wait time or network transmission overhead: + +1. **Start timer:** Capture `CheckStarted` (`Get-IcingaUnixTime -Milliseconds` in UTC) and start a monotonic `[System.Diagnostics.Stopwatch]` immediately upon entering `event::ExecuteCommand`. +2. **Resolve, parse & execute:** Run `Invoke-IcingaProtocolCheckCommand` (command resolution, macro parsing, type coercion, `SecureString` conversion, and check/binary execution). +3. **Stop timer:** Stop `$Stopwatch` immediately upon return and compute `CheckFinished = CheckStarted + Stopwatch.Elapsed.TotalSeconds`. +4. **Log & transmit:** Emit debug telemetry and enqueue `event::CheckResult` via `Send-IcingaProtocolCheckResult` (omitting the `'service'` field when `params.service` is absent or empty so Icinga 2 processes Host checks accurately, and falling back `'check_source'` to `params.host` if `Config.Hostname` is unset). + +--- + +## 7. Related Knowledgebase Articles + +- [IWKB001000 — Unable to map Custom-Variables to Icinga for Windows Check](../../Knowledgebase/IWKB001000.md) +- [IWKB001001 — Unknown Check-Command Parameter in `ifw_api_arguments`](../../Knowledgebase/IWKB001001.md) +- [IWKB001002 — Unable to map Custom-Variables to External Binary Check without `ifw-api`](../../Knowledgebase/IWKB001002.md) +- [IWKB001003 — Check Command Not Found, Missing `ifw_api_command`, or Binary Outside Approved Directory](../../Knowledgebase/IWKB001003.md) diff --git a/docs/Developer/Plugins/02-IcingaPlugin-Reference.md b/docs/Developer/Plugins/02-IcingaPlugin-Reference.md index 83ae7f6..fb5657e 100644 --- a/docs/Developer/Plugins/02-IcingaPlugin-Reference.md +++ b/docs/Developer/Plugins/02-IcingaPlugin-Reference.md @@ -11,7 +11,7 @@ This document is the complete technical reference for **[`New-IcingaPlugin`](#1- ## 1. `New-IcingaPlugin` Factory Cmdlet -`New-IcingaPlugin` is the runspace-safe factory function that every plugin and helper function outside `src/Classes` must use instead of `[IcingaPlugin]::new()`. It resolves the `IcingaPlugin` class in the calling runspace (`'IcingaPlugin' -as [type]`) and invokes either `$PluginType::new($Name)` (when neither `-Value` nor `-Unit` is bound) or `$PluginType::new($Name, $Value, $Unit)`. +Defined in [`src/Plugins/Lib/Public/New-IcingaPlugin.ps1`](../../../src/Plugins/Lib/Public/New-IcingaPlugin.ps1) and exported publicly as the Icinga for Windows Plugin SDK entrypoint, `New-IcingaPlugin` is the runspace-safe factory function that every built-in check, external custom plugin repository, and helper function outside `src/Classes` must use instead of `[IcingaPlugin]::new()`. It resolves the `IcingaPlugin` class in the calling runspace (`'IcingaPlugin' -as [type]`) and invokes either `$PluginType::new($Name)` (when neither `-Value` nor `-Unit` is bound) or `$PluginType::new($Name, $Value, $Unit)`. ### Syntax @@ -52,6 +52,8 @@ $CheckPackage.AddCheck( ## 2. `IcingaPlugin` Class Properties +The `IcingaPlugin` class is defined in [`src/Classes/Icinga/IcingaPlugin.ps1`](../../../src/Classes/Icinga/IcingaPlugin.ps1). + ### Public Instance Properties (10) These properties form the public state surface of an `IcingaPlugin` node. Each boolean/integer flag also has a corresponding fluent `Set*` method for method chaining. @@ -102,7 +104,7 @@ These properties hold the internal configuration, evaluation state, and tree poi | `MetricIndexValue` | `System.String` | `''` | `MetricIndex([string])` | Custom `index` segment for the `check_multi` performance-data label. | | `MetricNameValue` | `System.String` | `''` | `MetricName([string])` | Custom `template` segment for the `check_multi` performance-data label. | | `MetricLabelValue` | `System.String` | `''` | `MetricLabel([string])` | Custom `label` segment for the `check_multi` performance-data label. | -| `CheckCommand` | `System.String` | `''` | `Initialize()` -> `DetectCheckCommand()` | Calling `Invoke-IcingaCheck*` command detected from the PowerShell call stack at construction time. | +| `CheckCommand` | `System.String` | `''` | `Initialize()` -> `DetectCheckCommand()` | Calling `Invoke-IcingaCheck*` command detected on the first node and cached in `Private.Icinga.ActiveCheckCommand` for `O(1)` reuse until `Compile()` resets it. | | `Translation` | `System.Collections.Hashtable` | `@{}` | `Translate([hashtable])` | Lookup table mapping raw values (such as integer status codes) to human-readable strings. | | `TranslatedText` | `System.String` | `''` | `Translate()`, `Translate([string])` | Explicit display string for `Value` set by `.Translate()` or `.Translate([string])`. | @@ -133,7 +135,7 @@ All three constructors delegate to `hidden [void] Initialize([string]$Name, [obj * Stores `$this.Name = $Name`. * If `$Value -is [TimeSpan]`, converts `$Value` to `([TimeSpan]$Value).TotalSeconds` and sets `$this.Unit = 's'` when `$Unit` is `''` (otherwise keeps `$Unit`). * For all other values, stores `$this.Value = $Value` and `$this.Unit = $Unit` verbatim. -* Walks the PowerShell call stack via `DetectCheckCommand()` and stores the first `Invoke-IcingaCheck*` frame name in `$this.CheckCommand`. +* Resolves the calling `Invoke-IcingaCheck*` frame via `DetectCheckCommand()` (reading `Private.Icinga.ActiveCheckCommand` in `O(1)` after the first node caches it) and stores it in `$this.CheckCommand`. --- @@ -419,7 +421,7 @@ $CheckPackage.AddMissingChecks( | Method | Return Type | Description | |--------|-------------|-------------| | `Commit()` | `void` | No-op method with `[void]` return type that consumes the fluent chain return value so nothing leaks to the PowerShell pipeline. | -| `Compile()` | `System.Int32` | Executes `$this.ResolveState()`, `$this.PropagateVerbose($this.Verbose)`, renders output via `$this.RenderOutput()`, collects deduplicated metrics via `$this.CollectPerfData()`, ensures `$GlobalVariable.Private.Icinga.CheckResult` exists via `EnsureResultSlot()`, stores `[IcingaCheckResult]::new($this.State, $Output, $Perf)` in `Private.Icinga.CheckResult`, calls `WriteConsoleOutput($Output, $Perf)` when `-not $GlobalVariable.Protected.IsBackgroundDaemon`, and returns `$this.State` (`0`..`3`). | +| `Compile()` | `System.Int32` | Executes `$this.ResolveState()`, `$this.PropagateVerbose($this.Verbose)`, renders output via `$this.RenderOutput()`, collects deduplicated metrics via `$this.CollectPerfData()`, stores `[IcingaCheckResult]::new($this.State, $Output, $Perf)` in `Private.Icinga.CheckResult`, calls `WriteConsoleOutput($Output, $Perf)` when `-not $GlobalVariable.Protected.IsBackgroundDaemon`, resets `Private.Icinga.ActiveCheckCommand = $null` in a `finally` block, and returns `$this.State` (`0`..`3`). | --- @@ -468,11 +470,10 @@ For framework maintainers extending `IcingaPlugin.ps1` itself, the table below l | `ResolveNumericValue([object]$Item)` | `System.Object` | Converts enums to `[int]` and maps translated strings back to their numeric key in `Translation` for performance data. | | `ResolvePerfDataThreshold([string]$Threshold, [string]$Resolved)` | `System.String` | Returns a valid numeric/range Icinga perfdata threshold string (mapping translated threshold names to numeric keys and omitting non-numeric regex/wildcard patterns). | | `BuildPerfData()` | `void` | Formats `index::ifw_template::label=value;warn;crit;min;max` and stores it in `PerfData`. | -| `DetectCheckCommand()` | `System.String` | Walks `Get-PSCallStack` to find the first `Invoke-IcingaCheck*` command name. | +| `DetectCheckCommand()` | `System.String` | Resolves the calling `Invoke-IcingaCheck*` command name via `Get-PSCallStack` on the first node and caches it in `Private.Icinga.ActiveCheckCommand` until `Compile()` resets it. | | `SanitizeMetric([string]$Value)` | `System.String` | Strips non-word characters (`[\W]`) and lower-cases a metric label segment. | | `BuildPerfDataLabel()` | `System.String` | Builds the sanitized `index::ifw_template::label` identifier with `'default'`, `'ifw_check'`, and `'value'` fallbacks. | | `CollectPerfData()` | `System.Array` | Recursively gathers and deduplicates performance-data metrics across the subtree (returning `@()` when `NoPerfData` is `$true`). | | `IsNumeric([object]$Value)` | `System.Boolean` | Tests whether `$Value` is non-null, not a `[bool]`, and parses as a `[double]` under `InvariantCulture`. | | `FormatNumber([object]$Value)` | `System.String` | Formats `[decimal]` / `[double]` values with `'0.##########'` under `InvariantCulture` without scientific notation. | | `WriteConsoleOutput([string]$Output, [array]$Perf)` | `void` | Writes `$Output` and the `\| ` line directly via `[System.Console]::WriteLine()`. | -| `EnsureResultSlot([object]$Private)` | `void` | Ensures `$Private.Icinga.CheckResult` exists on the thread-local runtime state before `Compile()` writes to it. | diff --git a/docs/Developer/Plugins/03-Result-and-Error-Objects.md b/docs/Developer/Plugins/03-Result-and-Error-Objects.md index e6d5b39..3c30d12 100644 --- a/docs/Developer/Plugins/03-Result-and-Error-Objects.md +++ b/docs/Developer/Plugins/03-Result-and-Error-Objects.md @@ -14,7 +14,7 @@ Alongside [`IcingaPlugin`](02-IcingaPlugin-Reference.md), two lightweight compan ## 1. `IcingaCheckResult` Class -When `IcingaPlugin.Compile()` finishes evaluating a plugin tree, it stores an `IcingaCheckResult` instance in the current runspace's private runtime state: +Defined in [`src/Classes/Icinga/IcingaCheckResult.ps1`](../../../src/Classes/Icinga/IcingaCheckResult.ps1). When `IcingaPlugin.Compile()` finishes evaluating a plugin tree, it stores an `IcingaCheckResult` instance in the current runspace's private runtime state: ```powershell $Global:IcingaForWindows.Private.Icinga.CheckResult @@ -62,7 +62,7 @@ $Result.PerformanceData # e.g. @('icingaicingaforwindowsrenewcertificate::ifw_sc ## 2. `IcingaError` Class -Data collection functions (such as `Get-IcingaWindowsInformation` or provider functions like `Get-IcingaScheduledTask`) must **never** throw unhandled exceptions into a plugin. Instead, when an underlying query (CIM/WMI, Task Scheduler, Registry, Service Controller) fails, the provider returns an `IcingaError` object describing the failure. +Defined in [`src/Classes/Icinga/IcingaError.ps1`](../../../src/Classes/Icinga/IcingaError.ps1). Data collection functions (such as `Get-IcingaWindowsInformation` or provider functions like `Get-IcingaScheduledTask`) must **never** throw unhandled exceptions into a plugin. Instead, when an underlying query (CIM/WMI, Task Scheduler, Registry, Service Controller) fails, the provider returns an `IcingaError` object describing the failure. ### Properties @@ -111,7 +111,7 @@ try { ## 3. `Test-IcingaError` Cmdlet -`Test-IcingaError` is the runspace-safe cmdlet used by plugins and providers to check whether a data collection call returned an `IcingaError`. +Defined in [`src/Core/ErrorHandling/Public/Test-IcingaError.ps1`](../../../src/Core/ErrorHandling/Public/Test-IcingaError.ps1), `Test-IcingaError` is the runspace-safe cmdlet used by plugins and providers to check whether a data collection call returned an `IcingaError`. ### Syntax diff --git a/docs/Developer/Plugins/04-Custom-Plugin-Developer-Guide.md b/docs/Developer/Plugins/04-Custom-Plugin-Developer-Guide.md index 7ad1793..d0077e1 100644 --- a/docs/Developer/Plugins/04-Custom-Plugin-Developer-Guide.md +++ b/docs/Developer/Plugins/04-Custom-Plugin-Developer-Guide.md @@ -21,26 +21,31 @@ By the end of this tutorial, you will have built a realistic **Print Spooler Que ## 1. Repository Layout and Separation of Concerns -In Icinga for Windows, every check is split into two layers: +In Icinga for Windows, the plugin subsystem under `src/Plugins/` is organized into three areas: -* **Provider (`src/Provider//Public/Get-Icinga.ps1`)**: Queries the operating system (CIM/WMI, Performance Counters, Services, Task Scheduler, Registry), filters the raw objects, and returns either a clean collection/hashtable of data objects or an [`IcingaError`](03-Result-and-Error-Objects.md#2-icingaerror-class) when collection fails. -* **Plugin (`src/Plugins/Public/Invoke-IcingaCheck.ps1`)**: Accepts user threshold parameters (`-Warning`, `-Critical`, `-State`, `-NoPerfData`, `-Verbosity`), calls the provider, builds the `IcingaPlugin` check tree with `New-IcingaPlugin`, and returns `$CheckPackage.Compile()`. +* **Plugin SDK (`src/Plugins/Lib/Public/`)**: Public SDK factory functions such as [`New-IcingaPlugin`](02-IcingaPlugin-Reference.md#1-new-icingaplugin-factory-cmdlet) for creating runspace-safe `IcingaPlugin` nodes in both built-in checks and external custom plugin repositories. +* **Provider (`src/Plugins/Provider//Private/Get-Icinga.ps1`)**: Queries the operating system (CIM/WMI, Performance Counters, Services, Task Scheduler, Registry), filters the raw objects, and returns either a clean collection/hashtable of data objects or an [`IcingaError`](03-Result-and-Error-Objects.md#2-icingaerror-class) when collection fails. +* **Plugin (`src/Plugins/Checks/Public/Invoke-IcingaCheck.ps1`)**: Accepts user threshold parameters (`-Warning`, `-Critical`, `-State`, `-NoPerfData`, `-Verbosity`), calls the provider, builds the `IcingaPlugin` check tree with `New-IcingaPlugin`, and returns `$CheckPackage.Compile()`. ```text src |_ Classes | |_ DataTypes | |_ IcingaSpoolerState.ps1 # Optional enum for status codes - |_ Provider - | |_ Spooler - | |_ Public - | |_ Get-IcingaSpoolerQueue.ps1 |_ Plugins - |_ Public - |_ Invoke-IcingaCheckSpoolerTutorial.ps1 + |_ Lib + | |_ Public + | |_ New-IcingaPlugin.ps1 + |_ Provider + | |_ Spooler + | |_ Private + | |_ Get-IcingaSpoolerQueue.ps1 + |_ Checks + |_ Public + |_ Invoke-IcingaCheckSpoolerTutorial.ps1 ``` -> **Naming Rule:** Every check plugin function **must** begin with the prefix `Invoke-IcingaCheck`. `IcingaPlugin` inspects the call stack at construction time (`DetectCheckCommand()`) and uses the suffix after `Invoke-IcingaCheck` as the default `ifw_