From 4411dcccba89cb1294b8a7d82c00e7ca6e569260 Mon Sep 17 00:00:00 2001 From: Fabian Thomys Date: Fri, 28 Aug 2026 15:13:15 +0200 Subject: [PATCH 1/5] Add IcingaPlugin --- CLAUDE.md | 22 +- IcingaForWindows.psm1 | 3 + Tests/ClassLiteral.Tests.ps1 | 2 + Tests/IcingaError.Tests.ps1 | 57 + Tests/IcingaPlugin.Tests.ps1 | 540 +++ Tests/New-IcingaPlugin.Tests.ps1 | 76 + Tests/Test-IcingaError.Tests.ps1 | 35 + docs/Developer/Threading/01-Threading.md | 52 + src/Classes/Icinga/IcingaCheckResult.ps1 | 113 + src/Classes/Icinga/IcingaError.ps1 | 209 ++ src/Classes/Icinga/IcingaPlugin.ps1 | 3066 +++++++++++++++++ .../ErrorHandling/Public/Test-IcingaError.ps1 | 38 + .../Private/Start-IcingaProtocolWorker.ps1 | 49 +- src/Plugins/Public/New-IcingaPlugin.ps1 | 71 + 14 files changed, 4319 insertions(+), 14 deletions(-) create mode 100644 Tests/IcingaError.Tests.ps1 create mode 100644 Tests/IcingaPlugin.Tests.ps1 create mode 100644 Tests/New-IcingaPlugin.Tests.ps1 create mode 100644 Tests/Test-IcingaError.Tests.ps1 create mode 100644 src/Classes/Icinga/IcingaCheckResult.ps1 create mode 100644 src/Classes/Icinga/IcingaError.ps1 create mode 100644 src/Classes/Icinga/IcingaPlugin.ps1 create mode 100644 src/Core/ErrorHandling/Public/Test-IcingaError.ps1 create mode 100644 src/Plugins/Public/New-IcingaPlugin.ps1 diff --git a/CLAUDE.md b/CLAUDE.md index a2bb6ea..bd75f2f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -136,6 +136,26 @@ Levels: `Debug`, `Output`, `Audit`, `Info`, `Success`, `Warning`, `Error`, `Fata - ❌ Backticks for line continuation. Use natural pipeline breaks or splatting. - ❌ `-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). --- @@ -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..767a5e6 100644 --- a/IcingaForWindows.psm1 +++ b/IcingaForWindows.psm1 @@ -192,6 +192,9 @@ function New-ModuleBaseEnvironment() 'Logging' = [PSCustomObject]@{ 'CurrentLoggingId' = (New-Guid); }; + 'Icinga' = [PSCustomObject]@{ + 'CheckResult' = $null; + }; }; 'Protected' = [PSCustomObject]@{ 'Initialized' = $false; 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..148efc4 --- /dev/null +++ b/Tests/IcingaPlugin.Tests.ps1 @@ -0,0 +1,540 @@ +$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; + } + } +} diff --git a/Tests/New-IcingaPlugin.Tests.ps1 b/Tests/New-IcingaPlugin.Tests.ps1 new file mode 100644 index 0000000..9acc43b --- /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/docs/Developer/Threading/01-Threading.md b/docs/Developer/Threading/01-Threading.md index ff9ada1..571583d 100644 --- a/docs/Developer/Threading/01-Threading.md +++ b/docs/Developer/Threading/01-Threading.md @@ -195,6 +195,58 @@ If you are missing `IcingaThreadProcessing`, Icinga for Windows will flag the th The thread (dedb8fbb-5309-4173-bee8-847db488cf62, Start-IcingaProtocolListener) is marked as WaitForJobs, but you did not use "Set-ThreadProcessing" after a job was taken to update the thread state accordingly.; ``` +## Classes and Threads + +Icinga for Windows loads its PowerShell classes (`lib/IcingaForWindows.Classes.ps1`) separately into every runspace, while all runspaces dot-source the same compiled kernel (`lib/IcingaForWindows.Kernel.ps1`). PowerShell resolves a class literal such as `[IcingaPlugin]` inside the kernel only once, so inside every thread the literal still points to the class type of the **main** runspace. + +On Windows PowerShell 5.1 this has two effects: + +* **Stalls:** the script code of a class belongs to the runspace that loaded its type. A thread that calls a constructor, method or static method of the main runspace's type waits until the main runspace is idle. The main runspace of the service is always busy, so the thread hangs. +* **Type mismatch:** an object created with the thread's own type is not `-is` the main runspace's type, and handing it to a typed parameter fails with `Cannot convert the "IcingaError" value of type "IcingaError" to type "IcingaError"`. + +Functions therefore never use class literals. They resolve the class at runtime, which returns the type the current runspace loaded itself: + +```powershell +# Wrong: inside a thread these resolve to the main runspace's classes +$CheckPackage = [IcingaPlugin]::new('Services'); +$Services = Get-IcingaWindowsInformation -ClassName 'Win32_Service'; + +if ($Services -is [IcingaError]) { + return $CheckPackage.SetError($Services).Compile(); +} + +# Right +$CheckPackage = New-IcingaPlugin 'Services'; +$Services = Get-IcingaWindowsInformation -ClassName 'Win32_Service'; + +if (Test-IcingaError -InputObject $Services) { + return $CheckPackage.SetError($Services).Compile(); +} + +# Other classes: look the type up once, before the loop +$UnitType = 'IcingaUnit' -as [type]; + +foreach ($File in (Get-ChildItem -Path 'C:\Windows\Logs' -File)) { + $Size = $UnitType::new([string]$File.Length, 'B', '', $false).OutputString; +} +``` + +Class instances also never leave the thread that created them. Pass only primitive values, hashtables and arrays to other threads or into the `Public` space. For a plugin that is the rendered output, the exit code and the performance data, as `Start-IcingaProtocolWorker` does: + +```powershell +$ExitCode = & $ExecuteCommand; +$CheckResultOutput = $Global:IcingaForWindows.Private.Icinga.CheckResult.ToString(); +[array]$PerfData = $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData; + +$CheckResultData = @{ + 'output' = $CheckResultOutput; + 'exit_status' = $ExitCode; + 'performance_data' = $PerfData; +}; +``` + +The rule applies to all code outside `src/Classes` (see `CLAUDE.md`, section 2.9) and is checked by `Tests/ClassLiteral.Tests.ps1`. Enums are exempt, as they contain no script code and convert by value. + ## Current Thread Status You can display the current status of your Icinga for Windows threads by using the command `Show-IcingaThreads`. This command will print the current active threads for the local PowerShell session, but also query the Icinga for Windows API at the same time, to receive the status of all active threads within the daemon. diff --git a/src/Classes/Icinga/IcingaCheckResult.ps1 b/src/Classes/Icinga/IcingaCheckResult.ps1 new file mode 100644 index 0000000..d21c938 --- /dev/null +++ b/src/Classes/Icinga/IcingaCheckResult.ps1 @@ -0,0 +1,113 @@ +<# +.SYNOPSIS +Immutable result of a compiled Icinga plugin run + +.DESCRIPTION +IcingaCheckResult is the value object produced by IcingaPlugin.Compile(). It +carries the three artefacts a monitoring backend needs: the numeric Icinga plugin +exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN), the rendered multi-line plugin +output and the collected performance-data metrics as a flat array of strings. + +Compile() stores an instance of this class in the thread-local runtime state at +$Global:IcingaForWindows.Private.Icinga.CheckResult so that a background daemon or +the REST API can read the result of a check that was executed in a worker thread, +instead of the output being written to the console. + +.OUTPUTS +IcingaCheckResult — Result container exposing ExitCode, Output and PerformanceData. + +.EXAMPLE +PS> [IcingaCheckResult]::new(2, '[CRITICAL] Load: 95%', @("load=95%;80;90;0;100")) + +.NOTES +Plain data container; performs no evaluation itself. Safe to construct in +multi-threaded runspaces. +#> +class IcingaCheckResult +{ + [int]$ExitCode = 0; + [string]$Output = ''; + [array]$PerformanceData = @(); + + <# + .SYNOPSIS + Create an empty check result + + .DESCRIPTION + Creates a result with an OK exit code, an empty output and no performance data. + Used as the initial, not-yet-compiled placeholder. + + .OUTPUTS + IcingaCheckResult — Empty result instance. + + .EXAMPLE + PS> [IcingaCheckResult]::new() + + .NOTES + Values are meant to be replaced by a later Compile() run. + #> + IcingaCheckResult() + { + } + + <# + .SYNOPSIS + Create a check result from a compiled plugin + + .DESCRIPTION + Stores the numeric Icinga exit code, the rendered plugin output and the + collected performance-data metrics. + + .PARAMETER ExitCode + | Name | Type | Description | Default | + |----------|--------------|------------------------------------------------------|---------| + | ExitCode | System.Int32 | Icinga plugin state: 0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN. | | + + .PARAMETER Output + | Name | Type | Description | Default | + |--------|---------------|-------------------------------------------------|---------| + | Output | System.String | Rendered, possibly multi-line, plugin output. | | + + .PARAMETER PerformanceData + | Name | Type | Description | Default | + |-----------------|----------------|--------------------------------------------------|---------| + | PerformanceData | System.Array | Performance-data metrics, one string per metric. | | + + .OUTPUTS + IcingaCheckResult — Configured result instance. + + .EXAMPLE + PS> [IcingaCheckResult]::new(0, '[OK] Load: 5%', @("load=5%;80;90;0;100")) + + .NOTES + Does not modify global state; the caller decides where to store the instance. + #> + IcingaCheckResult([int]$ExitCode, [string]$Output, [array]$PerformanceData) + { + $this.ExitCode = $ExitCode; + $this.Output = $Output; + $this.PerformanceData = $PerformanceData; + } + + <# + .SYNOPSIS + Return the rendered plugin output + + .DESCRIPTION + Returns the Output message so the result renders as its plugin output when used + in string context. + + .OUTPUTS + System.String — The Output message. + + .EXAMPLE + PS> $result.ToString() + + .NOTES + Internal formatting helper. + #> + [string] ToString() + { + return $this.Output; + } +} diff --git a/src/Classes/Icinga/IcingaError.ps1 b/src/Classes/Icinga/IcingaError.ps1 new file mode 100644 index 0000000..bf4f9e6 --- /dev/null +++ b/src/Classes/Icinga/IcingaError.ps1 @@ -0,0 +1,209 @@ +<# +.SYNOPSIS +Structured error object returned by data collection functions instead of throwing + +.DESCRIPTION +IcingaError describes why a data collection step failed, so a function that +gathers data for a plugin (for example Get-IcingaWindowsInformation) can return +it in place of the data instead of throwing. The caller checks the result with +Test-IcingaError and hands it to IcingaPlugin.SetError, which puts the node into +UNKNOWN with the error message. + +Message holds the final, human-readable text. It can be built from a format +string and arguments in the style of [string]::Format ('Failed to query {0}', +'Win32_Service'). ReturnCode carries the semantic key of the return-code table +(Set-InternalExitCodes) when the error went through Write-FunctionReturnValue, +and Data holds the context values of the failure. + +.OUTPUTS +IcingaError — Error object with message, return code and context data. + +.EXAMPLE +PS> ('IcingaError' -as [type])::new('Failed to query the class {0}: {1}', @('Win32_Service', 'Access denied')) + +Creates an error with the message 'Failed to query the class Win32_Service: +Access denied'. + +.NOTES +Pure data object without external dependencies. Defined before IcingaPlugin in +the kernel, so IcingaPlugin may use it as a parameter type. + +Functions create and test errors through the type of the current runspace +(('IcingaError' -as [type]) and Test-IcingaError), never with an [IcingaError] +literal. Every runspace shares the compiled kernel, so the literal resolves to +the type of the main runspace; inside a background thread the error would then +not match the thread's own IcingaError type that IcingaPlugin.SetError expects. +#> +class IcingaError +{ + [string]$Message = ''; + [string]$ReturnCode = ''; + [hashtable]$Data = @{ }; + + <# + .SYNOPSIS + Create an error from a plain message + + .DESCRIPTION + Creates an error whose message is used verbatim, without format processing, + so braces such as those of volume GUIDs are kept as they are. + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|------------------------------|---------| + | Message | System.String | Human-readable error message. | | + + .OUTPUTS + IcingaError — The error object. + + .EXAMPLE + PS> ('IcingaError' -as [type])::new('The performance counter category is missing') + + .NOTES + No format processing is applied. + #> + IcingaError([string]$Message) + { + $this.Message = $Message; + } + + <# + .SYNOPSIS + Create an error from a format string and its arguments + + .DESCRIPTION + Creates an error whose message is the format string with its placeholders + ('{0}', '{1}', ...) replaced by the arguments, like [string]::Format. + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|---------------------------------------------|---------| + | Message | System.String | Format string with '{0}'-style placeholders. | | + + .PARAMETER Arguments + | Name | Type | Description | Default | + |-----------|-----------------|--------------------------------------|---------| + | Arguments | System.Object[] | Values inserted into the placeholders. | | + + .OUTPUTS + IcingaError — The error object. + + .EXAMPLE + PS> ('IcingaError' -as [type])::new('Failed to query {0}', @('Win32_Volume')) + + .NOTES + See FormatMessage for the handling of invalid format strings. + #> + IcingaError([string]$Message, [object[]]$Arguments) + { + $this.Message = [IcingaError]::FormatMessage($Message, $Arguments); + } + + <# + .SYNOPSIS + Create an error that belongs to a return code of the return-code table + + .DESCRIPTION + Creates an error with a semantic return code key (as used by + Write-FunctionReturnValue), the final message and the context data of the + failure. + + .PARAMETER ReturnCode + | Name | Type | Description | Default | + |------------|---------------|-----------------------------------------------|---------| + | ReturnCode | System.String | Semantic key of the return-code table entry. | | + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|-------------------------------|---------| + | Message | System.String | Human-readable error message. | | + + .PARAMETER Data + | Name | Type | Description | Default | + |------|------------------------------|---------------------------------|---------| + | Data | System.Collections.Hashtable | Context values of the failure. | | + + .OUTPUTS + IcingaError — The error object. + + .EXAMPLE + PS> ('IcingaError' -as [type])::new('WindowsInformationClassUnknown', 'The class Foo is unknown', @{ 'ClassName' = 'Foo'; }) + + .NOTES + A $null Data value is stored as an empty hashtable. + #> + IcingaError([string]$ReturnCode, [string]$Message, [hashtable]$Data) + { + $this.ReturnCode = $ReturnCode; + $this.Message = $Message; + + if ($null -ne $Data) { + $this.Data = $Data; + } + } + + <# + .SYNOPSIS + Format a message with its arguments without ever throwing + + .DESCRIPTION + Replaces the '{0}'-style placeholders of the message with the arguments. A + message without arguments is returned unchanged. When the message is no valid + format string (for example a literal '{' with arguments given), the arguments + are appended to the message instead, so an error report never fails itself. + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|----------------------------------------------|---------| + | Message | System.String | Format string with '{0}'-style placeholders. | | + + .PARAMETER Arguments + | Name | Type | Description | Default | + |-----------|-----------------|----------------------------------------|---------| + | Arguments | System.Object[] | Values inserted into the placeholders. | | + + .OUTPUTS + System.String — The formatted message. + + .EXAMPLE + PS> ('IcingaError' -as [type])::FormatMessage('Failed to query {0}', @('Win32_Volume')) + + .NOTES + Shared by IcingaError and IcingaPlugin.SetError. + #> + static [string] FormatMessage([string]$Message, [object[]]$Arguments) + { + if ($null -eq $Arguments -or $Arguments.Count -eq 0) { + return $Message; + } + + try { + return [string]::Format($Message, [object[]]$Arguments); + } catch { + $Error.Clear(); + } + + return ([string]::Format('{0} ({1})', $Message, ($Arguments -join ', '))); + } + + <# + .SYNOPSIS + Return the error message + + .DESCRIPTION + Returns the message, so the error renders as its text in strings and logs. + + .OUTPUTS + System.String — The error message. + + .EXAMPLE + PS> [string]$IcingaError + + .NOTES + Overrides Object.ToString. + #> + [string] ToString() + { + return $this.Message; + } +} diff --git a/src/Classes/Icinga/IcingaPlugin.ps1 b/src/Classes/Icinga/IcingaPlugin.ps1 new file mode 100644 index 0000000..04def4b --- /dev/null +++ b/src/Classes/Icinga/IcingaPlugin.ps1 @@ -0,0 +1,3066 @@ +<# +.SYNOPSIS +Unified Icinga plugin node that is both a single check and a container + +.DESCRIPTION +IcingaPlugin replaces the previous three-part construct (New-IcingaCheck, +New-IcingaCheckPackage, New-IcingaCheckResult) with a single class. One instance +can act as: + +- a leaf check — a measured value that is evaluated against warning and critical + thresholds and immediately put into a state (0 OK, 1 WARNING, 2 CRITICAL, + 3 UNKNOWN) the moment a comparison method is called; +- a container — a node that aggregates child plugins with a configurable operator + (default: all children must be OK). Nesting is arbitrary; a child may itself be a + container; +- a hybrid — a node that carries its own value AND child checks; its own evaluated + state then participates in the aggregation as one more element. A node with only + children (no own value evaluated) behaves exactly like the classic package. + +The surface is fluent: threshold setters, comparison methods, override methods, +operator methods and AddCheck all return the instance ($this) so calls chain. A +chain is terminated either by AddCheck / an assignment that consumes the return +value, by the integer-returning Compile() at the root, or by the void Commit() +end-of-chain marker, so callers never need '| Out-Null' or '[void]'. + +Threshold comparison is delegated to the existing IcingaThresholds class, so all +unit, percentage and range handling is shared and there is no duplicated +comparison math here. State transitions from threshold evaluation and from +aggregation are escalate-only (a state is only ever raised, never lowered); the +SetState override family is the single, central way to force a specific state, with +an optional lock that freezes it. SetError reports a failed data collection (a +message with format arguments, or an IcingaError returned by a data function) as a +locked UNKNOWN state. + +Compile() aggregates the tree, renders the indented plugin output, collects the +performance data and stores an IcingaCheckResult in the thread-local runtime state +at $Global:IcingaForWindows.Private.Icinga.CheckResult. On the main thread it also +writes the output to the console; inside a background daemon +(Protected.IsBackgroundDaemon) it writes nothing to the console and leaves the +result in Private for the REST API to pick up. Compile() returns the integer exit +code either way. + +.OUTPUTS +IcingaPlugin — Plugin node exposing the fluent check, override and container surface. + +.EXAMPLE +PS> return (New-IcingaPlugin 'Disks'). + AddCheck((New-IcingaPlugin 'C:' 55 '%').Warning('80').Critical('90').CheckRange()). + AddCheck((New-IcingaPlugin 'D:' 95 '%').Warning('80').Critical('90').CheckRange()). + CheckAnd(). + Compile() + +Builds a two-disk package, evaluates each disk immediately, aggregates with the +default "all must be OK" rule and returns the worst exit code. + +.NOTES +Reuses IcingaThresholds / IcingaThresholdResult for comparison and IcingaUnit for +unit handling. Those types are referenced only inside method bodies because the +build concatenates class files alphabetically and IcingaPlugin is parsed before +them; referencing them as property, parameter or base types would fail at parse +time. Writes only to the thread-local Private runtime state, never to Public. + +Functions create instances only through New-IcingaPlugin, never with +[IcingaPlugin]::new(). Every runspace shares the compiled kernel, so a class +literal inside a function resolves to the type of the main runspace; on Windows +PowerShell 5.1 the methods of such an instance stall in a background thread until +the main runspace is idle. +#> +class IcingaPlugin +{ + [string]$Name = ''; + [object]$Value = $null; + [string]$Unit = ''; + [int]$Verbose = 0; + [bool]$NoPerfData = $false; + [bool]$IsHidden = $false; + [bool]$IsNotice = $false; + [bool]$IgnoreEmptyPackage = $false; + [bool]$AddSummaryHeader = $false; + + hidden [int]$State = 0; + hidden [bool]$Locked = $false; + hidden [bool]$FixedState = $false; + hidden [bool]$IsNoticeObject = $false; + hidden [bool]$Evaluated = $false; + hidden [bool]$HasError = $false; + hidden [string]$OutputMessage = ''; + hidden [int]$Indention = 0; + hidden [IcingaPlugin]$Parent = $null; + hidden [array]$Checks = @(); + hidden [array]$PerfData = @(); + hidden [string]$Operator = 'And'; + hidden [int]$OperatorMin = -1; + hidden [int]$OperatorMax = -1; + hidden [string]$WarningThreshold = ''; + hidden [string]$CriticalThreshold = ''; + hidden [string]$ResolvedWarning = ''; + hidden [string]$ResolvedCritical = ''; + hidden [string]$MinimumValue = ''; + hidden [string]$MaximumValue = ''; + hidden [object]$BaseValueSetting = $null; + hidden [string]$MetricIndexValue = ''; + hidden [string]$MetricNameValue = ''; + hidden [string]$MetricLabelValue = ''; + hidden [string]$CheckCommand = ''; + + static hidden [hashtable]$StateText = @{ + 0 = '[OK]'; + 1 = '[WARNING]'; + 2 = '[CRITICAL]'; + 3 = '[UNKNOWN]'; + }; + + <# + .SYNOPSIS + Create a plugin node with a name only + + .DESCRIPTION + Creates a node without a measured value. Typically used as a container that + aggregates child checks added with AddCheck. + + .PARAMETER Name + | Name | Type | Description | Default | + |------|---------------|--------------------------------------|---------| + | Name | System.String | Display name of the plugin node. | | + + .OUTPUTS + IcingaPlugin — Configured plugin node. + + .EXAMPLE + PS> New-IcingaPlugin 'Disks' + + .NOTES + Delegates to the shared Initialize helper. Functions call it through + New-IcingaPlugin. + #> + IcingaPlugin([string]$Name) + { + $this.Initialize($Name, $null, ''); + } + + <# + .SYNOPSIS + Create a plugin node with a name and a measured value + + .DESCRIPTION + Creates a leaf check with a measured value but no unit. Thresholds are applied + afterwards through the fluent setters and comparison methods. + + .PARAMETER Name + | Name | Type | Description | Default | + |------|---------------|-----------------------------------|---------| + | Name | System.String | Display name of the check. | | + + .PARAMETER Value + | Name | Type | Description | Default | + |-------|---------------|-----------------------------------------------|---------| + | Value | System.Object | Measured value; number or ''. | | + + .OUTPUTS + IcingaPlugin — Configured plugin node. + + .EXAMPLE + PS> New-IcingaPlugin 'Load' 95 + + .NOTES + Delegates to the shared Initialize helper. Functions call it through + New-IcingaPlugin. + #> + IcingaPlugin([string]$Name, [object]$Value) + { + $this.Initialize($Name, $Value, ''); + } + + <# + .SYNOPSIS + Create a plugin node with a name, value and unit + + .DESCRIPTION + Creates a leaf check with a measured value and an Icinga unit (for example '%', + 'MB', 's'). The unit is appended to the performance data and reused by the + threshold comparison. + + .PARAMETER Name + | Name | Type | Description | Default | + |------|---------------|-----------------------------------|---------| + | Name | System.String | Display name of the check. | | + + .PARAMETER Value + | Name | Type | Description | Default | + |-------|---------------|-----------------------------------------------|---------| + | Value | System.Object | Measured value; number or ''. | | + + .PARAMETER Unit + | Name | Type | Description | Default | + |------|---------------|------------------------------------|---------| + | Unit | System.String | Icinga unit appended to perfdata. | | + + .OUTPUTS + IcingaPlugin — Configured plugin node. + + .EXAMPLE + PS> New-IcingaPlugin 'Load' 95 '%' + + .NOTES + Delegates to the shared Initialize helper. Functions call it through + New-IcingaPlugin. + #> + IcingaPlugin([string]$Name, [object]$Value, [string]$Unit) + { + $this.Initialize($Name, $Value, $Unit); + } + + <# + .SYNOPSIS + Store the base settings of the node + + .DESCRIPTION + Shared constructor logic that stores the name, measured value and unit. Kept in + a single helper so every constructor overload behaves identically. + + .PARAMETER Name + | Name | Type | Description | Default | + |------|---------------|--------------------------------|---------| + | Name | System.String | Display name of the node. | | + + .PARAMETER Value + | Name | Type | Description | Default | + |-------|---------------|-------------------------------|---------| + | Value | System.Object | Measured value or $null. | | + + .PARAMETER Unit + | Name | Type | Description | Default | + |------|---------------|--------------------|---------| + | Unit | System.String | Icinga unit. | | + + .OUTPUTS + None — Updates instance state. + + .EXAMPLE + PS> $this.Initialize('Load', 95, '%') + + .NOTES + Internal helper shared by all constructors. + #> + hidden [void] Initialize([string]$Name, [object]$Value, [string]$Unit) + { + $this.Name = $Name; + $this.Value = $Value; + $this.Unit = $Unit; + $this.CheckCommand = $this.DetectCheckCommand(); + } + + <# + .SYNOPSIS + Set the warning threshold and return the node for chaining + + .DESCRIPTION + Stores the warning threshold string verbatim. The threshold is not evaluated + until a comparison method (CheckRange, CheckGreater, ...) is called. + + .PARAMETER Warning + | Name | Type | Description | Default | + |---------|---------------|------------------------------------------|---------| + | Warning | System.String | Warning threshold string ('' = unset). | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.Warning('80') + + .NOTES + Fluent setter; combine with Critical and a comparison method. + #> + [IcingaPlugin] Warning([string]$Warning) + { + $this.WarningThreshold = $Warning; + return $this; + } + + <# + .SYNOPSIS + Set the critical threshold and return the node for chaining + + .DESCRIPTION + Stores the critical threshold string verbatim. The threshold is not evaluated + until a comparison method is called. + + .PARAMETER Critical + | Name | Type | Description | Default | + |----------|---------------|-----------------------------------------|---------| + | Critical | System.String | Critical threshold string ('' = unset). | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.Critical('90') + + .NOTES + Fluent setter; combine with Warning and a comparison method. + #> + [IcingaPlugin] Critical([string]$Critical) + { + $this.CriticalThreshold = $Critical; + return $this; + } + + <# + .SYNOPSIS + Set the performance-data minimum and return the node for chaining + + .DESCRIPTION + Stores the minimum value that is emitted as the 'min' field of the performance + data. Does not influence the threshold evaluation. + + .PARAMETER Minimum + | Name | Type | Description | Default | + |---------|---------------|-------------------------------------|---------| + | Minimum | System.String | Perfdata minimum ('' = unset). | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.Minimum('0') + + .NOTES + Fluent setter for the perfdata min field. + #> + [IcingaPlugin] Minimum([string]$Minimum) + { + $this.MinimumValue = $Minimum; + return $this; + } + + <# + .SYNOPSIS + Set the performance-data maximum and return the node for chaining + + .DESCRIPTION + Stores the maximum value that is emitted as the 'max' field of the performance + data. Does not influence the threshold evaluation. + + .PARAMETER Maximum + | Name | Type | Description | Default | + |---------|---------------|-------------------------------------|---------| + | Maximum | System.String | Perfdata maximum ('' = unset). | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.Maximum('100') + + .NOTES + Fluent setter for the perfdata max field. + #> + [IcingaPlugin] Maximum([string]$Maximum) + { + $this.MaximumValue = $Maximum; + return $this; + } + + <# + .SYNOPSIS + Set the base value for percentage and Max comparisons + + .DESCRIPTION + Stores the base value (a number or a unit string such as '1TB') that percent + thresholds and the CheckMax comparison resolve against. Passed on to + IcingaThresholds when a comparison method is called. + + .PARAMETER BaseValue + | Name | Type | Description | Default | + |-----------|---------------|------------------------------------------------|---------| + | BaseValue | System.Object | Base/maximum value; number or unit string. | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.BaseValue('1TB').Warning('80%').Critical('90%').CheckMax() + + .NOTES + Fluent setter; required for percent thresholds and CheckMax. + #> + [IcingaPlugin] BaseValue([object]$BaseValue) + { + $this.BaseValueSetting = $BaseValue; + return $this; + } + + <# + .SYNOPSIS + Set the performance-data metric index and return the node for chaining + + .DESCRIPTION + Sets the first segment of the check_multi performance-data label + ('index::ifw_template::label'). The index typically identifies the instance, such + as a CPU core number or a disk letter. Defaults to 'default' when left unset. + + .PARAMETER Index + | Name | Type | Description | Default | + |-------|---------------|--------------------------------------------|---------| + | Index | System.String | Metric index / instance identifier. | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.MetricIndex('0') + + .NOTES + Fluent setter; sanitized (non-word characters removed, lower-cased) at render time. + #> + [IcingaPlugin] MetricIndex([string]$Index) + { + $this.MetricIndexValue = $Index; + return $this; + } + + <# + .SYNOPSIS + Set the performance-data metric template and return the node for chaining + + .DESCRIPTION + Sets the template segment of the check_multi performance-data label + ('index::ifw_template::label'). The fixed 'ifw_' namespace is always prepended, so + passing 'cpu' yields 'ifw_cpu'. When left unset the template is derived from the + calling Invoke-IcingaCheck* command (for example Invoke-IcingaCheckCPU yields + 'cpu'), falling back to 'check' when no such command is on the call stack. + + .PARAMETER Name + | Name | Type | Description | Default | + |------|---------------|---------------------------------------------------|---------| + | Name | System.String | Template name without the fixed 'ifw_' namespace. | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.MetricName('cpu') + + .NOTES + Fluent setter; 'ifw_' is not doubled when the value already carries it. + #> + [IcingaPlugin] MetricName([string]$Name) + { + $this.MetricNameValue = $Name; + return $this; + } + + <# + .SYNOPSIS + Set the performance-data metric label and return the node for chaining + + .DESCRIPTION + Sets the label segment of the check_multi performance-data label + ('index::ifw_template::label'), for example 'load' or 'free'. Defaults to the + node's Name when left unset. + + .PARAMETER Label + | Name | Type | Description | Default | + |-------|---------------|--------------------------------|---------| + | Label | System.String | Metric label / measured value. | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.MetricLabel('load') + + .NOTES + Fluent setter; sanitized (non-word characters removed, lower-cased) at render time. + #> + [IcingaPlugin] MetricLabel([string]$Label) + { + $this.MetricLabelValue = $Label; + return $this; + } + + <# + .SYNOPSIS + Evaluate the value against the thresholds using the Icinga range grammar + + .DESCRIPTION + Builds an IcingaThresholds pair from the configured warning, critical and base + values, compares the node's value with the full Icinga/Nagios range grammar and + immediately puts the node into the resulting state (escalate-only). Performance + data is (re)built from the current value and thresholds. + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> (New-IcingaPlugin 'Load' 95 '%').Warning('80').Critical('90').CheckRange() + + .NOTES + Delegates to IcingaThresholds.CheckRange. + #> + [IcingaPlugin] CheckRange() + { + $this.ApplyThresholdResult($this.NewThresholds().CheckRange($this.AttachBaseUnit($this.Value))); + return $this; + } + + <# + .SYNOPSIS + Evaluate the value with a greater-than comparison + + .DESCRIPTION + Compares the node's value against the warning and critical thresholds with a + greater-than operator and puts the node into the resulting state. + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.Warning('80').Critical('90').CheckGreater() + + .NOTES + Delegates to IcingaThresholds.CheckGreater. + #> + [IcingaPlugin] CheckGreater() + { + $this.ApplyThresholdResult($this.NewThresholds().CheckGreater($this.AttachBaseUnit($this.Value))); + return $this; + } + + <# + .SYNOPSIS + Evaluate the value with a greater-than-or-equal comparison + + .DESCRIPTION + Compares the node's value against the warning and critical thresholds with a + greater-than-or-equal operator and puts the node into the resulting state. + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.Warning('80').Critical('90').CheckGreaterEqual() + + .NOTES + Delegates to IcingaThresholds.CheckGreaterEqual. + #> + [IcingaPlugin] CheckGreaterEqual() + { + $this.ApplyThresholdResult($this.NewThresholds().CheckGreaterEqual($this.AttachBaseUnit($this.Value))); + return $this; + } + + <# + .SYNOPSIS + Evaluate the value with a lower-than comparison + + .DESCRIPTION + Compares the node's value against the warning and critical thresholds with a + lower-than operator and puts the node into the resulting state. + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.Warning('20').Critical('10').CheckLower() + + .NOTES + Delegates to IcingaThresholds.CheckLower. + #> + [IcingaPlugin] CheckLower() + { + $this.ApplyThresholdResult($this.NewThresholds().CheckLower($this.AttachBaseUnit($this.Value))); + return $this; + } + + <# + .SYNOPSIS + Evaluate the value with a lower-than-or-equal comparison + + .DESCRIPTION + Compares the node's value against the warning and critical thresholds with a + lower-than-or-equal operator and puts the node into the resulting state. + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.Warning('20').Critical('10').CheckLowerEqual() + + .NOTES + Delegates to IcingaThresholds.CheckLowerEqual. + #> + [IcingaPlugin] CheckLowerEqual() + { + $this.ApplyThresholdResult($this.NewThresholds().CheckLowerEqual($this.AttachBaseUnit($this.Value))); + return $this; + } + + <# + .SYNOPSIS + Evaluate the value against its maximum-relative thresholds + + .DESCRIPTION + Requires a base value. Compares the node's value against the warning and + critical thresholds relative to the base value (commonly percentages of the + maximum) and puts the node into the resulting state. + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.BaseValue('1TB').Warning('80%').Critical('90%').CheckMax() + + .NOTES + Delegates to IcingaThresholds.CheckMax; without a base value the result is UNKNOWN. + #> + [IcingaPlugin] CheckMax() + { + $this.ApplyThresholdResult($this.NewThresholds().CheckMax($this.AttachBaseUnit($this.Value))); + return $this; + } + + <# + .SYNOPSIS + Evaluate the string value with a regular-expression match + + .DESCRIPTION + Tests the node's value against the warning and critical thresholds as regular + expressions and puts the node into the resulting state. + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.Warning('^warn').Critical('^err').CheckMatch() + + .NOTES + Delegates to IcingaThresholds.CheckMatch. + #> + [IcingaPlugin] CheckMatch() + { + $this.ApplyThresholdResult($this.NewThresholds().CheckMatch($this.Value)); + return $this; + } + + <# + .SYNOPSIS + Evaluate the string value with a negated regular-expression match + + .DESCRIPTION + Tests the node's value against the warning and critical thresholds as regular + expressions and alerts when the value does NOT match, then puts the node into + the resulting state. + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.Warning('^ok').Critical('^healthy').CheckNotMatch() + + .NOTES + Delegates to IcingaThresholds.CheckNotMatch. + #> + [IcingaPlugin] CheckNotMatch() + { + $this.ApplyThresholdResult($this.NewThresholds().CheckNotMatch($this.Value)); + return $this; + } + + <# + .SYNOPSIS + Evaluate the string value with a wildcard 'like' comparison + + .DESCRIPTION + Tests the node's value against the warning and critical thresholds as PowerShell + wildcard patterns and puts the node into the resulting state. + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.Warning('*warn*').Critical('*error*').CheckLike() + + .NOTES + Delegates to IcingaThresholds.CheckLike. + #> + [IcingaPlugin] CheckLike() + { + $this.ApplyThresholdResult($this.NewThresholds().CheckLike($this.Value)); + return $this; + } + + <# + .SYNOPSIS + Evaluate the string value with a negated wildcard 'like' comparison + + .DESCRIPTION + Tests the node's value against the warning and critical thresholds as PowerShell + wildcard patterns and alerts when the value is NOT like the pattern, then puts + the node into the resulting state. + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.Warning('*ok*').Critical('*healthy*').CheckNotLike() + + .NOTES + Delegates to IcingaThresholds.CheckNotLike. + #> + [IcingaPlugin] CheckNotLike() + { + $this.ApplyThresholdResult($this.NewThresholds().CheckNotLike($this.Value)); + return $this; + } + + <# + .SYNOPSIS + Evaluate the string value with an equality comparison + + .DESCRIPTION + Tests the node's value against the warning and critical thresholds with a + case-insensitive string equality test and puts the node into the resulting state. + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.Warning('degraded').Critical('offline').CheckEqual() + + .NOTES + Delegates to IcingaThresholds.CheckEqual. + #> + [IcingaPlugin] CheckEqual() + { + $this.ApplyThresholdResult($this.NewThresholds().CheckEqual($this.Value)); + return $this; + } + + <# + .SYNOPSIS + Evaluate the string value with a negated equality comparison + + .DESCRIPTION + Tests the node's value against the warning and critical thresholds with a + case-insensitive string inequality test and puts the node into the resulting + state. + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.Warning('online').Critical('online').CheckNotEqual() + + .NOTES + Delegates to IcingaThresholds.CheckNotEqual. + #> + [IcingaPlugin] CheckNotEqual() + { + $this.ApplyThresholdResult($this.NewThresholds().CheckNotEqual($this.Value)); + return $this; + } + + <# + .SYNOPSIS + Build an IcingaThresholds pair from the configured thresholds + + .DESCRIPTION + Creates an IcingaThresholds object from the stored warning and critical strings, + passing the base value as well when one was set. A plain numeric base value of a + byte or time node carries the 'B' or 's' unit, so percent thresholds resolve and + render in that unit. The return type is object because IcingaThresholds is + parsed after IcingaPlugin during the build and may therefore only be referenced + from method bodies. + + .OUTPUTS + System.Object — An IcingaThresholds instance. + + .EXAMPLE + PS> $this.NewThresholds() + + .NOTES + Internal helper used by every comparison method. + #> + hidden [object] NewThresholds() + { + if ($null -ne $this.BaseValueSetting -and '' -ne [string]$this.BaseValueSetting) { + return [IcingaThresholds]::new($this.WarningThreshold, $this.CriticalThreshold, [string]$this.AttachBaseUnit($this.BaseValueSetting)); + } + + return [IcingaThresholds]::new($this.WarningThreshold, $this.CriticalThreshold); + } + + <# + .SYNOPSIS + Test whether the node measures plain bytes or plain seconds + + .DESCRIPTION + Returns true when the node's unit is the byte base unit 'B' or the time base + unit 's'. Such a node hands its value to the threshold engine as a byte or time + quantity, so it compares exactly against size thresholds ('400GB'), duration + thresholds ('30m', '1d:') and percent thresholds of a base value, and its output + message shows human-readable sizes or durations. Plain-number thresholds keep + meaning bytes or seconds, which matches both the threshold engine and the Icinga + perfdata unit. Every other unit ('%', 'GiB', 'ms', none) returns false and keeps + the plain display-unit behaviour. + + .OUTPUTS + System.Boolean — True when the unit is 'B' or 's'. + + .EXAMPLE + PS> $this.HasBaseUnit() + + .NOTES + Internal helper. Larger units are excluded on purpose: a plain threshold such as + '80' would resolve to 80 bytes or seconds instead of 80 of the node's unit. + #> + hidden [bool] HasBaseUnit() + { + # Time units are case-sensitive in IcingaUnit ('m' minute, 'M' month), data units are not. + return ($this.Unit -eq 'B' -or $this.Unit -ceq 's'); + } + + <# + .SYNOPSIS + Append the base unit to a plain numeric value + + .DESCRIPTION + Turns a plain number into a 'B' or 's' string (for example + 442692000000 becomes '442692000000B') when the node measures bytes or seconds, so + the threshold engine resolves the value as a byte or time quantity. The number is + written in fixed-point notation under the invariant culture so large byte counts + never use an exponent. A duration below one second is written in milliseconds or + microseconds ('0.004' becomes '4ms'), so the output message keeps its precision. + Any other value, and every value of a node without such a base unit, is returned + unchanged. + + .PARAMETER Value + | Name | Type | Description | Default | + |-------|---------------|------------------------------------------|---------| + | Value | System.Object | Measured value or base value to adjust. | | + + .OUTPUTS + System.Object — The value with the unit attached, or the unchanged value. + + .EXAMPLE + PS> $this.AttachBaseUnit(442692000000) + + .NOTES + Internal helper used by the numeric comparison methods and NewThresholds. + #> + hidden [object] AttachBaseUnit([object]$Value) + { + if ($null -eq $Value -or -not $this.HasBaseUnit()) { + return $Value; + } + + [double]$Parsed = 0; + if (-not [double]::TryParse([string]$Value, [System.Globalization.NumberStyles]::Float, [System.Globalization.CultureInfo]::InvariantCulture, [ref]$Parsed)) { + return $Value; + } + + [string]$ValueUnit = $this.Unit; + + # The threshold engine renders a value in the unit it was given with at most two + # decimals, so 0.004s would show as 0s. Sub-second durations are therefore handed + # over in milli- or microseconds; the comparison is unaffected. + if ($ValueUnit -ceq 's' -and $Parsed -ne 0 -and [System.Math]::Abs($Parsed) -lt 1) { + if ([System.Math]::Abs($Parsed) -ge 0.001) { + $Parsed = $Parsed * 1000; + $ValueUnit = 'ms'; + } else { + $Parsed = $Parsed * 1000000; + $ValueUnit = 'us'; + } + } + + return ($Parsed.ToString('0.##########', [System.Globalization.CultureInfo]::InvariantCulture) + $ValueUnit); + } + + <# + .SYNOPSIS + Apply a threshold evaluation result to the node + + .DESCRIPTION + Marks the node as evaluated, stores the human-readable output message, escalates + the node state to the result's status code and rebuilds the performance data. + The thresholds as resolved by the comparison (base units, percentages already + applied) are kept for the performance data, because Icinga requires perfdata + thresholds in the same unit as the value. + + .PARAMETER Result + | Name | Type | Description | Default | + |--------|---------------|--------------------------------------------|---------| + | Result | System.Object | An IcingaThresholdResult from a comparison. | | + + .OUTPUTS + None — Updates instance state. + + .EXAMPLE + PS> $this.ApplyThresholdResult($result) + + .NOTES + Internal helper shared by every comparison method. + #> + hidden [void] ApplyThresholdResult([object]$Result) + { + $this.Evaluated = $true; + + # A locked node froze its state and message via an override; later threshold + # evaluation must not overwrite either. EscalateState honours the lock too. + if (-not $this.Locked) { + if ($this.Unit -eq 'B') { + $this.OutputMessage = $this.HumanizeByteValues([string]$Result.Output); + } elseif ($this.Unit -ceq 's') { + $this.OutputMessage = $this.HumanizeTimeValues([string]$Result.Output); + } else { + $this.OutputMessage = $this.ApplyDisplayUnit([string]$Result.Output); + } + } + + $this.ResolvedWarning = ''; + $this.ResolvedCritical = ''; + + if ($null -ne $Result.WarningValue) { + $this.ResolvedWarning = $this.FormatNumber($Result.WarningValue); + } + + if ($null -ne $Result.CriticalValue) { + $this.ResolvedCritical = $this.FormatNumber($Result.CriticalValue); + } + + $this.EscalateState([int]$Result.StatusCode); + $this.BuildPerfData(); + } + + <# + .SYNOPSIS + Render plain byte figures of an output message as human-readable sizes + + .DESCRIPTION + Replaces every 'B' figure in a threshold output message with its + best-fitting binary size (for example '442692000000B' becomes '412.29GiB'). The + threshold engine renders the value and the percent thresholds of a byte node in + plain bytes; figures in any other unit (such as a '400GB' threshold) and + percentages are left untouched. + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|--------------------------------|---------| + | Message | System.String | The threshold output message. | | + + .OUTPUTS + System.String — The message with byte figures converted to their best-fit unit. + + .EXAMPLE + PS> $this.HumanizeByteValues('442692000000B (86.46%) is greater than threshold 409600000000B (80%)') + + .NOTES + Internal helper used by ApplyThresholdResult for byte nodes. A figure that + IcingaUnit cannot convert is kept as it is. IcingaUnit is parsed after + IcingaPlugin during the build, so it is referenced only inside this method body. + #> + hidden [string] HumanizeByteValues([string]$Message) + { + [string]$Output = ''; + [int]$Position = 0; + + foreach ($Match in [regex]::Matches($Message, '(?s' figure in a threshold output message with its + decomposed duration (for example '93784s' becomes '1d 2h 3m 4s'). The threshold + engine renders the value and the percent thresholds of a time node in plain + seconds; figures in any other unit (such as a '30m' threshold), plain numbers and + percentages are left untouched. + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|--------------------------------|---------| + | Message | System.String | The threshold output message. | | + + .OUTPUTS + System.String — The message with second figures converted to durations. + + .EXAMPLE + PS> $this.HumanizeTimeValues('3600s is greater than threshold 30m') + + .NOTES + Internal helper used by ApplyThresholdResult for time nodes. A figure that + IcingaUnit cannot convert is kept as it is. IcingaUnit is parsed after + IcingaPlugin during the build, so it is referenced only inside this method body. + #> + hidden [string] HumanizeTimeValues([string]$Message) + { + [string]$Output = ''; + [int]$Position = 0; + + foreach ($Match in [regex]::Matches($Message, '(? $this.ApplyDisplayUnit('95 is greater than threshold 90') + + .NOTES + Internal helper used by ApplyThresholdResult. The unit's '$' characters are + escaped so they are not treated as regex replacement references. + #> + hidden [string] ApplyDisplayUnit([string]$Message) + { + if ('' -eq $this.Unit) { + return $Message; + } + + [string]$Replacement = '$0' + ($this.Unit -replace '\$', '$$$$'); + return [regex]::Replace($Message, '-?\d+(?:\.\d+)?', $Replacement); + } + + <# + .SYNOPSIS + Raise the node state without ever lowering it + + .DESCRIPTION + Sets the node state to the supplied value only when it is worse than the current + state, implementing the escalate-only rule shared by threshold evaluation and + aggregation. A locked node is never changed. + + .PARAMETER State + | Name | Type | Description | Default | + |-------|--------------|-------------------------------------------------|---------| + | State | System.Int32 | Candidate state (0 OK, 1 WARN, 2 CRIT, 3 UNKN). | | + + .OUTPUTS + None — Updates instance state. + + .EXAMPLE + PS> $this.EscalateState(2) + + .NOTES + Internal helper; use SetState to force a specific state instead. + #> + hidden [void] EscalateState([int]$State) + { + if ($this.Locked) { + return; + } + + if ($this.State -lt $State) { + $this.State = $State; + } + } + + <# + .SYNOPSIS + Central override that forces a specific node state + + .DESCRIPTION + The single, unified way to override a node's state. Unless the node is locked it + marks the state as fixed, sets the requested state (this override may lower the + state, unlike EscalateState) and replaces the output message when one is given. + When Lock is true the node is locked so no later evaluation or aggregation can + change it. Returns the node so overrides chain. + + .PARAMETER State + | Name | Type | Description | Default | + |-------|--------------|-------------------------------------------------|---------| + | State | System.Int32 | Forced state (0 OK, 1 WARN, 2 CRIT, 3 UNKN). | | + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|--------------------------------------------------|---------| + | Message | System.String | Output message; '' keeps the existing message. | | + + .PARAMETER Lock + | Name | Type | Description | Default | + |------|----------------|-------------------------------------------------|---------| + | Lock | System.Boolean | When true, freeze the state against later changes. | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.SetState(2, 'Service is stopped', $true) + + .NOTES + All SetOk/SetWarning/SetCritical/SetUnknown wrappers funnel through this method. + #> + hidden [IcingaPlugin] SetState([int]$State, [string]$Message, [bool]$Lock) + { + if (-not $this.Locked) { + $this.FixedState = $true; + $this.State = $State; + if ('' -ne $Message) { + $this.OutputMessage = $Message; + } + } + + if ($Lock) { + $this.Locked = $true; + } + + return $this; + } + + <# + .SYNOPSIS + Force the node into the OK state + + .DESCRIPTION + Overrides the node state to OK with the given message. + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|------------------------------------|---------| + | Message | System.String | Output message for the OK state. | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.SetOk('All good') + + .NOTES + Convenience wrapper around SetState; does not lock the state. + #> + [IcingaPlugin] SetOk([string]$Message) + { + return $this.SetState(0, $Message, $false); + } + + <# + .SYNOPSIS + Force the node into the OK state, optionally locking it + + .DESCRIPTION + Overrides the node state to OK with the given message and, when Lock is true, + freezes the state against later changes. + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|------------------------------------|---------| + | Message | System.String | Output message for the OK state. | | + + .PARAMETER Lock + | Name | Type | Description | Default | + |------|----------------|-------------------------------------|---------| + | Lock | System.Boolean | When true, freeze the state. | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.SetOk('All good', $true) + + .NOTES + Convenience wrapper around SetState. + #> + [IcingaPlugin] SetOk([string]$Message, [bool]$Lock) + { + return $this.SetState(0, $Message, $Lock); + } + + <# + .SYNOPSIS + Force the node into the WARNING state + + .DESCRIPTION + Overrides the node state to WARNING with the given message. + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|----------------------------------------|---------| + | Message | System.String | Output message for the WARNING state. | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.SetWarning('Approaching limit') + + .NOTES + Convenience wrapper around SetState; does not lock the state. + #> + [IcingaPlugin] SetWarning([string]$Message) + { + return $this.SetState(1, $Message, $false); + } + + <# + .SYNOPSIS + Force the node into the WARNING state, optionally locking it + + .DESCRIPTION + Overrides the node state to WARNING with the given message and, when Lock is + true, freezes the state against later changes. + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|----------------------------------------|---------| + | Message | System.String | Output message for the WARNING state. | | + + .PARAMETER Lock + | Name | Type | Description | Default | + |------|----------------|-------------------------------------|---------| + | Lock | System.Boolean | When true, freeze the state. | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.SetWarning('Approaching limit', $true) + + .NOTES + Convenience wrapper around SetState. + #> + [IcingaPlugin] SetWarning([string]$Message, [bool]$Lock) + { + return $this.SetState(1, $Message, $Lock); + } + + <# + .SYNOPSIS + Force the node into the CRITICAL state + + .DESCRIPTION + Overrides the node state to CRITICAL with the given message. + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|-----------------------------------------|---------| + | Message | System.String | Output message for the CRITICAL state. | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.SetCritical('Service is stopped') + + .NOTES + Convenience wrapper around SetState; does not lock the state. + #> + [IcingaPlugin] SetCritical([string]$Message) + { + return $this.SetState(2, $Message, $false); + } + + <# + .SYNOPSIS + Force the node into the CRITICAL state, optionally locking it + + .DESCRIPTION + Overrides the node state to CRITICAL with the given message and, when Lock is + true, freezes the state against later changes. + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|-----------------------------------------|---------| + | Message | System.String | Output message for the CRITICAL state. | | + + .PARAMETER Lock + | Name | Type | Description | Default | + |------|----------------|-------------------------------------|---------| + | Lock | System.Boolean | When true, freeze the state. | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.SetCritical('Service is stopped', $true) + + .NOTES + Convenience wrapper around SetState. + #> + [IcingaPlugin] SetCritical([string]$Message, [bool]$Lock) + { + return $this.SetState(2, $Message, $Lock); + } + + <# + .SYNOPSIS + Force the node into the UNKNOWN state + + .DESCRIPTION + Overrides the node state to UNKNOWN with the given message. + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|----------------------------------------|---------| + | Message | System.String | Output message for the UNKNOWN state. | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.SetUnknown('Data source unavailable') + + .NOTES + Convenience wrapper around SetState; does not lock the state. + #> + [IcingaPlugin] SetUnknown([string]$Message) + { + return $this.SetState(3, $Message, $false); + } + + <# + .SYNOPSIS + Force the node into the UNKNOWN state, optionally locking it + + .DESCRIPTION + Overrides the node state to UNKNOWN with the given message and, when Lock is + true, freezes the state against later changes. + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|----------------------------------------|---------| + | Message | System.String | Output message for the UNKNOWN state. | | + + .PARAMETER Lock + | Name | Type | Description | Default | + |------|----------------|-------------------------------------|---------| + | Lock | System.Boolean | When true, freeze the state. | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.SetUnknown('Data source unavailable', $true) + + .NOTES + Convenience wrapper around SetState. + #> + [IcingaPlugin] SetUnknown([string]$Message, [bool]$Lock) + { + return $this.SetState(3, $Message, $Lock); + } + + <# + .SYNOPSIS + Put the node into a locked UNKNOWN error state with a message + + .DESCRIPTION + Reports that the check could not be performed, typically because collecting + its data failed. The node is forced to UNKNOWN and locked, so no later + comparison or aggregation can change it, and the message is shown on the + node's output line even when the node is a container with children. + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|-------------------------|---------| + | Message | System.String | Error message to show. | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> return $CheckPackage.SetError('No partition data available').Compile() + + .NOTES + The message is used verbatim, without format processing. + #> + [IcingaPlugin] SetError([string]$Message) + { + return $this.ApplyError($Message); + } + + <# + .SYNOPSIS + Put the node into a locked UNKNOWN error state with a formatted message + + .DESCRIPTION + Like SetError([string]), with the '{0}' placeholder of the message replaced by + the argument in the style of [string]::Format. + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|--------------------------------------|---------| + | Message | System.String | Format string with a '{0}' placeholder. | | + + .PARAMETER Argument + | Name | Type | Description | Default | + |----------|---------------|--------------------------------|---------| + | Argument | System.Object | Value inserted for '{0}'. | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $CheckPackage.SetError('Failed to read the counter {0}', $CounterPath) + + .NOTES + Formatting never throws; see IcingaError.FormatMessage. + #> + [IcingaPlugin] SetError([string]$Message, [object]$Argument) + { + return $this.ApplyError([IcingaError]::FormatMessage($Message, @($Argument))); + } + + <# + .SYNOPSIS + Put the node into a locked UNKNOWN error state with a message and two arguments + + .DESCRIPTION + Like SetError([string]), with the '{0}' and '{1}' placeholders of the message + replaced by the arguments in the style of [string]::Format. + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|--------------------------------------------|---------| + | Message | System.String | Format string with '{0}' and '{1}'. | | + + .PARAMETER Argument1 + | Name | Type | Description | Default | + |-----------|---------------|---------------------------|---------| + | Argument1 | System.Object | Value inserted for '{0}'. | | + + .PARAMETER Argument2 + | Name | Type | Description | Default | + |-----------|---------------|---------------------------|---------| + | Argument2 | System.Object | Value inserted for '{1}'. | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $CheckPackage.SetError('Failed to query {0}: {1}', $ClassName, $Reason) + + .NOTES + Formatting never throws; see IcingaError.FormatMessage. + #> + [IcingaPlugin] SetError([string]$Message, [object]$Argument1, [object]$Argument2) + { + return $this.ApplyError([IcingaError]::FormatMessage($Message, @($Argument1, $Argument2))); + } + + <# + .SYNOPSIS + Put the node into a locked UNKNOWN error state with a message and three arguments + + .DESCRIPTION + Like SetError([string]), with the '{0}', '{1}' and '{2}' placeholders of the + message replaced by the arguments in the style of [string]::Format. + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|------------------------------------------|---------| + | Message | System.String | Format string with '{0}', '{1}', '{2}'. | | + + .PARAMETER Argument1 + | Name | Type | Description | Default | + |-----------|---------------|---------------------------|---------| + | Argument1 | System.Object | Value inserted for '{0}'. | | + + .PARAMETER Argument2 + | Name | Type | Description | Default | + |-----------|---------------|---------------------------|---------| + | Argument2 | System.Object | Value inserted for '{1}'. | | + + .PARAMETER Argument3 + | Name | Type | Description | Default | + |-----------|---------------|---------------------------|---------| + | Argument3 | System.Object | Value inserted for '{2}'. | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $CheckPackage.SetError('{0} failed on {1}: {2}', $Step, $Target, $Reason) + + .NOTES + For more arguments use the SetError([string], [object[]]) overload. + #> + [IcingaPlugin] SetError([string]$Message, [object]$Argument1, [object]$Argument2, [object]$Argument3) + { + return $this.ApplyError([IcingaError]::FormatMessage($Message, @($Argument1, $Argument2, $Argument3))); + } + + <# + .SYNOPSIS + Put the node into a locked UNKNOWN error state with a message and an argument list + + .DESCRIPTION + Like SetError([string]), with the placeholders of the message replaced by the + elements of the argument array in the style of [string]::Format. + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|---------------------------------------------|---------| + | Message | System.String | Format string with '{0}'-style placeholders. | | + + .PARAMETER Arguments + | Name | Type | Description | Default | + |-----------|-----------------|----------------------------------------|---------| + | Arguments | System.Object[] | Values inserted into the placeholders. | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $CheckPackage.SetError('{0}/{1}/{2}/{3}', @('a', 'b', 'c', 'd')) + + .NOTES + Formatting never throws; see IcingaError.FormatMessage. + #> + [IcingaPlugin] SetError([string]$Message, [object[]]$Arguments) + { + return $this.ApplyError([IcingaError]::FormatMessage($Message, $Arguments)); + } + + <# + .SYNOPSIS + Put the node into a locked UNKNOWN error state from an IcingaError + + .DESCRIPTION + Takes the error object a data collection function returned instead of its data + and shows its message, so a plugin reports the failure with a single call. + + .PARAMETER IcingaError + | Name | Type | Description | Default | + |-------------|-------------|---------------------------------------|---------| + | IcingaError | IcingaError | Error returned by a data collection. | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> if (Test-IcingaError -InputObject $Services) { return $CheckPackage.SetError($Services).Compile(); } + + .NOTES + A $null error falls back to a generic message instead of failing. + #> + [IcingaPlugin] SetError([IcingaError]$IcingaError) + { + if ($null -eq $IcingaError) { + return $this.ApplyError('An unknown error occurred'); + } + + return $this.ApplyError($IcingaError.Message); + } + + <# + .SYNOPSIS + Apply the error state shared by every SetError overload + + .DESCRIPTION + Marks the node as failed, so its output line shows the message even as a + container, and forces it into a locked UNKNOWN state. A node that is already + locked keeps its state and message. + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|-------------------------|---------| + | Message | System.String | Final error message. | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $this.ApplyError('Failed to query Win32_Service') + + .NOTES + Internal helper; funnels into SetState like every other override. + #> + hidden [IcingaPlugin] ApplyError([string]$Message) + { + if (-not $this.Locked) { + $this.HasError = $true; + } + + return $this.SetState(3, $Message, $true); + } + + <# + .SYNOPSIS + Mark the node as an informational notice + + .DESCRIPTION + Turns the node into an informational object that renders with the [INFO] prefix + and keeps the OK state, replacing the output message when one is given. + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|-----------------------------------|---------| + | Message | System.String | Informational message to display. | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.SetNotice('Collected 5 samples') + + .NOTES + Notices never raise the plugin state; they are purely informational. + #> + [IcingaPlugin] SetNotice([string]$Message) + { + return $this.SetNotice($Message, $false); + } + + <# + .SYNOPSIS + Mark the node as an informational notice, optionally locking it + + .DESCRIPTION + Turns the node into an informational object that renders with the [INFO] prefix + and keeps the OK state, replacing the output message when one is given. When Lock + is true the node is frozen against later changes. + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|-----------------------------------|---------| + | Message | System.String | Informational message to display. | | + + .PARAMETER Lock + | Name | Type | Description | Default | + |------|----------------|--------------------------------|---------| + | Lock | System.Boolean | When true, freeze the node. | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $check.SetNotice('Collected 5 samples', $true) + + .NOTES + Notices never raise the plugin state; they are purely informational. + #> + [IcingaPlugin] SetNotice([string]$Message, [bool]$Lock) + { + if (-not $this.Locked) { + $this.IsNoticeObject = $true; + if ('' -ne $Message) { + $this.OutputMessage = $Message; + } + } + + if ($Lock) { + $this.Locked = $true; + } + + return $this; + } + + <# + .SYNOPSIS + Aggregate children with the 'all must be OK' operator + + .DESCRIPTION + Sets the container operator so the node becomes not-OK as soon as any child is + not OK. This is the default operator. + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $package.CheckAnd() + + .NOTES + Equivalent to the default; use CheckDefault for the same effect. + #> + [IcingaPlugin] CheckAnd() + { + $this.Operator = 'And'; + return $this; + } + + <# + .SYNOPSIS + Aggregate children with the 'at least one must be OK' operator + + .DESCRIPTION + Sets the container operator so the node is OK as long as at least one child is + OK, and becomes not-OK only when every child is not OK. + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $package.CheckOr() + + .NOTES + Mirrors the classic OperatorOr package behaviour. + #> + [IcingaPlugin] CheckOr() + { + $this.Operator = 'Or'; + return $this; + } + + <# + .SYNOPSIS + Aggregate children with the 'none may be OK' operator + + .DESCRIPTION + Sets the container operator so the node becomes not-OK as soon as any child is + OK. + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $package.CheckNone() + + .NOTES + Mirrors the classic OperatorNone package behaviour. + #> + [IcingaPlugin] CheckNone() + { + $this.Operator = 'None'; + return $this; + } + + <# + .SYNOPSIS + Aggregate children with the default operator + + .DESCRIPTION + Sets the container operator to the default 'all must be OK'. Provided so the + intent can be stated explicitly in a chain. + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $package.CheckDefault() + + .NOTES + Identical to CheckAnd. + #> + [IcingaPlugin] CheckDefault() + { + $this.Operator = 'And'; + return $this; + } + + <# + .SYNOPSIS + Require at least a minimum number of OK children + + .DESCRIPTION + Sets the container so it becomes not-OK when fewer than Count children are OK. + + .PARAMETER Count + | Name | Type | Description | Default | + |-------|--------------|------------------------------------------|---------| + | Count | System.Int32 | Minimum number of children that must be OK. | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $package.CheckMinimum(3) + + .NOTES + Distinct from the leaf CheckMax comparison; this counts OK children. + #> + [IcingaPlugin] CheckMinimum([int]$Count) + { + $this.OperatorMin = $Count; + return $this; + } + + <# + .SYNOPSIS + Allow at most a maximum number of OK children + + .DESCRIPTION + Sets the container so it becomes not-OK when more than Count children are OK. + + .PARAMETER Count + | Name | Type | Description | Default | + |-------|--------------|---------------------------------------------|---------| + | Count | System.Int32 | Maximum number of children that may be OK. | | + + .OUTPUTS + IcingaPlugin — The same node, for chaining. + + .EXAMPLE + PS> $package.CheckMaximum(5) + + .NOTES + Distinct from the leaf CheckMax comparison; this counts OK children. + #> + [IcingaPlugin] CheckMaximum([int]$Count) + { + $this.OperatorMax = $Count; + return $this; + } + + <# + .SYNOPSIS + Add a child plugin to this node + + .DESCRIPTION + Registers a child plugin, sets its parent, indentation and verbosity, propagates + the indentation into any grandchildren and appends it to the list of children. + Returns this container so multiple AddCheck calls chain. + + .PARAMETER Check + | Name | Type | Description | Default | + |-------|-------------|---------------------------------|---------| + | Check | IcingaPlugin | Child plugin to add. | | + + .OUTPUTS + IcingaPlugin — This container, for chaining. + + .EXAMPLE + PS> $package.AddCheck($diskC).AddCheck($diskD) + + .NOTES + A $null child is ignored. + #> + [IcingaPlugin] AddCheck([IcingaPlugin]$Check) + { + if ($null -eq $Check) { + return $this; + } + + $Check.Parent = $this; + $Check.Indention = $this.Indention + 1; + $Check.Verbose = $this.Verbose; + $Check.PropagateIndention(); + $this.Checks += $Check; + + return $this; + } + + <# + .SYNOPSIS + Add multiple child plugins to this node + + .DESCRIPTION + Adds every plugin in the supplied array as a child, in order. Returns this + container so the call chains. + + .PARAMETER Checks + | Name | Type | Description | Default | + |--------|--------------|-------------------------------|---------| + | Checks | System.Array | Child plugins to add. | | + + .OUTPUTS + IcingaPlugin — This container, for chaining. + + .EXAMPLE + PS> $package.AddCheck(@($diskC, $diskD)) + + .NOTES + Each element is added through the single-child AddCheck overload. + #> + [IcingaPlugin] AddCheck([array]$Checks) + { + foreach ($Check in $Checks) { + $this.AddCheck($Check); + } + + return $this; + } + + <# + .SYNOPSIS + Add a check for every required entry that is missing from the available ones + + .DESCRIPTION + Compares a list of required entries (for example the -RequiredPartition or + -Service arguments of a plugin) with the entries found on the host and adds a + child check for every required entry without a match. The new check is named + after NameFormat with '{0}' replaced by the entry, carries the message and is + locked in the given state, so the plugin reports missing objects with a single + call instead of its own loop. + + Required entries are wildcard patterns compared case-insensitively, so a plain + name matches itself. An entry is found when either its raw form or its form + without NormalizePattern matches an available entry. The normalized form is + also used in the check name, so 'C:' with NormalizePattern '[:\\/]+$' is + found as 'C' and reported as 'Partition C'. + + .PARAMETER Required + | Name | Type | Description | Default | + |----------|--------------|---------------------------------------------|---------| + | Required | System.Array | Entries that must exist, wildcards allowed. | | + + .PARAMETER Available + | Name | Type | Description | Default | + |-----------|--------------|--------------------------------------|---------| + | Available | System.Array | Entries that were found on the host. | | + + .PARAMETER NameFormat + | Name | Type | Description | Default | + |------------|---------------|----------------------------------------------|---------| + | NameFormat | System.String | Check name with '{0}' for the missing entry. | | + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|---------------------------------------|---------| + | Message | System.String | Output message of every missing check. | | + + .PARAMETER State + | Name | Type | Description | Default | + |-------|--------------|------------------------------------------------------|---------| + | State | System.Int32 | State of the missing checks (0 OK, 1 WARN, 2 CRIT, 3 UNKN). | | + + .OUTPUTS + IcingaPlugin — This container, for chaining. + + .EXAMPLE + PS> $CheckPackage.AddMissingChecks($Service, $KnownServices, '{0}', 'Service not found', 3).Commit() + + .NOTES + Delegates to the overload with NormalizePattern, without normalization. + #> + [IcingaPlugin] AddMissingChecks([array]$Required, [array]$Available, [string]$NameFormat, [string]$Message, [int]$State) + { + return $this.AddMissingChecks($Required, $Available, $NameFormat, $Message, $State, ''); + } + + <# + .SYNOPSIS + Add a check for every required entry that is missing, with entry normalization + + .DESCRIPTION + Like AddMissingChecks without NormalizePattern; every match of the regular + expression NormalizePattern is removed from a required entry before it is + compared a second time and before it is used in the check name. An invalid + regular expression leaves the entries unchanged. + + .PARAMETER Required + | Name | Type | Description | Default | + |----------|--------------|---------------------------------------------|---------| + | Required | System.Array | Entries that must exist, wildcards allowed. | | + + .PARAMETER Available + | Name | Type | Description | Default | + |-----------|--------------|--------------------------------------|---------| + | Available | System.Array | Entries that were found on the host. | | + + .PARAMETER NameFormat + | Name | Type | Description | Default | + |------------|---------------|----------------------------------------------|---------| + | NameFormat | System.String | Check name with '{0}' for the missing entry. | | + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|---------------------------------------|---------| + | Message | System.String | Output message of every missing check. | | + + .PARAMETER State + | Name | Type | Description | Default | + |-------|--------------|------------------------------------------------------|---------| + | State | System.Int32 | State of the missing checks (0 OK, 1 WARN, 2 CRIT, 3 UNKN). | | + + .PARAMETER NormalizePattern + | Name | Type | Description | Default | + |------------------|---------------|----------------------------------------------------|---------| + | NormalizePattern | System.String | Regex removed from each entry; '' keeps it as is. | | + + .OUTPUTS + IcingaPlugin — This container, for chaining. + + .EXAMPLE + PS> $CheckPackage.AddMissingChecks($RequiredPartition, $KnownPartitions, 'Partition {0}', 'Mandatory partition not found on host', 2, '[:\\/]+$').Commit() + + .NOTES + An invalid wildcard pattern counts as not found, so the entry is reported. + #> + [IcingaPlugin] AddMissingChecks([array]$Required, [array]$Available, [string]$NameFormat, [string]$Message, [int]$State, [string]$NormalizePattern) + { + foreach ($Entry in $Required) { + [string]$Raw = [string]$Entry; + [string]$Normalized = $Raw; + + if ('' -eq $Raw) { + continue; + } + + if ('' -ne $NormalizePattern) { + try { + $Normalized = [regex]::Replace($Raw, $NormalizePattern, ''); + } catch { + $Error.Clear(); + } + } + + if ($this.ContainsMatch($Available, $Raw) -or $this.ContainsMatch($Available, $Normalized)) { + continue; + } + + $this.AddCheck( + [IcingaPlugin]::new([IcingaError]::FormatMessage($NameFormat, @($Normalized))).SetState($State, $Message, $true) + ).Commit(); + } + + return $this; + } + + <# + .SYNOPSIS + Test whether any entry matches a wildcard pattern + + .DESCRIPTION + Compares every entry, converted to a string, case-insensitively with the + wildcard pattern. An invalid pattern matches nothing instead of throwing. + + .PARAMETER Entries + | Name | Type | Description | Default | + |---------|--------------|-----------------------|---------| + | Entries | System.Array | Entries to compare. | | + + .PARAMETER Pattern + | Name | Type | Description | Default | + |---------|---------------|----------------------------|---------| + | Pattern | System.String | Wildcard pattern to match. | | + + .OUTPUTS + System.Boolean — True when at least one entry matches. + + .EXAMPLE + PS> $this.ContainsMatch(@('C', 'D'), 'c') + + .NOTES + Internal helper of AddMissingChecks. + #> + hidden [bool] ContainsMatch([array]$Entries, [string]$Pattern) + { + try { + foreach ($Entry in $Entries) { + if ([string]$Entry -like $Pattern) { + return $true; + } + } + } catch { + $Error.Clear(); + } + + return $false; + } + + <# + .SYNOPSIS + Test whether the node has any child check + + .DESCRIPTION + Returns true as soon as at least one child (hidden ones included) was added, + so a plugin can detect an empty package and report it, for example with + SetError('No service matches the given filter'). + + .OUTPUTS + System.Boolean — True when the node has children. + + .EXAMPLE + PS> if (-not $CheckPackage.HasChecks()) { return $CheckPackage.SetError('Nothing to check').Compile(); } + + .NOTES + Counts direct children only. + #> + [bool] HasChecks() + { + return ($this.Checks.Count -ne 0); + } + + <# + .SYNOPSIS + Recompute the indentation of all descendants + + .DESCRIPTION + Sets every child's indentation to one level below this node and propagates the + verbosity, then recurses. Needed when a subtree that already had children is + attached to a new parent. + + .OUTPUTS + None — Updates the children's state. + + .EXAMPLE + PS> $this.PropagateIndention() + + .NOTES + Internal helper used by AddCheck. + #> + hidden [void] PropagateIndention() + { + foreach ($Child in $this.Checks) { + $Child.Indention = $this.Indention + 1; + $Child.Verbose = $this.Verbose; + $Child.PropagateIndention(); + } + } + + <# + .SYNOPSIS + Propagate a verbosity level through the whole subtree + + .DESCRIPTION + Sets this node's verbosity and recursively applies it to every descendant. + Called at compile time so a verbosity set on the root after the tree was built + still reaches every child and controls the output pruning consistently. + + .PARAMETER Verbose + | Name | Type | Description | Default | + |---------|--------------|--------------------------------------|---------| + | Verbose | System.Int32 | Verbosity level to apply everywhere. | | + + .OUTPUTS + None — Updates this node and its descendants. + + .EXAMPLE + PS> $this.PropagateVerbose(2) + + .NOTES + Internal helper used by Compile. + #> + hidden [void] PropagateVerbose([int]$Verbose) + { + $this.Verbose = $Verbose; + + foreach ($Child in $this.Checks) { + $Child.PropagateVerbose($Verbose); + } + } + + <# + .SYNOPSIS + Resolve the final state of this node and its subtree + + .DESCRIPTION + For a leaf, returns the state that threshold evaluation or an override already + set. For a container, recursively resolves every child, counts OK versus not-OK + children (a hybrid node's own evaluated state counts as one more element), + determines the worst child state and escalates this node to it according to the + configured operator (And/Or/None and the Minimum/Maximum counts). + + .OUTPUTS + System.Int32 — The resolved state of this node. + + .EXAMPLE + PS> $this.ResolveState() + + .NOTES + Called by Compile before rendering; escalate-only, so overrides survive. + #> + hidden [int] ResolveState() + { + if ($this.Checks.Count -eq 0) { + return $this.State; + } + + [int]$Worst = 0; + [int]$OkCount = 0; + [int]$NotOk = 0; + + foreach ($Child in $this.Checks) { + [int]$ChildState = $Child.ResolveState(); + + if ($Child.IsHidden) { + continue; + } + + if ($Worst -lt $ChildState) { + $Worst = $ChildState; + } + + if ($ChildState -eq 0) { + $OkCount++; + } else { + $NotOk++; + } + } + + if ($this.Evaluated) { + if ($Worst -lt $this.State) { + $Worst = $this.State; + } + + if ($this.State -eq 0) { + $OkCount++; + } else { + $NotOk++; + } + } + + # A Minimum/Maximum count replaces the And/Or/None rule (Minimum and Maximum + # may be combined); otherwise the And/Or/None operator decides. + if ($this.OperatorMin -ne -1 -or $this.OperatorMax -ne -1) { + if ($this.OperatorMin -ne -1 -and $OkCount -lt $this.OperatorMin) { + $this.EscalateState($Worst); + } + + if ($this.OperatorMax -ne -1 -and $OkCount -gt $this.OperatorMax) { + $this.EscalateState($Worst); + } + } else { + switch ($this.Operator) { + 'And' { + if ($NotOk -ne 0) { + $this.EscalateState($Worst); + } + break; + } + 'Or' { + if ($OkCount -eq 0) { + $this.EscalateState($Worst); + } + break; + } + 'None' { + if ($OkCount -ne 0) { + $this.EscalateState($Worst); + } + break; + } + } + } + + return $this.State; + } + + <# + .SYNOPSIS + Report whether this node has any not-OK children + + .DESCRIPTION + Returns true when at least one child is not OK, or when a hybrid node's own + evaluated state is not OK. Used to decide whether a container is shown at low + verbosity levels. + + .OUTPUTS + System.Boolean — True when a not-OK child (or own state) exists. + + .EXAMPLE + PS> $this.HasNotOkChecks() + + .NOTES + Requires ResolveState to have run so child states are final. + #> + hidden [bool] HasNotOkChecks() + { + foreach ($Child in $this.Checks) { + if ($Child.State -ne 0) { + return $true; + } + } + + if ($this.Evaluated -and $this.State -ne 0) { + return $true; + } + + return $false; + } + + <# + .SYNOPSIS + Decide whether this node is printed at the current verbosity + + .DESCRIPTION + Reproduces the classic verbosity pruning: the root always prints; verbosity 2 or + higher prints everything; a not-OK node always prints; a container prints when it + has not-OK children; at verbosity 1 an OK child of an affected parent also + prints. Otherwise the node is hidden from the output. + + .OUTPUTS + System.Boolean — True when the node should be part of the output. + + .EXAMPLE + PS> $this.CanOutput() + + .NOTES + Verbosity is propagated from the root through AddCheck. + #> + hidden [bool] CanOutput() + { + if ($this.Indention -eq 0) { + return $true; + } + + if ($this.Verbose -ge 2) { + return $true; + } + + if ($this.State -ne 0) { + return $true; + } + + if ($this.Checks.Count -ne 0) { + return $this.HasNotOkChecks(); + } + + if ($this.Verbose -eq 1 -and $null -ne $this.Parent -and $this.Parent.Checks.Count -ne 0) { + return $this.Parent.HasNotOkChecks(); + } + + return $false; + } + + <# + .SYNOPSIS + Build the indentation prefix for a tree level + + .DESCRIPTION + Returns the leading whitespace and '\_ ' marker for the given indentation level, + matching the classic Icinga for Windows nested output. Level 0 has no prefix. + + .PARAMETER Indention + | Name | Type | Description | Default | + |-----------|--------------|--------------------------------|---------| + | Indention | System.Int32 | Zero-based tree depth. | | + + .OUTPUTS + System.String — The indentation prefix. + + .EXAMPLE + PS> $this.IndentPrefix(1) + + .NOTES + Level 1 is flush-left ('\_ '); each additional level adds three leading spaces. + #> + hidden [string] IndentPrefix([int]$Indention) + { + if ($Indention -le 0) { + return ''; + } + + # First level ('\_ ') starts at column 0; only deeper levels are indented. + [string]$Prefix = ''; + for ($i = 1; $i -lt $Indention; $i++) { + $Prefix += ' '; + } + + return $Prefix + '\_ '; + } + + <# + .SYNOPSIS + Build the single output line for this node + + .DESCRIPTION + Returns the container summary line when the node has children, otherwise the + leaf line. + + .OUTPUTS + System.String — The node's own one-line output (without indentation). + + .EXAMPLE + PS> $this.BuildLine() + + .NOTES + Internal helper used by RenderOutput. + #> + hidden [string] BuildLine() + { + if ($this.Checks.Count -ne 0) { + return $this.BuildContainerLine(); + } + + return $this.BuildLeafLine(); + } + + <# + .SYNOPSIS + Build the output line for a leaf check + + .DESCRIPTION + Renders '[STATE] Name: message' (or '[STATE] Name' without a message). A node + that was neither evaluated nor forced, or one explicitly marked as a notice, + renders with the [INFO] prefix. + + .OUTPUTS + System.String — The leaf output line. + + .EXAMPLE + PS> $this.BuildLeafLine() + + .NOTES + Internal helper used by BuildLine. + #> + hidden [string] BuildLeafLine() + { + [string]$Status = [IcingaPlugin]::StateText[$this.State]; + + if ($this.IsNoticeObject -or $this.IsNotice) { + $Status = '[INFO]'; + } elseif (-not $this.FixedState -and -not $this.Evaluated) { + $Status = '[INFO]'; + } + + if ('' -ne $this.OutputMessage) { + return [string]::Format('{0} {1}: {2}', $Status, $this.Name, $this.OutputMessage); + } + + return [string]::Format('{0} {1}', $Status, $this.Name); + } + + <# + .SYNOPSIS + Build the output line for a container + + .DESCRIPTION + Renders '[STATE] Name'. At the root, or when AddSummaryHeader is set, it also + appends the summary header: a per-state count of every leaf check in the whole + subtree (containers themselves are not counted) including the OK count, followed + by the named lists of the not-OK leaf checks, for example + '[CRITICAL] Disks: 2 Critical 2 Ok [CRITICAL] C:, D:'. At verbosity level 3 or + higher the operator configuration is appended, for example ' (All must be [OK])'. + A notice package renders with the [INFO] prefix. A container put into the error + state with SetError renders '[UNKNOWN] Name: message' instead of the summary + header. + + .OUTPUTS + System.String — The container output line. + + .EXAMPLE + PS> $this.BuildContainerLine() + + .NOTES + Internal helper used by BuildLine. The header aggregates leaf checks recursively + so the first line reflects the state of every actual check, not just the direct + children. + #> + hidden [string] BuildContainerLine() + { + [string]$Status = [IcingaPlugin]::StateText[$this.State]; + + if ($this.IsNotice) { + $Status = '[INFO]'; + } + + [string]$Config = ''; + if ($this.Verbose -ge 3) { + $Config = $this.ShowPackageConfig(); + } + + # The error explains why the checks below are incomplete, so it replaces the + # summary header instead of being hidden behind it. + if ($this.HasError -and '' -ne $this.OutputMessage) { + return [string]::Format('{0} {1}: {2}{3}', $Status, $this.Name, $this.OutputMessage, $Config); + } + + if ($this.Indention -ne 0 -and -not $this.AddSummaryHeader) { + return [string]::Format('{0} {1}{2}', $Status, $this.Name, $Config); + } + + [array]$Leaves = $this.CollectLeafChecks(); + [int]$OkCount = 0; + [array]$Unknown = @(); + [array]$Critical = @(); + [array]$Warning = @(); + + foreach ($Leaf in $Leaves) { + switch ($Leaf.State) { + 3 { $Unknown += $Leaf.Name; break; } + 2 { $Critical += $Leaf.Name; break; } + 1 { $Warning += $Leaf.Name; break; } + 0 { $OkCount++; break; } + } + } + + [string]$Summary = ''; + if ($Unknown.Count -gt 0) { + $Summary += [string]::Format(' {0} Unknown', $Unknown.Count); + } + if ($Critical.Count -gt 0) { + $Summary += [string]::Format(' {0} Critical', $Critical.Count); + } + if ($Warning.Count -gt 0) { + $Summary += [string]::Format(' {0} Warning', $Warning.Count); + } + if ($OkCount -gt 0) { + $Summary += [string]::Format(' {0} Ok', $OkCount); + } + + [string]$Lists = ''; + if ($Unknown.Count -gt 0) { + $Lists += [string]::Format(' [UNKNOWN] {0}', ($Unknown -join ', ')); + } + if ($Critical.Count -gt 0) { + $Lists += [string]::Format(' [CRITICAL] {0}', ($Critical -join ', ')); + } + if ($Warning.Count -gt 0) { + $Lists += [string]::Format(' [WARNING] {0}', ($Warning -join ', ')); + } + + [string]$Colon = ''; + if ('' -ne $Summary -or '' -ne $Lists) { + $Colon = ':'; + } + + return [string]::Format('{0} {1}{2}{3}{4}{5}', $Status, $this.Name, $Colon, $Summary, $Lists, $Config); + } + + <# + .SYNOPSIS + Collect every leaf check in the subtree + + .DESCRIPTION + Recursively gathers all descendant nodes that are leaf checks (nodes without + children), skipping container nodes, hidden nodes and notice packages. Used by + the summary header so the root line reflects the state of every actual check + regardless of nesting depth. A notice package (IsNotice) only lists information, + such as the files a directory check found, so its entries are not counted. + + .OUTPUTS + System.Array — The leaf IcingaPlugin nodes in the subtree. + + .EXAMPLE + PS> $this.CollectLeafChecks() + + .NOTES + Internal helper used by BuildContainerLine. + #> + hidden [array] CollectLeafChecks() + { + [array]$Leaves = @(); + + foreach ($Child in $this.Checks) { + if ($Child.IsHidden -or ($Child.IsNotice -and $Child.Checks.Count -ne 0)) { + continue; + } + + if ($Child.Checks.Count -eq 0) { + $Leaves += $Child; + } else { + $Leaves += $Child.CollectLeafChecks(); + } + } + + return $Leaves; + } + + <# + .SYNOPSIS + Describe the container's aggregation operator + + .DESCRIPTION + Returns a short, human-readable suffix describing how the container aggregates + its children, matching the classic package config text. Shown in the output at + verbosity level 3 or higher. + + .OUTPUTS + System.String — The operator description, for example ' (All must be [OK])'. + + .EXAMPLE + PS> $this.ShowPackageConfig() + + .NOTES + Internal helper used by BuildContainerLine; the Minimum/Maximum counts take + precedence over the And/Or/None operator when set. + #> + hidden [string] ShowPackageConfig() + { + # Match the original framework: notice packages and the 'None' operator carry + # no configuration text. + if ($this.IsNotice) { + return ''; + } + + if ($this.OperatorMin -ne -1) { + return [string]::Format(' (Atleast {0} must be [OK])', $this.OperatorMin); + } + + if ($this.OperatorMax -ne -1) { + return [string]::Format(' (Not more than {0} must be [OK])', $this.OperatorMax); + } + + if ($this.Operator -eq 'And') { + return ' (All must be [OK])'; + } + + if ($this.Operator -eq 'Or') { + return ' (Atleast one must be [OK])'; + } + + return ''; + } + + <# + .SYNOPSIS + Render the indented output tree for this node + + .DESCRIPTION + Produces the node's own line prefixed with its indentation and recursively + appends the rendered output of every visible child, joined with newlines. Hidden + nodes and nodes pruned by the current verbosity are skipped. + + .OUTPUTS + System.String — The multi-line, indented output. + + .EXAMPLE + PS> $this.RenderOutput() + + .NOTES + Requires ResolveState to have run so states are final. + #> + hidden [string] RenderOutput() + { + if ($this.IsHidden -or -not $this.CanOutput()) { + return ''; + } + + [array]$Lines = @(); + $Lines += ($this.IndentPrefix($this.Indention) + $this.BuildLine()); + + foreach ($Child in $this.Checks) { + if ($Child.IsHidden -or -not $Child.CanOutput()) { + continue; + } + + $Lines += $Child.RenderOutput(); + } + + return ($Lines -join "`n"); + } + + <# + .SYNOPSIS + Rebuild the performance data for a leaf check + + .DESCRIPTION + Formats a single performance-data metric of the form + index::ifw_template::label=value;warn;crit;min;max (the check_multi format) + from the current value, unit and thresholds, and stores it as this node's + performance data. The thresholds are written as resolved by the last comparison + (percent and unit thresholds in base units, for example '80%' of 500GB becomes + '400000000000'), falling back to the configured strings when no resolved value + exists. The structured label is built by BuildPerfDataLabel. No metric is produced + when performance data is disabled or the value is not numeric. + + .OUTPUTS + None — Updates this node's performance data. + + .EXAMPLE + PS> $this.BuildPerfData() + + .NOTES + Called after each comparison; only numeric values yield perfdata. + #> + hidden [void] BuildPerfData() + { + $this.PerfData = @(); + + if ($this.NoPerfData) { + return; + } + + if (-not $this.IsNumeric($this.Value)) { + return; + } + + [string]$Warning = $this.WarningThreshold; + [string]$Critical = $this.CriticalThreshold; + + if ('' -ne $this.ResolvedWarning) { + $Warning = $this.ResolvedWarning; + } + + if ('' -ne $this.ResolvedCritical) { + $Critical = $this.ResolvedCritical; + } + + [string]$Metric = [string]::Format( + '{0}={1}{2};{3};{4};{5};{6}', + $this.BuildPerfDataLabel(), + $this.FormatNumber($this.Value), + $this.Unit, + $Warning, + $Critical, + $this.MinimumValue, + $this.MaximumValue + ); + + $this.PerfData = @($Metric); + } + + <# + .SYNOPSIS + Detect the calling Invoke-IcingaCheck* command from the call stack + + .DESCRIPTION + Walks the PowerShell call stack and returns the name of the first frame whose + command looks like an Icinga check command (Invoke-IcingaCheck*). This is used to + derive the default performance-data template. Returns an empty string when no such + command is on the stack (for example when constructed outside a plugin). + + .OUTPUTS + System.String — The check command name, or '' when none was found. + + .EXAMPLE + PS> $this.DetectCheckCommand() + + .NOTES + Internal helper called once at construction. + #> + hidden [string] DetectCheckCommand() + { + foreach ($Frame in (Get-PSCallStack)) { + if (([string]$Frame.Command).ToLower() -like 'invoke-icingacheck*') { + return [string]$Frame.Command; + } + } + + return ''; + } + + <# + .SYNOPSIS + Sanitize a performance-data metric segment + + .DESCRIPTION + Removes every non-word character and lower-cases the value so a metric segment is + a safe, space-free token for the check_multi label. Underscores are preserved. + + .PARAMETER Value + | Name | Type | Description | Default | + |-------|---------------|-----------------------------|---------| + | Value | System.String | The raw metric segment. | | + + .OUTPUTS + System.String — The sanitized, lower-cased segment. + + .EXAMPLE + PS> $this.SanitizeMetric('Core #0') + + .NOTES + Internal helper used by BuildPerfDataLabel. + #> + hidden [string] SanitizeMetric([string]$Value) + { + return ($Value -replace '[\W]', '').ToLower(); + } + + <# + .SYNOPSIS + Build the check_multi performance-data label + + .DESCRIPTION + Assembles the structured label 'index::ifw_template::label' used by the check_multi + performance-data format. The index defaults to 'default'; the template defaults to + the calling Invoke-IcingaCheck* command with that prefix stripped (falling back to + 'check'), always carries the fixed 'ifw_' namespace, and can be overridden with + MetricName; the label defaults to the node's Name and can be overridden with + MetricLabel. Every segment is sanitized and lower-cased. + + .OUTPUTS + System.String — The structured performance-data label. + + .EXAMPLE + PS> $this.BuildPerfDataLabel() + + .NOTES + Internal helper used by BuildPerfData. Example: 'c::ifw_partitionspace::free'. + #> + hidden [string] BuildPerfDataLabel() + { + [string]$Index = $this.MetricIndexValue; + if ('' -eq $Index) { + $Index = 'default'; + } + + [string]$Template = $this.MetricNameValue; + if ('' -eq $Template) { + $Template = ([string]$this.CheckCommand) -replace '(?i)^Invoke-IcingaCheck', ''; + } + if ('' -eq $Template) { + $Template = 'check'; + } + if ($Template.ToLower() -notlike 'ifw_*') { + $Template = 'ifw_' + $Template; + } + + [string]$Label = $this.MetricLabelValue; + if ('' -eq $Label) { + $Label = $this.Name; + } + + return [string]::Format( + '{0}::{1}::{2}', + $this.SanitizeMetric($Index), + $this.SanitizeMetric($Template), + $this.SanitizeMetric($Label) + ); + } + + <# + .SYNOPSIS + Collect the performance data of this node and its subtree + + .DESCRIPTION + Returns a flat array containing this node's performance-data metric (if any) and, + recursively, the metrics of every child. + + .OUTPUTS + System.Array — All performance-data metric strings in the subtree. + + .EXAMPLE + PS> $this.CollectPerfData() + + .NOTES + Internal helper used by Compile. + #> + hidden [array] CollectPerfData() + { + [array]$Perf = @(); + + if ($this.PerfData.Count -gt 0) { + $Perf += $this.PerfData; + } + + foreach ($Child in $this.Checks) { + $Perf += $Child.CollectPerfData(); + } + + return $Perf; + } + + <# + .SYNOPSIS + Test whether a value can be treated as a number + + .DESCRIPTION + Returns true when the value parses as a number under the invariant culture. Used + to decide whether a leaf produces performance data. + + .PARAMETER Value + | Name | Type | Description | Default | + |-------|---------------|---------------------------|---------| + | Value | System.Object | Value to test. | | + + .OUTPUTS + System.Boolean — True when the value is numeric. + + .EXAMPLE + PS> $this.IsNumeric(95) + + .NOTES + Internal helper used by BuildPerfData. + #> + hidden [bool] IsNumeric([object]$Value) + { + if ($null -eq $Value) { + return $false; + } + + [double]$Parsed = 0; + return [double]::TryParse([string]$Value, [System.Globalization.NumberStyles]::Any, [System.Globalization.CultureInfo]::InvariantCulture, [ref]$Parsed); + } + + <# + .SYNOPSIS + Format a numeric value for performance data + + .DESCRIPTION + Formats the value under the invariant culture so the decimal separator is always + a dot. Falls back to the raw string when the value is not numeric. + + .PARAMETER Value + | Name | Type | Description | Default | + |-------|---------------|---------------------------|---------| + | Value | System.Object | Value to format. | | + + .OUTPUTS + System.String — The formatted value. + + .EXAMPLE + PS> $this.FormatNumber(95) + + .NOTES + Internal helper used by BuildPerfData. + #> + hidden [string] FormatNumber([object]$Value) + { + [double]$Parsed = 0; + if ([double]::TryParse([string]$Value, [System.Globalization.NumberStyles]::Any, [System.Globalization.CultureInfo]::InvariantCulture, [ref]$Parsed)) { + return $Parsed.ToString([System.Globalization.CultureInfo]::InvariantCulture); + } + + return [string]$Value; + } + + <# + .SYNOPSIS + Write the plugin output and performance data to the console + + .DESCRIPTION + Writes the rendered output and, on a following line, the performance-data block + ('| metric1 metric2 ...') straight to the console so an Icinga agent can parse it + verbatim. Used only on the main thread; inside a background daemon Compile skips + this and leaves the result in the thread-local runtime state. + + .PARAMETER Output + | Name | Type | Description | Default | + |--------|---------------|------------------------------|---------| + | Output | System.String | Rendered plugin output. | | + + .PARAMETER Perf + | Name | Type | Description | Default | + |------|--------------|--------------------------------------|---------| + | Perf | System.Array | Performance-data metric strings. | | + + .OUTPUTS + None — Writes to the console. + + .EXAMPLE + PS> $this.WriteConsoleOutput('[OK] Load: 5%', @('load=5%;80;90;0;100')) + + .NOTES + Uses System.Console directly because Icinga parses the plugin output literally + and it must not be reformatted by the logging subsystem. + #> + hidden [void] WriteConsoleOutput([string]$Output, [array]$Perf) + { + [string]$Line = $Output; + + if ($Perf.Count -gt 0) { + $Line = [string]::Format('{0}{1}| {2}', $Output, "`n", ($Perf -join ' ')); + } + + [System.Console]::WriteLine($Line); + } + + <# + .SYNOPSIS + Ensure the thread-local check-result slot exists + + .DESCRIPTION + Guarantees that the supplied Private runtime object has an Icinga sub-object with + a CheckResult property before Compile writes to it. New-ModuleBaseEnvironment + creates this slot for fresh sessions and worker runspaces, but a session that was + already warm when the module was updated keeps an older Private object without it; + this makes Compile self-sufficient in that case too, adding the missing members + on demand. + + .PARAMETER Private + | Name | Type | Description | Default | + |---------|---------------|-----------------------------------------------|---------| + | Private | System.Object | The Private runtime object to normalise. | | + + .OUTPUTS + None — Adds the Icinga.CheckResult slot when it is missing. + + .EXAMPLE + PS> $this.EnsureResultSlot((Get-GlobalRuntimeVariable).Private) + + .NOTES + Internal helper used by Compile. + #> + hidden [void] EnsureResultSlot([object]$Private) + { + if ($null -eq $Private.PSObject.Properties['Icinga'] -or $null -eq $Private.Icinga) { + $Private | Add-Member -MemberType NoteProperty -Name 'Icinga' -Value ([PSCustomObject]@{ 'CheckResult' = $null }) -Force; + return; + } + + if ($null -eq $Private.Icinga.PSObject.Properties['CheckResult']) { + $Private.Icinga | Add-Member -MemberType NoteProperty -Name 'CheckResult' -Value $null; + } + } + + <# + .SYNOPSIS + Terminate a configuration chain without producing output + + .DESCRIPTION + A void end-of-chain marker. Because every fluent setter, comparison, override and + operator method returns the node, an unconsumed chain would otherwise leak the + node to the pipeline. Calling Commit at the end consumes it so callers never need + '| Out-Null' or a '[void]' cast. + + .OUTPUTS + None — Ends the chain. + + .EXAMPLE + PS> $check.Warning('80').Critical('90').CheckRange().Commit() + + .NOTES + Compile is the terminator at the root; Commit is for configuration-only chains. + #> + [void] Commit() + { + } + + <# + .SYNOPSIS + Compile the plugin tree into a result and return the exit code + + .DESCRIPTION + Resolves the state of the whole tree, renders the indented output, collects the + performance data and stores an IcingaCheckResult in the thread-local runtime + state at $Global:IcingaForWindows.Private.Icinga.CheckResult. On the main thread + it also writes the output to the console; inside a background daemon it writes + nothing and leaves the result in Private for the REST API. Always returns the + integer Icinga exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). + + .OUTPUTS + System.Int32 — The Icinga plugin exit code. + + .EXAMPLE + PS> return $package.Compile() + + .NOTES + The result (exit code, output and the performance-data array) is always written + to Private, never to Public. Access the global via Get-GlobalRuntimeVariable so + the correct per-runspace state is used inside worker threads. + #> + [int] Compile() + { + $this.ResolveState(); + $this.PropagateVerbose($this.Verbose); + + [string]$Output = $this.RenderOutput(); + [array]$Perf = $this.CollectPerfData(); + + $GlobalVariable = Get-GlobalRuntimeVariable; + $this.EnsureResultSlot($GlobalVariable.Private); + $GlobalVariable.Private.Icinga.CheckResult = [IcingaCheckResult]::new($this.State, $Output, $Perf); + + if (-not $GlobalVariable.Protected.IsBackgroundDaemon) { + $this.WriteConsoleOutput($Output, $Perf); + } + + return $this.State; + } +} diff --git a/src/Core/ErrorHandling/Public/Test-IcingaError.ps1 b/src/Core/ErrorHandling/Public/Test-IcingaError.ps1 new file mode 100644 index 0000000..5de515e --- /dev/null +++ b/src/Core/ErrorHandling/Public/Test-IcingaError.ps1 @@ -0,0 +1,38 @@ +<# +.SYNOPSIS +Test whether a value is an IcingaError returned by a data collection function + +.DESCRIPTION +Data collection functions such as Get-IcingaWindowsInformation return an +IcingaError in place of their data when they fail. Test-IcingaError checks a +result against the IcingaError type of the current runspace, so a plugin or +provider can stop with a single check before it uses the data. It returns $false +for $null, for collections and for every other value. + +.PARAMETER InputObject +| Name | Type | Description | Default | +|-------------|---------------|------------------------------------------------|---------| +| InputObject | System.Object | Result of a data collection function to test. | $null | + +.OUTPUTS +System.Boolean — $true when InputObject is an IcingaError, otherwise $false. + +.EXAMPLE +PS> $Services = Get-IcingaWindowsInformation -ClassName 'Win32_Service'; +PS> if (Test-IcingaError -InputObject $Services) { return $CheckPackage.SetError($Services).Compile(); } + +Stops the plugin with the error message when the query failed. + +.NOTES +Use it instead of '-is [IcingaError]'. Every runspace shares the compiled kernel, +so the literal resolves to the type of the main runspace and does not match an +error created inside a background thread. No external dependencies. +#> +function Test-IcingaError() +{ + param ( + [object]$InputObject = $null + ); + + return ($InputObject -is ('IcingaError' -as [type])); +} diff --git a/src/IcingaProtocol/Private/Start-IcingaProtocolWorker.ps1 b/src/IcingaProtocol/Private/Start-IcingaProtocolWorker.ps1 index 9eb2b59..249aa3c 100644 --- a/src/IcingaProtocol/Private/Start-IcingaProtocolWorker.ps1 +++ b/src/IcingaProtocol/Private/Start-IcingaProtocolWorker.ps1 @@ -143,23 +143,42 @@ function Start-IcingaProtocolWorker() 'ExecutionTime' = ($CheckFinished - $CheckStarted); }; - $CheckFinished = (Get-IcingaUnixTime -Milliseconds); - $CheckResult = $CheckFinished; + # Initialize variables for check result data + $CheckResultOutput = ''; + [array]$CheckPerfData = @(); + + # Execute the command, and catch any exceptions + try { + $ExitCode = & $ExecuteCommand; + } catch { + $ExitCode = 3; + $CheckResultOutput = "[UNKNOWN] Icinga Plugin Command Execution was thrown:`n`n" + $_.Exception.Message.ToString(); + } + + # In case we have a CheckResult, store the result in our variables + if ($null -ne $Global:IcingaForWindows.Private.Icinga.CheckResult) { + $CheckResultOutput = $Global:IcingaForWindows.Private.Icinga.CheckResult.ToString(); + [array]$CheckPerfData = $Global:IcingaForWindows.Private.Icinga.CheckResult.PerformanceData; + } + # Create the finish timestamp after our plugin execution + $CheckFinished = (Get-IcingaUnixTime -Milliseconds); + + # Build our entire CheckResult object for Icinga $CheckResultData = @{ 'host' = $RPCMessage.params.host; 'service' = $RPCMessage.params.service; 'cr' = @{ 'check_source' = $Global:IcingaForWindows.Public.IcingaProtocol.Config.Hostname; 'command' = 'full call stack with arguments'; - 'output' = $CheckResult; - 'exit_status' = 0; + 'output' = $CheckResultOutput; + 'exit_status' = $ExitCode; 'active' = $TRUE; - 'state' = 0; + 'state' = $ExitCode; 'type' = 'CheckResult'; 'execution_start' = $CheckStarted; 'execution_end' = $CheckFinished; - 'performance_data' = @(); + 'performance_data' = @($CheckPerfData); }; }; @@ -197,13 +216,17 @@ function Start-IcingaProtocolWorker() } catch { Write-LoggingEntry -Message 'An error occurred in Icinga Protocol Worker' -Level 'Error' -Data @{ 'ExceptionMessage' = $_.Exception.Message; }; } finally { - $RPCMessage = $null; - $RPCObject = $null; - $CheckStarted = $null; - $CheckFinished = $null; - $ExecuteCommand = $null; - $CheckResult = $null; - $CheckResultData = $null; + # Cleanup our entire scop + $RPCMessage = $null; + $RPCObject = $null; + $CheckStarted = $null; + $CheckFinished = $null; + $ExecuteCommand = $null; + $CheckResultOutput = $null; + $CheckPerfData = $null; + $ExitCode = $null; + $CheckResultData = $null; + $Global:IcingaForWindows.Private.Icinga.CheckResult = $null; } } } diff --git a/src/Plugins/Public/New-IcingaPlugin.ps1 b/src/Plugins/Public/New-IcingaPlugin.ps1 new file mode 100644 index 0000000..535050b --- /dev/null +++ b/src/Plugins/Public/New-IcingaPlugin.ps1 @@ -0,0 +1,71 @@ +<# +.SYNOPSIS +Create an IcingaPlugin node with the class type of the current runspace + +.DESCRIPTION +New-IcingaPlugin is the factory every plugin and function uses instead of +[IcingaPlugin]::new(). It resolves the IcingaPlugin type at runtime in the +calling runspace and calls the matching constructor: with a name only it creates +a container that aggregates child checks, with a value it creates a check, and +with a unit the value and the thresholds of the check use that unit. + +The returned node exposes the full fluent surface of IcingaPlugin. Wrap the call +in parentheses to chain methods directly, for example +(New-IcingaPlugin 'C:' 55 '%').Warning('80').CheckRange(). The parameters are +positional in the order Name, Value, Unit. + +.PARAMETER Name +| Name | Type | Description | Default | +|------|---------------|--------------------------------------|---------| +| Name | System.String | Display name of the plugin node. | $null | + +.PARAMETER Value +| Name | Type | Description | Default | +|-------|---------------|--------------------------------------------------------------------|---------| +| Value | System.Object | Measured value, a number or ''. Makes the node a check. | $null | + +.PARAMETER Unit +| Name | Type | Description | Default | +|------|---------------|--------------------------------------------------------------|---------| +| Unit | System.String | Icinga unit of the value and thresholds, e.g. '%', 'B', 's'. | | + +.OUTPUTS +IcingaPlugin — The new plugin node, an instance of the IcingaPlugin type loaded by +the current runspace. + +.EXAMPLE +PS> $CheckPackage = New-IcingaPlugin 'Disks'; +PS> $CheckPackage.AddCheck((New-IcingaPlugin 'C:' 55 '%').Warning('80').Critical('90').CheckRange()).Commit(); + +Creates a container and adds a disk check that is evaluated immediately. + +.EXAMPLE +PS> (New-IcingaPlugin 'System Uptime' 93784 's').Warning('1d:').CheckRange() + +Creates a time check whose output renders the value as '1d 2h 3m 4s'. + +.NOTES +Every runspace shares the compiled kernel, so a class literal such as +[IcingaPlugin]::new() inside a function resolves to the type of the main +runspace. On Windows PowerShell 5.1 a method call on such an instance from a +background thread waits until the main runspace is idle, which stalls daemons and +workers. The runtime lookup returns the type the current runspace loaded itself. +Keep the node inside the runspace that created it and hand only its rendered +output, exit code and performance data to other threads. +#> +function New-IcingaPlugin() +{ + param ( + [string]$Name = $null, + [object]$Value = $null, + [string]$Unit = '' + ); + + $PluginType = 'IcingaPlugin' -as [type]; + + if ($PSBoundParameters.ContainsKey('Value') -or $PSBoundParameters.ContainsKey('Unit')) { + return $PluginType::new($Name, $Value, $Unit); + } + + return $PluginType::new($Name); +} From abb8a2bd5e07ccaa4badbef8d9f87656589fa0ae Mon Sep 17 00:00:00 2001 From: Lord Hepipud Date: Wed, 11 Nov 2026 17:07:46 +0100 Subject: [PATCH 2/5] Enhance IcingaPlugin with multi-value thresholds, translations, comfort overloads and code-styling compliance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This commit expands the `IcingaPlugin` class and its companion components to cover all real-world check plugin patterns (such as Services, Scheduled Tasks, CPU, Partition Space, Certificates, and Uptime) without requiring boilerplate loops or manual type conversions in individual plugins, while fixing aggregation, formatting, and cross-platform test edge cases. ### 1. Multi-Value Thresholds & List Comparisons (`CheckIn`, `CheckNotIn`, Array Overloads) * **Why**: Plugins such as `Invoke-IcingaCheckScheduledTask` (`-State @('Ready', 'Running')`) or `Invoke-IcingaCheckService` frequently validate a measured state against an array of allowed or forbidden values/patterns rather than a single scalar string. * **What & How**: * Added `Warning([array]$Warning)` and `Critical([array]$Critical)` overloads alongside `Warning([object])` and `Critical([object])` to normalize single and multi-value thresholds (numbers, enums, `[TimeSpan]`, strings) through `ConvertThresholdEntry()` and `CleanThresholdList()`. * Added `CheckIn()` and `CheckNotIn()` comparison methods for membership checks (`value must be in list` vs. `value must not be in list`). * Extended `CheckEqual()`, `CheckNotEqual()`, `CheckLike()`, `CheckNotLike()`, `CheckMatch()`, and `CheckNotMatch()` so they automatically evaluate against multi-value threshold arrays via `EvaluateListComparison()`, `FindMatchingPattern()`, and `ResolveThresholdList()`. ### 2. Value & Threshold Translation (`.Translate()`) * **Why**: System APIs often return numeric status codes or enums (e.g. Service status `4` -> `'Running'`, Task status `3` -> `'Ready'`, or sentinel timestamp `0` -> `'Never'`) where human-readable names are required in plugin output while numeric values must be preserved in Icinga performance data. * **What & How**: * Added `.Translate()`, `.Translate([hashtable]$Mapping)`, and `.Translate([string]$Text)` on `IcingaPlugin`. * Automatically resolves enum values, lookup hashtables, or direct display strings for output rendering (`ApplyValueTranslation()`, `EnsureLeafDefaults()`) and string/list comparisons, while `ResolveNumericValue()` and `ResolvePerfDataThreshold()` map values and thresholds back to their numeric representation for performance data. ### 3. Automatic `[TimeSpan]` & Percentage Threshold Handling * **Why**: Date/time difference checks (such as certificate expiration or task run times) naturally produce `[TimeSpan]` objects, and percentage checks (`Unit = '%'`) should accept both `'80'` and `'80%'` without forcing `.BaseValue(100)`. * **What & How**: * Updated `Initialize()` and `BaseValue()` to automatically convert `[TimeSpan]` instances to `.TotalSeconds` and default an empty node unit to `'s'`. * Updated `NewThresholds()` and `ResolvePerfDataThreshold()` to strip `%` suffixes on `'%'`-unit checks when no `BaseValueSetting` is configured, preventing `MissingBaseValue` (UNKNOWN) errors when users pass `'80%'` to a percentage check. ### 4. Empty Package Handling & Container Aggregation Fixes * **Why**: Classic Icinga for Windows check packages report `UNKNOWN: No checks added to this object` when a filter matches nothing, unless `-MitigateUnknown` / `IgnoreEmptyPackage` is set or the package is an informational notice (`[INFO] Nothing to report`). Additionally, container operators (`CheckMinimum`, `CheckMaximum`, `CheckNone`, `CheckOr`) had edge cases when all children were OK or when `[INFO]` notice children were present. * **What & How**: * Added `SetIgnoreEmptyPackage()` (`$true` default and `[bool]` overload), `IsEmptyPackage()`, and `IsNoticeNode()` in `ResolveState()`. * Updated `HasChecks()` to ignore `IsHidden` background-metric nodes so containers with only hidden children are properly recognized as having no visible checks. * Excluded `[INFO]` notice nodes and ignored-empty subpackages from parent state aggregation (`ResolveState()`) and root summary counts (`CollectLeafChecks()`). * Fixed `CheckMinimum`, `CheckMaximum`, and `CheckNone` in `ResolveState()` to escalate to `CRITICAL` (`[System.Math]::Max($Worst, 2)`) when a count or `None` rule is violated even if individual children are `OK` (`$Worst -eq 0`). * Fixed `CheckOr` so an empty container does not falsely escalate, and updated `ShowPackageConfig()` to render `' (Between {0} and {1} must be [OK])'` when both `CheckMinimum` and `CheckMaximum` are configured. * Added `SetSkipSummary()` (`$true` default and `[bool]` overload) to exclude informational or auxiliary checks from the root summary header. ### 5. Comfort State Overloads & Performance Data Refinements * **Why**: Plugins with `-OverrideNotOk` / `-OverrideNotFound` parameters pass state names (`'Ok'`, `'Warning'`, `'Critical'`, `'Unknown'`) as strings, and often flip a check's state (e.g. `.SetCritical()`) while keeping its auto-formatted value message or passing numeric `Minimum(0)` / `Maximum(100)` bounds. * **What & How**: * Added `[string]` state overloads to `SetState()` and `AddMissingChecks()` backed by `ResolveStateCode()`. * Added parameterless overloads `SetOk()`, `SetWarning()`, `SetCritical()`, `SetUnknown()`, and `SetNotice()`, and widened `Minimum([object])` and `Maximum([object])` to accept numbers directly and rebuild performance data when called after evaluation. * Updated `CollectPerfData()` to respect `NoPerfData` on containers (suppressing subtree metrics) and deduplicate metrics by `index::ifw_template::label`. * Updated `BuildPerfDataLabel()` to apply the `'value'` fallback after `SanitizeMetric()` so names consisting only of special characters never produce an empty label. * Updated `FormatNumber()` to use fixed-point `0.##########` formatting (avoiding scientific notation in perfdata), `HumanizeByteValues()` / `HumanizeTimeValues()` to support negative values, and `ApplyDisplayUnit()` to suppress the continuous counter unit `'c'` in display messages. ### 6. Code-Styling Compliance, Em-Dash Removal & Test Fixes * **Why**: Windows PowerShell 5.1 reads UTF-8 files without BOM as Windows-1252, turning Unicode em-dashes (`—`, `U+2014`) into `—` Mojibake in help blocks. Furthermore, `Tests/ClassLiteral.Tests.ps1` failed on UNC paths (`\\Mac\Home\...`) in PowerShell 5.1 and PowerShell 7 due to `Resolve-Path` provider-prefix and `..` normalization differences. * **What & How**: * Updated `CLAUDE.md` to forbid Unicode em-dashes/en-dashes in PowerShell files and removed the obsolete backtick restriction. * Replaced all Unicode em-dashes with ASCII `--` and aligned all assignment blocks (`=`) and `.PARAMETER` Markdown help tables across `IcingaPlugin.ps1`, `IcingaCheckResult.ps1`, `IcingaError.ps1`, `New-IcingaPlugin.ps1`, `Test-IcingaError.ps1`, and their test files. * Fixed `Tests/ClassLiteral.Tests.ps1` to resolve `$script:SourceRoot` via `[System.IO.Path]::GetFullPath(...)` so substring path slicing works reliably on local and UNC paths in both PowerShell 5.1 and PowerShell 7. * Expanded `Tests/IcingaPlugin.Tests.ps1` to 82 comprehensive unit tests covering all new methods, overloads, and edge cases. --- CLAUDE.md | 6 +- Tests/IcingaPlugin.Tests.ps1 | 438 ++- Tests/New-IcingaPlugin.Tests.ps1 | 2 +- src/Classes/Icinga/IcingaCheckResult.ps1 | 14 +- src/Classes/Icinga/IcingaError.ps1 | 30 +- src/Classes/Icinga/IcingaPlugin.ps1 | 2612 ++++++++++++++--- .../ErrorHandling/Public/Test-IcingaError.ps1 | 2 +- src/Plugins/Public/New-IcingaPlugin.ps1 | 8 +- 8 files changed, 2693 insertions(+), 419 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index bd75f2f..680339e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -133,7 +133,7 @@ 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. @@ -187,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 @@ -212,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. diff --git a/Tests/IcingaPlugin.Tests.ps1 b/Tests/IcingaPlugin.Tests.ps1 index 148efc4..a4fdb6e 100644 --- a/Tests/IcingaPlugin.Tests.ps1 +++ b/Tests/IcingaPlugin.Tests.ps1 @@ -8,7 +8,7 @@ Describe 'IcingaPlugin' { # 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 | + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | Where-Object { $_.ModuleType -eq 'Script' } | Select-Object -First 1; @@ -99,7 +99,10 @@ Describe 'IcingaPlugin' { 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; } + 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%;;;;'; @@ -229,7 +232,7 @@ Describe 'IcingaPlugin' { It 'writes the result to Private without console output in daemon mode' { $Global:IcingaForWindows.Protected.IsBackgroundDaemon = $true; - $ExitCode = & $script:IcingaModule { + $ExitCode = & $script:IcingaModule { [IcingaPlugin]::new('Load', 95, '%').Warning('80').Critical('90').CheckRange().Compile() }; $ExitCode | Should -Be 2; @@ -284,8 +287,8 @@ Describe 'IcingaPlugin' { It 'does not count the entries of a notice package in the header' { & $script:IcingaModule { - $List = [IcingaPlugin]::new('File List'); - $List.IsNotice = $true; + $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')); @@ -302,7 +305,7 @@ Describe 'IcingaPlugin' { It 'appends the operator configuration at verbosity 3, even when set after building' { & $script:IcingaModule { - $Package = [IcingaPlugin]::new('Disks'). + $Package = [IcingaPlugin]::new('Disks'). AddCheck([IcingaPlugin]::new('C:', 95, '%').Warning('80').Critical('90').CheckRange()); $Package.Verbose = 3; $Package.Compile() @@ -311,8 +314,8 @@ Describe 'IcingaPlugin' { } 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()); + $None = & $script:IcingaModule { + $Package = [IcingaPlugin]::new('Grp').AddCheck([IcingaPlugin]::new('a', 5, '%').Critical('90').CheckRange()); $Package.CheckNone(); $Package.Verbose = 3; $Package.Compile() | Out-Null; @@ -321,10 +324,10 @@ Describe 'IcingaPlugin' { $None | Should -Not -Match 'must be'; $Notice = & $script:IcingaModule { - $Package = [IcingaPlugin]::new('Grp'); + $Package = [IcingaPlugin]::new('Grp'); $Package.IsNotice = $true; [void]$Package.AddCheck([IcingaPlugin]::new('a', 5, '%').Critical('90').CheckRange()); - $Package.Verbose = 3; + $Package.Verbose = 3; $Package.Compile() | Out-Null; return $Global:IcingaForWindows.Private.Icinga.CheckResult.Output; }; @@ -457,7 +460,7 @@ Describe 'IcingaPlugin' { It 'shows the error on a container with children instead of the summary header' { & $script:IcingaModule { - $Package = [IcingaPlugin]::new('Disks'); + $Package = [IcingaPlugin]::new('Disks'); $Package.Verbose = 2; $Package.AddCheck([IcingaPlugin]::new('C', 5, '%').Critical('90').CheckRange()).SetError('Volume data is incomplete').Compile() | Out-Null; }; @@ -475,8 +478,8 @@ Describe 'IcingaPlugin' { Context 'Missing required entries' { It 'adds a locked check in the given state for every missing entry' { - $ExitCode = & $script:IcingaModule { - $Package = [IcingaPlugin]::new('Services'); + $ExitCode = & $script:IcingaModule { + $Package = [IcingaPlugin]::new('Services'); $Package.Verbose = 2; $Package.AddMissingChecks(@('Spooler', 'DoesNotExist', 'Other'), @('Spooler', 'WinRM'), '{0}', 'Service not found', 3).Compile(); }; @@ -537,4 +540,413 @@ Describe 'IcingaPlugin' { $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 index 9acc43b..5dffde2 100644 --- a/Tests/New-IcingaPlugin.Tests.ps1 +++ b/Tests/New-IcingaPlugin.Tests.ps1 @@ -5,7 +5,7 @@ if (-not (Get-Module -Name 'IcingaForWindows')) { Describe 'New-IcingaPlugin' { BeforeAll { - $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | Where-Object { $_.ModuleType -eq 'Script' } | Select-Object -First 1; diff --git a/src/Classes/Icinga/IcingaCheckResult.ps1 b/src/Classes/Icinga/IcingaCheckResult.ps1 index d21c938..99454f4 100644 --- a/src/Classes/Icinga/IcingaCheckResult.ps1 +++ b/src/Classes/Icinga/IcingaCheckResult.ps1 @@ -14,7 +14,7 @@ the REST API can read the result of a check that was executed in a worker thread instead of the output being written to the console. .OUTPUTS -IcingaCheckResult — Result container exposing ExitCode, Output and PerformanceData. +IcingaCheckResult -- Result container exposing ExitCode, Output and PerformanceData. .EXAMPLE PS> [IcingaCheckResult]::new(2, '[CRITICAL] Load: 95%', @("load=95%;80;90;0;100")) @@ -38,7 +38,7 @@ class IcingaCheckResult Used as the initial, not-yet-compiled placeholder. .OUTPUTS - IcingaCheckResult — Empty result instance. + IcingaCheckResult -- Empty result instance. .EXAMPLE PS> [IcingaCheckResult]::new() @@ -59,9 +59,9 @@ class IcingaCheckResult collected performance-data metrics. .PARAMETER ExitCode - | Name | Type | Description | Default | - |----------|--------------|------------------------------------------------------|---------| - | ExitCode | System.Int32 | Icinga plugin state: 0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN. | | + | Name | Type | Description | Default | + |----------|--------------|--------------------------------------------------------------|---------| + | ExitCode | System.Int32 | Icinga plugin state: 0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN. | | .PARAMETER Output | Name | Type | Description | Default | @@ -74,7 +74,7 @@ class IcingaCheckResult | PerformanceData | System.Array | Performance-data metrics, one string per metric. | | .OUTPUTS - IcingaCheckResult — Configured result instance. + IcingaCheckResult -- Configured result instance. .EXAMPLE PS> [IcingaCheckResult]::new(0, '[OK] Load: 5%', @("load=5%;80;90;0;100")) @@ -98,7 +98,7 @@ class IcingaCheckResult in string context. .OUTPUTS - System.String — The Output message. + System.String -- The Output message. .EXAMPLE PS> $result.ToString() diff --git a/src/Classes/Icinga/IcingaError.ps1 b/src/Classes/Icinga/IcingaError.ps1 index bf4f9e6..bb15fd1 100644 --- a/src/Classes/Icinga/IcingaError.ps1 +++ b/src/Classes/Icinga/IcingaError.ps1 @@ -16,7 +16,7 @@ string and arguments in the style of [string]::Format ('Failed to query {0}', and Data holds the context values of the failure. .OUTPUTS -IcingaError — Error object with message, return code and context data. +IcingaError -- Error object with message, return code and context data. .EXAMPLE PS> ('IcingaError' -as [type])::new('Failed to query the class {0}: {1}', @('Win32_Service', 'Access denied')) @@ -49,12 +49,12 @@ class IcingaError so braces such as those of volume GUIDs are kept as they are. .PARAMETER Message - | Name | Type | Description | Default | - |---------|---------------|------------------------------|---------| - | Message | System.String | Human-readable error message. | | + | Name | Type | Description | Default | + |---------|---------------|-------------------------------|---------| + | Message | System.String | Human-readable error message. | | .OUTPUTS - IcingaError — The error object. + IcingaError -- The error object. .EXAMPLE PS> ('IcingaError' -as [type])::new('The performance counter category is missing') @@ -76,17 +76,17 @@ class IcingaError ('{0}', '{1}', ...) replaced by the arguments, like [string]::Format. .PARAMETER Message - | Name | Type | Description | Default | - |---------|---------------|---------------------------------------------|---------| - | Message | System.String | Format string with '{0}'-style placeholders. | | + | Name | Type | Description | Default | + |---------|---------------|----------------------------------------------|---------| + | Message | System.String | Format string with '{0}'-style placeholders. | | .PARAMETER Arguments - | Name | Type | Description | Default | - |-----------|-----------------|--------------------------------------|---------| - | Arguments | System.Object[] | Values inserted into the placeholders. | | + | Name | Type | Description | Default | + |-----------|-----------------|----------------------------------------|---------| + | Arguments | System.Object[] | Values inserted into the placeholders. | | .OUTPUTS - IcingaError — The error object. + IcingaError -- The error object. .EXAMPLE PS> ('IcingaError' -as [type])::new('Failed to query {0}', @('Win32_Volume')) @@ -124,7 +124,7 @@ class IcingaError | Data | System.Collections.Hashtable | Context values of the failure. | | .OUTPUTS - IcingaError — The error object. + IcingaError -- The error object. .EXAMPLE PS> ('IcingaError' -as [type])::new('WindowsInformationClassUnknown', 'The class Foo is unknown', @{ 'ClassName' = 'Foo'; }) @@ -163,7 +163,7 @@ class IcingaError | Arguments | System.Object[] | Values inserted into the placeholders. | | .OUTPUTS - System.String — The formatted message. + System.String -- The formatted message. .EXAMPLE PS> ('IcingaError' -as [type])::FormatMessage('Failed to query {0}', @('Win32_Volume')) @@ -194,7 +194,7 @@ class IcingaError Returns the message, so the error renders as its text in strings and logs. .OUTPUTS - System.String — The error message. + System.String -- The error message. .EXAMPLE PS> [string]$IcingaError diff --git a/src/Classes/Icinga/IcingaPlugin.ps1 b/src/Classes/Icinga/IcingaPlugin.ps1 index 04def4b..512c939 100644 --- a/src/Classes/Icinga/IcingaPlugin.ps1 +++ b/src/Classes/Icinga/IcingaPlugin.ps1 @@ -5,17 +5,14 @@ Unified Icinga plugin node that is both a single check and a container .DESCRIPTION IcingaPlugin replaces the previous three-part construct (New-IcingaCheck, New-IcingaCheckPackage, New-IcingaCheckResult) with a single class. One instance -can act as: - -- a leaf check — a measured value that is evaluated against warning and critical - thresholds and immediately put into a state (0 OK, 1 WARNING, 2 CRITICAL, - 3 UNKNOWN) the moment a comparison method is called; -- a container — a node that aggregates child plugins with a configurable operator - (default: all children must be OK). Nesting is arbitrary; a child may itself be a - container; -- a hybrid — a node that carries its own value AND child checks; its own evaluated - state then participates in the aggregation as one more element. A node with only - children (no own value evaluated) behaves exactly like the classic package. +can act as a leaf check (a measured value evaluated against warning and critical +thresholds and immediately put into a state 0 OK, 1 WARNING, 2 CRITICAL or +3 UNKNOWN the moment a comparison method is called), as a container (a node that +aggregates child plugins with a configurable operator, defaulting to all children +must be OK, with arbitrary nesting), or as a hybrid node that carries its own +value and child checks so its own evaluated state participates in the aggregation +as one more element. A node with only children and no own evaluated value behaves +identically to the classic package. The surface is fluent: threshold setters, comparison methods, override methods, operator methods and AddCheck all return the instance ($this) so calls chain. A @@ -41,7 +38,7 @@ result in Private for the REST API to pick up. Compile() returns the integer exi code either way. .OUTPUTS -IcingaPlugin — Plugin node exposing the fluent check, override and container surface. +IcingaPlugin -- Plugin node exposing the fluent check, override and container surface. .EXAMPLE PS> return (New-IcingaPlugin 'Disks'). @@ -68,41 +65,47 @@ the main runspace is idle. #> class IcingaPlugin { - [string]$Name = ''; - [object]$Value = $null; - [string]$Unit = ''; - [int]$Verbose = 0; - [bool]$NoPerfData = $false; - [bool]$IsHidden = $false; - [bool]$IsNotice = $false; - [bool]$IgnoreEmptyPackage = $false; - [bool]$AddSummaryHeader = $false; - - hidden [int]$State = 0; - hidden [bool]$Locked = $false; - hidden [bool]$FixedState = $false; - hidden [bool]$IsNoticeObject = $false; - hidden [bool]$Evaluated = $false; - hidden [bool]$HasError = $false; - hidden [string]$OutputMessage = ''; - hidden [int]$Indention = 0; - hidden [IcingaPlugin]$Parent = $null; - hidden [array]$Checks = @(); - hidden [array]$PerfData = @(); - hidden [string]$Operator = 'And'; - hidden [int]$OperatorMin = -1; - hidden [int]$OperatorMax = -1; - hidden [string]$WarningThreshold = ''; - hidden [string]$CriticalThreshold = ''; - hidden [string]$ResolvedWarning = ''; - hidden [string]$ResolvedCritical = ''; - hidden [string]$MinimumValue = ''; - hidden [string]$MaximumValue = ''; - hidden [object]$BaseValueSetting = $null; - hidden [string]$MetricIndexValue = ''; - hidden [string]$MetricNameValue = ''; - hidden [string]$MetricLabelValue = ''; - hidden [string]$CheckCommand = ''; + [string]$Name = ''; + [object]$Value = $null; + [string]$Unit = ''; + [int]$Verbose = 0; + [bool]$NoPerfData = $false; + [bool]$IsHidden = $false; + [bool]$IsNotice = $false; + [bool]$IgnoreEmptyPackage = $false; + [bool]$AddSummaryHeader = $false; + [bool]$SkipSummary = $false; + + hidden [int]$State = 0; + hidden [bool]$Locked = $false; + hidden [bool]$FixedState = $false; + hidden [bool]$IsNoticeObject = $false; + hidden [bool]$IgnoredEmpty = $false; + hidden [bool]$Evaluated = $false; + hidden [bool]$HasError = $false; + hidden [string]$OutputMessage = ''; + hidden [int]$Indention = 0; + hidden [IcingaPlugin]$Parent = $null; + hidden [array]$Checks = @(); + hidden [array]$PerfData = @(); + hidden [string]$Operator = 'And'; + hidden [int]$OperatorMin = -1; + hidden [int]$OperatorMax = -1; + hidden [string]$WarningThreshold = ''; + hidden [string]$CriticalThreshold = ''; + hidden [array]$WarningList = @(); + hidden [array]$CriticalList = @(); + hidden [string]$ResolvedWarning = ''; + hidden [string]$ResolvedCritical = ''; + hidden [string]$MinimumValue = ''; + hidden [string]$MaximumValue = ''; + hidden [object]$BaseValueSetting = $null; + hidden [string]$MetricIndexValue = ''; + hidden [string]$MetricNameValue = ''; + hidden [string]$MetricLabelValue = ''; + hidden [string]$CheckCommand = ''; + hidden [hashtable]$Translation = @{}; + hidden [string]$TranslatedText = ''; static hidden [hashtable]$StateText = @{ 0 = '[OK]'; @@ -111,6 +114,17 @@ class IcingaPlugin 3 = '[UNKNOWN]'; }; + static hidden [hashtable]$StateMap = @{ + 'ok' = 0; + 'warning' = 1; + 'critical' = 2; + 'unknown' = 3; + '0' = 0; + '1' = 1; + '2' = 2; + '3' = 3; + }; + <# .SYNOPSIS Create a plugin node with a name only @@ -125,7 +139,7 @@ class IcingaPlugin | Name | System.String | Display name of the plugin node. | | .OUTPUTS - IcingaPlugin — Configured plugin node. + IcingaPlugin -- Configured plugin node. .EXAMPLE PS> New-IcingaPlugin 'Disks' @@ -158,7 +172,7 @@ class IcingaPlugin | Value | System.Object | Measured value; number or ''. | | .OUTPUTS - IcingaPlugin — Configured plugin node. + IcingaPlugin -- Configured plugin node. .EXAMPLE PS> New-IcingaPlugin 'Load' 95 @@ -197,7 +211,7 @@ class IcingaPlugin | Unit | System.String | Icinga unit appended to perfdata. | | .OUTPUTS - IcingaPlugin — Configured plugin node. + IcingaPlugin -- Configured plugin node. .EXAMPLE PS> New-IcingaPlugin 'Load' 95 '%' @@ -235,7 +249,7 @@ class IcingaPlugin | Unit | System.String | Icinga unit. | | .OUTPUTS - None — Updates instance state. + None -- Updates instance state. .EXAMPLE PS> $this.Initialize('Load', 95, '%') @@ -245,9 +259,20 @@ class IcingaPlugin #> hidden [void] Initialize([string]$Name, [object]$Value, [string]$Unit) { - $this.Name = $Name; - $this.Value = $Value; - $this.Unit = $Unit; + $this.Name = $Name; + + if ($Value -is [TimeSpan]) { + $this.Value = ([TimeSpan]$Value).TotalSeconds; + if ('' -eq $Unit) { + $this.Unit = 's'; + } else { + $this.Unit = $Unit; + } + } else { + $this.Value = $Value; + $this.Unit = $Unit; + } + $this.CheckCommand = $this.DetectCheckCommand(); } @@ -256,8 +281,9 @@ class IcingaPlugin Set the warning threshold and return the node for chaining .DESCRIPTION - Stores the warning threshold string verbatim. The threshold is not evaluated - until a comparison method (CheckRange, CheckGreater, ...) is called. + Stores the warning threshold string verbatim and clears any multi-value warning + list. The threshold is not evaluated until a comparison method (CheckRange, + CheckGreater, ...) is called. .PARAMETER Warning | Name | Type | Description | Default | @@ -265,7 +291,7 @@ class IcingaPlugin | Warning | System.String | Warning threshold string ('' = unset). | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $check.Warning('80') @@ -275,17 +301,97 @@ class IcingaPlugin #> [IcingaPlugin] Warning([string]$Warning) { + $this.WarningList = @(); $this.WarningThreshold = $Warning; return $this; } + <# + .SYNOPSIS + Set a multi-value warning threshold list and return the node for chaining + + .DESCRIPTION + Stores one or more warning threshold entries for multi-value comparisons + (CheckIn, CheckNotIn, CheckEqual, CheckNotEqual, CheckLike, CheckNotLike, + CheckMatch, CheckNotMatch). Null and empty entries are ignored; an empty array + leaves the warning threshold unset, a single entry is stored as a standard + threshold string, and multiple entries are stored both in WarningList and as a + comma-separated display string in WarningThreshold. + + .PARAMETER Warning + | Name | Type | Description | Default | + |---------|--------------|-------------------------------------------------|---------| + | Warning | System.Array | Array of warning threshold values or patterns. | | + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.Warning(@('Paused', 'Pending')).CheckIn() + + .NOTES + Fluent setter; also accepts single non-string values such as numbers, enums or TimeSpans. + #> + [IcingaPlugin] Warning([array]$Warning) + { + [array]$Cleaned = $this.CleanThresholdList($Warning); + + if ($Cleaned.Count -eq 0) { + $this.WarningList = @(); + $this.WarningThreshold = ''; + } elseif ($Cleaned.Count -eq 1) { + $this.WarningList = @(); + $this.WarningThreshold = [string]$Cleaned[0]; + } else { + $this.WarningList = $Cleaned; + $this.WarningThreshold = ($Cleaned -join ', '); + } + + return $this; + } + + <# + .SYNOPSIS + Set a single object warning threshold and return the node for chaining + + .DESCRIPTION + Converts a single non-string warning threshold value (such as a number, enum or + TimeSpan) to its invariant threshold string representation via + ConvertThresholdEntry, or delegates to Warning([array]) when an array is passed + through an untyped variable. + + .PARAMETER Warning + | Name | Type | Description | Default | + |---------|---------------|--------------------------------------------------|---------| + | Warning | System.Object | Warning threshold value (number, enum, TimeSpan).| | + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.Warning([TimeSpan]::FromMinutes(30)).CheckRange() + + .NOTES + Fluent setter; normalizes TimeSpans to seconds and numbers to invariant strings. + #> + [IcingaPlugin] Warning([object]$Warning) + { + if ($Warning -is [array]) { + return $this.Warning([array]$Warning); + } + + $this.WarningList = @(); + $this.WarningThreshold = $this.ConvertThresholdEntry($Warning); + return $this; + } + <# .SYNOPSIS Set the critical threshold and return the node for chaining .DESCRIPTION - Stores the critical threshold string verbatim. The threshold is not evaluated - until a comparison method is called. + Stores the critical threshold string verbatim and clears any multi-value critical + list. The threshold is not evaluated until a comparison method is called. .PARAMETER Critical | Name | Type | Description | Default | @@ -293,7 +399,7 @@ class IcingaPlugin | Critical | System.String | Critical threshold string ('' = unset). | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $check.Critical('90') @@ -303,25 +409,186 @@ class IcingaPlugin #> [IcingaPlugin] Critical([string]$Critical) { + $this.CriticalList = @(); $this.CriticalThreshold = $Critical; return $this; } + <# + .SYNOPSIS + Set a multi-value critical threshold list and return the node for chaining + + .DESCRIPTION + Stores one or more critical threshold entries for multi-value comparisons + (CheckIn, CheckNotIn, CheckEqual, CheckNotEqual, CheckLike, CheckNotLike, + CheckMatch, CheckNotMatch). Null and empty entries are ignored; an empty array + leaves the critical threshold unset, a single entry is stored as a standard + threshold string, and multiple entries are stored both in CriticalList and as a + comma-separated display string in CriticalThreshold. + + .PARAMETER Critical + | Name | Type | Description | Default | + |----------|--------------|--------------------------------------------------|---------| + | Critical | System.Array | Array of critical threshold values or patterns. | | + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.Critical(@('Ready', 'Running')).CheckNotIn() + + .NOTES + Fluent setter; also accepts single non-string values such as numbers, enums or TimeSpans. + #> + [IcingaPlugin] Critical([array]$Critical) + { + [array]$Cleaned = $this.CleanThresholdList($Critical); + + if ($Cleaned.Count -eq 0) { + $this.CriticalList = @(); + $this.CriticalThreshold = ''; + } elseif ($Cleaned.Count -eq 1) { + $this.CriticalList = @(); + $this.CriticalThreshold = [string]$Cleaned[0]; + } else { + $this.CriticalList = $Cleaned; + $this.CriticalThreshold = ($Cleaned -join ', '); + } + + return $this; + } + + <# + .SYNOPSIS + Set a single object critical threshold and return the node for chaining + + .DESCRIPTION + Converts a single non-string critical threshold value (such as a number, enum or + TimeSpan) to its invariant threshold string representation via + ConvertThresholdEntry, or delegates to Critical([array]) when an array is passed + through an untyped variable. + + .PARAMETER Critical + | Name | Type | Description | Default | + |----------|---------------|---------------------------------------------------|---------| + | Critical | System.Object | Critical threshold value (number, enum, TimeSpan).| | + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.Critical([TimeSpan]::FromHours(1)).CheckRange() + + .NOTES + Fluent setter; normalizes TimeSpans to seconds and numbers to invariant strings. + #> + [IcingaPlugin] Critical([object]$Critical) + { + if ($Critical -is [array]) { + return $this.Critical([array]$Critical); + } + + $this.CriticalList = @(); + $this.CriticalThreshold = $this.ConvertThresholdEntry($Critical); + return $this; + } + + <# + .SYNOPSIS + Normalize a single threshold list entry to its invariant string form + + .DESCRIPTION + Converts a threshold list item to a string under the invariant culture. TimeSpan + values are converted to seconds with an 's' unit suffix, floating-point numbers + are formatted without scientific notation using a dot decimal separator, and all + other non-null values use their string representation. + + .PARAMETER Entry + | Name | Type | Description | Default | + |-------|---------------|------------------------------------|---------| + | Entry | System.Object | Threshold list item to normalize. | | + + .OUTPUTS + System.String -- Normalized threshold string, or '' when null. + + .EXAMPLE + PS> $this.ConvertThresholdEntry(80.5) + + .NOTES + Internal helper used by CleanThresholdList. + #> + hidden [string] ConvertThresholdEntry([object]$Entry) + { + if ($null -eq $Entry) { + return ''; + } + + if ($Entry -is [TimeSpan]) { + return (([TimeSpan]$Entry).TotalSeconds.ToString('0.##########', [System.Globalization.CultureInfo]::InvariantCulture) + 's'); + } + + if ($Entry -is [double] -or $Entry -is [single] -or $Entry -is [decimal]) { + return $this.FormatNumber($Entry); + } + + return [string]$Entry; + } + + <# + .SYNOPSIS + Filter and normalize an array of threshold entries + + .DESCRIPTION + Converts each non-null, non-empty entry in the supplied array through + ConvertThresholdEntry and returns the resulting string array. + + .PARAMETER Thresholds + | Name | Type | Description | Default | + |------------|--------------|---------------------------------------|---------| + | Thresholds | System.Array | Raw threshold array passed by caller. | | + + .OUTPUTS + System.Array -- Cleaned array of non-empty threshold strings. + + .EXAMPLE + PS> $this.CleanThresholdList(@('Ready', 'Running')) + + .NOTES + Internal helper used by Warning([array]) and Critical([array]). + #> + hidden [array] CleanThresholdList([array]$Thresholds) + { + [array]$Cleaned = @(); + + if ($null -eq $Thresholds) { + return $Cleaned; + } + + foreach ($Entry in $Thresholds) { + [string]$Text = $this.ConvertThresholdEntry($Entry); + if ('' -ne $Text) { + $Cleaned += $Text; + } + } + + return $Cleaned; + } + <# .SYNOPSIS Set the performance-data minimum and return the node for chaining .DESCRIPTION Stores the minimum value that is emitted as the 'min' field of the performance - data. Does not influence the threshold evaluation. + data. Accepts a number or string; does not influence the threshold evaluation. .PARAMETER Minimum | Name | Type | Description | Default | |---------|---------------|-------------------------------------|---------| - | Minimum | System.String | Perfdata minimum ('' = unset). | | + | Minimum | System.Object | Perfdata minimum ('' = unset). | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $check.Minimum('0') @@ -329,9 +596,18 @@ class IcingaPlugin .NOTES Fluent setter for the perfdata min field. #> - [IcingaPlugin] Minimum([string]$Minimum) + [IcingaPlugin] Minimum([object]$Minimum) { - $this.MinimumValue = $Minimum; + if ($null -eq $Minimum -or '' -eq [string]$Minimum) { + $this.MinimumValue = ''; + } else { + $this.MinimumValue = $this.FormatNumber($Minimum); + } + + if ($this.Evaluated) { + $this.BuildPerfData(); + } + return $this; } @@ -341,15 +617,15 @@ class IcingaPlugin .DESCRIPTION Stores the maximum value that is emitted as the 'max' field of the performance - data. Does not influence the threshold evaluation. + data. Accepts a number or string; does not influence the threshold evaluation. .PARAMETER Maximum | Name | Type | Description | Default | |---------|---------------|-------------------------------------|---------| - | Maximum | System.String | Perfdata maximum ('' = unset). | | + | Maximum | System.Object | Perfdata maximum ('' = unset). | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $check.Maximum('100') @@ -357,9 +633,18 @@ class IcingaPlugin .NOTES Fluent setter for the perfdata max field. #> - [IcingaPlugin] Maximum([string]$Maximum) + [IcingaPlugin] Maximum([object]$Maximum) { - $this.MaximumValue = $Maximum; + if ($null -eq $Maximum -or '' -eq [string]$Maximum) { + $this.MaximumValue = ''; + } else { + $this.MaximumValue = $this.FormatNumber($Maximum); + } + + if ($this.Evaluated) { + $this.BuildPerfData(); + } + return $this; } @@ -378,7 +663,7 @@ class IcingaPlugin | BaseValue | System.Object | Base/maximum value; number or unit string. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $check.BaseValue('1TB').Warning('80%').Critical('90%').CheckMax() @@ -388,7 +673,12 @@ class IcingaPlugin #> [IcingaPlugin] BaseValue([object]$BaseValue) { - $this.BaseValueSetting = $BaseValue; + if ($BaseValue -is [TimeSpan]) { + $this.BaseValueSetting = ([TimeSpan]$BaseValue).TotalSeconds; + } else { + $this.BaseValueSetting = $BaseValue; + } + return $this; } @@ -407,7 +697,7 @@ class IcingaPlugin | Index | System.String | Metric index / instance identifier. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $check.MetricIndex('0') @@ -438,7 +728,7 @@ class IcingaPlugin | Name | System.String | Template name without the fixed 'ifw_' namespace. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $check.MetricName('cpu') @@ -467,7 +757,7 @@ class IcingaPlugin | Label | System.String | Metric label / measured value. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $check.MetricLabel('load') @@ -483,314 +773,1112 @@ class IcingaPlugin <# .SYNOPSIS - Evaluate the value against the thresholds using the Icinga range grammar + Translate the node's value (such as an enum or boolean) for human-readable output .DESCRIPTION - Builds an IcingaThresholds pair from the configured warning, critical and base - values, compares the node's value with the full Icinga/Nagios range grammar and - immediately puts the node into the resulting state (escalate-only). Performance - data is (re)built from the current value and thresholds. + Enables display translation for the node's current value while keeping its numeric + representation for performance data. Useful when Value is a [System.Enum] or + [System.Boolean] whose string name should be shown in the output message and whose + integer code should be emitted in performance data. .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE - PS> (New-IcingaPlugin 'Load' 95 '%').Warning('80').Critical('90').CheckRange() + PS> (New-IcingaPlugin 'Spooler' ([IcingaServiceStatus]::Running)).Translate().Critical('Running').CheckNotEqual() .NOTES - Delegates to IcingaThresholds.CheckRange. + Fluent setter; may be called before or after a comparison method. #> - [IcingaPlugin] CheckRange() + [IcingaPlugin] Translate() { - $this.ApplyThresholdResult($this.NewThresholds().CheckRange($this.AttachBaseUnit($this.Value))); + if ($null -ne $this.Value) { + $this.TranslatedText = [string]$this.Value; + } + return $this; } <# .SYNOPSIS - Evaluate the value with a greater-than comparison + Set a translation table for human-readable output while preserving numeric perfdata .DESCRIPTION - Compares the node's value against the warning and critical thresholds with a - greater-than operator and puts the node into the resulting state. + Stores a lookup hashtable (for example @{ 1 = 'Stopped'; 4 = 'Running' } or + @{ 0 = 'Never' }) used to translate both the measured value and threshold values + into human-readable text in the output message while emitting the underlying + numeric value in the performance data. + + .PARAMETER Translation + | Name | Type | Description | Default | + |-------------|------------------------------|------------------------------------------------|---------| + | Translation | System.Collections.Hashtable | Mapping of raw values to display strings. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE - PS> $check.Warning('80').Critical('90').CheckGreater() + PS> (New-IcingaPlugin 'Spooler' 4).Translate(@{ 1 = 'Stopped'; 4 = 'Running' }).Critical('Running').CheckNotEqual() .NOTES - Delegates to IcingaThresholds.CheckGreater. + Lookups match both direct keys and case-insensitive string representations. #> - [IcingaPlugin] CheckGreater() + [IcingaPlugin] Translate([hashtable]$Translation) { - $this.ApplyThresholdResult($this.NewThresholds().CheckGreater($this.AttachBaseUnit($this.Value))); + if ($null -eq $Translation) { + $this.Translation = @{}; + } else { + $this.Translation = $Translation; + } + return $this; } <# .SYNOPSIS - Evaluate the value with a greater-than-or-equal comparison + Set an explicit human-readable display string for the node's value .DESCRIPTION - Compares the node's value against the warning and critical thresholds with a - greater-than-or-equal operator and puts the node into the resulting state. + Overrides the human-readable text used to render the node's measured value in the + output message while keeping the raw numeric Value for threshold evaluation and + performance data. + + .PARAMETER Text + | Name | Type | Description | Default | + |------|---------------|--------------------------------------------------|---------| + | Text | System.String | Human-readable display representation of Value. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE - PS> $check.Warning('80').Critical('90').CheckGreaterEqual() + PS> (New-IcingaPlugin 'Spooler' 4).Translate('Running').CheckRange() .NOTES - Delegates to IcingaThresholds.CheckGreaterEqual. + Fluent setter. #> - [IcingaPlugin] CheckGreaterEqual() + [IcingaPlugin] Translate([string]$Text) { - $this.ApplyThresholdResult($this.NewThresholds().CheckGreaterEqual($this.AttachBaseUnit($this.Value))); + $this.TranslatedText = $Text; return $this; } <# .SYNOPSIS - Evaluate the value with a lower-than comparison + Set the verbosity level and return the node for chaining .DESCRIPTION - Compares the node's value against the warning and critical thresholds with a - lower-than operator and puts the node into the resulting state. + Sets the output verbosity level (0 problems only, 1 plus affected siblings, + 2 all checks, 3 all checks plus operator configuration) and returns the node. + + .PARAMETER Verbose + | Name | Type | Description | Default | + |---------|--------------|------------------------------|---------| + | Verbose | System.Int32 | Verbosity level (0..3). | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE - PS> $check.Warning('20').Critical('10').CheckLower() + PS> $package.SetVerbose(2) .NOTES - Delegates to IcingaThresholds.CheckLower. + Fluent counterpart to the Verbose property. #> - [IcingaPlugin] CheckLower() + [IcingaPlugin] SetVerbose([int]$Verbose) { - $this.ApplyThresholdResult($this.NewThresholds().CheckLower($this.AttachBaseUnit($this.Value))); + $this.Verbose = $Verbose; return $this; } <# .SYNOPSIS - Evaluate the value with a lower-than-or-equal comparison + Disable performance data for this node and its subtree .DESCRIPTION - Compares the node's value against the warning and critical thresholds with a - lower-than-or-equal operator and puts the node into the resulting state. + Sets NoPerfData to true so neither this node nor its children emit performance + data, and returns the node for chaining. .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE - PS> $check.Warning('20').Critical('10').CheckLowerEqual() + PS> $check.SetNoPerfData() .NOTES - Delegates to IcingaThresholds.CheckLowerEqual. + Fluent counterpart to the NoPerfData property. #> - [IcingaPlugin] CheckLowerEqual() + [IcingaPlugin] SetNoPerfData() { - $this.ApplyThresholdResult($this.NewThresholds().CheckLowerEqual($this.AttachBaseUnit($this.Value))); - return $this; + return $this.SetNoPerfData($true); } <# .SYNOPSIS - Evaluate the value against its maximum-relative thresholds + Configure whether performance data is disabled for this node and its subtree .DESCRIPTION - Requires a base value. Compares the node's value against the warning and - critical thresholds relative to the base value (commonly percentages of the - maximum) and puts the node into the resulting state. + Sets NoPerfData to the supplied boolean and returns the node for chaining. + + .PARAMETER NoPerfData + | Name | Type | Description | Default | + |------------|----------------|--------------------------------------------|---------| + | NoPerfData | System.Boolean | When true, suppress performance data. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE - PS> $check.BaseValue('1TB').Warning('80%').Critical('90%').CheckMax() + PS> $package.SetNoPerfData($NoPerfData) .NOTES - Delegates to IcingaThresholds.CheckMax; without a base value the result is UNKNOWN. + Fluent counterpart to the NoPerfData property. #> - [IcingaPlugin] CheckMax() + [IcingaPlugin] SetNoPerfData([bool]$NoPerfData) { - $this.ApplyThresholdResult($this.NewThresholds().CheckMax($this.AttachBaseUnit($this.Value))); + $this.NoPerfData = $NoPerfData; return $this; } <# .SYNOPSIS - Evaluate the string value with a regular-expression match + Hide this node from the rendered text output and summary counts .DESCRIPTION - Tests the node's value against the warning and critical thresholds as regular - expressions and puts the node into the resulting state. + Marks the node as hidden so it is omitted from the text output and aggregation + while still contributing its performance data. .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE - PS> $check.Warning('^warn').Critical('^err').CheckMatch() + PS> $metricPackage.SetHidden() .NOTES - Delegates to IcingaThresholds.CheckMatch. + Fluent counterpart to the IsHidden property. #> - [IcingaPlugin] CheckMatch() + [IcingaPlugin] SetHidden() { - $this.ApplyThresholdResult($this.NewThresholds().CheckMatch($this.Value)); - return $this; + return $this.SetHidden($true); } <# .SYNOPSIS - Evaluate the string value with a negated regular-expression match + Configure whether this node is hidden from the rendered text output .DESCRIPTION - Tests the node's value against the warning and critical thresholds as regular - expressions and alerts when the value does NOT match, then puts the node into - the resulting state. + Sets IsHidden to the supplied boolean and returns the node for chaining. + + .PARAMETER Hidden + | Name | Type | Description | Default | + |--------|----------------|--------------------------------------------|---------| + | Hidden | System.Boolean | When true, hide the node from output. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE - PS> $check.Warning('^ok').Critical('^healthy').CheckNotMatch() + PS> $metricPackage.SetHidden($true) .NOTES - Delegates to IcingaThresholds.CheckNotMatch. + Fluent counterpart to the IsHidden property. #> - [IcingaPlugin] CheckNotMatch() + [IcingaPlugin] SetHidden([bool]$Hidden) { - $this.ApplyThresholdResult($this.NewThresholds().CheckNotMatch($this.Value)); + $this.IsHidden = $Hidden; return $this; } <# .SYNOPSIS - Evaluate the string value with a wildcard 'like' comparison + Allow an empty package to compile as OK instead of UNKNOWN .DESCRIPTION - Tests the node's value against the warning and critical thresholds as PowerShell - wildcard patterns and puts the node into the resulting state. + Sets IgnoreEmptyPackage to true so a container without child checks and without + an own measured value resolves to OK instead of raising UNKNOWN ('No checks added + to this package'). .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE - PS> $check.Warning('*warn*').Critical('*error*').CheckLike() + PS> $package.SetIgnoreEmptyPackage() .NOTES - Delegates to IcingaThresholds.CheckLike. + Fluent counterpart to the IgnoreEmptyPackage property. #> - [IcingaPlugin] CheckLike() + [IcingaPlugin] SetIgnoreEmptyPackage() { - $this.ApplyThresholdResult($this.NewThresholds().CheckLike($this.Value)); - return $this; + return $this.SetIgnoreEmptyPackage($true); } <# .SYNOPSIS - Evaluate the string value with a negated wildcard 'like' comparison + Configure whether an empty package compiles as OK instead of UNKNOWN .DESCRIPTION - Tests the node's value against the warning and critical thresholds as PowerShell - wildcard patterns and alerts when the value is NOT like the pattern, then puts - the node into the resulting state. + Sets IgnoreEmptyPackage to the supplied boolean and returns the node for chaining. + + .PARAMETER Ignore + | Name | Type | Description | Default | + |--------|----------------|--------------------------------------------------|---------| + | Ignore | System.Boolean | When true, an empty package resolves to OK. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE - PS> $check.Warning('*ok*').Critical('*healthy*').CheckNotLike() + PS> $package.SetIgnoreEmptyPackage($MitigateUnknown) .NOTES - Delegates to IcingaThresholds.CheckNotLike. + Fluent counterpart to the IgnoreEmptyPackage property. #> - [IcingaPlugin] CheckNotLike() + [IcingaPlugin] SetIgnoreEmptyPackage([bool]$Ignore) { - $this.ApplyThresholdResult($this.NewThresholds().CheckNotLike($this.Value)); + $this.IgnoreEmptyPackage = $Ignore; return $this; } <# .SYNOPSIS - Evaluate the string value with an equality comparison + Enable the summary header on a nested container .DESCRIPTION - Tests the node's value against the warning and critical thresholds with a - case-insensitive string equality test and puts the node into the resulting state. + Sets AddSummaryHeader to true so a non-root container also renders the per-state + leaf summary on its container line. .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE - PS> $check.Warning('degraded').Critical('offline').CheckEqual() + PS> $subPackage.SetSummaryHeader() .NOTES - Delegates to IcingaThresholds.CheckEqual. + Fluent counterpart to the AddSummaryHeader property. #> - [IcingaPlugin] CheckEqual() + [IcingaPlugin] SetSummaryHeader() { - $this.ApplyThresholdResult($this.NewThresholds().CheckEqual($this.Value)); - return $this; + return $this.SetSummaryHeader($true); } <# .SYNOPSIS - Evaluate the string value with a negated equality comparison + Configure whether a nested container renders a summary header .DESCRIPTION - Tests the node's value against the warning and critical thresholds with a - case-insensitive string inequality test and puts the node into the resulting - state. + Sets AddSummaryHeader to the supplied boolean and returns the node for chaining. + + .PARAMETER AddHeader + | Name | Type | Description | Default | + |-----------|----------------|------------------------------------------------|---------| + | AddHeader | System.Boolean | When true, include the summary header. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE - PS> $check.Warning('online').Critical('online').CheckNotEqual() + PS> $subPackage.SetSummaryHeader($true) .NOTES - Delegates to IcingaThresholds.CheckNotEqual. + Fluent counterpart to the AddSummaryHeader property. #> - [IcingaPlugin] CheckNotEqual() + [IcingaPlugin] SetSummaryHeader([bool]$AddHeader) { - $this.ApplyThresholdResult($this.NewThresholds().CheckNotEqual($this.Value)); + $this.AddSummaryHeader = $AddHeader; return $this; } <# .SYNOPSIS - Build an IcingaThresholds pair from the configured thresholds + Exclude this node from its parent container's summary header counts .DESCRIPTION - Creates an IcingaThresholds object from the stored warning and critical strings, - passing the base value as well when one was set. A plain numeric base value of a - byte or time node carries the 'B' or 's' unit, so percent thresholds resolve and - render in that unit. The return type is object because IcingaThresholds is - parsed after IcingaPlugin during the build and may therefore only be referenced - from method bodies. + Sets SkipSummary to true so the node still participates in state aggregation and + tree output, but is omitted from the per-state leaf count and name lists in the + container summary header (matching the classic -NoHeaderReport switch). + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.SetSkipSummary() + + .NOTES + Fluent counterpart to the SkipSummary property. + #> + [IcingaPlugin] SetSkipSummary() + { + return $this.SetSkipSummary($true); + } + + <# + .SYNOPSIS + Configure whether this node is excluded from the container summary header + + .DESCRIPTION + Sets SkipSummary to the supplied boolean and returns the node for chaining. + + .PARAMETER Skip + | Name | Type | Description | Default | + |------|----------------|------------------------------------------------------|---------| + | Skip | System.Boolean | When true, omit from the container summary header. | | + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.SetSkipSummary($true) + + .NOTES + Fluent counterpart to the SkipSummary property. + #> + [IcingaPlugin] SetSkipSummary([bool]$Skip) + { + $this.SkipSummary = $Skip; + return $this; + } + + <# + .SYNOPSIS + Evaluate the value against the thresholds using the Icinga range grammar + + .DESCRIPTION + Builds an IcingaThresholds pair from the configured warning, critical and base + values, compares the node's value with the full Icinga/Nagios range grammar and + immediately puts the node into the resulting state (escalate-only). Performance + data is (re)built from the current value and thresholds. + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> (New-IcingaPlugin 'Load' 95 '%').Warning('80').Critical('90').CheckRange() + + .NOTES + Delegates to IcingaThresholds.CheckRange. + #> + [IcingaPlugin] CheckRange() + { + $this.ApplyThresholdResult($this.NewThresholds().CheckRange($this.AttachBaseUnit($this.Value))); + return $this; + } + + <# + .SYNOPSIS + Evaluate the value with a greater-than comparison + + .DESCRIPTION + Compares the node's value against the warning and critical thresholds with a + greater-than operator and puts the node into the resulting state. + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.Warning('80').Critical('90').CheckGreater() + + .NOTES + Delegates to IcingaThresholds.CheckGreater. + #> + [IcingaPlugin] CheckGreater() + { + $this.ApplyThresholdResult($this.NewThresholds().CheckGreater($this.AttachBaseUnit($this.Value))); + return $this; + } + + <# + .SYNOPSIS + Evaluate the value with a greater-than-or-equal comparison + + .DESCRIPTION + Compares the node's value against the warning and critical thresholds with a + greater-than-or-equal operator and puts the node into the resulting state. + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.Warning('80').Critical('90').CheckGreaterEqual() + + .NOTES + Delegates to IcingaThresholds.CheckGreaterEqual. + #> + [IcingaPlugin] CheckGreaterEqual() + { + $this.ApplyThresholdResult($this.NewThresholds().CheckGreaterEqual($this.AttachBaseUnit($this.Value))); + return $this; + } + + <# + .SYNOPSIS + Evaluate the value with a lower-than comparison + + .DESCRIPTION + Compares the node's value against the warning and critical thresholds with a + lower-than operator and puts the node into the resulting state. + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.Warning('20').Critical('10').CheckLower() + + .NOTES + Delegates to IcingaThresholds.CheckLower. + #> + [IcingaPlugin] CheckLower() + { + $this.ApplyThresholdResult($this.NewThresholds().CheckLower($this.AttachBaseUnit($this.Value))); + return $this; + } + + <# + .SYNOPSIS + Evaluate the value with a lower-than-or-equal comparison + + .DESCRIPTION + Compares the node's value against the warning and critical thresholds with a + lower-than-or-equal operator and puts the node into the resulting state. + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.Warning('20').Critical('10').CheckLowerEqual() + + .NOTES + Delegates to IcingaThresholds.CheckLowerEqual. + #> + [IcingaPlugin] CheckLowerEqual() + { + $this.ApplyThresholdResult($this.NewThresholds().CheckLowerEqual($this.AttachBaseUnit($this.Value))); + return $this; + } + + <# + .SYNOPSIS + Evaluate the value against its maximum-relative thresholds + + .DESCRIPTION + Requires a base value. Compares the node's value against the warning and + critical thresholds relative to the base value (commonly percentages of the + maximum) and puts the node into the resulting state. + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.BaseValue('1TB').Warning('80%').Critical('90%').CheckMax() + + .NOTES + Delegates to IcingaThresholds.CheckMax; without a base value the result is UNKNOWN. + #> + [IcingaPlugin] CheckMax() + { + $this.ApplyThresholdResult($this.NewThresholds().CheckMax($this.AttachBaseUnit($this.Value))); + return $this; + } + + <# + .SYNOPSIS + Evaluate the string value with a regular-expression match + + .DESCRIPTION + Tests the node's value against the warning and critical thresholds as regular + expressions and puts the node into the resulting state. + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.Warning('^warn').Critical('^err').CheckMatch() + + .NOTES + Delegates to IcingaThresholds.CheckMatch. + #> + [IcingaPlugin] CheckMatch() + { + if ($this.WarningList.Count -gt 1 -or $this.CriticalList.Count -gt 1) { + $this.ApplyThresholdResult($this.EvaluateListComparison('match', 'matches')); + return $this; + } + + $this.ApplyThresholdResult($this.NewStringThresholds().CheckMatch($this.ResolveStringValue())); + return $this; + } + + <# + .SYNOPSIS + Evaluate the string value with a negated regular-expression match + + .DESCRIPTION + Tests the node's value against the warning and critical thresholds as regular + expressions and alerts when the value does NOT match, then puts the node into + the resulting state. + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.Warning('^ok').Critical('^healthy').CheckNotMatch() + + .NOTES + Delegates to IcingaThresholds.CheckNotMatch. + #> + [IcingaPlugin] CheckNotMatch() + { + if ($this.WarningList.Count -gt 1 -or $this.CriticalList.Count -gt 1) { + $this.ApplyThresholdResult($this.EvaluateListComparison('notmatch', 'does not match')); + return $this; + } + + $this.ApplyThresholdResult($this.NewStringThresholds().CheckNotMatch($this.ResolveStringValue())); + return $this; + } + + <# + .SYNOPSIS + Evaluate the string value with a wildcard 'like' comparison + + .DESCRIPTION + Tests the node's value against the warning and critical thresholds as PowerShell + wildcard patterns and puts the node into the resulting state. + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.Warning('*warn*').Critical('*error*').CheckLike() + + .NOTES + Delegates to IcingaThresholds.CheckLike. + #> + [IcingaPlugin] CheckLike() + { + if ($this.WarningList.Count -gt 1 -or $this.CriticalList.Count -gt 1) { + $this.ApplyThresholdResult($this.EvaluateListComparison('like', 'is like')); + return $this; + } + + $this.ApplyThresholdResult($this.NewStringThresholds().CheckLike($this.ResolveStringValue())); + return $this; + } + + <# + .SYNOPSIS + Evaluate the string value with a negated wildcard 'like' comparison + + .DESCRIPTION + Tests the node's value against the warning and critical thresholds as PowerShell + wildcard patterns and alerts when the value is NOT like the pattern, then puts + the node into the resulting state. + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.Warning('*ok*').Critical('*healthy*').CheckNotLike() + + .NOTES + Delegates to IcingaThresholds.CheckNotLike. + #> + [IcingaPlugin] CheckNotLike() + { + if ($this.WarningList.Count -gt 1 -or $this.CriticalList.Count -gt 1) { + $this.ApplyThresholdResult($this.EvaluateListComparison('notlike', 'is not like')); + return $this; + } + + $this.ApplyThresholdResult($this.NewStringThresholds().CheckNotLike($this.ResolveStringValue())); + return $this; + } + + <# + .SYNOPSIS + Evaluate the string value with an equality comparison + + .DESCRIPTION + Tests the node's value against the warning and critical thresholds with a + case-insensitive string equality test and puts the node into the resulting state. + When an array of multiple warning or critical values was configured, alerts when + the value equals any entry in the list. + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.Warning('degraded').Critical('offline').CheckEqual() + + .NOTES + Delegates to IcingaThresholds.CheckEqual or EvaluateListComparison. + #> + [IcingaPlugin] CheckEqual() + { + if ($this.WarningList.Count -gt 1 -or $this.CriticalList.Count -gt 1) { + $this.ApplyThresholdResult($this.EvaluateListComparison('eq', 'equals')); + return $this; + } + + $this.ApplyThresholdResult($this.NewStringThresholds().CheckEqual($this.ResolveStringValue())); + return $this; + } + + <# + .SYNOPSIS + Evaluate the string value with a negated equality comparison + + .DESCRIPTION + Tests the node's value against the warning and critical thresholds with a + case-insensitive string inequality test and puts the node into the resulting + state. When an array of multiple warning or critical values was configured, + alerts when the value does not equal any entry in the allowed list. + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.Warning('online').Critical('online').CheckNotEqual() + + .NOTES + Delegates to IcingaThresholds.CheckNotEqual or EvaluateListComparison. + #> + [IcingaPlugin] CheckNotEqual() + { + if ($this.WarningList.Count -gt 1 -or $this.CriticalList.Count -gt 1) { + $this.ApplyThresholdResult($this.EvaluateListComparison('ne', 'does not equal')); + return $this; + } + + $this.ApplyThresholdResult($this.NewStringThresholds().CheckNotEqual($this.ResolveStringValue())); + return $this; + } + + <# + .SYNOPSIS + Alert when the value matches any entry in the configured threshold list + + .DESCRIPTION + Evaluates the node's value against the configured warning and critical threshold + lists (or single values) using case-insensitive equality and alerts when the value + is found in the list. Critical takes precedence over warning. + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.Warning(@('Paused', 'Pending')).Critical(@('Stopped')).CheckIn() + + .NOTES + Delegates to CheckEqual. + #> + [IcingaPlugin] CheckIn() + { + return $this.CheckEqual(); + } + + <# + .SYNOPSIS + Alert when the value is not in the configured allowed threshold list + + .DESCRIPTION + Evaluates the node's value against the configured warning and critical threshold + lists (or single values) using case-insensitive equality and alerts when the value + does not match any entry in the allowed list. Critical takes precedence over + warning. + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.Critical(@('Ready', 'Running')).CheckNotIn() + + .NOTES + Delegates to CheckNotEqual. + #> + [IcingaPlugin] CheckNotIn() + { + return $this.CheckNotEqual(); + } + + <# + .SYNOPSIS + Resolve a threshold list with translation mapping applied + + .DESCRIPTION + Returns the effective array of threshold strings from the supplied list (or the + single fallback string when the list is empty), mapping each item through + ResolveTranslation when a translation applies. + + .PARAMETER List + | Name | Type | Description | Default | + |------|--------------|-------------------------------------------|---------| + | List | System.Array | Multi-value threshold list on the node. | | + + .PARAMETER Fallback + | Name | Type | Description | Default | + |----------|---------------|------------------------------------------|---------| + | Fallback | System.String | Single threshold string when List empty. | | + + .OUTPUTS + System.Array -- Resolved threshold strings for comparison. + + .EXAMPLE + PS> $this.ResolveThresholdList($this.CriticalList, $this.CriticalThreshold) + + .NOTES + Internal helper used by EvaluateListComparison. + #> + hidden [array] ResolveThresholdList([array]$List, [string]$Fallback) + { + [array]$Source = @(); + + if ($null -ne $List -and $List.Count -gt 0) { + $Source = $List; + } elseif ('' -ne $Fallback) { + $Source = @($Fallback); + } + + [array]$Resolved = @(); + + foreach ($Entry in $Source) { + [string]$Mapped = $this.ResolveTranslation($Entry); + if ($null -ne $Mapped -and '' -ne $Mapped) { + $Resolved += $Mapped; + } else { + $Resolved += [string]$Entry; + } + } + + return $Resolved; + } + + <# + .SYNOPSIS + Find the first pattern in a list that matches the supplied string value + + .DESCRIPTION + Iterates through the supplied pattern list and tests each entry against Value + using case-insensitive equality ('eq'/'ne'), wildcard matching ('like'/'notlike') + or regular-expression matching ('match'/'notmatch'). Returns the first matching + pattern string, or $null when no entry matches. + + .PARAMETER InputValue + | Name | Type | Description | Default | + |------------|---------------|------------------------------|---------| + | InputValue | System.String | String value to test. | | + + .PARAMETER Patterns + | Name | Type | Description | Default | + |----------|--------------|------------------------------|---------| + | Patterns | System.Array | Candidate patterns to check. | | + + .PARAMETER Operator + | Name | Type | Description | Default | + |----------|---------------|------------------------------------------------------------|---------| + | Operator | System.String | One of 'eq', 'ne', 'like', 'notlike', 'match', 'notmatch'. | | + + .OUTPUTS + System.String -- The first matching pattern, or '' when none matches. + + .EXAMPLE + PS> $this.FindMatchingPattern('Ready', @('Ready', 'Running'), 'ne') + + .NOTES + Internal helper used by EvaluateListComparison. + #> + hidden [string] FindMatchingPattern([string]$InputValue, [array]$Patterns, [string]$Operator) + { + foreach ($Entry in $Patterns) { + [string]$Pattern = [string]$Entry; + + if ($Operator -eq 'eq' -or $Operator -eq 'ne') { + if ($InputValue -eq $Pattern) { + return $Pattern; + } + } elseif ($Operator -eq 'like' -or $Operator -eq 'notlike') { + if ($InputValue -like $Pattern) { + return $Pattern; + } + } elseif ($Operator -eq 'match' -or $Operator -eq 'notmatch') { + if ($InputValue -match $Pattern) { + return $Pattern; + } + } + } + + return ''; + } + + <# + .SYNOPSIS + Evaluate a multi-value threshold list comparison against the node's string value + + .DESCRIPTION + Evaluates the node's resolved string value against multi-value warning and + critical threshold lists. For positive operators ('eq', 'like', 'match'), raises + an alert when the value matches any entry in the list; for negated operators + ('ne', 'notlike', 'notmatch'), raises an alert when the list is non-empty and the + value does not match any entry in the allowed list. Critical is evaluated before + warning. + + .PARAMETER Operator + | Name | Type | Description | Default | + |----------|---------------|------------------------------------------------------------|---------| + | Operator | System.String | One of 'eq', 'ne', 'like', 'notlike', 'match', 'notmatch'. | | + + .PARAMETER OperatorText + | Name | Type | Description | Default | + |--------------|---------------|------------------------------------------|---------| + | OperatorText | System.String | Human-readable operator for the message. | | + + .OUTPUTS + System.Object -- An IcingaThresholdResult describing the outcome. + + .EXAMPLE + PS> $this.EvaluateListComparison('ne', 'does not equal') + + .NOTES + Internal helper used when WarningList or CriticalList contains multiple entries. + #> + hidden [object] EvaluateListComparison([string]$Operator, [string]$OperatorText) + { + [object]$ResolvedValue = $this.ResolveStringValue(); + if ($null -eq $ResolvedValue) { + return [IcingaThresholdResult]::new($null, $this.WarningThreshold, $this.CriticalThreshold, 3, 'the value is null and cannot be compared as a string'); + } + + [string]$Text = [string]$ResolvedValue; + [array]$WarnItems = $this.ResolveThresholdList($this.WarningList, $this.WarningThreshold); + [array]$CritItems = $this.ResolveThresholdList($this.CriticalList, $this.CriticalThreshold); + [bool]$WarnSet = ($WarnItems.Count -gt 0); + [bool]$CritSet = ($CritItems.Count -gt 0); + [string]$WarnJoin = ($WarnItems -join ', '); + [string]$CritJoin = ($CritItems -join ', '); + + if ($Operator -eq 'match' -or $Operator -eq 'notmatch') { + foreach ($Pattern in $CritItems) { + try { + [void][regex]::new([string]$Pattern); + } catch { + return [IcingaThresholdResult]::new($Text, $WarnJoin, $CritJoin, 3, ("The critical pattern '{0}' is not a valid regular expression" -f $Pattern)); + } + } + + foreach ($Pattern in $WarnItems) { + try { + [void][regex]::new([string]$Pattern); + } catch { + return [IcingaThresholdResult]::new($Text, $WarnJoin, $CritJoin, 3, ("The warning pattern '{0}' is not a valid regular expression" -f $Pattern)); + } + } + } + + [bool]$IsNegated = ($Operator -eq 'ne' -or $Operator -eq 'notlike' -or $Operator -eq 'notmatch'); + + if ($CritSet) { + [string]$MatchedCrit = $this.FindMatchingPattern($Text, $CritItems, $Operator); + if ($IsNegated) { + if ('' -eq $MatchedCrit) { + return [IcingaThresholdResult]::new($Text, $WarnJoin, $CritJoin, 2, ("'{0}' {1} pattern '{2}'" -f $Text, $OperatorText, $CritJoin)); + } + } else { + if ('' -ne $MatchedCrit) { + return [IcingaThresholdResult]::new($Text, $WarnJoin, $CritJoin, 2, ("'{0}' {1} pattern '{2}'" -f $Text, $OperatorText, $MatchedCrit)); + } + } + } + + if ($WarnSet) { + [string]$MatchedWarn = $this.FindMatchingPattern($Text, $WarnItems, $Operator); + if ($IsNegated) { + if ('' -eq $MatchedWarn) { + return [IcingaThresholdResult]::new($Text, $WarnJoin, $CritJoin, 1, ("'{0}' {1} pattern '{2}'" -f $Text, $OperatorText, $WarnJoin)); + } + } else { + if ('' -ne $MatchedWarn) { + return [IcingaThresholdResult]::new($Text, $WarnJoin, $CritJoin, 1, ("'{0}' {1} pattern '{2}'" -f $Text, $OperatorText, $MatchedWarn)); + } + } + } + + return [IcingaThresholdResult]::new($Text, $WarnJoin, $CritJoin, 0, ("'{0}' is ok" -f $Text)); + } + + <# + .SYNOPSIS + Build an IcingaThresholds pair from the configured thresholds + + .DESCRIPTION + Creates an IcingaThresholds object from the stored warning and critical strings, + passing the base value as well when one was set. A plain numeric base value of a + byte or time node carries the 'B' or 's' unit, so percent thresholds resolve and + render in that unit. When the node itself already measures a percentage (Unit '%'), + percentage signs on threshold bounds ('10%', '10%:80%') are normalized to plain + numbers in that same '%' unit so callers may write either '10' or '10%' without + requiring a separate base value or duplicating the percentage in the output. The + return type is object because IcingaThresholds is parsed after IcingaPlugin during + the build and may therefore only be referenced from method bodies. + + .OUTPUTS + System.Object -- An IcingaThresholds instance. + + .EXAMPLE + PS> $this.NewThresholds() + + .NOTES + Internal helper used by every comparison method. + #> + hidden [object] NewThresholds() + { + [string]$Warning = $this.WarningThreshold; + [string]$Critical = $this.CriticalThreshold; + + if ($this.Unit -eq '%' -and ($null -eq $this.BaseValueSetting -or '' -eq [string]$this.BaseValueSetting -or [string]$this.BaseValueSetting -eq '100')) { + $Warning = $Warning -replace '(?<=\d)%', ''; + $Critical = $Critical -replace '(?<=\d)%', ''; + + return [IcingaThresholds]::new($Warning, $Critical); + } + + if ($null -ne $this.BaseValueSetting -and '' -ne [string]$this.BaseValueSetting) { + return [IcingaThresholds]::new($Warning, $Critical, [string]$this.AttachBaseUnit($this.BaseValueSetting)); + } + + return [IcingaThresholds]::new($Warning, $Critical); + } + + <# + .SYNOPSIS + Build an IcingaThresholds pair with translated string thresholds when applicable + + .DESCRIPTION + Creates an IcingaThresholds instance for string/pattern comparison methods. When a + translation table is configured, translates the warning and critical threshold + tokens through ResolveTranslation so a caller may pass either a raw code ('4') or + its translated display name ('Running'). + + .OUTPUTS + System.Object -- An IcingaThresholds instance. + + .EXAMPLE + PS> $this.NewStringThresholds() + + .NOTES + Internal helper used by CheckMatch, CheckNotMatch, CheckLike, CheckNotLike, + CheckEqual and CheckNotEqual. + #> + hidden [object] NewStringThresholds() + { + [string]$Warning = $this.WarningThreshold; + [string]$Critical = $this.CriticalThreshold; + + if ('' -ne $Warning) { + [string]$MappedWarning = $this.ResolveTranslation($Warning); + if ($null -ne $MappedWarning -and '' -ne $MappedWarning) { + $Warning = $MappedWarning; + } + } + + if ('' -ne $Critical) { + [string]$MappedCritical = $this.ResolveTranslation($Critical); + if ($null -ne $MappedCritical -and '' -ne $MappedCritical) { + $Critical = $MappedCritical; + } + } + + return [IcingaThresholds]::new($Warning, $Critical); + } + + <# + .SYNOPSIS + Resolve the node's value for string comparison and display + + .DESCRIPTION + Returns the translated representation of the node's value when a translation is + configured (or when Value is an enum), otherwise returns Value as-is. + + .OUTPUTS + System.Object -- The value to compare in string comparison methods. + + .EXAMPLE + PS> $this.ResolveStringValue() + + .NOTES + Internal helper used by string comparison methods. + #> + hidden [object] ResolveStringValue() + { + if ($null -eq $this.Value) { + return $null; + } + + [string]$Mapped = $this.ResolveTranslation($this.Value); + if ($null -ne $Mapped -and '' -ne $Mapped) { + return $Mapped; + } + + return $this.Value; + } + + <# + .SYNOPSIS + Look up the human-readable translation for a value or threshold + + .DESCRIPTION + Resolves an input item against TranslatedText (when matching the node's Value), + the Translation hashtable (matching direct keys, numeric enum values and + case-insensitive string keys), or a [System.Enum] name. Returns $null when no + translation applies. + + .PARAMETER Item + | Name | Type | Description | Default | + |------|---------------|------------------------------------|---------| + | Item | System.Object | Value or threshold token to map. | | .OUTPUTS - System.Object — An IcingaThresholds instance. + System.String -- Translated display string, or $null when none applies. .EXAMPLE - PS> $this.NewThresholds() + PS> $this.ResolveTranslation(4) .NOTES - Internal helper used by every comparison method. + Internal helper shared by display rendering and string threshold comparisons. #> - hidden [object] NewThresholds() + hidden [string] ResolveTranslation([object]$Item) { - if ($null -ne $this.BaseValueSetting -and '' -ne [string]$this.BaseValueSetting) { - return [IcingaThresholds]::new($this.WarningThreshold, $this.CriticalThreshold, [string]$this.AttachBaseUnit($this.BaseValueSetting)); + if ($null -eq $Item) { + return $null; + } + + if ('' -ne $this.TranslatedText -and [string]$Item -eq [string]$this.Value) { + return $this.TranslatedText; + } + + if ($null -ne $this.Translation -and $this.Translation.Count -gt 0) { + if ($this.Translation.ContainsKey($Item)) { + return [string]$this.Translation[$Item]; + } + + if ($Item -is [System.Enum]) { + [int]$EnumCode = [int]$Item; + if ($this.Translation.ContainsKey($EnumCode)) { + return [string]$this.Translation[$EnumCode]; + } + } + + [string]$ItemText = [string]$Item; + foreach ($Key in $this.Translation.Keys) { + if ([string]::Equals([string]$Key, $ItemText, [System.StringComparison]::OrdinalIgnoreCase)) { + return [string]$this.Translation[$Key]; + } + } } - return [IcingaThresholds]::new($this.WarningThreshold, $this.CriticalThreshold); + if ($Item -is [System.Enum]) { + return [string]$Item; + } + + return $null; } <# @@ -808,7 +1896,7 @@ class IcingaPlugin the plain display-unit behaviour. .OUTPUTS - System.Boolean — True when the unit is 'B' or 's'. + System.Boolean -- True when the unit is 'B' or 's'. .EXAMPLE PS> $this.HasBaseUnit() @@ -843,7 +1931,7 @@ class IcingaPlugin | Value | System.Object | Measured value or base value to adjust. | | .OUTPUTS - System.Object — The value with the unit attached, or the unchanged value. + System.Object -- The value with the unit attached, or the unchanged value. .EXAMPLE PS> $this.AttachBaseUnit(442692000000) @@ -892,12 +1980,12 @@ class IcingaPlugin thresholds in the same unit as the value. .PARAMETER Result - | Name | Type | Description | Default | - |--------|---------------|--------------------------------------------|---------| - | Result | System.Object | An IcingaThresholdResult from a comparison. | | + | Name | Type | Description | Default | + |--------|---------------|---------------------------------------------|---------| + | Result | System.Object | An IcingaThresholdResult from a comparison. | | .OUTPUTS - None — Updates instance state. + None -- Updates instance state. .EXAMPLE PS> $this.ApplyThresholdResult($result) @@ -912,13 +2000,20 @@ class IcingaPlugin # A locked node froze its state and message via an override; later threshold # evaluation must not overwrite either. EscalateState honours the lock too. if (-not $this.Locked) { - if ($this.Unit -eq 'B') { + if ([int]$Result.StatusCode -eq 3) { + # Do not suffix units onto threshold parse/configuration error explanations. + $this.OutputMessage = [string]$Result.Output; + } elseif ($this.Unit -eq 'B') { $this.OutputMessage = $this.HumanizeByteValues([string]$Result.Output); } elseif ($this.Unit -ceq 's') { $this.OutputMessage = $this.HumanizeTimeValues([string]$Result.Output); } else { $this.OutputMessage = $this.ApplyDisplayUnit([string]$Result.Output); } + + if ([int]$Result.StatusCode -ne 3) { + $this.OutputMessage = $this.ApplyValueTranslation($this.OutputMessage); + } } $this.ResolvedWarning = ''; @@ -936,6 +2031,56 @@ class IcingaPlugin $this.BuildPerfData(); } + <# + .SYNOPSIS + Replace the leading value figure in a numeric comparison message with its translation + + .DESCRIPTION + When a translation applies to the node's measured value (for example 0 -> 'Never' + on a time check, or 4 -> 'Running' on a numeric check), replaces the leading + rendered value token in the threshold message with the translated string. + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|----------------------------------------|---------| + | Message | System.String | Output message after unit formatting. | | + + .OUTPUTS + System.String -- Message with the translated value applied when configured. + + .EXAMPLE + PS> $this.ApplyValueTranslation('0s is ok') + + .NOTES + Internal helper used by ApplyThresholdResult. + #> + hidden [string] ApplyValueTranslation([string]$Message) + { + [string]$Mapped = $this.ResolveTranslation($this.Value); + if ($null -eq $Mapped -or '' -eq $Mapped) { + return $Message; + } + + # String comparisons already receive the translated value directly. + if ($Message.StartsWith("'" + $Mapped + "'", [System.StringComparison]::OrdinalIgnoreCase)) { + return $Message; + } + + [string]$Updated = [regex]::Replace($Message, '^-?\d+(?:\.\d+)?[A-Za-z%]*', ($Mapped -replace '\$', '$$$$')); + + if ($null -ne $this.Translation -and $this.Translation.Count -gt 0) { + $ThresholdMatch = [regex]::Match($Updated, '\bthreshold\s+(-?\d+(?:\.\d+)?)\b'); + if ($ThresholdMatch.Success) { + [string]$MappedThreshold = $this.ResolveTranslation($ThresholdMatch.Groups[1].Value); + if ($null -ne $MappedThreshold -and '' -ne $MappedThreshold) { + $Updated = [regex]::Replace($Updated, '\bthreshold\s+-?\d+(?:\.\d+)?\b', ('threshold ' + ($MappedThreshold -replace '\$', '$$$$'))); + } + } + } + + return $Updated; + } + <# .SYNOPSIS Render plain byte figures of an output message as human-readable sizes @@ -953,7 +2098,7 @@ class IcingaPlugin | Message | System.String | The threshold output message. | | .OUTPUTS - System.String — The message with byte figures converted to their best-fit unit. + System.String -- The message with byte figures converted to their best-fit unit. .EXAMPLE PS> $this.HumanizeByteValues('442692000000B (86.46%) is greater than threshold 409600000000B (80%)') @@ -968,7 +2113,7 @@ class IcingaPlugin [string]$Output = ''; [int]$Position = 0; - foreach ($Match in [regex]::Matches($Message, '(? $this.HumanizeTimeValues('3600s is greater than threshold 30m') @@ -1014,7 +2159,7 @@ class IcingaPlugin [string]$Output = ''; [int]$Position = 0; - foreach ($Match in [regex]::Matches($Message, '(? $this.ApplyDisplayUnit('95 is greater than threshold 90') @@ -1057,12 +2203,14 @@ class IcingaPlugin #> hidden [string] ApplyDisplayUnit([string]$Message) { - if ('' -eq $this.Unit) { + if ('' -eq $this.Unit -or $this.Unit -ceq 'c') { return $Message; } + [string]$EscapedUnit = [regex]::Escape($this.Unit); + [string]$Pattern = [string]::Format('(? $this.EscalateState(2) @@ -1099,6 +2247,101 @@ class IcingaPlugin } } + <# + .SYNOPSIS + Resolve a state name or numeric string to its integer exit code + + .DESCRIPTION + Maps 'Ok', 'Warning', 'Critical', 'Unknown' (case-insensitively) or '0'..'3' to + the corresponding Icinga plugin exit code (0..3). Unknown strings default to 3. + + .PARAMETER State + | Name | Type | Description | Default | + |-------|---------------|------------------------------------------------------|---------| + | State | System.String | State name ('Ok', 'Warning', 'Critical', 'Unknown'). | | + + .OUTPUTS + System.Int32 -- The resolved Icinga state code (0..3). + + .EXAMPLE + PS> $this.ResolveStateCode('Critical') + + .NOTES + Internal helper used by the string overloads of SetState and AddMissingChecks. + #> + hidden [int] ResolveStateCode([string]$State) + { + if ($null -eq $State) { + return 3; + } + + [string]$Key = $State.Trim().ToLowerInvariant(); + if ([IcingaPlugin]::StateMap.ContainsKey($Key)) { + return [IcingaPlugin]::StateMap[$Key]; + } + + return 3; + } + + <# + .SYNOPSIS + Force the node into a specific numeric state + + .DESCRIPTION + Overrides the node state to the given integer exit code (0..3) without changing + the output message or locking the node. + + .PARAMETER State + | Name | Type | Description | Default | + |-------|--------------|-------------------------------------------------|---------| + | State | System.Int32 | Forced state (0 OK, 1 WARN, 2 CRIT, 3 UNKN). | | + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.SetState(2) + + .NOTES + Delegates to SetState([int], [string], [bool]). + #> + [IcingaPlugin] SetState([int]$State) + { + return $this.SetState($State, '', $false); + } + + <# + .SYNOPSIS + Force the node into a specific numeric state with a message + + .DESCRIPTION + Overrides the node state to the given integer exit code (0..3) and replaces the + output message when one is given, without locking the node. + + .PARAMETER State + | Name | Type | Description | Default | + |-------|--------------|-------------------------------------------------|---------| + | State | System.Int32 | Forced state (0 OK, 1 WARN, 2 CRIT, 3 UNKN). | | + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|--------------------------------------------------|---------| + | Message | System.String | Output message; '' keeps the existing message. | | + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.SetState(2, 'Service is stopped') + + .NOTES + Delegates to SetState([int], [string], [bool]). + #> + [IcingaPlugin] SetState([int]$State, [string]$Message) + { + return $this.SetState($State, $Message, $false); + } + <# .SYNOPSIS Central override that forces a specific node state @@ -1121,12 +2364,12 @@ class IcingaPlugin | Message | System.String | Output message; '' keeps the existing message. | | .PARAMETER Lock - | Name | Type | Description | Default | - |------|----------------|-------------------------------------------------|---------| - | Lock | System.Boolean | When true, freeze the state against later changes. | | + | Name | Type | Description | Default | + |------|----------------|----------------------------------------------------|---------| + | Lock | System.Boolean | When true, freeze the state against later changes. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $check.SetState(2, 'Service is stopped', $true) @@ -1134,11 +2377,12 @@ class IcingaPlugin .NOTES All SetOk/SetWarning/SetCritical/SetUnknown wrappers funnel through this method. #> - hidden [IcingaPlugin] SetState([int]$State, [string]$Message, [bool]$Lock) + [IcingaPlugin] SetState([int]$State, [string]$Message, [bool]$Lock) { if (-not $this.Locked) { - $this.FixedState = $true; - $this.State = $State; + $this.FixedState = $true; + $this.IsNoticeObject = $false; + $this.State = $State; if ('' -ne $Message) { $this.OutputMessage = $Message; } @@ -1151,6 +2395,125 @@ class IcingaPlugin return $this; } + <# + .SYNOPSIS + Force the node into a state specified by name + + .DESCRIPTION + Overrides the node state using a state name ('Ok', 'Warning', 'Critical', + 'Unknown') without changing the output message or locking the node. + + .PARAMETER State + | Name | Type | Description | Default | + |-------|---------------|--------------------------------------------------------|---------| + | State | System.String | Forced state ('Ok', 'Warning', 'Critical', 'Unknown'). | | + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.SetState($OverrideNotOk) + + .NOTES + Delegates to SetState([int], [string], [bool]). + #> + [IcingaPlugin] SetState([string]$State) + { + return $this.SetState($this.ResolveStateCode($State), '', $false); + } + + <# + .SYNOPSIS + Force the node into a state specified by name with a message + + .DESCRIPTION + Overrides the node state using a state name ('Ok', 'Warning', 'Critical', + 'Unknown') and replaces the output message when one is given. + + .PARAMETER State + | Name | Type | Description | Default | + |-------|---------------|--------------------------------------------------------|---------| + | State | System.String | Forced state ('Ok', 'Warning', 'Critical', 'Unknown'). | | + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|--------------------------------------------------|---------| + | Message | System.String | Output message; '' keeps the existing message. | | + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.SetState($OverrideNotOk, 'Service is stopped') + + .NOTES + Delegates to SetState([int], [string], [bool]). + #> + [IcingaPlugin] SetState([string]$State, [string]$Message) + { + return $this.SetState($this.ResolveStateCode($State), $Message, $false); + } + + <# + .SYNOPSIS + Force the node into a state specified by name, optionally locking it + + .DESCRIPTION + Overrides the node state using a state name ('Ok', 'Warning', 'Critical', + 'Unknown'), replaces the output message when one is given, and optionally locks + the state against later changes. + + .PARAMETER State + | Name | Type | Description | Default | + |-------|---------------|--------------------------------------------------------|---------| + | State | System.String | Forced state ('Ok', 'Warning', 'Critical', 'Unknown'). | | + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|--------------------------------------------------|---------| + | Message | System.String | Output message; '' keeps the existing message. | | + + .PARAMETER Lock + | Name | Type | Description | Default | + |------|----------------|----------------------------------------------------|---------| + | Lock | System.Boolean | When true, freeze the state against later changes. | | + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.SetState($OverrideNotOk, '', $true) + + .NOTES + Delegates to SetState([int], [string], [bool]). + #> + [IcingaPlugin] SetState([string]$State, [string]$Message, [bool]$Lock) + { + return $this.SetState($this.ResolveStateCode($State), $Message, $Lock); + } + + <# + .SYNOPSIS + Force the node into the OK state without changing the output message + + .DESCRIPTION + Overrides the node state to OK while keeping the existing or default output + message. + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.SetOk() + + .NOTES + Convenience wrapper around SetState; does not lock the state. + #> + [IcingaPlugin] SetOk() + { + return $this.SetState(0, '', $false); + } + <# .SYNOPSIS Force the node into the OK state @@ -1164,7 +2527,7 @@ class IcingaPlugin | Message | System.String | Output message for the OK state. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $check.SetOk('All good') @@ -1196,7 +2559,7 @@ class IcingaPlugin | Lock | System.Boolean | When true, freeze the state. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $check.SetOk('All good', $true) @@ -1209,6 +2572,28 @@ class IcingaPlugin return $this.SetState(0, $Message, $Lock); } + <# + .SYNOPSIS + Force the node into the WARNING state without changing the output message + + .DESCRIPTION + Overrides the node state to WARNING while keeping the existing or default output + message. + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.SetWarning() + + .NOTES + Convenience wrapper around SetState; does not lock the state. + #> + [IcingaPlugin] SetWarning() + { + return $this.SetState(1, '', $false); + } + <# .SYNOPSIS Force the node into the WARNING state @@ -1222,7 +2607,7 @@ class IcingaPlugin | Message | System.String | Output message for the WARNING state. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $check.SetWarning('Approaching limit') @@ -1254,7 +2639,7 @@ class IcingaPlugin | Lock | System.Boolean | When true, freeze the state. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $check.SetWarning('Approaching limit', $true) @@ -1267,6 +2652,28 @@ class IcingaPlugin return $this.SetState(1, $Message, $Lock); } + <# + .SYNOPSIS + Force the node into the CRITICAL state without changing the output message + + .DESCRIPTION + Overrides the node state to CRITICAL while keeping the existing or default output + message. + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.SetCritical() + + .NOTES + Convenience wrapper around SetState; does not lock the state. + #> + [IcingaPlugin] SetCritical() + { + return $this.SetState(2, '', $false); + } + <# .SYNOPSIS Force the node into the CRITICAL state @@ -1280,7 +2687,7 @@ class IcingaPlugin | Message | System.String | Output message for the CRITICAL state. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $check.SetCritical('Service is stopped') @@ -1312,7 +2719,7 @@ class IcingaPlugin | Lock | System.Boolean | When true, freeze the state. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $check.SetCritical('Service is stopped', $true) @@ -1325,6 +2732,28 @@ class IcingaPlugin return $this.SetState(2, $Message, $Lock); } + <# + .SYNOPSIS + Force the node into the UNKNOWN state without changing the output message + + .DESCRIPTION + Overrides the node state to UNKNOWN while keeping the existing or default output + message. + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $check.SetUnknown() + + .NOTES + Convenience wrapper around SetState; does not lock the state. + #> + [IcingaPlugin] SetUnknown() + { + return $this.SetState(3, '', $false); + } + <# .SYNOPSIS Force the node into the UNKNOWN state @@ -1338,7 +2767,7 @@ class IcingaPlugin | Message | System.String | Output message for the UNKNOWN state. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $check.SetUnknown('Data source unavailable') @@ -1370,7 +2799,7 @@ class IcingaPlugin | Lock | System.Boolean | When true, freeze the state. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $check.SetUnknown('Data source unavailable', $true) @@ -1399,7 +2828,7 @@ class IcingaPlugin | Message | System.String | Error message to show. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> return $CheckPackage.SetError('No partition data available').Compile() @@ -1421,9 +2850,9 @@ class IcingaPlugin the argument in the style of [string]::Format. .PARAMETER Message - | Name | Type | Description | Default | - |---------|---------------|--------------------------------------|---------| - | Message | System.String | Format string with a '{0}' placeholder. | | + | Name | Type | Description | Default | + |---------|---------------|-----------------------------------------|---------| + | Message | System.String | Format string with a '{0}' placeholder. | | .PARAMETER Argument | Name | Type | Description | Default | @@ -1431,7 +2860,7 @@ class IcingaPlugin | Argument | System.Object | Value inserted for '{0}'. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $CheckPackage.SetError('Failed to read the counter {0}', $CounterPath) @@ -1468,7 +2897,7 @@ class IcingaPlugin | Argument2 | System.Object | Value inserted for '{1}'. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $CheckPackage.SetError('Failed to query {0}: {1}', $ClassName, $Reason) @@ -1510,7 +2939,7 @@ class IcingaPlugin | Argument3 | System.Object | Value inserted for '{2}'. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $CheckPackage.SetError('{0} failed on {1}: {2}', $Step, $Target, $Reason) @@ -1532,9 +2961,9 @@ class IcingaPlugin elements of the argument array in the style of [string]::Format. .PARAMETER Message - | Name | Type | Description | Default | - |---------|---------------|---------------------------------------------|---------| - | Message | System.String | Format string with '{0}'-style placeholders. | | + | Name | Type | Description | Default | + |---------|---------------|----------------------------------------------|---------| + | Message | System.String | Format string with '{0}'-style placeholders. | | .PARAMETER Arguments | Name | Type | Description | Default | @@ -1542,7 +2971,7 @@ class IcingaPlugin | Arguments | System.Object[] | Values inserted into the placeholders. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $CheckPackage.SetError('{0}/{1}/{2}/{3}', @('a', 'b', 'c', 'd')) @@ -1569,7 +2998,7 @@ class IcingaPlugin | IcingaError | IcingaError | Error returned by a data collection. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> if (Test-IcingaError -InputObject $Services) { return $CheckPackage.SetError($Services).Compile(); } @@ -1601,21 +3030,48 @@ class IcingaPlugin | Message | System.String | Final error message. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. + + .EXAMPLE + PS> $this.ApplyError('Failed to query Win32_Service') + + .NOTES + Internal helper; funnels into SetState like every other override. + #> + hidden [IcingaPlugin] ApplyError([string]$Message) + { + if (-not $this.Locked) { + $this.HasError = $true; + } + + return $this.SetState(3, $Message, $true); + } + + <# + .SYNOPSIS + Mark the node or container as an informational notice + + .DESCRIPTION + Turns the node or package into an informational notice that renders with the + [INFO] prefix and keeps the OK state without changing the output message. + + .OUTPUTS + IcingaPlugin -- The same node, for chaining. .EXAMPLE - PS> $this.ApplyError('Failed to query Win32_Service') + PS> $noticePkg.SetNotice() .NOTES - Internal helper; funnels into SetState like every other override. + Notices never raise the plugin state; they are purely informational. #> - hidden [IcingaPlugin] ApplyError([string]$Message) + [IcingaPlugin] SetNotice() { if (-not $this.Locked) { - $this.HasError = $true; + $this.State = 0; + $this.IsNotice = $true; } - return $this.SetState(3, $Message, $true); + return $this; } <# @@ -1632,7 +3088,7 @@ class IcingaPlugin | Message | System.String | Informational message to display. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $check.SetNotice('Collected 5 samples') @@ -1665,7 +3121,7 @@ class IcingaPlugin | Lock | System.Boolean | When true, freeze the node. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $check.SetNotice('Collected 5 samples', $true) @@ -1676,6 +3132,7 @@ class IcingaPlugin [IcingaPlugin] SetNotice([string]$Message, [bool]$Lock) { if (-not $this.Locked) { + $this.State = 0; $this.IsNoticeObject = $true; if ('' -ne $Message) { $this.OutputMessage = $Message; @@ -1698,7 +3155,7 @@ class IcingaPlugin not OK. This is the default operator. .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $package.CheckAnd() @@ -1721,7 +3178,7 @@ class IcingaPlugin OK, and becomes not-OK only when every child is not OK. .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $package.CheckOr() @@ -1744,7 +3201,7 @@ class IcingaPlugin OK. .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $package.CheckNone() @@ -1767,7 +3224,7 @@ class IcingaPlugin intent can be stated explicitly in a chain. .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $package.CheckDefault() @@ -1789,12 +3246,12 @@ class IcingaPlugin Sets the container so it becomes not-OK when fewer than Count children are OK. .PARAMETER Count - | Name | Type | Description | Default | - |-------|--------------|------------------------------------------|---------| - | Count | System.Int32 | Minimum number of children that must be OK. | | + | Name | Type | Description | Default | + |-------|--------------|---------------------------------------------|---------| + | Count | System.Int32 | Minimum number of children that must be OK. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $package.CheckMinimum(3) @@ -1821,7 +3278,7 @@ class IcingaPlugin | Count | System.Int32 | Maximum number of children that may be OK. | | .OUTPUTS - IcingaPlugin — The same node, for chaining. + IcingaPlugin -- The same node, for chaining. .EXAMPLE PS> $package.CheckMaximum(5) @@ -1845,12 +3302,12 @@ class IcingaPlugin Returns this container so multiple AddCheck calls chain. .PARAMETER Check - | Name | Type | Description | Default | - |-------|-------------|---------------------------------|---------| + | Name | Type | Description | Default | + |-------|--------------|--------------------------------|---------| | Check | IcingaPlugin | Child plugin to add. | | .OUTPUTS - IcingaPlugin — This container, for chaining. + IcingaPlugin -- This container, for chaining. .EXAMPLE PS> $package.AddCheck($diskC).AddCheck($diskD) @@ -1887,7 +3344,7 @@ class IcingaPlugin | Checks | System.Array | Child plugins to add. | | .OUTPUTS - IcingaPlugin — This container, for chaining. + IcingaPlugin -- This container, for chaining. .EXAMPLE PS> $package.AddCheck(@($diskC, $diskD)) @@ -1938,17 +3395,17 @@ class IcingaPlugin | NameFormat | System.String | Check name with '{0}' for the missing entry. | | .PARAMETER Message - | Name | Type | Description | Default | - |---------|---------------|---------------------------------------|---------| - | Message | System.String | Output message of every missing check. | | + | Name | Type | Description | Default | + |---------|---------------|----------------------------------------|---------| + | Message | System.String | Output message of every missing check. | | .PARAMETER State - | Name | Type | Description | Default | - |-------|--------------|------------------------------------------------------|---------| - | State | System.Int32 | State of the missing checks (0 OK, 1 WARN, 2 CRIT, 3 UNKN). | | + | Name | Type | Description | Default | + |-------|--------------|-------------------------------------------------------------|---------| + | State | System.Int32 | State of the missing checks (0 OK, 1 WARN, 2 CRIT, 3 UNKN). | | .OUTPUTS - IcingaPlugin — This container, for chaining. + IcingaPlugin -- This container, for chaining. .EXAMPLE PS> $CheckPackage.AddMissingChecks($Service, $KnownServices, '{0}', 'Service not found', 3).Commit() @@ -1987,14 +3444,14 @@ class IcingaPlugin | NameFormat | System.String | Check name with '{0}' for the missing entry. | | .PARAMETER Message - | Name | Type | Description | Default | - |---------|---------------|---------------------------------------|---------| - | Message | System.String | Output message of every missing check. | | + | Name | Type | Description | Default | + |---------|---------------|----------------------------------------|---------| + | Message | System.String | Output message of every missing check. | | .PARAMETER State - | Name | Type | Description | Default | - |-------|--------------|------------------------------------------------------|---------| - | State | System.Int32 | State of the missing checks (0 OK, 1 WARN, 2 CRIT, 3 UNKN). | | + | Name | Type | Description | Default | + |-------|--------------|-------------------------------------------------------------|---------| + | State | System.Int32 | State of the missing checks (0 OK, 1 WARN, 2 CRIT, 3 UNKN). | | .PARAMETER NormalizePattern | Name | Type | Description | Default | @@ -2002,7 +3459,7 @@ class IcingaPlugin | NormalizePattern | System.String | Regex removed from each entry; '' keeps it as is. | | .OUTPUTS - IcingaPlugin — This container, for chaining. + IcingaPlugin -- This container, for chaining. .EXAMPLE PS> $CheckPackage.AddMissingChecks($RequiredPartition, $KnownPartitions, 'Partition {0}', 'Mandatory partition not found on host', 2, '[:\\/]+$').Commit() @@ -2040,6 +3497,105 @@ class IcingaPlugin return $this; } + <# + .SYNOPSIS + Add a check for every required entry that is missing, using a state name + + .DESCRIPTION + Like AddMissingChecks with an integer state, accepting the state by name + ('Ok', 'Warning', 'Critical', 'Unknown'). + + .PARAMETER Required + | Name | Type | Description | Default | + |----------|--------------|---------------------------------------------|---------| + | Required | System.Array | Entries that must exist, wildcards allowed. | | + + .PARAMETER Available + | Name | Type | Description | Default | + |-----------|--------------|--------------------------------------|---------| + | Available | System.Array | Entries that were found on the host. | | + + .PARAMETER NameFormat + | Name | Type | Description | Default | + |------------|---------------|----------------------------------------------|---------| + | NameFormat | System.String | Check name with '{0}' for the missing entry. | | + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|----------------------------------------|---------| + | Message | System.String | Output message of every missing check. | | + + .PARAMETER State + | Name | Type | Description | Default | + |-------|---------------|-----------------------------------------------------------|---------| + | State | System.String | State name ('Ok', 'Warning', 'Critical', 'Unknown'). | | + + .OUTPUTS + IcingaPlugin -- This container, for chaining. + + .EXAMPLE + PS> $CheckPackage.AddMissingChecks($Service, $KnownServices, '{0}', 'Service not found', 'Critical').Commit() + + .NOTES + Delegates to the overload with NormalizePattern, without normalization. + #> + [IcingaPlugin] AddMissingChecks([array]$Required, [array]$Available, [string]$NameFormat, [string]$Message, [string]$State) + { + return $this.AddMissingChecks($Required, $Available, $NameFormat, $Message, $this.ResolveStateCode($State), ''); + } + + <# + .SYNOPSIS + Add a check for every required entry that is missing, with entry normalization and a state name + + .DESCRIPTION + Like AddMissingChecks with NormalizePattern, accepting the state by name + ('Ok', 'Warning', 'Critical', 'Unknown'). + + .PARAMETER Required + | Name | Type | Description | Default | + |----------|--------------|---------------------------------------------|---------| + | Required | System.Array | Entries that must exist, wildcards allowed. | | + + .PARAMETER Available + | Name | Type | Description | Default | + |-----------|--------------|--------------------------------------|---------| + | Available | System.Array | Entries that were found on the host. | | + + .PARAMETER NameFormat + | Name | Type | Description | Default | + |------------|---------------|----------------------------------------------|---------| + | NameFormat | System.String | Check name with '{0}' for the missing entry. | | + + .PARAMETER Message + | Name | Type | Description | Default | + |---------|---------------|----------------------------------------|---------| + | Message | System.String | Output message of every missing check. | | + + .PARAMETER State + | Name | Type | Description | Default | + |-------|---------------|-----------------------------------------------------------|---------| + | State | System.String | State name ('Ok', 'Warning', 'Critical', 'Unknown'). | | + + .PARAMETER NormalizePattern + | Name | Type | Description | Default | + |------------------|---------------|----------------------------------------------------|---------| + | NormalizePattern | System.String | Regex removed from each entry; '' keeps it as is. | | + + .OUTPUTS + IcingaPlugin -- This container, for chaining. + + .EXAMPLE + PS> $CheckPackage.AddMissingChecks($RequiredPartition, $KnownPartitions, 'Partition {0}', 'Mandatory partition not found on host', 'Critical', '[:\\/]+$').Commit() + + .NOTES + Delegates to the integer state overload after resolving the state name. + #> + [IcingaPlugin] AddMissingChecks([array]$Required, [array]$Available, [string]$NameFormat, [string]$Message, [string]$State, [string]$NormalizePattern) + { + return $this.AddMissingChecks($Required, $Available, $NameFormat, $Message, $this.ResolveStateCode($State), $NormalizePattern); + } + <# .SYNOPSIS Test whether any entry matches a wildcard pattern @@ -2059,7 +3615,7 @@ class IcingaPlugin | Pattern | System.String | Wildcard pattern to match. | | .OUTPUTS - System.Boolean — True when at least one entry matches. + System.Boolean -- True when at least one entry matches. .EXAMPLE PS> $this.ContainsMatch(@('C', 'D'), 'c') @@ -2084,25 +3640,143 @@ class IcingaPlugin <# .SYNOPSIS - Test whether the node has any child check + Test whether the node has any visible child check .DESCRIPTION - Returns true as soon as at least one child (hidden ones included) was added, - so a plugin can detect an empty package and report it, for example with - SetError('No service matches the given filter'). + Returns true as soon as at least one non-hidden child was added, so a plugin can + detect an empty package and report it, for example with + SetError('No service matches the given filter'). Hidden children carry background + metrics only and do not count as active checks. .OUTPUTS - System.Boolean — True when the node has children. + System.Boolean -- True when the node has at least one non-hidden child. .EXAMPLE PS> if (-not $CheckPackage.HasChecks()) { return $CheckPackage.SetError('Nothing to check').Compile(); } .NOTES - Counts direct children only. + Counts direct non-hidden children only. #> [bool] HasChecks() { - return ($this.Checks.Count -ne 0); + foreach ($Child in $this.Checks) { + if (-not $Child.IsHidden) { + return $true; + } + } + + return $false; + } + + <# + .SYNOPSIS + Test whether this node is an empty container without value, state or checks + + .DESCRIPTION + Returns true when the node has no visible child checks, no own value, was neither + evaluated nor locked into a fixed or error state, is not a notice leaf and carries + no output message. Used by ResolveState to apply the classic empty-package handling + (UNKNOWN 'No checks added to this package', OK when IgnoreEmptyPackage is set, or + [INFO] 'Nothing to report' for a notice package). + + .OUTPUTS + System.Boolean -- True when this node is an empty package. + + .EXAMPLE + PS> $this.IsEmptyPackage() + + .NOTES + Internal helper used by ResolveState. + #> + hidden [bool] IsEmptyPackage() + { + return ( + -not $this.HasChecks() -and + $null -eq $this.Value -and + -not $this.Evaluated -and + -not $this.FixedState -and + -not $this.IsNoticeObject -and + -not $this.HasError -and + '' -eq $this.OutputMessage + ); + } + + <# + .SYNOPSIS + Test whether this node is an informational notice node + + .DESCRIPTION + Returns true when the node is a notice package (IsNotice), an explicit notice leaf + (SetNotice / IsNoticeObject), or an unevaluated leaf without a fixed state (which + renders as [INFO]). Notice nodes never participate in state aggregation or summary + counts. + + .OUTPUTS + System.Boolean -- True when this node is purely informational. + + .EXAMPLE + PS> $this.IsNoticeNode() + + .NOTES + Internal helper used by ResolveState and CollectLeafChecks. + #> + hidden [bool] IsNoticeNode() + { + if ($this.IsNotice -or $this.IsNoticeObject) { + return $true; + } + + if (-not $this.HasChecks() -and -not $this.FixedState -and -not $this.Evaluated -and -not $this.IgnoredEmpty) { + return $true; + } + + return $false; + } + + <# + .SYNOPSIS + Ensure a leaf check with a value has a default output message and performance data + + .DESCRIPTION + Populates a default output message from the node's value (applying any configured + translation, human-readable byte/time conversion or display unit) when no threshold + comparison or state override set one, and builds the node's performance data when + none was built yet or when metric attributes were updated after comparison. + + .OUTPUTS + None -- Updates OutputMessage and PerfData on this node. + + .EXAMPLE + PS> $this.EnsureLeafDefaults() + + .NOTES + Internal helper called by ResolveState. + #> + hidden [void] EnsureLeafDefaults() + { + if ($null -eq $this.Value -or $this.HasError) { + return; + } + + if ('' -eq $this.OutputMessage) { + [string]$Translated = $this.ResolveTranslation($this.Value); + + if ('' -ne $Translated) { + $this.OutputMessage = $Translated; + } elseif ($this.Unit -eq 'B' -and $this.IsNumeric($this.Value)) { + $this.OutputMessage = $this.HumanizeByteValues([string]::Format('{0}B', $this.FormatNumber($this.Value))); + } elseif ($this.Unit -ceq 's' -and $this.IsNumeric($this.Value)) { + $this.OutputMessage = $this.HumanizeTimeValues([string]::Format('{0}s', $this.FormatNumber($this.Value))); + } elseif ($this.IsNumeric($this.Value)) { + $this.OutputMessage = $this.ApplyDisplayUnit($this.FormatNumber($this.Value)); + } else { + $this.OutputMessage = [string]$this.Value; + } + } + + if (-not ($this.Evaluated -and $this.PerfData.Count -eq 0 -and $this.State -eq 3)) { + $this.BuildPerfData(); + } } <# @@ -2115,7 +3789,7 @@ class IcingaPlugin attached to a new parent. .OUTPUTS - None — Updates the children's state. + None -- Updates the children's state. .EXAMPLE PS> $this.PropagateIndention() @@ -2147,7 +3821,7 @@ class IcingaPlugin | Verbose | System.Int32 | Verbosity level to apply everywhere. | | .OUTPUTS - None — Updates this node and its descendants. + None -- Updates this node and its descendants. .EXAMPLE PS> $this.PropagateVerbose(2) @@ -2169,14 +3843,18 @@ class IcingaPlugin Resolve the final state of this node and its subtree .DESCRIPTION - For a leaf, returns the state that threshold evaluation or an override already - set. For a container, recursively resolves every child, counts OK versus not-OK - children (a hybrid node's own evaluated state counts as one more element), - determines the worst child state and escalates this node to it according to the - configured operator (And/Or/None and the Minimum/Maximum counts). + For a leaf, ensures default output and performance data are populated and returns + the state that threshold evaluation or an override set. For an empty package + without value or children, marks the node as UNKNOWN ('No checks added to this + package'), OK when IgnoreEmptyPackage is enabled, or [INFO] ('Nothing to report') + when IsNotice is enabled. For a container, recursively resolves every child, + counts OK versus not-OK children (skipping hidden, notice and ignored-empty nodes; + a hybrid node's own evaluated state counts as one more element), determines the + worst child state and escalates this node according to the configured operator + (And/Or/None and the Minimum/Maximum counts). .OUTPUTS - System.Int32 — The resolved state of this node. + System.Int32 -- The resolved state of this node. .EXAMPLE PS> $this.ResolveState() @@ -2186,10 +3864,35 @@ class IcingaPlugin #> hidden [int] ResolveState() { - if ($this.Checks.Count -eq 0) { + if (-not $this.HasChecks()) { + foreach ($Child in $this.Checks) { + [void]$Child.ResolveState(); + } + + if ($this.IsEmptyPackage()) { + if ($this.IsNotice) { + $this.OutputMessage = 'Nothing to report'; + return $this.State; + } + + if ($this.IgnoreEmptyPackage) { + $this.IgnoredEmpty = $true; + $this.FixedState = $true; + return $this.State; + } + + $this.ApplyError('No checks added to this object'); + return $this.State; + } + + $this.EnsureLeafDefaults(); return $this.State; } + if ($null -ne $this.Value) { + $this.EnsureLeafDefaults(); + } + [int]$Worst = 0; [int]$OkCount = 0; [int]$NotOk = 0; @@ -2197,7 +3900,7 @@ class IcingaPlugin foreach ($Child in $this.Checks) { [int]$ChildState = $Child.ResolveState(); - if ($Child.IsHidden) { + if ($Child.IsHidden -or $Child.IsNoticeNode() -or $Child.IgnoredEmpty) { continue; } @@ -2225,14 +3928,16 @@ class IcingaPlugin } # A Minimum/Maximum count replaces the And/Or/None rule (Minimum and Maximum - # may be combined); otherwise the And/Or/None operator decides. + # may be combined); otherwise the And/Or/None operator decides. When a count + # or None rule is violated even though all children are OK ($Worst -eq 0), + # escalate to CRITICAL (2). if ($this.OperatorMin -ne -1 -or $this.OperatorMax -ne -1) { if ($this.OperatorMin -ne -1 -and $OkCount -lt $this.OperatorMin) { - $this.EscalateState($Worst); + $this.EscalateState([System.Math]::Max($Worst, 2)); } if ($this.OperatorMax -ne -1 -and $OkCount -gt $this.OperatorMax) { - $this.EscalateState($Worst); + $this.EscalateState([System.Math]::Max($Worst, 2)); } } else { switch ($this.Operator) { @@ -2243,14 +3948,14 @@ class IcingaPlugin break; } 'Or' { - if ($OkCount -eq 0) { + if (($OkCount + $NotOk) -gt 0 -and $OkCount -eq 0) { $this.EscalateState($Worst); } break; } 'None' { if ($OkCount -ne 0) { - $this.EscalateState($Worst); + $this.EscalateState([System.Math]::Max($Worst, 2)); } break; } @@ -2265,12 +3970,12 @@ class IcingaPlugin Report whether this node has any not-OK children .DESCRIPTION - Returns true when at least one child is not OK, or when a hybrid node's own - evaluated state is not OK. Used to decide whether a container is shown at low + Returns true when at least one visible child is not OK, or when a hybrid node's + own evaluated state is not OK. Used to decide whether a container is shown at low verbosity levels. .OUTPUTS - System.Boolean — True when a not-OK child (or own state) exists. + System.Boolean -- True when a not-OK child (or own state) exists. .EXAMPLE PS> $this.HasNotOkChecks() @@ -2281,6 +3986,10 @@ class IcingaPlugin hidden [bool] HasNotOkChecks() { foreach ($Child in $this.Checks) { + if ($Child.IsHidden) { + continue; + } + if ($Child.State -ne 0) { return $true; } @@ -2304,7 +4013,7 @@ class IcingaPlugin prints. Otherwise the node is hidden from the output. .OUTPUTS - System.Boolean — True when the node should be part of the output. + System.Boolean -- True when the node should be part of the output. .EXAMPLE PS> $this.CanOutput() @@ -2326,11 +4035,11 @@ class IcingaPlugin return $true; } - if ($this.Checks.Count -ne 0) { + if ($this.HasChecks()) { return $this.HasNotOkChecks(); } - if ($this.Verbose -eq 1 -and $null -ne $this.Parent -and $this.Parent.Checks.Count -ne 0) { + if ($this.Verbose -eq 1 -and $null -ne $this.Parent -and $this.Parent.HasChecks()) { return $this.Parent.HasNotOkChecks(); } @@ -2351,7 +4060,7 @@ class IcingaPlugin | Indention | System.Int32 | Zero-based tree depth. | | .OUTPUTS - System.String — The indentation prefix. + System.String -- The indentation prefix. .EXAMPLE PS> $this.IndentPrefix(1) @@ -2379,11 +4088,11 @@ class IcingaPlugin Build the single output line for this node .DESCRIPTION - Returns the container summary line when the node has children, otherwise the - leaf line. + Returns the container summary line when the node has visible children, otherwise + the leaf line. .OUTPUTS - System.String — The node's own one-line output (without indentation). + System.String -- The node's own one-line output (without indentation). .EXAMPLE PS> $this.BuildLine() @@ -2393,7 +4102,7 @@ class IcingaPlugin #> hidden [string] BuildLine() { - if ($this.Checks.Count -ne 0) { + if ($this.HasChecks()) { return $this.BuildContainerLine(); } @@ -2410,7 +4119,7 @@ class IcingaPlugin renders with the [INFO] prefix. .OUTPUTS - System.String — The leaf output line. + System.String -- The leaf output line. .EXAMPLE PS> $this.BuildLeafLine() @@ -2451,7 +4160,7 @@ class IcingaPlugin header. .OUTPUTS - System.String — The container output line. + System.String -- The container output line. .EXAMPLE PS> $this.BuildContainerLine() @@ -2537,14 +4246,14 @@ class IcingaPlugin Collect every leaf check in the subtree .DESCRIPTION - Recursively gathers all descendant nodes that are leaf checks (nodes without - children), skipping container nodes, hidden nodes and notice packages. Used by + Recursively gathers all descendant nodes that are active leaf checks (nodes + without visible children), skipping container nodes, hidden nodes, nodes with + SkipSummary set, ignored-empty packages and informational notice nodes. Used by the summary header so the root line reflects the state of every actual check - regardless of nesting depth. A notice package (IsNotice) only lists information, - such as the files a directory check found, so its entries are not counted. + regardless of nesting depth. .OUTPUTS - System.Array — The leaf IcingaPlugin nodes in the subtree. + System.Array -- The leaf IcingaPlugin nodes in the subtree. .EXAMPLE PS> $this.CollectLeafChecks() @@ -2557,11 +4266,11 @@ class IcingaPlugin [array]$Leaves = @(); foreach ($Child in $this.Checks) { - if ($Child.IsHidden -or ($Child.IsNotice -and $Child.Checks.Count -ne 0)) { + if ($Child.IsHidden -or $Child.SkipSummary -or $Child.IsNoticeNode() -or $Child.IgnoredEmpty) { continue; } - if ($Child.Checks.Count -eq 0) { + if (-not $Child.HasChecks()) { $Leaves += $Child; } else { $Leaves += $Child.CollectLeafChecks(); @@ -2581,7 +4290,7 @@ class IcingaPlugin verbosity level 3 or higher. .OUTPUTS - System.String — The operator description, for example ' (All must be [OK])'. + System.String -- The operator description, for example ' (All must be [OK])'. .EXAMPLE PS> $this.ShowPackageConfig() @@ -2598,6 +4307,10 @@ class IcingaPlugin return ''; } + if ($this.OperatorMin -ne -1 -and $this.OperatorMax -ne -1) { + return [string]::Format(' (Between {0} and {1} must be [OK])', $this.OperatorMin, $this.OperatorMax); + } + if ($this.OperatorMin -ne -1) { return [string]::Format(' (Atleast {0} must be [OK])', $this.OperatorMin); } @@ -2627,7 +4340,7 @@ class IcingaPlugin nodes and nodes pruned by the current verbosity are skipped. .OUTPUTS - System.String — The multi-line, indented output. + System.String -- The multi-line, indented output. .EXAMPLE PS> $this.RenderOutput() @@ -2642,7 +4355,7 @@ class IcingaPlugin } [array]$Lines = @(); - $Lines += ($this.IndentPrefix($this.Indention) + $this.BuildLine()); + $Lines += ($this.IndentPrefix($this.Indention) + $this.BuildLine()); foreach ($Child in $this.Checks) { if ($Child.IsHidden -or -not $Child.CanOutput()) { @@ -2655,6 +4368,123 @@ class IcingaPlugin return ($Lines -join "`n"); } + <# + .SYNOPSIS + Resolve a node value to its numeric representation for performance data + + .DESCRIPTION + Converts enumeration values to their underlying integer and maps translated string + values back to their numeric key when a translation hashtable is present. Returns + the value unchanged when it is already numeric or has no numeric representation. + + .PARAMETER Item + | Name | Type | Description | Default | + |------|---------------|------------------------------|---------| + | Item | System.Object | Value to resolve numerically.| | + + .OUTPUTS + System.Object -- The numeric representation, or the original value. + + .EXAMPLE + PS> $this.ResolveNumericValue($this.Value) + + .NOTES + Internal helper used by BuildPerfData. + #> + hidden [object] ResolveNumericValue([object]$Item) + { + if ($null -eq $Item) { + return $null; + } + + if ($Item -is [System.Enum]) { + return [int]$Item; + } + + if ($this.IsNumeric($Item)) { + return $Item; + } + + if ($this.Translation.Count -gt 0) { + [string]$ItemText = [string]$Item; + foreach ($Key in $this.Translation.Keys) { + if ([string]$this.Translation[$Key] -ieq $ItemText -and $this.IsNumeric($Key)) { + return $Key; + } + } + } + + return $Item; + } + + <# + .SYNOPSIS + Resolve a threshold to a valid numeric Icinga performance-data threshold string + + .DESCRIPTION + Returns the resolved threshold when it is already a valid numeric or Icinga range + expression. When a string threshold matches a translated display name (for example + 'Running' mapped from 4), returns the corresponding numeric key ('4'). Non-numeric + string patterns (such as regex or wildcard patterns) are omitted from performance + data by returning an empty string. + + .PARAMETER Threshold + | Name | Type | Description | Default | + |-----------|---------------|------------------------------------|---------| + | Threshold | System.String | Configured threshold string. | | + + .PARAMETER Resolved + | Name | Type | Description | Default | + |----------|---------------|------------------------------------|---------| + | Resolved | System.String | Threshold resolved by comparison. | | + + .OUTPUTS + System.String -- Numeric Icinga threshold string, or '' when non-numeric. + + .EXAMPLE + PS> $this.ResolvePerfDataThreshold($this.CriticalThreshold, $this.ResolvedCritical) + + .NOTES + Internal helper used by BuildPerfData. + #> + hidden [string] ResolvePerfDataThreshold([string]$Threshold, [string]$Resolved) + { + if ($this.Unit -eq '%' -and '' -ne $Threshold) { + $Threshold = $Threshold -replace '(?<=\d)%', ''; + } + + if ('' -ne $Resolved -and $Resolved -match '^@?(~|-?\d+(?:\.\d+)?)(:(-?\d+(?:\.\d+)?)?)?$') { + return $Resolved; + } + + if ('' -ne $Threshold -and $Threshold -match '^@?(~|-?\d+(?:\.\d+)?)(:(-?\d+(?:\.\d+)?)?)?$') { + return $Threshold; + } + + [string]$Candidate = $Threshold; + if ('' -ne $Resolved) { + $Candidate = $Resolved; + } + + if ('' -eq $Candidate) { + return ''; + } + + if ('' -ne $this.TranslatedText -and $this.TranslatedText -ieq $Candidate -and $this.IsNumeric($this.Value)) { + return $this.FormatNumber($this.Value); + } + + if ($this.Translation.Count -gt 0) { + foreach ($Key in $this.Translation.Keys) { + if (([string]$this.Translation[$Key] -ieq $Candidate -or [string]$Key -ieq $Candidate) -and $this.IsNumeric($Key)) { + return $this.FormatNumber($Key); + } + } + } + + return ''; + } + <# .SYNOPSIS Rebuild the performance data for a leaf check @@ -2670,13 +4500,13 @@ class IcingaPlugin when performance data is disabled or the value is not numeric. .OUTPUTS - None — Updates this node's performance data. + None -- Updates this node's performance data. .EXAMPLE PS> $this.BuildPerfData() .NOTES - Called after each comparison; only numeric values yield perfdata. + Called after each comparison and during state resolution; only numeric values yield perfdata. #> hidden [void] BuildPerfData() { @@ -2686,25 +4516,19 @@ class IcingaPlugin return; } - if (-not $this.IsNumeric($this.Value)) { - return; - } - - [string]$Warning = $this.WarningThreshold; - [string]$Critical = $this.CriticalThreshold; + [object]$NumericValue = $this.ResolveNumericValue($this.Value); - if ('' -ne $this.ResolvedWarning) { - $Warning = $this.ResolvedWarning; + if (-not $this.IsNumeric($NumericValue)) { + return; } - if ('' -ne $this.ResolvedCritical) { - $Critical = $this.ResolvedCritical; - } + [string]$Warning = $this.ResolvePerfDataThreshold($this.WarningThreshold, $this.ResolvedWarning); + [string]$Critical = $this.ResolvePerfDataThreshold($this.CriticalThreshold, $this.ResolvedCritical); - [string]$Metric = [string]::Format( + [string]$Metric = [string]::Format( '{0}={1}{2};{3};{4};{5};{6}', $this.BuildPerfDataLabel(), - $this.FormatNumber($this.Value), + $this.FormatNumber($NumericValue), $this.Unit, $Warning, $Critical, @@ -2712,7 +4536,7 @@ class IcingaPlugin $this.MaximumValue ); - $this.PerfData = @($Metric); + $this.PerfData = @($Metric); } <# @@ -2726,7 +4550,7 @@ class IcingaPlugin command is on the stack (for example when constructed outside a plugin). .OUTPUTS - System.String — The check command name, or '' when none was found. + System.String -- The check command name, or '' when none was found. .EXAMPLE PS> $this.DetectCheckCommand() @@ -2759,7 +4583,7 @@ class IcingaPlugin | Value | System.String | The raw metric segment. | | .OUTPUTS - System.String — The sanitized, lower-cased segment. + System.String -- The sanitized, lower-cased segment. .EXAMPLE PS> $this.SanitizeMetric('Core #0') @@ -2781,11 +4605,12 @@ class IcingaPlugin performance-data format. The index defaults to 'default'; the template defaults to the calling Invoke-IcingaCheck* command with that prefix stripped (falling back to 'check'), always carries the fixed 'ifw_' namespace, and can be overridden with - MetricName; the label defaults to the node's Name and can be overridden with - MetricLabel. Every segment is sanitized and lower-cased. + MetricName; the label defaults to the node's Name (falling back to 'value' when + sanitizing strips all characters) and can be overridden with MetricLabel. Every + segment is sanitized and lower-cased, with fallbacks applied after sanitization. .OUTPUTS - System.String — The structured performance-data label. + System.String -- The structured performance-data label. .EXAMPLE PS> $this.BuildPerfDataLabel() @@ -2795,32 +4620,36 @@ class IcingaPlugin #> hidden [string] BuildPerfDataLabel() { - [string]$Index = $this.MetricIndexValue; + [string]$Index = $this.SanitizeMetric($this.MetricIndexValue); if ('' -eq $Index) { $Index = 'default'; } - [string]$Template = $this.MetricNameValue; - if ('' -eq $Template) { - $Template = ([string]$this.CheckCommand) -replace '(?i)^Invoke-IcingaCheck', ''; + [string]$RawTemplate = $this.MetricNameValue; + if ('' -eq $RawTemplate) { + $RawTemplate = ([string]$this.CheckCommand) -replace '(?i)^Invoke-IcingaCheck', ''; } + $RawTemplate = $RawTemplate -replace '(?i)^ifw_', ''; + + [string]$Template = $this.SanitizeMetric($RawTemplate); if ('' -eq $Template) { $Template = 'check'; } - if ($Template.ToLower() -notlike 'ifw_*') { - $Template = 'ifw_' + $Template; - } + $Template = 'ifw_' + $Template; - [string]$Label = $this.MetricLabelValue; + [string]$Label = $this.SanitizeMetric($this.MetricLabelValue); if ('' -eq $Label) { - $Label = $this.Name; + $Label = $this.SanitizeMetric($this.Name); + } + if ('' -eq $Label) { + $Label = 'value'; } return [string]::Format( '{0}::{1}::{2}', - $this.SanitizeMetric($Index), - $this.SanitizeMetric($Template), - $this.SanitizeMetric($Label) + $Index, + $Template, + $Label ); } @@ -2829,11 +4658,14 @@ class IcingaPlugin Collect the performance data of this node and its subtree .DESCRIPTION - Returns a flat array containing this node's performance-data metric (if any) and, - recursively, the metrics of every child. + Returns a flat, deduplicated array containing this node's performance-data metric + (if any) and, recursively, the metrics of every child. Returns an empty array when + NoPerfData is set on this node, suppressing performance data for the entire + subtree. Duplicate metric labels are skipped so each index::ifw_template::label + appears at most once. .OUTPUTS - System.Array — All performance-data metric strings in the subtree. + System.Array -- All unique performance-data metric strings in the subtree. .EXAMPLE PS> $this.CollectPerfData() @@ -2843,14 +4675,36 @@ class IcingaPlugin #> hidden [array] CollectPerfData() { - [array]$Perf = @(); + if ($this.NoPerfData) { + return @(); + } + + [array]$RawPerf = @(); if ($this.PerfData.Count -gt 0) { - $Perf += $this.PerfData; + $RawPerf += $this.PerfData; } foreach ($Child in $this.Checks) { - $Perf += $Child.CollectPerfData(); + $RawPerf += $Child.CollectPerfData(); + } + + [array]$Perf = @(); + [hashtable]$Seen = @{}; + + foreach ($Entry in $RawPerf) { + [string]$Metric = [string]$Entry; + if ('' -eq $Metric) { + continue; + } + + [string]$MetricKey = ($Metric -split '=', 2)[0]; + if ($Seen.ContainsKey($MetricKey)) { + continue; + } + + $Seen[$MetricKey] = $true; + $Perf += $Metric; } return $Perf; @@ -2861,8 +4715,9 @@ class IcingaPlugin Test whether a value can be treated as a number .DESCRIPTION - Returns true when the value parses as a number under the invariant culture. Used - to decide whether a leaf produces performance data. + Returns true when the value parses as a number under the invariant culture (excluding + booleans, which parse as False/True strings). Used to decide whether a leaf produces + performance data. .PARAMETER Value | Name | Type | Description | Default | @@ -2870,7 +4725,7 @@ class IcingaPlugin | Value | System.Object | Value to test. | | .OUTPUTS - System.Boolean — True when the value is numeric. + System.Boolean -- True when the value is numeric. .EXAMPLE PS> $this.IsNumeric(95) @@ -2880,7 +4735,7 @@ class IcingaPlugin #> hidden [bool] IsNumeric([object]$Value) { - if ($null -eq $Value) { + if ($null -eq $Value -or $Value -is [bool]) { return $false; } @@ -2893,8 +4748,10 @@ class IcingaPlugin Format a numeric value for performance data .DESCRIPTION - Formats the value under the invariant culture so the decimal separator is always - a dot. Falls back to the raw string when the value is not numeric. + Formats the value under the invariant culture without scientific notation so the + decimal separator is always a dot and very small or large numbers remain plain + decimals for Icinga 2 performance data. Falls back to the raw string when the + value is not numeric. .PARAMETER Value | Name | Type | Description | Default | @@ -2902,7 +4759,7 @@ class IcingaPlugin | Value | System.Object | Value to format. | | .OUTPUTS - System.String — The formatted value. + System.String -- The formatted value. .EXAMPLE PS> $this.FormatNumber(95) @@ -2912,9 +4769,14 @@ class IcingaPlugin #> hidden [string] FormatNumber([object]$Value) { + [decimal]$ParsedDecimal = 0; + if ([decimal]::TryParse([string]$Value, [System.Globalization.NumberStyles]::Any, [System.Globalization.CultureInfo]::InvariantCulture, [ref]$ParsedDecimal)) { + return $ParsedDecimal.ToString('0.##########', [System.Globalization.CultureInfo]::InvariantCulture); + } + [double]$Parsed = 0; if ([double]::TryParse([string]$Value, [System.Globalization.NumberStyles]::Any, [System.Globalization.CultureInfo]::InvariantCulture, [ref]$Parsed)) { - return $Parsed.ToString([System.Globalization.CultureInfo]::InvariantCulture); + return $Parsed.ToString('0.##########', [System.Globalization.CultureInfo]::InvariantCulture); } return [string]$Value; @@ -2941,7 +4803,7 @@ class IcingaPlugin | Perf | System.Array | Performance-data metric strings. | | .OUTPUTS - None — Writes to the console. + None -- Writes to the console. .EXAMPLE PS> $this.WriteConsoleOutput('[OK] Load: 5%', @('load=5%;80;90;0;100')) @@ -2979,7 +4841,7 @@ class IcingaPlugin | Private | System.Object | The Private runtime object to normalise. | | .OUTPUTS - None — Adds the Icinga.CheckResult slot when it is missing. + None -- Adds the Icinga.CheckResult slot when it is missing. .EXAMPLE PS> $this.EnsureResultSlot((Get-GlobalRuntimeVariable).Private) @@ -3010,7 +4872,7 @@ class IcingaPlugin '| Out-Null' or a '[void]' cast. .OUTPUTS - None — Ends the chain. + None -- Ends the chain. .EXAMPLE PS> $check.Warning('80').Critical('90').CheckRange().Commit() @@ -3035,7 +4897,7 @@ class IcingaPlugin integer Icinga exit code (0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN). .OUTPUTS - System.Int32 — The Icinga plugin exit code. + System.Int32 -- The Icinga plugin exit code. .EXAMPLE PS> return $package.Compile() @@ -3050,10 +4912,10 @@ class IcingaPlugin $this.ResolveState(); $this.PropagateVerbose($this.Verbose); - [string]$Output = $this.RenderOutput(); - [array]$Perf = $this.CollectPerfData(); + [string]$Output = $this.RenderOutput(); + [array]$Perf = $this.CollectPerfData(); - $GlobalVariable = Get-GlobalRuntimeVariable; + $GlobalVariable = Get-GlobalRuntimeVariable; $this.EnsureResultSlot($GlobalVariable.Private); $GlobalVariable.Private.Icinga.CheckResult = [IcingaCheckResult]::new($this.State, $Output, $Perf); diff --git a/src/Core/ErrorHandling/Public/Test-IcingaError.ps1 b/src/Core/ErrorHandling/Public/Test-IcingaError.ps1 index 5de515e..6fceb61 100644 --- a/src/Core/ErrorHandling/Public/Test-IcingaError.ps1 +++ b/src/Core/ErrorHandling/Public/Test-IcingaError.ps1 @@ -15,7 +15,7 @@ for $null, for collections and for every other value. | InputObject | System.Object | Result of a data collection function to test. | $null | .OUTPUTS -System.Boolean — $true when InputObject is an IcingaError, otherwise $false. +System.Boolean -- $true when InputObject is an IcingaError, otherwise $false. .EXAMPLE PS> $Services = Get-IcingaWindowsInformation -ClassName 'Win32_Service'; diff --git a/src/Plugins/Public/New-IcingaPlugin.ps1 b/src/Plugins/Public/New-IcingaPlugin.ps1 index 535050b..26ed95d 100644 --- a/src/Plugins/Public/New-IcingaPlugin.ps1 +++ b/src/Plugins/Public/New-IcingaPlugin.ps1 @@ -20,9 +20,9 @@ positional in the order Name, Value, Unit. | Name | System.String | Display name of the plugin node. | $null | .PARAMETER Value -| Name | Type | Description | Default | -|-------|---------------|--------------------------------------------------------------------|---------| -| Value | System.Object | Measured value, a number or ''. Makes the node a check. | $null | +| Name | Type | Description | Default | +|-------|---------------|-----------------------------------------------------------------------|---------| +| Value | System.Object | Measured value, a number or ''. Makes the node a check. | $null | .PARAMETER Unit | Name | Type | Description | Default | @@ -30,7 +30,7 @@ positional in the order Name, Value, Unit. | Unit | System.String | Icinga unit of the value and thresholds, e.g. '%', 'B', 's'. | | .OUTPUTS -IcingaPlugin — The new plugin node, an instance of the IcingaPlugin type loaded by +IcingaPlugin -- The new plugin node, an instance of the IcingaPlugin type loaded by the current runspace. .EXAMPLE From c4aad195e5c00704197917f011523183fa454846 Mon Sep 17 00:00:00 2001 From: Lord Hepipud Date: Wed, 11 Nov 2026 17:43:34 +0100 Subject: [PATCH 3/5] Add comprehensive developer documentation for the IcingaPlugin check framework Why: - With the introduction of the unified `IcingaPlugin` class, `New-IcingaPlugin` factory cmdlet, `IcingaCheckResult` result container, and `IcingaError` / `Test-IcingaError` error-handling pipeline, developers need complete technical documentation explaining the architecture, runspace-safety rules, member signatures, method overloads, and a practical step-by-step workflow for building custom check plugins. What & How: - `docs/Developer/Plugins/01-Architecture-and-Concepts.md`: - Explains the unified node model (containers, leaf checks, hybrid nodes, and `[INFO]` notice nodes) and arbitrary tree nesting. - Details fluent method chaining and why every chain must end with `.Commit()` (`[void]`) or `.Compile()` (`[int]`), including PowerShell multiline chaining rules. - Documents runspace and threading safety (why class literals are forbidden in functions outside `src/Classes` on Windows PowerShell 5.1 and why `New-IcingaPlugin`, `Test-IcingaError`, and `('IcingaError' -as [type])` must be used). - Covers supported units (`'B'`, `'s'`, `'%'`, `'c'`, and display units), automatic `[TimeSpan]` handling, Icinga range threshold syntax, value and threshold translations (`.Translate()`), multi-value list comparisons, `check_multi` performance-data formatting, and verbosity levels (`0`..`3`). - `docs/Developer/Plugins/02-IcingaPlugin-Reference.md`: - Complete technical reference for `New-IcingaPlugin` and `IcingaPlugin`. - Documents all 10 public instance properties, 30 hidden instance properties, 2 static hidden maps (`StateText`, `StateMap`), and all 3 constructors. - Groups and explains every public method and all overload variants: configuration setters (`Warning`, `Critical`, `Minimum`, `Maximum`, `BaseValue`, `MetricIndex`, `MetricName`, `MetricLabel`, `Translate`, `SetVerbose`, `SetNoPerfData`, `SetHidden`, `SetIgnoreEmptyPackage`, `SetSummaryHeader`, `SetSkipSummary`), numeric and string/list comparisons (`CheckRange`, `CheckGreater`, `CheckGreaterEqual`, `CheckLower`, `CheckLowerEqual`, `CheckMax`, `CheckMatch`, `CheckNotMatch`, `CheckLike`, `CheckNotLike`, `CheckEqual`, `CheckNotEqual`, `CheckIn`, `CheckNotIn`), state overrides (`SetState`, `SetOk`, `SetWarning`, `SetCritical`, `SetUnknown`, `SetNotice`, `SetError`), container operators and tree management (`CheckAnd`, `CheckDefault`, `CheckOr`, `CheckNone`, `CheckMinimum`, `CheckMaximum`, `AddCheck`, `AddMissingChecks`, `HasChecks`), chain terminators (`Commit`, `Compile`), and all 46 internal `hidden` helper methods. - `docs/Developer/Plugins/03-Result-and-Error-Objects.md`: - Documents `IcingaCheckResult` (properties, constructors, `ToString()`, and reading results from `$Global:IcingaForWindows.Private.Icinga.CheckResult` in background daemons and Pester tests). - Documents `IcingaError` (properties, all 3 constructors, static `FormatMessage()` helper, and runspace-safe instantiation in providers) and the `Test-IcingaError` cmdlet. - `docs/Developer/Plugins/04-Custom-Plugin-Developer-Guide.md`: - Provides an end-to-end, step-by-step developer tutorial building a provider (`Get-IcingaSpoolerQueue`) and check plugin (`Invoke-IcingaCheckSpoolerTutorial`) demonstrating provider error propagation, numeric/byte/TimeSpan range checks, translated state list checks, `[INFO]` notices, `AddMissingChecks`, `-MitigateUnknown`, and output verification across multiple scenarios. --- .../Plugins/01-Architecture-and-Concepts.md | 166 ++++++ .../Plugins/02-IcingaPlugin-Reference.md | 478 ++++++++++++++++++ .../Plugins/03-Result-and-Error-Objects.md | 141 ++++++ .../04-Custom-Plugin-Developer-Guide.md | 368 ++++++++++++++ 4 files changed, 1153 insertions(+) create mode 100644 docs/Developer/Plugins/01-Architecture-and-Concepts.md create mode 100644 docs/Developer/Plugins/02-IcingaPlugin-Reference.md create mode 100644 docs/Developer/Plugins/03-Result-and-Error-Objects.md create mode 100644 docs/Developer/Plugins/04-Custom-Plugin-Developer-Guide.md 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_