Skip to content

Feature: Add IcingaPlugin - #20

Merged
LordHepipud merged 5 commits into
mainfrom
feature/icingaplugin-class
Nov 13, 2026
Merged

LordHepipud merged 5 commits into
mainfrom
feature/icingaplugin-class

Conversation

@fthomys

@fthomys fthomys commented Aug 28, 2026

Copy link
Copy Markdown
Member

This pull request introduces a new immutable result container class for Icinga plugin checks and adds tests for the plugin logic.

New Icinga plugin result container:

  • Added the IcingaCheckResult class in src/Classes/Icinga/IcingaCheckResult.ps1, which encapsulates the exit code, output, and performance data of a compiled plugin check. This class is designed to be thread-safe and is used to store check results in the runtime state.

Runtime state updates:

  • Updated New-ModuleBaseEnvironment in IcingaForWindows.psm1 to add a new CheckResult property to the thread-local Private.Icinga state, initializing it to $null. This provides a dedicated location for storing the latest check result.

Plugin tests:

  • Introduced new tests in Tests/IcingaPlugin.Tests.ps1 that covers a wide range of scenarios for the IcingaPlugin class, including threshold evaluation, output formatting, performance data generation, state overrides, container aggregation, hybrid nodes, output targets, verbosity. The tests ensure correct behavior both in daemon and CLI modes and verify state handling in the new result container.

@cla-bot cla-bot Bot added the cla/signed CLA is signed by all contributors of a PR label Aug 28, 2026
@fthomys
fthomys requested a review from LordHepipud August 28, 2026 12:17
@fthomys
fthomys force-pushed the feature/icingaplugin-class branch from 37f82d9 to 1cebc0e Compare August 28, 2026 13:13
@fthomys
fthomys force-pushed the feature/icingaplugin-class branch 6 times, most recently from 326d920 to 9331049 Compare October 2, 2026 13:23
@fthomys

fthomys commented Oct 2, 2026

Copy link
Copy Markdown
Member Author

Summary of recent changes:

Adds the IcingaPlugin class, which replaces New-IcingaCheck, New-IcingaCheckPackage and New-IcingaCheckResult, plus IcingaError and IcingaCheckResult.

  • One class for checks and packages, nesting works on any level. Methods can be chained, Commit() ends a chain, Compile() returns the exit code.
  • Check* methods evaluate right away. States can only go up, SetState with lock is the only way to force a state. SetError sets a locked UNKNOWN with the message.
  • Threshold logic comes from IcingaThresholds, unit handling from IcingaUnit.
  • Output has a summary header and verbosity 0-3. Notice and hidden packages are not counted. Console output only happens on the main thread, the result is stored in Private.Icinga.CheckResult.
  • The perfdata label is index::ifw_::label, the command is taken from the calling Invoke-IcingaCheck*. Thresholds are written in the unit of the value.
  • Bytes and seconds are printed readable (412.29GiB, 1d 2h 3m 4s). Values below one second are passed as ms or us, since the threshold output only has 2 decimals.
  • Data functions return an IcingaError instead of throwing.
  • The build creates lib/IcingaForWindows.Classes.ps1 and lib/IcingaForWindows.Kernel.ps1. On 5.1 the classes are loaded per runspace and the kernel is shared. Loading the full kernel per runspace cost 65-75 MB more with 13 runspaces.
  • Since the kernel is shared, a class literal inside a function points to the main runspace type. On 5.1 calls from a thread then wait for the main runspace and type checks fail. Functions now use New-IcingaPlugin, Test-IcingaError or ('Name' -as [type]). In a 5.1 thread test a plugin hung for 60 s before, now all plugins finish in about 10 s while main is blocked. The factory adds about 0.1 ms per node.
  • The rule is documented in CLAUDE.md and docs/Developer/Threading. Tests/ClassLiteral.Tests.ps1 fails on class literals outside src/Classes.
  • The protocol worker now sends the real output, exit code and perfdata. Only strings and arrays are passed between threads.

@fthomys
fthomys force-pushed the feature/icingaplugin-class branch 2 times, most recently from ffc29e9 to 846f81b Compare October 2, 2026 14:41
@LordHepipud
LordHepipud force-pushed the feature/icingaplugin-class branch from 846f81b to e457668 Compare October 23, 2026 15:33
fthomys and others added 5 commits November 12, 2026 18:07
…rt overloads and code-styling compliance

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.
…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.
…code styling

Why:
- The introduction of New-IcingaPlugin (Icinga.Plugins) and Test-IcingaError (Icinga.Core.ErrorHandling) required regenerating the Markdown API reference under docs/.
- When a component contained exactly one function (such as Icinga.Plugins or Icinga.Core.ErrorHandling), Build-ModuleDocs.ps1 evaluated .Count on an unrolled single hashtable entry and reported 4 (the number of hashtable keys) instead of 1 in docs/index.md.
- Running Build-ModuleDocs.ps1 on Windows PowerShell 5.1 wrote a UTF-8 BOM via Set-Content -Encoding UTF8.
- The remaining build scripts and helper files touched on this branch still contained em-dashes and minor assignment/table alignment differences flagged by the code-styling check.

What changed:
- build/Build-ModuleDocs.ps1:
  - Wrap Where-Object pipelines in @(...) when filtering public and private functions so single-function components report a count of 1 instead of 4 in docs/index.md.
  - Write generated Markdown files via [System.IO.File]::WriteAllText with UTF8Encoding() to guarantee UTF-8 without BOM across PowerShell 5.1 and 7+.
  - Align .PARAMETER Markdown tables and '=' assignments to pass code-styling validation.
- IcingaForWindows.psm1, build/Build-ModuleProject.ps1, build/Invoke-ModuleTests.ps1, src/IcingaProtocol/Private/Start-IcingaProtocolWorker.ps1, src/Tools/Public/ConvertTo-IcingaUnit.ps1:
  - Replace em-dashes with ASCII '--', align .PARAMETER Markdown table pipes, and align '=' assignments in contiguous blocks.
- docs/Icinga.Plugins.md, docs/Icinga.Core.ErrorHandling.md, docs/Icinga.IcingaProtocol.md, docs/Icinga.Tools.md, docs/index.md:
  - Regenerate the API reference cleanly for all functions belonging to this branch.
…tform doc generation

Why:
- In Start-IcingaProtocolWorker, Write-LoggingEntry logged CheckFinished and ExecutionTime before the check command executed and before CheckFinished was populated, resulting in null/negative timing values in debug logs.
- Start-IcingaProtocolWorker.ps1 contained a leading UTF-8 BOM (U+FEFF) that Read-IcingaSourceFile preserved when concatenating files into lib/IcingaForWindows.Kernel.ps1, causing a parser error in the middle of the compiled kernel.
- In Build-ModuleDocs.ps1, Sort-Object FunctionName did not sort hashtable entries without a scriptblock key selector, and StringBuilder.AppendLine produced platform-dependent line endings (CRLF on Windows vs. LF on macOS/Linux).
- docs/Icinga.Tools.md was still modified on this branch even though src/Tools changes were already merged into main.

What changed:
- src/IcingaProtocol/Private/Start-IcingaProtocolWorker.ps1:
  - Move Write-LoggingEntry for 'Executing check command' below the CheckFinished timestamp assignment after command execution.
  - Strip the leading UTF-8 BOM from the source file.
- build/Build-ModuleProject.ps1:
  - Trim any leading U+FEFF BOM character in Read-IcingaSourceFile so BOM-prefixed source files can never corrupt the concatenated kernel or class files.
- build/Build-ModuleDocs.ps1:
  - Sort discovered source files deterministically via Sort-Object FullName.
  - Use Sort-Object { $_.FunctionName } when sorting public and private function hashtables.
  - Normalize generated Markdown content to LF line endings before writing UTF-8 without BOM so documentation builds are identical across Windows, macOS, and Linux.
- docs/Icinga.Tools.md, docs/index.md:
  - Restore docs/Icinga.Tools.md to the main branch state and update docs/index.md.
@LordHepipud
LordHepipud force-pushed the feature/icingaplugin-class branch from 916232d to 9482d11 Compare November 13, 2026 09:07

@LordHepipud LordHepipud left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@LordHepipud
LordHepipud merged commit be19ae1 into main Nov 13, 2026
6 checks passed
@LordHepipud
LordHepipud deleted the feature/icingaplugin-class branch November 13, 2026 09:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cla/signed CLA is signed by all contributors of a PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants