Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 24 additions & 4 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,9 +133,29 @@ Levels: `Debug`, `Output`, `Audit`, `Info`, `Success`, `Warning`, `Error`, `Fata
- ❌ `Write-Output` for logging — use it only when you genuinely return a value to the pipeline.
- ❌ Stream redirects like `2>$null` or `*>&1`. Handle errors explicitly.
- ❌ Aliases in source code (`%`, `?`, `select`, `where`). Use full cmdlet names (`ForEach-Object`, `Where-Object`).
- ❌ Backticks for line continuation. Use natural pipeline breaks or splatting.
- ❌ Em-dashes (`—`, U+2014) or en-dashes (`–`, U+2013) in PowerShell files — Windows PowerShell 5.1 reads BOM-less UTF-8 files as Windows-1252 and turns them into `—` Mojibake. Use plain ASCII `-` or `--` instead.
- ❌ `-ErrorAction SilentlyContinue` as a "make the warning go away" tool. If you don't want to handle the error, that's a bug.
- ❌ Editing files under `lib/` or `docs/api/` by hand.
- ❌ Class literals in functions (`[IcingaPlugin]::new()`, `[IcingaSortKey]::FromObject()`, `-is [IcingaError]`). See §2.9.

### 2.9 Classes and threads

Every runspace dot-sources the same compiled kernel, while the classes from `src/Classes` are loaded separately into each runspace. A class literal inside a function is resolved once and then points to the class type of the **main** runspace — also when the function runs in a daemon or worker thread. On Windows PowerShell 5.1 a constructor, method or static call on that type from a thread waits until the main runspace is idle, so the thread stalls. Objects of the thread's own type also no longer match the literal: `-is` returns `$false` and typed parameters fail with *Cannot convert the "IcingaError" value of type "IcingaError" to type "IcingaError"*.

1. **Never use a class literal in a function** — not to create an object, not for a static member, not for `-is`, casts or typed variables and parameters. Resolve the class of the current runspace instead:

| Instead of | Use |
|--------------------------------------|-----|
| `[IcingaPlugin]::new('C:', 55, '%')` | `New-IcingaPlugin 'C:' 55 '%'` |
| `$Data -is [IcingaError]` | `Test-IcingaError -InputObject $Data` |
| `[IcingaError]::new(...)` | `('IcingaError' -as [type])::new(...)` |
| `[IcingaSortKey]::FromObject(...)` in a loop | `$SortKeyType = 'IcingaSortKey' -as [type];` once before the loop, then `$SortKeyType::FromObject(...)` |

2. Exceptions: code inside `src/Classes` (the class files are loaded per runspace, so literals there resolve correctly), Pester tests, and enums such as `[IcingaServiceStatus]::Running` — enums carry no script code and convert by value.
3. **Never pass class instances between threads.** Hand over only primitive values, hashtables and arrays. A plugin result travels as its rendered output, exit code and performance data array, never as the `IcingaCheckResult` object (see `Start-IcingaProtocolWorker`).
4. `Tests/ClassLiteral.Tests.ps1` enforces rule 1 and names the file and line of every literal it finds.

Background and examples: [docs/Developer/Threading/01-Threading.md](docs/Developer/Threading/01-Threading.md#classes-and-threads).

---

Expand Down Expand Up @@ -167,7 +187,7 @@ external dependencies).
| Count | System.Int32 | Number of iterations to perform. | 1 |

.OUTPUTS
System.Object — Description of the returned value or object shape.
System.Object -- Description of the returned value or object shape.
Use `None` if the function returns nothing.

.EXAMPLE
Expand All @@ -192,7 +212,7 @@ function Verb-IcingaNoun()
3. **Every `.PARAMETER` block uses the Markdown table form** shown above. The table has exactly four columns: `Name | Type | Description | Default`. This is what the doc generator extracts.
4. `.SYNOPSIS` is **one line, no period at the end** unless it is a full sentence.
5. `.DESCRIPTION` wraps at ~80 columns. Use plain prose, not bullet lists.
6. `.OUTPUTS` starts with the .NET type name (`System.Int32`, `System.Collections.Hashtable`, `System.Object`, `None`), followed by `— Description`.
6. `.OUTPUTS` starts with the .NET type name (`System.Int32`, `System.Collections.Hashtable`, `System.Object`, `None`), followed by `-- Description`.
7. `.EXAMPLE` begins with `PS> ` and shows a realistic invocation.
8. `.NOTES` mentions: external services touched, config files read, required permissions, threading caveats.
9. **All documentation is written in English.** No German (or any other language) in any help block section.
Expand Down Expand Up @@ -271,4 +291,4 @@ When you (Claude, Copilot, etc.) edit this repo:

---

*Last updated: 2026-05-26*
*Last updated: 2026-10-02*
64 changes: 34 additions & 30 deletions IcingaForWindows.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,10 @@ function New-ModuleBaseEnvironment()
'Public' = [hashtable]::Synchronized(
@{
'Config' = [PSCustomObject]@{
'ModuleRoot' = $PSScriptRoot;
'Root' = (Join-Path -Path $env:ProgramData -ChildPath (Get-ModuleProjectName));
'Theme' = 'DefaultDark';
'Colors' = [PSCustomObject]@{
'ModuleRoot' = $PSScriptRoot;
'Root' = (Join-Path -Path $env:ProgramData -ChildPath (Get-ModuleProjectName));
'Theme' = 'DefaultDark';
'Colors' = [PSCustomObject]@{
'Debug' = 'Magenta';
'Audit' = 'DarkGreen';
'Info' = 'Cyan';
Expand Down Expand Up @@ -159,8 +159,8 @@ function New-ModuleBaseEnvironment()
'EvictionMinutes' = 60;
};
};
'External' = $null;
'ReturnCodes' = $null;
'External' = $null;
'ReturnCodes' = $null;
}
);
'Private' = [PSCustomObject]@{
Expand Down Expand Up @@ -192,6 +192,9 @@ function New-ModuleBaseEnvironment()
'Logging' = [PSCustomObject]@{
'CurrentLoggingId' = (New-Guid);
};
'Icinga' = [PSCustomObject]@{
'CheckResult' = $null;
};
};
'Protected' = [PSCustomObject]@{
'Initialized' = $false;
Expand Down Expand Up @@ -241,22 +244,22 @@ under `lib/`, updates the module manifest, and optionally generates documentatio
or executes memory leak tests.

.PARAMETER SkipTests
| Name | Type | Description | Default |
|------|------|-------------|---------|
| SkipTests | System.Management.Automation.SwitchParameter | When set, skip running automated tests during the build. | $false |
| Name | Type | Description | Default |
|-----------|----------------------------------------------|----------------------------------------------------------|---------|
| SkipTests | System.Management.Automation.SwitchParameter | When set, skip running automated tests during the build. | $false |

.PARAMETER GenerateDocs
| Name | Type | Description | Default |
|------|------|-------------|---------|
| GenerateDocs | System.Management.Automation.SwitchParameter | When set, regenerate API Markdown documentation from comment help. | $false |
| Name | Type | Description | Default |
|--------------|----------------------------------------------|--------------------------------------------------------------------|---------|
| GenerateDocs | System.Management.Automation.SwitchParameter | When set, regenerate API Markdown documentation from comment help. | $false |

.PARAMETER TestDaemonMemoryLeaks
| Name | Type | Description | Default |
|------|------|-------------|---------|
| TestDaemonMemoryLeaks | System.Management.Automation.SwitchParameter | When set, run daemon memory leak stress tests. | $false |
| Name | Type | Description | Default |
|-----------------------|----------------------------------------------|------------------------------------------------|---------|
| TestDaemonMemoryLeaks | System.Management.Automation.SwitchParameter | When set, run daemon memory leak stress tests. | $false |

.OUTPUTS
None — Side effects only: generates module artifacts under lib/ and docs/.
None -- Side effects only: generates module artifacts under lib/ and docs/.

.EXAMPLE
PS> Build-ModuleProject -GenerateDocs
Expand Down Expand Up @@ -287,12 +290,12 @@ It executes all test suites under the specified path or the default `Tests/`
directory using `build/Invoke-ModuleTests.ps1`.

.PARAMETER Path
| Name | Type | Description | Default |
|------|------|-------------|---------|
| Path | System.String | Path to a specific test file or directory containing Pester test suites to execute. | $null |
| Name | Type | Description | Default |
|------|---------------|--------------------------------------------------------------------------------------|---------|
| Path | System.String | Path to a specific test file or directory containing Pester test suites to execute. | $null |

.OUTPUTS
System.Object — Pester test result summary object and test execution output.
System.Object -- Pester test result summary object and test execution output.

.EXAMPLE
PS> Invoke-IcingaModuleTests
Expand Down Expand Up @@ -342,22 +345,22 @@ and Icinga agent). The function is idempotent; repeated calls while already
initialized return immediately.

.PARAMETER LogLevel
| Name | Type | Description | Default |
|------|------|-------------|---------|
| Name | Type | Description | Default |
|----------|---------------|---------------------------------------------------------------------------------------------------------|---------|
| LogLevel | System.String | Minimum log level for the session. Accepted values: Debug, Audit, Info, Success, Warning, Error, Fatal. | Warning |

.PARAMETER RunBackgroundDaemons
| Name | Type | Description | Default |
|------|------|-------------|---------|
| RunBackgroundDaemons | System.Management.Automation.SwitchParameter | When set, start the standard background daemon threads (logging, garbage collector, housekeeper, REST API, WebSocket, Icinga agent). Default is false. | $false |
| Name | Type | Description | Default |
|----------------------|----------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------|---------|
| RunBackgroundDaemons | System.Management.Automation.SwitchParameter | When set, start the standard background daemon threads (logging, garbage collector, housekeeper, REST API, WebSocket, Icinga agent). Default is false. | $false |

.PARAMETER NoNewShell
| Name | Type | Description | Default |
|------|------|-------------|---------|
| NoNewShell | System.Management.Automation.SwitchParameter | When set, initialize directly in the current shell instead of spawning a new process. | $false |
| Name | Type | Description | Default |
|------------|----------------------------------------------|-------------------------------------------------------------------------------------------------|---------|
| NoNewShell | System.Management.Automation.SwitchParameter | When set, initialize directly in the current shell instead of spawning a new process. | $false |

.OUTPUTS
None — Side effects only: configures global runtime state and optionally starts background threads.
None -- Side effects only: configures global runtime state and optionally starts background threads.

.EXAMPLE
PS> Use-IcingaForWindows
Expand Down Expand Up @@ -428,7 +431,8 @@ function Use-IcingaForWindows()
# have a proper call stack and can manage everything way easier
Use-IcingaForWindows -NoNewShell -LogLevel $LogLevel -RunBackgroundDaemons:$RunBackgroundDaemons;

function prompt {
function prompt()
{
Write-Host -Object 'icinga' -NoNewline;
return '> '
}
Expand Down
2 changes: 2 additions & 0 deletions Tests/ClassLiteral.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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';
}
Expand Down
57 changes: 57 additions & 0 deletions Tests/IcingaError.Tests.ps1
Original file line number Diff line number Diff line change
@@ -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)';
}
}
}
Loading
Loading