Repository navigation
Feature: Add IcingaPlugin - #20
Merged
Merged
Conversation
fthomys
force-pushed
the
feature/icingaplugin-class
branch
from
August 28, 2026 13:13
37f82d9 to
1cebc0e
Compare
fthomys
force-pushed
the
feature/icingaplugin-class
branch
6 times, most recently
from
October 2, 2026 13:23
326d920 to
9331049
Compare
Member
Author
|
Summary of recent changes: Adds the IcingaPlugin class, which replaces New-IcingaCheck, New-IcingaCheckPackage and New-IcingaCheckResult, plus IcingaError and IcingaCheckResult.
|
fthomys
force-pushed
the
feature/icingaplugin-class
branch
2 times, most recently
from
October 2, 2026 14:41
ffc29e9 to
846f81b
Compare
LordHepipud
force-pushed
the
feature/icingaplugin-class
branch
from
October 23, 2026 15:33
846f81b to
e457668
Compare
…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
force-pushed
the
feature/icingaplugin-class
branch
from
November 13, 2026 09:07
916232d to
9482d11
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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:
IcingaCheckResultclass insrc/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:
New-ModuleBaseEnvironmentinIcingaForWindows.psm1to add a newCheckResultproperty to the thread-localPrivate.Icingastate, initializing it to$null. This provides a dedicated location for storing the latest check result.Plugin tests:
Tests/IcingaPlugin.Tests.ps1that covers a wide range of scenarios for theIcingaPluginclass, 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.