diff --git a/CLAUDE.md b/CLAUDE.md index a2bb6ea..680339e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -133,9 +133,29 @@ Levels: `Debug`, `Output`, `Audit`, `Info`, `Success`, `Warning`, `Error`, `Fata - ❌ `Write-Output` for logging — use it only when you genuinely return a value to the pipeline. - ❌ Stream redirects like `2>$null` or `*>&1`. Handle errors explicitly. - ❌ Aliases in source code (`%`, `?`, `select`, `where`). Use full cmdlet names (`ForEach-Object`, `Where-Object`). -- ❌ Backticks for line continuation. Use natural pipeline breaks or splatting. +- ❌ Em-dashes (`—`, U+2014) or en-dashes (`–`, U+2013) in PowerShell files — Windows PowerShell 5.1 reads BOM-less UTF-8 files as Windows-1252 and turns them into `—` Mojibake. Use plain ASCII `-` or `--` instead. - ❌ `-ErrorAction SilentlyContinue` as a "make the warning go away" tool. If you don't want to handle the error, that's a bug. - ❌ Editing files under `lib/` or `docs/api/` by hand. +- ❌ Class literals in functions (`[IcingaPlugin]::new()`, `[IcingaSortKey]::FromObject()`, `-is [IcingaError]`). See §2.9. + +### 2.9 Classes and threads + +Every runspace dot-sources the same compiled kernel, while the classes from `src/Classes` are loaded separately into each runspace. A class literal inside a function is resolved once and then points to the class type of the **main** runspace — also when the function runs in a daemon or worker thread. On Windows PowerShell 5.1 a constructor, method or static call on that type from a thread waits until the main runspace is idle, so the thread stalls. Objects of the thread's own type also no longer match the literal: `-is` returns `$false` and typed parameters fail with *Cannot convert the "IcingaError" value of type "IcingaError" to type "IcingaError"*. + +1. **Never use a class literal in a function** — not to create an object, not for a static member, not for `-is`, casts or typed variables and parameters. Resolve the class of the current runspace instead: + + | Instead of | Use | + |--------------------------------------|-----| + | `[IcingaPlugin]::new('C:', 55, '%')` | `New-IcingaPlugin 'C:' 55 '%'` | + | `$Data -is [IcingaError]` | `Test-IcingaError -InputObject $Data` | + | `[IcingaError]::new(...)` | `('IcingaError' -as [type])::new(...)` | + | `[IcingaSortKey]::FromObject(...)` in a loop | `$SortKeyType = 'IcingaSortKey' -as [type];` once before the loop, then `$SortKeyType::FromObject(...)` | + +2. Exceptions: code inside `src/Classes` (the class files are loaded per runspace, so literals there resolve correctly), Pester tests, and enums such as `[IcingaServiceStatus]::Running` — enums carry no script code and convert by value. +3. **Never pass class instances between threads.** Hand over only primitive values, hashtables and arrays. A plugin result travels as its rendered output, exit code and performance data array, never as the `IcingaCheckResult` object (see `Start-IcingaProtocolWorker`). +4. `Tests/ClassLiteral.Tests.ps1` enforces rule 1 and names the file and line of every literal it finds. + +Background and examples: [docs/Developer/Threading/01-Threading.md](docs/Developer/Threading/01-Threading.md#classes-and-threads). --- @@ -167,7 +187,7 @@ external dependencies). | Count | System.Int32 | Number of iterations to perform. | 1 | .OUTPUTS -System.Object — Description of the returned value or object shape. +System.Object -- Description of the returned value or object shape. Use `None` if the function returns nothing. .EXAMPLE @@ -192,7 +212,7 @@ function Verb-IcingaNoun() 3. **Every `.PARAMETER` block uses the Markdown table form** shown above. The table has exactly four columns: `Name | Type | Description | Default`. This is what the doc generator extracts. 4. `.SYNOPSIS` is **one line, no period at the end** unless it is a full sentence. 5. `.DESCRIPTION` wraps at ~80 columns. Use plain prose, not bullet lists. -6. `.OUTPUTS` starts with the .NET type name (`System.Int32`, `System.Collections.Hashtable`, `System.Object`, `None`), followed by `— Description`. +6. `.OUTPUTS` starts with the .NET type name (`System.Int32`, `System.Collections.Hashtable`, `System.Object`, `None`), followed by `-- Description`. 7. `.EXAMPLE` begins with `PS> ` and shows a realistic invocation. 8. `.NOTES` mentions: external services touched, config files read, required permissions, threading caveats. 9. **All documentation is written in English.** No German (or any other language) in any help block section. @@ -271,4 +291,4 @@ When you (Claude, Copilot, etc.) edit this repo: --- -*Last updated: 2026-05-26* +*Last updated: 2026-10-02* diff --git a/IcingaForWindows.psm1 b/IcingaForWindows.psm1 index 60a3138..9a86e2b 100644 --- a/IcingaForWindows.psm1 +++ b/IcingaForWindows.psm1 @@ -70,10 +70,10 @@ function New-ModuleBaseEnvironment() 'Public' = [hashtable]::Synchronized( @{ 'Config' = [PSCustomObject]@{ - 'ModuleRoot' = $PSScriptRoot; - 'Root' = (Join-Path -Path $env:ProgramData -ChildPath (Get-ModuleProjectName)); - 'Theme' = 'DefaultDark'; - 'Colors' = [PSCustomObject]@{ + 'ModuleRoot' = $PSScriptRoot; + 'Root' = (Join-Path -Path $env:ProgramData -ChildPath (Get-ModuleProjectName)); + 'Theme' = 'DefaultDark'; + 'Colors' = [PSCustomObject]@{ 'Debug' = 'Magenta'; 'Audit' = 'DarkGreen'; 'Info' = 'Cyan'; @@ -159,8 +159,8 @@ function New-ModuleBaseEnvironment() 'EvictionMinutes' = 60; }; }; - 'External' = $null; - 'ReturnCodes' = $null; + 'External' = $null; + 'ReturnCodes' = $null; } ); 'Private' = [PSCustomObject]@{ @@ -192,6 +192,9 @@ function New-ModuleBaseEnvironment() 'Logging' = [PSCustomObject]@{ 'CurrentLoggingId' = (New-Guid); }; + 'Icinga' = [PSCustomObject]@{ + 'CheckResult' = $null; + }; }; 'Protected' = [PSCustomObject]@{ 'Initialized' = $false; @@ -241,22 +244,22 @@ under `lib/`, updates the module manifest, and optionally generates documentatio or executes memory leak tests. .PARAMETER SkipTests -| Name | Type | Description | Default | -|------|------|-------------|---------| -| SkipTests | System.Management.Automation.SwitchParameter | When set, skip running automated tests during the build. | $false | +| Name | Type | Description | Default | +|-----------|----------------------------------------------|----------------------------------------------------------|---------| +| SkipTests | System.Management.Automation.SwitchParameter | When set, skip running automated tests during the build. | $false | .PARAMETER GenerateDocs -| Name | Type | Description | Default | -|------|------|-------------|---------| -| GenerateDocs | System.Management.Automation.SwitchParameter | When set, regenerate API Markdown documentation from comment help. | $false | +| Name | Type | Description | Default | +|--------------|----------------------------------------------|--------------------------------------------------------------------|---------| +| GenerateDocs | System.Management.Automation.SwitchParameter | When set, regenerate API Markdown documentation from comment help. | $false | .PARAMETER TestDaemonMemoryLeaks -| Name | Type | Description | Default | -|------|------|-------------|---------| -| TestDaemonMemoryLeaks | System.Management.Automation.SwitchParameter | When set, run daemon memory leak stress tests. | $false | +| Name | Type | Description | Default | +|-----------------------|----------------------------------------------|------------------------------------------------|---------| +| TestDaemonMemoryLeaks | System.Management.Automation.SwitchParameter | When set, run daemon memory leak stress tests. | $false | .OUTPUTS -None — Side effects only: generates module artifacts under lib/ and docs/. +None -- Side effects only: generates module artifacts under lib/ and docs/. .EXAMPLE PS> Build-ModuleProject -GenerateDocs @@ -287,12 +290,12 @@ It executes all test suites under the specified path or the default `Tests/` directory using `build/Invoke-ModuleTests.ps1`. .PARAMETER Path -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Path | System.String | Path to a specific test file or directory containing Pester test suites to execute. | $null | +| Name | Type | Description | Default | +|------|---------------|--------------------------------------------------------------------------------------|---------| +| Path | System.String | Path to a specific test file or directory containing Pester test suites to execute. | $null | .OUTPUTS -System.Object — Pester test result summary object and test execution output. +System.Object -- Pester test result summary object and test execution output. .EXAMPLE PS> Invoke-IcingaModuleTests @@ -342,22 +345,22 @@ and Icinga agent). The function is idempotent; repeated calls while already initialized return immediately. .PARAMETER LogLevel -| Name | Type | Description | Default | -|------|------|-------------|---------| +| Name | Type | Description | Default | +|----------|---------------|---------------------------------------------------------------------------------------------------------|---------| | LogLevel | System.String | Minimum log level for the session. Accepted values: Debug, Audit, Info, Success, Warning, Error, Fatal. | Warning | .PARAMETER RunBackgroundDaemons -| Name | Type | Description | Default | -|------|------|-------------|---------| -| RunBackgroundDaemons | System.Management.Automation.SwitchParameter | When set, start the standard background daemon threads (logging, garbage collector, housekeeper, REST API, WebSocket, Icinga agent). Default is false. | $false | +| Name | Type | Description | Default | +|----------------------|----------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------|---------| +| RunBackgroundDaemons | System.Management.Automation.SwitchParameter | When set, start the standard background daemon threads (logging, garbage collector, housekeeper, REST API, WebSocket, Icinga agent). Default is false. | $false | .PARAMETER NoNewShell -| Name | Type | Description | Default | -|------|------|-------------|---------| -| NoNewShell | System.Management.Automation.SwitchParameter | When set, initialize directly in the current shell instead of spawning a new process. | $false | +| Name | Type | Description | Default | +|------------|----------------------------------------------|-------------------------------------------------------------------------------------------------|---------| +| NoNewShell | System.Management.Automation.SwitchParameter | When set, initialize directly in the current shell instead of spawning a new process. | $false | .OUTPUTS -None — Side effects only: configures global runtime state and optionally starts background threads. +None -- Side effects only: configures global runtime state and optionally starts background threads. .EXAMPLE PS> Use-IcingaForWindows @@ -428,7 +431,8 @@ function Use-IcingaForWindows() # have a proper call stack and can manage everything way easier Use-IcingaForWindows -NoNewShell -LogLevel $LogLevel -RunBackgroundDaemons:$RunBackgroundDaemons; - function prompt { + function prompt() + { Write-Host -Object 'icinga' -NoNewline; return '> ' } diff --git a/Tests/ClassLiteral.Tests.ps1 b/Tests/ClassLiteral.Tests.ps1 index 28642db..e5afed3 100644 --- a/Tests/ClassLiteral.Tests.ps1 +++ b/Tests/ClassLiteral.Tests.ps1 @@ -25,6 +25,8 @@ Describe 'Class literals in functions' { } It 'reads the class names from the class files' { + $script:ClassNames | Should -Contain 'IcingaPlugin'; + $script:ClassNames | Should -Contain 'IcingaError'; $script:ClassNames | Should -Contain 'IcingaPerformanceCounter'; $script:ClassNames | Should -Contain 'IcingaUnit'; } diff --git a/Tests/IcingaError.Tests.ps1 b/Tests/IcingaError.Tests.ps1 new file mode 100644 index 0000000..5c20fbc --- /dev/null +++ b/Tests/IcingaError.Tests.ps1 @@ -0,0 +1,57 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'IcingaError' { + BeforeAll { + # The class lives in the dot-sourced kernel and is only visible inside the + # script module scope. + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + } + + Context 'Construction' { + It 'keeps a plain message verbatim, including braces' { + $Error1 = & $script:IcingaModule { [IcingaError]::new('Volume \\?\Volume{1234}\ is offline') }; + $Error1.Message | Should -Be 'Volume \\?\Volume{1234}\ is offline'; + $Error1.ReturnCode | Should -Be ''; + $Error1.Data.Count | Should -Be 0; + } + + It 'formats a message with its arguments' { + $Error1 = & $script:IcingaModule { [IcingaError]::new('Failed to query {0}: {1}', @('Win32_Service', 'Access denied')) }; + $Error1.Message | Should -Be 'Failed to query Win32_Service: Access denied'; + } + + It 'stores return code and data' { + $Error1 = & $script:IcingaModule { [IcingaError]::new('WindowsInformationClassUnknown', 'The class Foo is unknown', @{ 'ClassName' = 'Foo'; }) }; + $Error1.ReturnCode | Should -Be 'WindowsInformationClassUnknown'; + $Error1.Message | Should -Be 'The class Foo is unknown'; + $Error1.Data['ClassName'] | Should -Be 'Foo'; + } + + It 'stores an empty hashtable for $null data' { + $Error1 = & $script:IcingaModule { [IcingaError]::new('Key', 'Message', $null) }; + ($Error1.Data -is [hashtable]) | Should -BeTrue; + $Error1.Data.Count | Should -Be 0; + } + + It 'renders as its message' { + $Text = & $script:IcingaModule { [string]([IcingaError]::new('boom')) }; + $Text | Should -Be 'boom'; + } + } + + Context 'FormatMessage' { + It 'returns the message unchanged without arguments' { + (& $script:IcingaModule { [IcingaError]::FormatMessage('Value {x}', @()) }) | Should -Be 'Value {x}'; + (& $script:IcingaModule { [IcingaError]::FormatMessage('Value {x}', $null) }) | Should -Be 'Value {x}'; + } + + It 'appends the arguments instead of throwing on an invalid format string' { + (& $script:IcingaModule { [IcingaError]::FormatMessage('Value {x}', @('a', 'b')) }) | Should -Be 'Value {x} (a, b)'; + } + } +} diff --git a/Tests/IcingaPlugin.Tests.ps1 b/Tests/IcingaPlugin.Tests.ps1 new file mode 100644 index 0000000..a4fdb6e --- /dev/null +++ b/Tests/IcingaPlugin.Tests.ps1 @@ -0,0 +1,952 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'IcingaPlugin' { + BeforeAll { + # Class types defined in the dot-sourced kernel are not visible in the test + # scope, so grab the script module and construct plugins in its scope. This + # must live in BeforeAll (run phase) so it survives Pester's discovery phase. + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + # Remember the daemon switch so the shared runtime state is restored after the + # suite; otherwise a test run would leave the session in daemon mode and later + # interactive checks would print nothing. + $script:OriginalDaemonFlag = $Global:IcingaForWindows.Protected.IsBackgroundDaemon; + } + + AfterAll { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $script:OriginalDaemonFlag; + } + + BeforeEach { + # Run every check in daemon mode so Compile writes NO console output during + # the test run (System.Console output cannot be swallowed with | Out-Null). + # The result is still stored in Private.Icinga.CheckResult, which every + # assertion reads. The CLI console path is covered separately with a captured + # System.Console redirect so it, too, prints nothing. + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $true; + } + + Context 'Leaf checks' { + It 'evaluates a value inside the thresholds as OK and returns exit code 0' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('Load', 5, '%').Warning('80').Critical('90').CheckRange().Compile() + }; + $ExitCode | Should -Be 0; + } + + It 'raises WARNING when the warning threshold is exceeded' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('Load', 85, '%').Warning('80').Critical('90').CheckRange().Compile() + }; + $ExitCode | Should -Be 1; + } + + It 'raises CRITICAL when the critical threshold is exceeded' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('Load', 95, '%').Warning('80').Critical('90').CheckRange().Compile() + }; + $ExitCode | Should -Be 2; + } + + It 'renders the leaf output as "[STATE] Name: message"' { + & $script:IcingaModule { + [IcingaPlugin]::new('Load', 95, '%').Warning('80').Critical('90').CheckRange().Compile() + } | Out-Null; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match '^\[CRITICAL\] Load: '; + } + + It 'appends the display unit to the value and thresholds in the message' { + & $script:IcingaModule { + [IcingaPlugin]::new('Load', 95, '%').Warning('80').Critical('90').CheckRange().Compile() + } | Out-Null; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[CRITICAL] Load: 95% is greater than threshold 90%'; + } + + It 'produces a single perfdata metric in the check_multi index::ifw_template::label format' { + & $script:IcingaModule { + [IcingaPlugin]::new('Load', 95, '%').Warning('80').Critical('90').Minimum('0').Maximum('100').CheckRange().Compile() + } | Out-Null; + $Perf = $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData; + $Perf.Count | Should -Be 1; + # No metric parts set and no command on the stack -> fallbacks default / ifw_check / . + $Perf[0] | Should -Be 'default::ifw_check::load=95%;80;90;0;100'; + } + + It 'builds the check_multi label from explicit MetricIndex/MetricName/MetricLabel' { + & $script:IcingaModule { + [IcingaPlugin]::new('Free Partition Space'). + AddCheck([IcingaPlugin]::new('C', 41.28, 'GiB').MetricIndex('c').MetricName('partitionspace').MetricLabel('free').Warning('80').Critical('90').Maximum('254').CheckRange()). + AddCheck([IcingaPlugin]::new('D', 95.67, 'MiB').MetricIndex('d').MetricName('partitionspace').MetricLabel('free').Warning('80').Critical('90').Maximum('786').CheckRange()). + Compile() + } | Out-Null; + $Perf = $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData; + $Perf.Count | Should -Be 2; + $Perf[0] | Should -Be 'c::ifw_partitionspace::free=41.28GiB;80;90;;254'; + ($Perf -join ' ') | Should -Be 'c::ifw_partitionspace::free=41.28GiB;80;90;;254 d::ifw_partitionspace::free=95.67MiB;80;90;;786'; + } + + It 'sanitizes metric segments and does not double the ifw_ namespace' { + & $script:IcingaModule { + [IcingaPlugin]::new('X', 5, '%').MetricIndex('Core #0').MetricName('ifw_cpu').MetricLabel('Load %').CheckRange().Compile() + } | Out-Null; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData[0] | Should -Be 'core0::ifw_cpu::load=5%;;;;'; + } + + It 'derives the template from the calling Invoke-IcingaCheck* command' { + & $script:IcingaModule { + function Invoke-IcingaCheckFoo() + { + [IcingaPlugin]::new('bar', 5, '%').MetricLabel('load').CheckRange().Compile() | Out-Null; + } + Invoke-IcingaCheckFoo + }; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData[0] | Should -Be 'default::ifw_foo::load=5%;;;;'; + } + + It 'evaluates greater/lower comparison modes' { + (& $script:IcingaModule { [IcingaPlugin]::new('X', 95).Critical('90').CheckGreater().Compile() }) | Should -Be 2; + (& $script:IcingaModule { [IcingaPlugin]::new('X', 5).Critical('10').CheckLower().Compile() }) | Should -Be 2; + } + } + + Context 'State overrides' { + It 'forces the state through SetCritical' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('Svc', 5, '%').Warning('80').Critical('90').CheckRange().SetCritical('Service is stopped').Compile() + }; + $ExitCode | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[CRITICAL] Svc: Service is stopped'; + } + + It 'freezes state and message when locked, ignoring later evaluation' { + & $script:IcingaModule { + [IcingaPlugin]::new('Svc', 5, '%').Warning('80').Critical('90').CheckRange().SetCritical('forced', $true).CheckRange().Compile() + } | Out-Null; + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result.ExitCode | Should -Be 2; + $Result.Output | Should -Be '[CRITICAL] Svc: forced'; + } + } + + Context 'Container aggregation' { + It 'is OK when all children are OK (default And operator)' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('Disks'). + AddCheck([IcingaPlugin]::new('C:', 55, '%').Warning('80').Critical('90').CheckRange()). + AddCheck([IcingaPlugin]::new('D:', 60, '%').Warning('80').Critical('90').CheckRange()). + Compile() + }; + $ExitCode | Should -Be 0; + } + + It 'takes the worst child state with the And operator' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('Disks'). + AddCheck([IcingaPlugin]::new('C:', 55, '%').Warning('80').Critical('90').CheckRange()). + AddCheck([IcingaPlugin]::new('D:', 95, '%').Warning('80').Critical('90').CheckRange()). + CheckAnd().Compile() + }; + $ExitCode | Should -Be 2; + } + + It 'is OK with the Or operator when at least one child is OK' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('Any'). + AddCheck([IcingaPlugin]::new('A', 95, '%').Warning('80').Critical('90').CheckRange()). + AddCheck([IcingaPlugin]::new('B', 5, '%').Warning('80').Critical('90').CheckRange()). + CheckOr().Compile() + }; + $ExitCode | Should -Be 0; + } + + It 'honours CheckMinimum independently of the And rule' { + # Enough OK children -> OK, even though one child is CRITICAL (no And leak). + (& $script:IcingaModule { + [IcingaPlugin]::new('Grp'). + AddCheck([IcingaPlugin]::new('a', 5, '%').Critical('90').CheckRange()). + AddCheck([IcingaPlugin]::new('b', 5, '%').Critical('90').CheckRange()). + AddCheck([IcingaPlugin]::new('c', 5, '%').Critical('90').CheckRange()). + AddCheck([IcingaPlugin]::new('d', 95, '%').Critical('90').CheckRange()). + CheckMinimum(3).Compile() + }) | Should -Be 0; + + # Fewer than the minimum OK -> escalate to the worst child state. + (& $script:IcingaModule { + [IcingaPlugin]::new('Grp'). + AddCheck([IcingaPlugin]::new('a', 5, '%').Critical('90').CheckRange()). + AddCheck([IcingaPlugin]::new('b', 95, '%').Critical('90').CheckRange()). + AddCheck([IcingaPlugin]::new('c', 95, '%').Critical('90').CheckRange()). + CheckMinimum(3).Compile() + }) | Should -Be 2; + } + + It 'renders the summary header and the indented child tree at the root' { + & $script:IcingaModule { + [IcingaPlugin]::new('Disks'). + AddCheck([IcingaPlugin]::new('C:', 55, '%').Warning('80').Critical('90').CheckRange()). + AddCheck([IcingaPlugin]::new('D:', 95, '%').Warning('80').Critical('90').CheckRange()). + CheckAnd().Compile() + } | Out-Null; + $Output = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output; + $Output | Should -Match '^\[CRITICAL\] Disks: 1 Critical 1 Ok \[CRITICAL\] D:'; + $Output | Should -Match "\n\\_ \[CRITICAL\] D:"; + } + + It 'collects perfdata from all children' { + & $script:IcingaModule { + [IcingaPlugin]::new('Disks'). + AddCheck([IcingaPlugin]::new('C:', 55, '%').Warning('80').Critical('90').CheckRange()). + AddCheck([IcingaPlugin]::new('D:', 95, '%').Warning('80').Critical('90').CheckRange()). + Compile() + } | Out-Null; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData.Count | Should -Be 2; + } + } + + Context 'Hybrid node (own value and children)' { + It 'lets the container own check escalate the aggregate state' { + $ExitCode = & $script:IcingaModule { + $Cpu = [IcingaPlugin]::new('CPU', 99, '%').Warning('80').Critical('90').CheckRange(); + [void]$Cpu.AddCheck([IcingaPlugin]::new('Core0', 10, '%').Critical('95').CheckRange()); + $Cpu.CheckAnd().Compile() + }; + $ExitCode | Should -Be 2; + } + } + + Context 'Compile output targets' { + It 'always stores an IcingaCheckResult in the thread-local Private state' { + & $script:IcingaModule { + [IcingaPlugin]::new('Load', 95, '%').Warning('80').Critical('90').CheckRange().Compile() + } | Out-Null; + $Result = $Global:IcingaForWindows.Private.Icinga.CheckResult; + $Result | Should -Not -BeNullOrEmpty; + $Result.ExitCode | Should -Be 2; + $Result.Output | Should -Not -BeNullOrEmpty; + } + + It 'writes the result to Private without console output in daemon mode' { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $true; + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('Load', 95, '%').Warning('80').Critical('90').CheckRange().Compile() + }; + $ExitCode | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.ExitCode | Should -Be 2; + } + + It 'writes output and space-joined perfdata to the console on the CLI path' { + # Capture the CLI (non-daemon) console write via a StringWriter so the + # assertion runs without printing anything during the test. + $Captured = & $script:IcingaModule { + $Original = [System.Console]::Out; + $Writer = [System.IO.StringWriter]::new(); + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $false; + [System.Console]::SetOut($Writer); + try { + [IcingaPlugin]::new('Disks'). + AddCheck([IcingaPlugin]::new('C:', 95, '%').Warning('80').Critical('90').CheckRange()). + Compile() | Out-Null; + } finally { + [System.Console]::SetOut($Original); + } + return $Writer.ToString(); + }; + $Captured | Should -Match "\| default::ifw_check::c=95%;80;90;;"; + } + } + + Context 'Verbosity and summary header' { + It 'counts every leaf check in the header recursively, including OK, excluding containers' { + & $script:IcingaModule { + $Sub = [IcingaPlugin]::new('Cores'). + AddCheck([IcingaPlugin]::new('Core0', 99, '%').Critical('95').CheckRange()). + AddCheck([IcingaPlugin]::new('Core1', 10, '%').Critical('95').CheckRange()); + [IcingaPlugin]::new('CPU').AddCheck($Sub).Compile() + } | Out-Null; + $Header = ($Global:IcingaForWindows.Private.Icinga.CheckResult.Output -split "`n")[0]; + $Header | Should -Match '^\[CRITICAL\] CPU: 1 Critical 1 Ok \[CRITICAL\] Core0'; + $Header | Should -Not -Match 'Cores'; + } + + It 'prunes OK leaves from the tree at verbosity 0 but still counts them in the header' { + & $script:IcingaModule { + [IcingaPlugin]::new('Disks'). + AddCheck([IcingaPlugin]::new('C:', 55, '%').Warning('80').Critical('90').CheckRange()). + AddCheck([IcingaPlugin]::new('D:', 95, '%').Warning('80').Critical('90').CheckRange()). + Compile() + } | Out-Null; + $Output = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output; + $Output | Should -Match '1 Critical 1 Ok'; + ($Output -split "`n" | Where-Object { $_ -match '\\_ .*C:' }) | Should -BeNullOrEmpty; + } + + It 'does not count the entries of a notice package in the header' { + & $script:IcingaModule { + $List = [IcingaPlugin]::new('File List'); + $List.IsNotice = $true; + [void]$List.AddCheck([IcingaPlugin]::new('a.log').SetNotice('1KiB')); + [void]$List.AddCheck([IcingaPlugin]::new('b.log').SetNotice('2KiB')); + + $Package = [IcingaPlugin]::new('Directory'); + $Package.Verbose = 2; + [void]$Package.AddCheck([IcingaPlugin]::new('File Count', 2).Critical('1').CheckRange()); + [void]$Package.AddCheck($List); + $Package.Compile() + } | Out-Null; + $Output = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output; + ($Output -split "`n")[0] | Should -Be '[CRITICAL] Directory: 1 Critical [CRITICAL] File Count'; + $Output | Should -Match ([regex]::Escape('[INFO] a.log: 1KiB')); + } + + It 'appends the operator configuration at verbosity 3, even when set after building' { + & $script:IcingaModule { + $Package = [IcingaPlugin]::new('Disks'). + AddCheck([IcingaPlugin]::new('C:', 95, '%').Warning('80').Critical('90').CheckRange()); + $Package.Verbose = 3; + $Package.Compile() + } | Out-Null; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match '\(All must be \[OK\]\)'; + } + + It 'shows no operator configuration for None or notice packages at verbosity 3' { + $None = & $script:IcingaModule { + $Package = [IcingaPlugin]::new('Grp').AddCheck([IcingaPlugin]::new('a', 5, '%').Critical('90').CheckRange()); + $Package.CheckNone(); + $Package.Verbose = 3; + $Package.Compile() | Out-Null; + return $Global:IcingaForWindows.Private.Icinga.CheckResult.Output; + }; + $None | Should -Not -Match 'must be'; + + $Notice = & $script:IcingaModule { + $Package = [IcingaPlugin]::new('Grp'); + $Package.IsNotice = $true; + [void]$Package.AddCheck([IcingaPlugin]::new('a', 5, '%').Critical('90').CheckRange()); + $Package.Verbose = 3; + $Package.Compile() | Out-Null; + return $Global:IcingaForWindows.Private.Icinga.CheckResult.Output; + }; + $Notice | Should -Not -Match 'must be'; + } + } + + Context 'Byte values' { + It 'compares bytes against percent thresholds of the base value and renders human-readable sizes' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('C', 442692000000, 'B').Warning('80%').Critical('90%').BaseValue(512000000000).CheckRange().Compile() + }; + $ExitCode | Should -Be 1; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[WARNING] C: 412.29GiB (86.46%) is greater than threshold 381.47GiB (80%)'; + } + + It 'writes the resolved percent thresholds in bytes into the perfdata' { + & $script:IcingaModule { + [IcingaPlugin]::new('C', 442692000000, 'B').MetricIndex('c').MetricLabel('used').Warning('80%').Critical('90%').BaseValue(512000000000).Minimum('0').Maximum('512000000000').CheckRange().Compile() + } | Out-Null; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData[0] | Should -Be 'c::ifw_check::used=442692000000B;409600000000;460800000000;0;512000000000'; + } + + It 'keeps absolute size thresholds in their own unit in the message' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('C', 442692000000, 'B').MetricLabel('used').Warning('400GB').Critical('450GB').CheckRange().Compile() + }; + $ExitCode | Should -Be 1; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[WARNING] C: 412.29GiB is greater than threshold 400GB'; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData[0] | Should -Be 'default::ifw_check::used=442692000000B;400000000000;450000000000;;'; + } + + It 'resolves percent range thresholds into byte ranges for the perfdata' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('C', 30000000000, 'B').MetricLabel('free').Warning('10%:').Critical('5%:').BaseValue(512000000000).CheckRange().Compile() + }; + $ExitCode | Should -Be 1; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[WARNING] C: 27.94GiB (5.86%) is lower than threshold 47.68GiB (10%)'; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData[0] | Should -Be 'default::ifw_check::free=30000000000B;51200000000:;25600000000:;;'; + } + + It 'treats plain-number thresholds of a byte node as bytes' { + (& $script:IcingaModule { [IcingaPlugin]::new('X', 2048, 'B').Critical('1024').CheckRange().Compile() }) | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[CRITICAL] X: 2KiB is greater than threshold 1024'; + } + + It 'leaves larger data units on the plain display-unit behaviour' { + (& $script:IcingaModule { [IcingaPlugin]::new('X', 41.28, 'GiB').Warning('80').Critical('90').CheckRange().Compile() }) | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[OK] X: 41.28GiB is ok'; + } + } + + Context 'Time values' { + It 'compares seconds against duration thresholds and renders human-readable durations' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('Uptime', 3600, 's').MetricLabel('uptime').Warning('30m').Critical('2h').CheckRange().Compile() + }; + $ExitCode | Should -Be 1; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[WARNING] Uptime: 1h is greater than threshold 30m'; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData[0] | Should -Be 'default::ifw_check::uptime=3600s;1800;7200;;'; + } + + It 'resolves duration range thresholds into seconds for the perfdata' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('Uptime', 3600, 's').MetricLabel('uptime').Warning('1d:').CheckRange().Compile() + }; + $ExitCode | Should -Be 1; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[WARNING] Uptime: 1h is lower than threshold 1d'; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData[0] | Should -Be 'default::ifw_check::uptime=3600s;86400:;;;'; + } + + It 'decomposes the value into every non-zero unit' { + (& $script:IcingaModule { [IcingaPlugin]::new('Uptime', 93784, 's').CheckRange().Compile() }) | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[OK] Uptime: 1d 2h 3m 4s is ok'; + } + + It 'renders sub-second durations in milli- and microseconds and keeps seconds in the perfdata' { + (& $script:IcingaModule { [IcingaPlugin]::new('Latency', 0.004, 's').MetricLabel('read').Warning('0.002').CheckRange().Compile() }) | Should -Be 1; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[WARNING] Latency: 4ms is greater than threshold 0.002'; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData[0] | Should -Be 'default::ifw_check::read=0.004s;0.002;;;'; + + (& $script:IcingaModule { [IcingaPlugin]::new('Latency', 0.000412, 's').CheckRange().Compile() }) | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[OK] Latency: 412us is ok'; + } + + It 'treats plain-number thresholds of a time node as seconds' { + (& $script:IcingaModule { [IcingaPlugin]::new('X', 3600, 's').Critical('1800').CheckRange().Compile() }) | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[CRITICAL] X: 1h is greater than threshold 1800'; + } + + It 'leaves other time units on the plain display-unit behaviour' { + (& $script:IcingaModule { [IcingaPlugin]::new('X', 250, 'ms').Warning('100').CheckRange().Compile() }) | Should -Be 1; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[WARNING] X: 250ms is greater than threshold 100ms'; + } + } + + Context 'Error state' { + It 'reports a formatted error message as UNKNOWN' { + (& $script:IcingaModule { [IcingaPlugin]::new('CPU Load').SetError('Failed to read {0}', '\Processor(*)').Compile() }) | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] CPU Load: Failed to read \Processor(*)'; + } + + It 'formats up to three comma-separated arguments and an argument array' { + & $script:IcingaModule { [IcingaPlugin]::new('X').SetError('{0}-{1}', 'a', 'b').Compile() } | Out-Null; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] X: a-b'; + + & $script:IcingaModule { [IcingaPlugin]::new('X').SetError('{0}-{1}-{2}', 'a', 'b', 'c').Compile() } | Out-Null; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] X: a-b-c'; + + & $script:IcingaModule { [IcingaPlugin]::new('X').SetError('{0}-{1}-{2}-{3}', @('a', 'b', 'c', 'd')).Compile() } | Out-Null; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] X: a-b-c-d'; + } + + It 'keeps a message without arguments verbatim' { + & $script:IcingaModule { [IcingaPlugin]::new('X').SetError('Volume {1234} is offline').Compile() } | Out-Null; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] X: Volume {1234} is offline'; + } + + It 'reports an IcingaError returned by a data function' { + $ExitCode = & $script:IcingaModule { + $Data = [IcingaError]::new('Failed to query {0}', @('Win32_Service')); + if ($Data -is [IcingaError]) { + return [IcingaPlugin]::new('Services').SetError($Data).Compile(); + } + return 0; + }; + $ExitCode | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Services: Failed to query Win32_Service'; + } + + It 'shows the error on a container with children instead of the summary header' { + & $script:IcingaModule { + $Package = [IcingaPlugin]::new('Disks'); + $Package.Verbose = 2; + $Package.AddCheck([IcingaPlugin]::new('C', 5, '%').Critical('90').CheckRange()).SetError('Volume data is incomplete').Compile() | Out-Null; + }; + [array]$Lines = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output -split "`n"; + $Lines[0] | Should -Be '[UNKNOWN] Disks: Volume data is incomplete'; + $Lines[1] | Should -Match '^\\_ \[OK\] C: '; + $Global:IcingaForWindows.Private.Icinga.CheckResult.ExitCode | Should -Be 3; + } + + It 'locks the error state against later comparisons' { + (& $script:IcingaModule { [IcingaPlugin]::new('X', 95, '%').SetError('broken').Critical('90').CheckRange().Compile() }) | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] X: broken'; + } + } + + Context 'Missing required entries' { + It 'adds a locked check in the given state for every missing entry' { + $ExitCode = & $script:IcingaModule { + $Package = [IcingaPlugin]::new('Services'); + $Package.Verbose = 2; + $Package.AddMissingChecks(@('Spooler', 'DoesNotExist', 'Other'), @('Spooler', 'WinRM'), '{0}', 'Service not found', 3).Compile(); + }; + $ExitCode | Should -Be 3; + + [array]$Lines = $Global:IcingaForWindows.Private.Icinga.CheckResult.Output -split "`n"; + $Lines.Count | Should -Be 3; + $Lines[1] | Should -Be '\_ [UNKNOWN] DoesNotExist: Service not found'; + $Lines[2] | Should -Be '\_ [UNKNOWN] Other: Service not found'; + } + + It 'matches case-insensitively and with wildcards' { + $HasChecks = & $script:IcingaModule { + $Package = [IcingaPlugin]::new('Services'); + $Package.AddMissingChecks(@('spooler', 'Win*'), @('Spooler', 'WinRM'), '{0}', 'Service not found', 3).Commit(); + return $Package.HasChecks(); + }; + $HasChecks | Should -BeFalse; + } + + It 'compares the normalized entry and uses it in the check name' { + & $script:IcingaModule { + $Package = [IcingaPlugin]::new('Used Partition Space'); + $Package.AddMissingChecks(@('C:', 'C:\', 'E:'), @('C', 'D'), 'Partition {0}', 'Mandatory partition not found on host', 2, '[:\\/]+$').Compile() | Out-Null; + }; + $Global:IcingaForWindows.Private.Icinga.CheckResult.ExitCode | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match ([regex]::Escape('[CRITICAL] Partition E: Mandatory partition not found on host')); + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Not -Match 'Partition C'; + } + + It 'skips empty entries and survives an invalid pattern' { + $Names = & $script:IcingaModule { + $Package = [IcingaPlugin]::new('X'); + $Package.AddMissingChecks(@('', $null, '[abc'), @('abc'), '{0}', 'missing', 2, '(').Commit(); + return @($Package.Checks | ForEach-Object { $_.Name }); + }; + $Names | Should -Be @('[abc'); + } + } + + Context 'HasChecks' { + It 'reports whether the node has children' { + $Result = & $script:IcingaModule { + $Package = [IcingaPlugin]::new('X'); + $Before = $Package.HasChecks(); + $Package.AddCheck([IcingaPlugin]::new('a', 5).CheckRange()).Commit(); + return @($Before, $Package.HasChecks()); + }; + $Result | Should -Be @($false, $true); + } + } + + Context 'Fluent surface' { + It 'Commit terminates a chain without leaking the node to the pipeline' { + $Leak = & $script:IcingaModule { + [IcingaPlugin]::new('X', 5, '%').Warning('80').Critical('90').CheckRange().Commit() + }; + $Leak | Should -BeNullOrEmpty; + } + } + + Context 'IgnoreEmptyPackage and empty package handling' { + It 'returns UNKNOWN with "No checks added to this object" for an empty package by default' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('Empty Package').Compile() + }; + $ExitCode | Should -Be 3; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[UNKNOWN] Empty Package: No checks added to this object'; + } + + It 'returns OK for an empty package when IgnoreEmptyPackage is true' { + $ExitCode = & $script:IcingaModule { + $Package = [IcingaPlugin]::new('Empty Package'); + $Package.IgnoreEmptyPackage = $true; + $Package.Compile() + }; + $ExitCode | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[OK] Empty Package'; + } + + It 'returns OK for an empty package when SetIgnoreEmptyPackage() is chained' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('Empty Package').SetIgnoreEmptyPackage().Compile() + }; + $ExitCode | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[OK] Empty Package'; + } + + It 'returns OK when only hidden metric checks exist and IgnoreEmptyPackage is enabled' { + $ExitCode = & $script:IcingaModule { + $Metric = [IcingaPlugin]::new('HiddenMetrics').SetHidden(); + $Metric.AddCheck([IcingaPlugin]::new('count', 0).MetricIndex('summary').MetricLabel('count')).Commit(); + + [IcingaPlugin]::new('Services'). + SetIgnoreEmptyPackage(). + AddCheck($Metric). + Compile() + }; + $ExitCode | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[OK] Services'; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData[0] | Should -Be 'summary::ifw_check::count=0;;;;'; + } + + It 'does not treat an ignored empty child package as a failure in the parent container' { + $ExitCode = & $script:IcingaModule { + $EmptySub = [IcingaPlugin]::new('Optional Sub').SetIgnoreEmptyPackage(); + [IcingaPlugin]::new('Root'). + AddCheck([IcingaPlugin]::new('C:', 50, '%').Warning('80').Critical('90').CheckRange()). + AddCheck($EmptySub). + Compile() + }; + $ExitCode | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[OK] Root: 1 Ok'; + } + + It 'renders an empty notice package as [INFO] with "Nothing to report"' { + $ExitCode = & $script:IcingaModule { + $Notice = [IcingaPlugin]::new('File List'); + $Notice.IsNotice = $true; + $Notice.Compile() + }; + $ExitCode | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[INFO] File List: Nothing to report'; + } + } + + Context 'Translate (.Translate)' { + It 'translates a numeric value and threshold with a hashtable while keeping numeric perfdata' { + $ExitCode = & $script:IcingaModule { + $Map = @{ + 1 = 'Stopped'; + 4 = 'Running'; + }; + [IcingaPlugin]::new('Spooler', 1). + Translate($Map). + MetricIndex('spooler'). + MetricName('service'). + MetricLabel('status'). + Critical('Running'). + CheckNotEqual(). + Compile() + }; + $ExitCode | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be "[CRITICAL] Spooler: 'Stopped' does not equal pattern 'Running'"; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData[0] | Should -Be 'spooler::ifw_service::status=1;;4;;'; + } + + It 'translates a numeric value with an explicit display text string' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('Spooler', 4). + Translate('Running'). + MetricIndex('spooler'). + MetricName('service'). + MetricLabel('status'). + Critical('Running'). + CheckNotEqual(). + Compile() + }; + $ExitCode | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be "[OK] Spooler: 'Running' is ok"; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData[0] | Should -Be 'spooler::ifw_service::status=4;;4;;'; + } + + It 'translates an enum value automatically via parameterless .Translate() and emits integer perfdata' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('WinRM', [System.DayOfWeek]::Monday). + Translate(). + MetricIndex('winrm'). + MetricName('day'). + MetricLabel('state'). + Critical('Monday'). + CheckNotEqual(). + Compile() + }; + $ExitCode | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be "[OK] WinRM: 'Monday' is ok"; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData[0] | Should -Be 'winrm::ifw_day::state=1;;;;'; + } + + It 'translates 0s on a time node to a custom label like "Never" when configured' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('Last Backup', 0, 's'). + Translate(@{ 0 = 'Never' }). + CheckRange(). + Compile() + }; + $ExitCode | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[OK] Last Backup: Never is ok'; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData[0] | Should -Be 'default::ifw_check::lastbackup=0s;;;;'; + } + } + + Context 'Multi-value array thresholds and TimeSpan values' { + It 'evaluates CheckNotIn / CheckNotEqual with an array of allowed values as OK when matched' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('Scheduled Task', 'Running'). + Critical(@('Ready', 'Running')). + CheckNotIn(). + Compile() + }; + $ExitCode | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be "[OK] Scheduled Task: 'Running' is ok"; + } + + It 'raises CRITICAL when CheckNotIn / CheckNotEqual value is not in the allowed array' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('Scheduled Task', 'Disabled'). + Critical(@('Ready', 'Running')). + CheckNotEqual(). + Compile() + }; + $ExitCode | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be "[CRITICAL] Scheduled Task: 'Disabled' does not equal pattern 'Ready, Running'"; + } + + It 'evaluates CheckIn / CheckEqual with warning and critical arrays' { + $WarnCode = & $script:IcingaModule { + [IcingaPlugin]::new('Service State', 'Paused'). + Warning(@('Paused', 'Pending')). + Critical(@('Stopped', 'Offline')). + CheckIn(). + Compile() + }; + $WarnCode | Should -Be 1; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be "[WARNING] Service State: 'Paused' equals pattern 'Paused'"; + + $CritCode = & $script:IcingaModule { + [IcingaPlugin]::new('Service State', 'Offline'). + Warning(@('Paused', 'Pending')). + Critical(@('Stopped', 'Offline')). + CheckIn(). + Compile() + }; + $CritCode | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be "[CRITICAL] Service State: 'Offline' equals pattern 'Offline'"; + } + + It 'evaluates CheckLike and CheckNotLike with wildcard pattern arrays' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('Status', 'degraded-disk'). + Warning(@('*warn*', '*degraded*')). + Critical(@('*err*', '*fail*')). + CheckLike(). + Compile() + }; + $ExitCode | Should -Be 1; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be "[WARNING] Status: 'degraded-disk' is like pattern '*degraded*'"; + + $NotLikeCode = & $script:IcingaModule { + [IcingaPlugin]::new('Status', 'failed'). + Critical(@('*ok*', '*healthy*')). + CheckNotLike(). + Compile() + }; + $NotLikeCode | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be "[CRITICAL] Status: 'failed' is not like pattern '*ok*, *healthy*'"; + } + + It 'treats an empty threshold array as unset (OK)' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('Task', 'Disabled'). + Warning(@()). + Critical(@()). + CheckNotIn(). + Compile() + }; + $ExitCode | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be "[OK] Task: 'Disabled' is ok"; + } + + It 'supports translated values and thresholds with multi-value arrays' { + $ExitCode = & $script:IcingaModule { + $Map = @{ + 1 = 'Stopped'; + 3 = 'Ready'; + 4 = 'Running'; + }; + [IcingaPlugin]::new('Task', 4). + Translate($Map). + Critical(@(3, 4)). + CheckNotIn(). + Compile() + }; + $ExitCode | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be "[OK] Task: 'Running' is ok"; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData[0] | Should -Be 'default::ifw_check::task=4;;;;'; + } + + It 'auto-converts a [TimeSpan] value and base value to seconds with unit "s"' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('Uptime', [TimeSpan]::FromHours(2)). + MetricLabel('uptime'). + Warning('1h'). + Critical('3h'). + CheckRange(). + Compile() + }; + $ExitCode | Should -Be 1; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[WARNING] Uptime: 2h is greater than threshold 1h'; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData[0] | Should -Be 'default::ifw_check::uptime=7200s;3600;10800;;'; + + $BaseExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('Elapsed', [TimeSpan]::FromMinutes(45)). + BaseValue([TimeSpan]::FromHours(1)). + Warning('50%'). + Critical('80%'). + CheckRange(). + Compile() + }; + $BaseExitCode | Should -Be 1; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[WARNING] Elapsed: 45m (75%) is greater than threshold 30m (50%)'; + } + } + + Context 'Extended container aggregation and formatting' { + It 'escalates to CRITICAL when CheckMaximum is violated even if all children are OK' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('Cluster'). + AddCheck([IcingaPlugin]::new('Node1', 10, '%').CheckRange()). + AddCheck([IcingaPlugin]::new('Node2', 10, '%').CheckRange()). + CheckMaximum(1). + Compile() + }; + $ExitCode | Should -Be 2; + } + + It 'escalates to CRITICAL when CheckNone has an OK child' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('Forbidden'). + AddCheck([IcingaPlugin]::new('Node1', 10, '%').CheckRange()). + CheckNone(). + Compile() + }; + $ExitCode | Should -Be 2; + } + + It 'excludes [INFO] notice leaves from OkCount in CheckOr and CheckMinimum' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('Group'). + AddCheck([IcingaPlugin]::new('Note').SetNotice('info only')). + AddCheck([IcingaPlugin]::new('Disk', 95, '%').Critical('90').CheckRange()). + CheckOr(). + Compile() + }; + $ExitCode | Should -Be 2; + } + + It 'renders combined CheckMinimum and CheckMaximum configuration at verbosity 3' { + & $script:IcingaModule { + $Package = [IcingaPlugin]::new('Nodes'). + AddCheck([IcingaPlugin]::new('Node1', 10, '%').CheckRange()). + CheckMinimum(1). + CheckMaximum(2). + SetVerbose(3); + $Package.Compile() + } | Out-Null; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match '\(Between 1 and 2 must be \[OK\]\)'; + } + + It 'omits a SkipSummary leaf from the header counts while still aggregating its state' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('Certs'). + AddCheck([IcingaPlugin]::new('Cert A', 10).Critical('5').CheckRange().SetSkipSummary()). + AddCheck([IcingaPlugin]::new('Cert B', 1).Critical('5').CheckRange()). + Compile() + }; + $ExitCode | Should -Be 2; + $Header = ($Global:IcingaForWindows.Private.Icinga.CheckResult.Output -split "`n")[0]; + $Header | Should -Be '[CRITICAL] Certs: 1 Ok'; + } + + It 'suppresses subtree performance data when NoPerfData is set on the container' { + & $script:IcingaModule { + [IcingaPlugin]::new('Disks'). + SetNoPerfData(). + AddCheck([IcingaPlugin]::new('C:', 50, '%').CheckRange()). + Compile() + } | Out-Null; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData.Count | Should -Be 0; + } + + It 'deduplicates identical performance data metric labels' { + & $script:IcingaModule { + [IcingaPlugin]::new('Disks'). + AddCheck([IcingaPlugin]::new('C', 50, '%').MetricIndex('c').MetricLabel('used').CheckRange()). + AddCheck([IcingaPlugin]::new('C duplicate', 60, '%').MetricIndex('c').MetricLabel('used').CheckRange()). + Compile() + } | Out-Null; + $Perf = $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData; + $Perf.Count | Should -Be 1; + $Perf[0] | Should -Be 'c::ifw_check::used=50%;;;;'; + } + + It 'falls back to "value" when a metric label consists only of special characters' { + & $script:IcingaModule { + [IcingaPlugin]::new('---', 42).CheckRange().Compile() + } | Out-Null; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData[0] | Should -Be 'default::ifw_check::value=42;;;;'; + } + + It 'formats very small floating-point numbers without scientific notation in perfdata' { + & $script:IcingaModule { + [IcingaPlugin]::new('Latency', 0.00005).CheckRange().Compile() + } | Out-Null; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData[0] | Should -Be 'default::ifw_check::latency=0.00005;;;;'; + } + + It 'humanizes negative byte and time values and omits the continuous counter "c" unit from display text' { + & $script:IcingaModule { + [IcingaPlugin]::new('Offset', -3600, 's').CheckRange().Compile() + } | Out-Null; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[OK] Offset: -1h is ok'; + + & $script:IcingaModule { + [IcingaPlugin]::new('Delta', -2048, 'B').CheckRange().Compile() + } | Out-Null; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[OK] Delta: -2KiB is ok'; + + & $script:IcingaModule { + [IcingaPlugin]::new('Packets', 100, 'c').Warning('50').CheckRange().Compile() + } | Out-Null; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[WARNING] Packets: 100 is greater than threshold 50'; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData[0] | Should -Be 'default::ifw_check::packets=100c;50;;;'; + } + + It 'accepts percentage thresholds like "10%" on a "%" unit node without requiring BaseValue' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('CPU Load', 16.25, '%').Warning('10%').Critical('90%').CheckRange().Compile() + }; + $ExitCode | Should -Be 1; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[WARNING] CPU Load: 16.25% is greater than threshold 10%'; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData[0] | Should -Be 'default::ifw_check::cpuload=16.25%;10;90;;'; + } + + It 'accepts string state names in SetState and AddMissingChecks' { + $ExitCode = & $script:IcingaModule { + $Package = [IcingaPlugin]::new('Services'); + $Package.AddCheck([IcingaPlugin]::new('Spooler').SetState('Warning', 'Manual warning', $true)).Commit(); + $Package.AddMissingChecks(@('MissingSvc'), @('Spooler'), '{0}', 'Service not found', 'Critical').Commit(); + $Package.Compile() + }; + $ExitCode | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Match '\[CRITICAL\] Services: 1 Critical 1 Warning'; + } + + It 'supports parameterless SetOk, SetWarning, SetCritical, SetUnknown, SetNotice and numeric Minimum/Maximum' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('Last Task Result', 1).Minimum(0).Maximum(255).SetCritical().Compile() + }; + $ExitCode | Should -Be 2; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[CRITICAL] Last Task Result: 1'; + $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData[0] | Should -Be 'default::ifw_check::lasttaskresult=1;;;0;255'; + + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('NoticePkg').SetNotice().Compile() + }; + $ExitCode | Should -Be 0; + $Global:IcingaForWindows.Private.Icinga.CheckResult.Output | Should -Be '[INFO] NoticePkg: Nothing to report'; + } + + It 'accepts TimeSpan and numeric objects directly in Warning() and Critical()' { + $ExitCode = & $script:IcingaModule { + [IcingaPlugin]::new('Duration', [TimeSpan]::FromMinutes(45)).Warning([TimeSpan]::FromMinutes(30)).Critical([TimeSpan]::FromHours(1)).CheckRange().Compile() + }; + $ExitCode | Should -Be 1; + $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;;'; + } + } +} diff --git a/Tests/New-IcingaPlugin.Tests.ps1 b/Tests/New-IcingaPlugin.Tests.ps1 new file mode 100644 index 0000000..5dffde2 --- /dev/null +++ b/Tests/New-IcingaPlugin.Tests.ps1 @@ -0,0 +1,76 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'New-IcingaPlugin' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + + # Daemon mode keeps Compile from writing to the console; the result is still + # stored in Private.Icinga.CheckResult. + $script:OriginalDaemonFlag = $Global:IcingaForWindows.Protected.IsBackgroundDaemon; + } + + AfterAll { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $script:OriginalDaemonFlag; + } + + BeforeEach { + $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $true; + } + + It 'creates an instance of the IcingaPlugin type loaded by the current runspace' { + $PluginType = & $script:IcingaModule { 'IcingaPlugin' -as [type] }; + $Plugin = New-IcingaPlugin 'Disks'; + + ($Plugin.GetType() -eq $PluginType) | Should -BeTrue; + } + + It 'creates a container from a name only' { + $Plugin = New-IcingaPlugin -Name 'Disks'; + + $Plugin.Name | Should -Be 'Disks'; + $Plugin.Value | Should -BeNullOrEmpty; + $Plugin.Unit | Should -Be ''; + } + + It 'creates a check from a name and a value' { + $Plugin = 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.Value | Should -Be 95; + $Plugin.Unit | Should -Be '%'; + } + + It 'binds name, value and unit by position' { + $Plugin = New-IcingaPlugin 'C:' 55 '%'; + + $Plugin.Name | Should -Be 'C:'; + $Plugin.Value | Should -Be 55; + $Plugin.Unit | Should -Be '%'; + } + + It 'returns a node whose fluent chain evaluates and compiles the check' { + $ExitCode = (New-IcingaPlugin '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.Compile() | Should -Be 1; + } +} diff --git a/Tests/Test-IcingaError.Tests.ps1 b/Tests/Test-IcingaError.Tests.ps1 new file mode 100644 index 0000000..9f54a34 --- /dev/null +++ b/Tests/Test-IcingaError.Tests.ps1 @@ -0,0 +1,35 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Test-IcingaError' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | + Select-Object -First 1; + } + + It 'returns $true for an IcingaError' { + $IcingaError = & $script:IcingaModule { ('IcingaError' -as [type])::new('Failed to query Win32_Service') }; + + Test-IcingaError -InputObject $IcingaError | Should -BeTrue; + } + + It 'returns $false for ' -TestCases @( + @{ 'Case' = '$null'; 'Value' = $null; }, + @{ 'Case' = 'a string'; 'Value' = 'Failed to query'; }, + @{ 'Case' = 'a number'; 'Value' = 3; }, + @{ 'Case' = 'a hashtable'; 'Value' = @{ 'Message' = 'Failed'; }; }, + @{ 'Case' = 'an empty array'; 'Value' = @(); }, + @{ 'Case' = 'an array'; 'Value' = @('a', 'b'); } + ) { + Test-IcingaError -InputObject $Value | Should -BeFalse; + } + + It 'returns $false for an array that contains an IcingaError' { + $IcingaError = & $script:IcingaModule { ('IcingaError' -as [type])::new('Failed') }; + + Test-IcingaError -InputObject @($IcingaError, 'b') | Should -BeFalse; + } +} diff --git a/build/Build-ModuleDocs.ps1 b/build/Build-ModuleDocs.ps1 index f3adf07..71e13eb 100644 --- a/build/Build-ModuleDocs.ps1 +++ b/build/Build-ModuleDocs.ps1 @@ -20,25 +20,25 @@ When `-Strict` is enabled (default), the generator fails with a non-zero exit code if any file violates these rules. .PARAMETER ModuleBasePath -| Name | Type | Description | Default | -|----------------|---------------|-------------------------------------------------------------------|----------------------------------| -| ModuleBasePath | System.String | Absolute path to the Icinga module root (the folder above `src`).| Resolved from the script path | +| Name | Type | Description | Default | +|----------------|---------------|--------------------------------------------------------------------|-------------------------------| +| ModuleBasePath | System.String | Absolute path to the Icinga module root (the folder above `src`). | Resolved from the script path | .PARAMETER OutputPath -| Name | Type | Description | Default | -|------------|---------------|----------------------------------------------------------|-----------------------------------------------| -| OutputPath | System.String | Directory where the generated Markdown files are written.| `\docs\api` | +| Name | Type | Description | Default | +|------------|---------------|-----------------------------------------------------------|-----------------------------| +| OutputPath | System.String | Directory where the generated Markdown files are written. | `\docs\api` | .PARAMETER IncludePrivate -| Name | Type | Description | Default | -|----------------|-------------------------|-------------------------------------------------------------------|---------| -| IncludePrivate | System.Boolean | When `$true`, private functions are documented too. When `$false`,| $true | -| | | only `Public/` functions are included. | | +| Name | Type | Description | Default | +|----------------|----------------|--------------------------------------------------------------------|---------| +| IncludePrivate | System.Boolean | When `$true`, private functions are documented too. When `$false`, | $true | +| | | only `Public/` functions are included. | | .PARAMETER Strict -| Name | Type | Description | Default | -|--------|-----------------|--------------------------------------------------------------------------|---------| -| Strict | System.Boolean | Fail with a non-zero exit code if any function violates the doc rules. | True | +| Name | Type | Description | Default | +|--------|----------------|------------------------------------------------------------------------|---------| +| Strict | System.Boolean | Fail with a non-zero exit code if any function violates the doc rules. | True | .OUTPUTS System.Int32 -- Number of Markdown files written. Throws on strict violations. @@ -61,10 +61,10 @@ violations, fix the help block in the source file. [CmdletBinding()] param ( - [string]$ModuleBasePath = $null, - [string]$OutputPath = $null, - [bool]$IncludePrivate = $true, - [bool]$Strict = $true + [string]$ModuleBasePath = $null, + [string]$OutputPath = $null, + [bool]$IncludePrivate = $true, + [bool]$Strict = $true ); $ErrorActionPreference = 'Stop'; @@ -103,9 +103,9 @@ function Read-IcingaHelpBlock() `$null` for the `Help` property so the caller can report it. .PARAMETER Path - | Name | Type | Description | Default | - |------|---------------|------------------------------------------|---------| - | Path | System.String | Absolute path to a Icinga `.ps1` source.| | + | Name | Type | Description | Default | + |------|---------------|-------------------------------------------|---------| + | Path | System.String | Absolute path to a Icinga `.ps1` source. | | .OUTPUTS System.Collections.Hashtable -- Parsed structure with keys: @@ -161,10 +161,10 @@ function Read-IcingaHelpBlock() $FunctionName = $FuncMatch.Groups[1].Value -replace '^Global:', ''; # Determine visibility from path - $Visibility = if ($Path -match '[\\/]Public[\\/]') { 'Public' } elseif ($Path -match '[\\/]Private[\\/]') { 'Private' } else { 'Unknown' }; + $Visibility = if ($Path -match '[\\/]Public[\\/]') { 'Public' } elseif ($Path -match '[\\/]Private[\\/]') { 'Private' } else { 'Unknown' }; # Pick the last help block that ends before the function declaration - $HelpMatch = $null; + $HelpMatch = $null; foreach ($block in $HelpBlocks) { if (($block.Index + $block.Length) -le $FuncMatch.Index) { $HelpMatch = $block; @@ -186,7 +186,7 @@ function Read-IcingaHelpBlock() # Split on top-level dot-prefixed section headers (.SYNOPSIS, .DESCRIPTION, etc.) # Section headers must be at line start (possibly after whitespace). - $Sections = [regex]::Split($HelpBody, '(?m)^\s*\.(?=[A-Z]+)'); + $Sections = [regex]::Split($HelpBody, '(?m)^\s*\.(?=[A-Z]+)'); foreach ($section in $Sections) { if ([string]::IsNullOrWhiteSpace($section)) { @@ -248,14 +248,14 @@ function Test-IcingaHelpCompleteness() strings (empty when the block is valid). .PARAMETER ParsedEntry - | Name | Type | Description | Default | - |-------------|-------------------------------|----------------------------------------------------------|---------| - | ParsedEntry | System.Collections.Hashtable | Output of `Read-IcingaHelpBlock`. | | + | Name | Type | Description | Default | + |-------------|------------------------------|-----------------------------------|---------| + | ParsedEntry | System.Collections.Hashtable | Output of `Read-IcingaHelpBlock`. | | .PARAMETER DeclaredParameters - | Name | Type | Description | Default | - |--------------------|----------------------|--------------------------------------------------------------------------|---------| - | DeclaredParameters | System.String[] | Parameter names found in the source file's `param( ... )` block. | @() | + | Name | Type | Description | Default | + |--------------------|-----------------|------------------------------------------------------------------|---------| + | DeclaredParameters | System.String[] | Parameter names found in the source file's `param( ... )` block. | @() | .OUTPUTS System.String[] -- Zero or more violation messages. @@ -332,9 +332,9 @@ function Get-IcingaDeclaredParameters() by the validator to detect undocumented parameters. .PARAMETER Path - | Name | Type | Description | Default | - |------|---------------|------------------------------------------|---------| - | Path | System.String | Absolute path to a Icinga `.ps1` source.| | + | Name | Type | Description | Default | + |------|---------------|-------------------------------------------|---------| + | Path | System.String | Absolute path to a Icinga `.ps1` source. | | .OUTPUTS System.String[] -- Parameter names (without `$` prefix). @@ -352,7 +352,7 @@ function Get-IcingaDeclaredParameters() [string]$Path ); - $Content = Get-Content -Path $Path -Raw -Encoding UTF8; + $Content = Get-Content -Path $Path -Raw -Encoding UTF8; # Locate the param block of the first function $FuncMatch = [regex]::Match($Content, '(?ms)function\s+[a-zA-Z0-9_\-:]+\s*\([^\)]*\)\s*\{(.*?)\}'); @@ -376,7 +376,7 @@ function Get-IcingaDeclaredParameters() # The token immediately before $Name is always a closing bracket of an # attribute or type annotation. Match exactly that to avoid picking up # $null / $false / $true used as default values. - $Names = [regex]::Matches($ParamBody, '\]\s*\$([a-zA-Z_][a-zA-Z0-9_]*)'); + $Names = [regex]::Matches($ParamBody, '\]\s*\$([a-zA-Z_][a-zA-Z0-9_]*)'); return @($Names | ForEach-Object { $_.Groups[1].Value } | Select-Object -Unique); } @@ -395,7 +395,7 @@ $BuildStartTime = Get-Date; Write-Host "[1/4] Discovering source files in $SourcePath ..." -ForegroundColor Yellow; -$SourceFiles = Get-ChildItem -Path $SourcePath -Recurse -Filter '*.ps1'; +$SourceFiles = Get-ChildItem -Path $SourcePath -Recurse -Filter '*.ps1' | Sort-Object FullName; if (-not $IncludePrivate) { $SourceFiles = $SourceFiles | Where-Object { $_.FullName -match '[\\/]Public[\\/]' }; @@ -454,7 +454,7 @@ if (Test-Path -Path $OutputPath) { } # Group functions by component (relative path under src/, up to and including the subcomponent) -$Grouped = $Parsed | Group-Object -Property { +$Grouped = $Parsed | Group-Object -Property { $rel = $_.File.Substring($SourcePath.Length).TrimStart('\', '/'); $parts = $rel -split '[\\/]'; # parts: , , {Public|Private}, .ps1 @@ -467,19 +467,19 @@ $Grouped = $Parsed | Group-Object -Property { $WrittenFiles = 0; foreach ($group in ($Grouped | Sort-Object Name)) { - $componentName = $group.Name; - $outFile = Join-Path -Path $OutputPath -ChildPath ("Icinga.$componentName.md"); + $componentName = $group.Name; + $outFile = Join-Path -Path $OutputPath -ChildPath ("Icinga.$componentName.md"); [System.Text.StringBuilder]$md = New-Object System.Text.StringBuilder; [void]$md.AppendLine("# Icinga.$componentName"); [void]$md.AppendLine(); - $srcDir = $componentName.Replace('.', '/'); + $srcDir = $componentName.Replace('.', '/'); [void]$md.AppendLine('*Auto-generated from `src/' + $srcDir + '/`. Do not edit by hand -- run `build/Build-ModuleDocs.ps1` to regenerate.*'); [void]$md.AppendLine(); - $publicFns = $group.Group | Where-Object { $_.Visibility -eq 'Public' } | Sort-Object FunctionName; - $privateFns = $group.Group | Where-Object { $_.Visibility -eq 'Private' } | Sort-Object FunctionName; + $publicFns = @($group.Group | Where-Object { $_.Visibility -eq 'Public' } | Sort-Object { $_.FunctionName }); + $privateFns = @($group.Group | Where-Object { $_.Visibility -eq 'Private' } | Sort-Object { $_.FunctionName }); if ($publicFns.Count -gt 0) { [void]$md.AppendLine('## Public functions'); @@ -566,12 +566,12 @@ foreach ($group in ($Grouped | Sort-Object Name)) { [void]$md.AppendLine(); } - Set-Content -Path $outFile -Value $md.ToString() -Encoding UTF8 -Force; + [System.IO.File]::WriteAllText($outFile, ($md.ToString() -replace "`r`n", "`n"), (New-Object System.Text.UTF8Encoding($false))); $WrittenFiles++; } # Index file -$indexFile = Join-Path -Path $OutputPath -ChildPath 'index.md'; +$indexFile = Join-Path -Path $OutputPath -ChildPath 'index.md'; [System.Text.StringBuilder]$idx = New-Object System.Text.StringBuilder; [void]$idx.AppendLine('# Icinga API Reference'); [void]$idx.AppendLine(); @@ -581,8 +581,8 @@ $indexFile = Join-Path -Path $OutputPath -ChildPath 'index.md'; [void]$idx.AppendLine('|-----------|------------------|-----------------|'); foreach ($group in ($Grouped | Sort-Object Name)) { - $pubCount = ($group.Group | Where-Object { $_.Visibility -eq 'Public' }).Count; - $prvCount = ($group.Group | Where-Object { $_.Visibility -eq 'Private' }).Count; + $pubCount = @($group.Group | Where-Object { $_.Visibility -eq 'Public' }).Count; + $prvCount = @($group.Group | Where-Object { $_.Visibility -eq 'Private' }).Count; [void]$idx.AppendLine("| [Icinga.$($group.Name)](Icinga.$($group.Name).md) | $pubCount | $prvCount |"); } @@ -594,7 +594,7 @@ foreach ($group in ($Grouped | Sort-Object Name)) { [void]$idx.AppendLine("- Public: $($Parsed | Where-Object { $_.Visibility -eq 'Public' } | Measure-Object | Select-Object -ExpandProperty Count)"); [void]$idx.AppendLine("- Private: $($Parsed | Where-Object { $_.Visibility -eq 'Private' } | Measure-Object | Select-Object -ExpandProperty Count)"); -Set-Content -Path $indexFile -Value $idx.ToString() -Encoding UTF8 -Force; +[System.IO.File]::WriteAllText($indexFile, ($idx.ToString() -replace "`r`n", "`n"), (New-Object System.Text.UTF8Encoding($false))); $WrittenFiles++; Write-Host " * Wrote $WrittenFiles Markdown file(s)" -ForegroundColor Green; diff --git a/build/Build-ModuleProject.ps1 b/build/Build-ModuleProject.ps1 index db01bd0..374ef4c 100644 --- a/build/Build-ModuleProject.ps1 +++ b/build/Build-ModuleProject.ps1 @@ -43,9 +43,9 @@ function Read-IcingaSourceFile() [System.IO.FileShare]::Read ); - $ReadArray = New-Object Byte[] $FileStream.Length; - $UTF8Encoding = New-Object System.Text.UTF8Encoding $false; - $FileContent = ''; + $ReadArray = New-Object Byte[] $FileStream.Length; + $UTF8Encoding = New-Object System.Text.UTF8Encoding $false; + $FileContent = ''; while ($FileStream.Read($ReadArray, 0, $ReadArray.Length)) { $FileContent = [System.String]::Concat($FileContent, $UTF8Encoding.GetString($ReadArray)); @@ -53,7 +53,7 @@ function Read-IcingaSourceFile() $FileStream.Dispose(); - return $FileContent; + return $FileContent.TrimStart([char]0xFEFF); } function Remove-IcingaComments() @@ -111,7 +111,7 @@ function Write-IcingaSourceFile() [System.IO.FileShare]::Read ); - $ContentBytes = [System.Text.Encoding]::UTF8.GetBytes($Value); + $ContentBytes = [System.Text.Encoding]::UTF8.GetBytes($Value); $FileStream.Write($ContentBytes, 0, $ContentBytes.Length); $FileStream.Dispose(); } @@ -134,8 +134,8 @@ function Get-IcingaModuleStructure() }; [int]$FileCount = 0; - $PowerShellSourcePath = Join-Path -Path $ModuleBasePath -ChildPath 'src\'; - [array]$SourceFiles = Get-ChildItem -Path $PowerShellSourcePath -Recurse -Filter '*.ps1'; + $PowerShellSourcePath = Join-Path -Path $ModuleBasePath -ChildPath 'src\'; + [array]$SourceFiles = Get-ChildItem -Path $PowerShellSourcePath -Recurse -Filter '*.ps1'; foreach ($sourceFile in $SourceFiles) { $FileCount += 1; @@ -164,7 +164,7 @@ Write-Host "| Icinga for Windows - Module Compiler Write-Host "| |" -ForegroundColor Cyan; Write-Host "+---------------------------------------------------------------------+`n" -ForegroundColor Cyan; -$BuildStartTime = Get-Date +$BuildStartTime = Get-Date # First we need to analyze the module structure and gather all components Write-Host "[1/4] Analyzing module structure..." -ForegroundColor Yellow; @@ -258,7 +258,7 @@ foreach ($privateFile in $Components['Private']) { # Append all public functions once Write-Host " * Appending $($Components['Public'].Count) public function file(s)..." -ForegroundColor White; foreach ($publicFile in $Components['Public']) { - $FileContent = Read-IcingaSourceFile -Path $publicFile; + $FileContent = Read-IcingaSourceFile -Path $publicFile; $FunctionMatches = [regex]::Matches($FileContent, '(?m)^\s*function\s+([a-zA-Z0-9_-]+)'); diff --git a/build/Invoke-ModuleTests.ps1 b/build/Invoke-ModuleTests.ps1 index 73eb70d..a8b04cb 100644 --- a/build/Invoke-ModuleTests.ps1 +++ b/build/Invoke-ModuleTests.ps1 @@ -28,7 +28,7 @@ the build job produces those artifacts; locally run | Path | System.String | Directory containing the `*.Tests.ps1` files to execute. | `\Tests` | .OUTPUTS -System.Object — The Pester result object. Throws when one or more +System.Object -- The Pester result object. Throws when one or more tests fail. .EXAMPLE @@ -116,7 +116,7 @@ $PesterConfiguration.TestResult.Enabled = $true; $PesterConfiguration.TestResult.OutputPath = Join-Path -Path $ModuleBasePath -ChildPath 'TestResults.xml'; $PesterConfiguration.TestResult.OutputFormat = 'NUnitXml'; -$TestResults = Invoke-Pester -Configuration $PesterConfiguration; +$TestResults = Invoke-Pester -Configuration $PesterConfiguration; Write-Host '' -ForegroundColor White; Write-Host '[2/2] Evaluating results ...' -ForegroundColor Yellow; diff --git a/docs/Developer/Plugins/01-Architecture-and-Concepts.md b/docs/Developer/Plugins/01-Architecture-and-Concepts.md new file mode 100644 index 0000000..cfb121b --- /dev/null +++ b/docs/Developer/Plugins/01-Architecture-and-Concepts.md @@ -0,0 +1,166 @@ +# Plugin Architecture and Core Concepts + +Icinga for Windows provides a unified, fluent object model for building monitoring check plugins. Instead of splitting check items, check packages, and result compilation across three separate cmdlets (`New-IcingaCheck`, `New-IcingaCheckPackage`, and `New-IcingaCheckResult`), every check node, container package, and root plugin is represented by a single class: **`IcingaPlugin`**, instantiated through the runspace-safe factory cmdlet **[`New-IcingaPlugin`](02-IcingaPlugin-Reference.md#1-new-icingaplugin-factory-cmdlet)**. + +This document explains how the plugin architecture works under the hood, how nodes are structured and evaluated, and which rules must be followed when developing plugins. + +* **[01 - Plugin Architecture and Core Concepts](01-Architecture-and-Concepts.md)** *(this page)* +* **[02 - IcingaPlugin Technical Reference](02-IcingaPlugin-Reference.md)** +* **[03 - Result and Error Objects (`IcingaCheckResult` & `IcingaError`)](03-Result-and-Error-Objects.md)** +* **[04 - Step-by-Step Developer Guide: Writing a Custom Plugin](04-Custom-Plugin-Developer-Guide.md)** + +--- + +## 1. Unified Node Model: Checks, Containers, and Hybrid Nodes + +Every node created by `New-IcingaPlugin` is an instance of `IcingaPlugin` that can act in one of four roles depending on how it is constructed and used: + +| Role | Construction | Behaviour | +|------|--------------|-----------| +| **Container (Check Package)** | `New-IcingaPlugin 'Disks'` | Holds no measured value of its own (`Value = $null`). Aggregates child nodes added via `.AddCheck()` according to its operator (`CheckAnd`, `CheckOr`, `CheckNone`, `CheckMinimum`, `CheckMaximum`). | +| **Leaf Check** | `New-IcingaPlugin 'C: Used' 75 '%'` | Holds a measured `Value` and an optional `Unit`. Evaluates the value against warning/critical thresholds and emits performance data. | +| **Hybrid Node** | `(New-IcingaPlugin 'Cluster' 1).Warning('1').CheckRange()` + `.AddCheck(...)` | Carries both its own evaluated `Value` and child checks. Its own evaluated state counts as one additional element alongside its children during aggregation. | +| **Informational Notice (`[INFO]`)** | `(New-IcingaPlugin 'Driver' 'v1.2').SetNotice()` or unevaluated leaf | Renders with an `[INFO]` prefix, always stays in state `OK` (`0`), and is excluded from parent state aggregation and root summary counts. | + +Because containers and leaf checks share the same class, trees can be nested to arbitrary depth (for example: a root package `Scheduled Tasks` -> per-folder sub-packages `\Icinga\` -> per-task sub-packages `Renew Certificate` -> leaf checks `State`, `Missed Runs`, `Last Run Time`, `Last Task Result`). + +--- + +## 2. Fluent Chaining: `.Commit()` vs. `.Compile()` + +Every configuration setter, comparison method, state override, and tree operation on `IcingaPlugin` returns `$this` (the node itself) so calls can be chained fluently. + +Because PowerShell sends any uncaptured return value to the output pipeline, **every fluent chain must be consumed** by an assignment, passed as an argument to `.AddCheck(...)`, or terminated with `.Commit()` or `.Compile()`: + +* **`.Commit()`** has a `[void]` return type. Use it at the end of every non-returning configuration or `.AddCheck(...)` statement so the node is not leaked to the PowerShell pipeline (replacing `| Out-Null` or `[void]` casts). +* **`.Compile()`** resolves the entire check tree, writes the formatted plugin output and performance data to the console (when running on the main thread), stores an [`IcingaCheckResult`](03-Result-and-Error-Objects.md#1-icingacheckresult-class) in `$Global:IcingaForWindows.Private.Icinga.CheckResult`, and returns the numeric Icinga exit code (`0` OK, `1` WARNING, `2` CRITICAL, `3` UNKNOWN). Use `return $CheckPackage.Compile();` as the final return statement of your plugin. + +```powershell +$CheckPackage = New-IcingaPlugin 'Partition Space'; + +$DiskCheck = (New-IcingaPlugin 'Partition C:' 442692000000 'B').BaseValue('500GiB').Minimum(0).Maximum(536870912000); +$DiskCheck.MetricIndex('c').MetricLabel('Used Space').Warning('80%').Critical('90%').CheckRange().Commit(); + +$CheckPackage.AddCheck($DiskCheck).Commit(); + +return $CheckPackage.Compile(); +``` + +> **PowerShell Multiline Chaining Note:** If you split a fluent method chain across multiple lines in PowerShell, keep the dot `.` at the **end** of each line (not at the start of the next line), or assign the intermediate node to a variable as shown above. + +--- + +## 3. Runspace and Threading Safety (No Class Literals in Functions) + +Icinga for Windows loads its PowerShell classes (`lib/IcingaForWindows.Classes.ps1`) separately into each runspace, whereas all runspaces dot-source the shared compiled kernel (`lib/IcingaForWindows.Kernel.ps1`). + +In Windows PowerShell 5.1, a class literal such as `[IcingaPlugin]::new()` or `-is [IcingaError]` inside a function is bound at parse time to the class type of the **main** runspace: + +1. **Cross-thread stalls:** Calling a constructor or method on the main runspace's class type from a background worker thread blocks until the main runspace is idle, which stalls background daemons and API workers. +2. **Type mismatches:** An `IcingaError` created with a worker thread's own runspace type does not match `-is [IcingaError]` against the main runspace's type. + +Therefore, **functions outside `src/Classes` must never use class literals**: + +| Task | Forbidden (Class Literal) | Required (Runspace-Safe) | +|------|---------------------------|--------------------------| +| Create a plugin node | `[IcingaPlugin]::new('Disks')` | `New-IcingaPlugin 'Disks'` | +| Test for an `IcingaError` | `$Data -is [IcingaError]` | `Test-IcingaError -InputObject $Data` | +| Create an `IcingaError` | `[IcingaError]::new('Failed')` | `('IcingaError' -as [type])::new('Failed')` | + +> **Note:** Native PowerShell `enum` types (such as `[IcingaServiceStatus]` or `[IcingaScheduledTaskStatus]`) contain no script methods and convert by value, so enum literals are safe to use in `param()` blocks and function bodies. This rule is enforced by `Tests/ClassLiteral.Tests.ps1`. For full background threading details, see [Icinga for Windows Threading](../Threading/01-Threading.md#classes-and-threads). + +--- + +## 4. Units, Automatic Conversions, and Threshold Syntax + +### Supported Units + +When creating a leaf check via `New-IcingaPlugin -Name -Value -Unit `, the `Unit` parameter controls both how the value is formatted in human-readable output and how thresholds and performance data are emitted. + +Specifically, `IcingaPlugin` treats `'B'` (bytes) and `'s'` (seconds) as **base units** (`HasBaseUnit()`), which unlock automatic unit conversion in `IcingaThresholds` and human-readable output formatting via `IcingaUnit`: + +| Unit | Category | Output Behaviour | Performance Data & Threshold Behaviour | +|------|----------|------------------|----------------------------------------| +| `''` *(empty)* | Dimensionless | Prints the raw number or string (`42`, `'Running'`). | Emits bare numeric value (`42;80;90;;`). | +| `'%'` | Percentage | Appends `%` to numeric values and thresholds (`75% is greater than threshold 70%`). | Emits `%` unit (`75%;70;85;0;100`). Thresholds passed as `'70%'` or `'70'` both work without requiring `.BaseValue(100)`. | +| `'B'` | Byte base unit | Converts `B` figures in output messages to the best-fitting binary unit via `IcingaUnit` (e.g. `442692000000B` renders as `412.29GiB`). Supports negative byte values as well. | Emits base bytes (`442692000000B;400000000000;450000000000;0;500000000000`). Thresholds given in any byte unit (`'400GB'`, `'500MiB'`) or as a percentage (`'80%'` with `.BaseValue()`) are resolved to bytes. | +| `'s'` | Time base unit | Decomposes `s` figures in output messages into readable durations via `IcingaUnit` (e.g. `93784s` renders as `1d 2h 3m 4s`; sub-second durations below `1s` are handed to the threshold engine as `ms` or `us` to preserve precision). | Emits base seconds (`93784s;86400;172800;;`). Thresholds given as `'30m'`, `'2h'`, `'7d'`, or `[TimeSpan]` objects are resolved to seconds. | +| `'c'` | Continuous counter | Suppresses `'c'` in the human-readable output message (`120 is greater than threshold 100`). | Appends `'c'` to the performance data value (`120c;100;200;;`) as required by Icinga 2 for continuous counters. | +| Any other unit (e.g. `'GiB'`, `'ms'`, `'rpm'`) | Display unit | Appends the unit string as a display suffix to bare numbers in the output message (`1500rpm is greater than threshold 1200rpm`). | Emits the unit string verbatim in performance data without unit-family conversion. | + +### Automatic `[TimeSpan]` Handling + +You can pass a `[TimeSpan]` directly as the node's `Value`, `BaseValue()`, `Warning()`, or `Critical()` threshold: + +* In `New-IcingaPlugin 'Last Run' ([datetime]::Now - $LastRun)`: `Initialize()` automatically converts the `[TimeSpan]` to `.TotalSeconds` and defaults an empty `Unit` to `'s'`. +* In `.BaseValue([TimeSpan]::FromHours(24))`: converts the base value to `.TotalSeconds`. +* In `.Warning([TimeSpan]::FromMinutes(30))` or `.Warning(@([TimeSpan]::FromMinutes(30)))`: `ConvertThresholdEntry()` converts the `[TimeSpan]` to `'1800s'`. + +### Icinga Range Threshold Syntax (`CheckRange`) + +The primary numeric comparison method `.CheckRange()` evaluates Icinga / Nagios range expressions: + +| Expression | Alert Condition (Outside Range) | Description | +|------------|---------------------------------|-------------| +| `'10'` | `< 0` or `> 10` | Alert when value is below `0` or above `10`. | +| `'10:'` | `< 10` | Alert when value is below `10`. | +| `'~:10'` | `> 10` | Alert when value is above `10` (negative values allowed). | +| `'10:20'` | `< 10` or `> 20` | Alert when value is outside `10..20`. | +| `'@10:20'` | `>= 10` and `<= 20` | Alert when value is **inside** `10..20` (inclusive). | + +--- + +## 5. Value and Threshold Translations (`.Translate()`) + +Many Windows APIs report status values as integers or enums (for example `Win32_Service` status `4` for `Running`, Task Scheduler state `3` for `Ready`, or sentinel timestamp `0` for `Never`). + +Calling `.Translate()` on a leaf check separates the **human-readable display text** from the **numeric performance data**: + +1. **Enum values (`.Translate()`):** When `Value` is an enum instance (e.g. `[IcingaScheduledTaskStatus]::Ready`), `.Translate()` caches the enum member name (`'Ready'`) in `TranslatedText` for display and string/list comparisons while `ResolveNumericValue()` emits `[int]$Value` (`3`) in performance data. +2. **Lookup hashtable (`.Translate([hashtable])`):** Stores a mapping table (e.g. `@{ 0 = 'Never' }` or `@{ 4 = 'Running'; 1 = 'Stopped' }`) in `Translation`. Both the node's `Value` and threshold tokens (e.g. `.Critical('Running')` or `.Critical(4)`) are resolved through this table for output messages (`[INFO] Next Run Time [Never]: Never` or `[CRITICAL] State: 'Stopped' does not equal pattern 'Running'`) while `ResolvePerfDataThreshold()` maps a single translated threshold name back to its numeric key (`4`) in performance data. +3. **Direct display string (`.Translate([string])`):** Overrides `TranslatedText` for the current `Value` directly while keeping the numeric `Value` for threshold evaluation and performance data. + +--- + +## 6. Multi-Value Thresholds and List Comparisons + +Plugins often accept an array of allowed or forbidden states/patterns (for example `-State @('Ready', 'Running')` or `-Status @('Running')`). `IcingaPlugin` natively supports array thresholds via `.Warning([array])` and `.Critical([array])`: + +* **`.CheckIn()`** (alias for `.CheckEqual()`): Uses case-insensitive string equality and raises WARNING/CRITICAL when the value **equals any** entry in the threshold list (e.g. forbidden states). Output on match: `"'Paused' equals pattern 'Paused'"`. +* **`.CheckNotIn()`** (alias for `.CheckNotEqual()`): Uses case-insensitive string inequality and raises WARNING/CRITICAL when the value **does not equal any** entry in the allowed threshold list (e.g. required states such as `-State @('Ready', 'Running')`). Output on mismatch: `"'Disabled' does not equal pattern 'Ready, Running'"`. +* **`.CheckLike()` / `.CheckNotLike()`**: Evaluate the value against one or more PowerShell wildcard patterns (`-like`). +* **`.CheckMatch()` / `.CheckNotMatch()`**: Evaluate the value against one or more regular expressions. Invalid regex patterns in a list safely resolve the check to `UNKNOWN` (`3`) with an explanatory error message instead of throwing. + +--- + +## 7. Performance Data Format (`check_multi`) + +Every leaf check whose value is numeric (or resolves numerically via enum/translation) emits a performance-data metric in the Icinga for Windows `check_multi` format: + +```text +::ifw_