diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 60738dc..0f2ea42 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -1,69 +1,22 @@ --- -applyTo: "**/*.ps1, **/*.psm1" +applyTo: "**/*.ps1, **/*.psm1, **/*.psd1, **/*.md" --- -# Icinga for Windows – AI Coding Agent Instructions +# Icinga for Windows -- GitHub Copilot Instructions -## Project Architecture -- **Modular PowerShell**: The project is organized into feature-based modules (e.g., `Api`, `Config`, `Core`, `Environment`, `IcingaProtocol`, `Security`, `Tools`). Each module has `Public` and `Private` subfolders for exported and internal functions. -- **Core Components**: Key logic is in `lib/` (core modules), with `src/` containing feature implementations. `IcingaForWindows.psm1` is the main entry point, importing all modules. -- **Threading & Async**: Threading is handled in `Core/Threading` and related docs. Use `$ThreadId` as a `System.String` (GUID format) for thread identification. -- **API & Protocol**: Communication with Icinga is managed via the `Api` and `IcingaProtocol` modules, using worker queues and message passing (see `Add-IcingaApiCallToWorkerQueue.ps1`, `Start-IcingaProtocolWorker.ps1`). +All binding architecture, PowerShell code-style, SPDX licensing, runspace/threading safety, comment-based help, changelog/roadmap governance, testing, and feature task-tracking rules for **Icinga for Windows** are maintained in the central single source of truth: -## Documentation & Code Patterns -- **Function Documentation**: Every function must use PowerShell comment-based help. Required sections: - - `.SYNOPSIS`, `.DESCRIPTION`, `.PARAMETER` (with markdown table: Name, Type, Description, Default), `.EXAMPLE`, `.INPUTS`, `.OUTPUTS`, `.NOTES` -- **Parameter Types**: Use explicit types. For GUIDs, document as `System.String` in GUID format. -- **Consistent Naming**: Functions use `Verb-IcingaNoun` (e.g., `Start-IcingaApi`). -- **Public/Private Split**: Only export functions in `Public/`. Internal helpers go in `Private/`. -- **Error Handling**: Use `IcingaForWindows.Core.ErrorHandling` for all error and exit code logic. -- `.NOTES` Section: Include dependencies on other modules and all used functions from IcingaForWindows. -- The documentation must always start at the beginning of each new line, without any leading spaces. +- **Binding Ruleset (MUST READ FIRST):** [docs/Agents/guidelines/01-Instruction.md](../docs/Agents/guidelines/01-Instruction.md) +- **Changelog & Roadmap Governance:** [docs/General/Changelog.md](../docs/General/Changelog.md) · [docs/General/Roadmap.md](../docs/General/Roadmap.md) +- **Per-Branch Feature Plans, Todos & Walkthroughs:** [docs/Agents/tasks/](../docs/Agents/tasks/) +- **Knowledgebase (`IWKB001xxx`):** [docs/Knowledgebase/index.md](../docs/Knowledgebase/index.md) -## Developer Workflows -- **Build**: Use `build/build.ps1` or `build/Build-ModuleProject.ps1` to package or prepare the module. -- **Testing**: No standard test runner is present; manual testing is typical. Review `docs/Developer/` for guidance. -- **Debugging**: Use verbose output and logging via `IcingaForWindows.Core.Logging`. -- **Extending**: Add new features as modules under `src/`, following the existing structure. Update the main `.psm1` to import new modules. +## Mandatory Instructions for GitHub Copilot -## Conventions & Integration -- **Markdown Tables**: Always use markdown tables for parameter documentation. -- **External Integration**: Communicates with Icinga and Windows services via TCP, file I/O, and PowerShell remoting. See `IcingaProtocol` and `Api` modules for integration points. - -## Key Files & Directories -- `IcingaForWindows.psm1` – Main module entry/import logic -- `lib/` – Core logic (logging, error handling, runtime, etc.) -- `src/` – Feature modules (Api, Config, Protocol, Security, Tools, etc.) -- `build/` – Build scripts -- `docs/Developer/` – Developer documentation - -## Example: Function Documentation -```powershell -<# -.SYNOPSIS -Starts the Icinga API listener. - -.DESCRIPTION -Initializes and starts the API listener for Icinga, handling incoming requests asynchronously. - -.PARAMETER ThreadId -| Name | Type | Description | Default | -|-----------|--------------|------------------------------------|---------| -| ThreadId | System.String| Unique thread identifier (GUID) | | - -.EXAMPLE -PS> Start-IcingaApi -ThreadId "56449934-1cbf-4285-a04a-511825b6d919" - -.INPUTS -System.String - -.OUTPUTS -System.Object - -.NOTES -Depends on IcingaForWindows.Core.Threading -#> -``` - ---- -For questions or unclear conventions, review `docs/Developer/` or ask for clarification. \ No newline at end of file +1. **Read [docs/Agents/guidelines/01-Instruction.md](../docs/Agents/guidelines/01-Instruction.md) first** before proposing or applying changes in this repository. +2. **100% English & prose naming:** Write all code, comments, help blocks, Markdown docs, changelogs, roadmaps, and task artifacts 100% in English. Always write **"Icinga for Windows"** in prose and reserve **`IcingaForWindows`** strictly for technical module, file, path, and `$Global:IcingaForWindows` identifiers. +3. **Strict PowerShell formatting & function scope:** UTF-8 without BOM, 4-space indentation, Allman `function Name()` braces, semicolons `;` ending every non-function statement, single-line `if`/`elseif` conditions, vertical `=` alignment across assignment and hashtable blocks, vertical `|` alignment in `.PARAMETER` tables, and at most **one** top-level function with **no** nested functions in `src/` (helper/nested functions are permitted in `build/`, `IcingaForWindows.psm1`, and `Tests/`). +4. **Mandatory `.NOTES` & Icinga SPDX headers:** Every file under `src/`, `build/`, `Tests/`, `IcingaForWindows.psm1`, and compiled `lib/` artifacts must include `.NOTES` ending with `SPDX-FileCopyrightText: 2026 Icinga GmbH ` and `SPDX-License-Identifier: GPL-3.0-or-later` (and `# SPDX-...` when commented outside `<# ... #>`, such as under `PrivateData.SPDX` in `IcingaForWindows.psd1` and in `PSScriptAnalyzerSettings.psd1`). +5. **Threading & class isolation:** Never use PowerShell class literals from `src/Classes` inside functions (`Tests/ClassLiteral.Tests.ps1`), use `Get-GlobalRuntimeVariable` inside worker/daemon contexts, and null per-iteration variables in daemon `finally` blocks (`build/Test-ModuleDaemonMemoryLeak.ps1`). +6. **Validation, Changelog & Roadmap tracking:** Run `.\build\Test-ModuleCodeStyling.ps1` (`0` violations), `.\build\Test-ModuleChangelog.ps1`, and `.\build\Invoke-ModuleTests.ps1`; add a bullet entry to `docs/General/Changelog.md` on every non-`main` branch; synchronize `docs/General/Roadmap.md` whenever creating or completing plans under `docs/Agents/tasks//`; and never hand-edit generated files under `lib/` or `docs/Icinga.*.md` / `docs/index.md`. +7. **Do not commit to Git** unless explicitly instructed by the user. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bfe07b4..10aa569 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,6 +23,11 @@ jobs: $env:PSModulePath = "$(Split-Path $env:GITHUB_WORKSPACE -Parent)$([System.IO.Path]::PathSeparator)$env:PSModulePath"; & .\build\Build-ModuleProject.ps1 -SkipTests; + - name: Validate compiled lib SPDX headers and UTF-8 encoding + shell: pwsh + run: | + & .\build\Test-ModuleCodeStyling.ps1 -Path .\lib\IcingaForWindows.Classes.ps1, .\lib\IcingaForWindows.Kernel.ps1; + - name: Upload compiled module uses: actions/upload-artifact@v4 with: @@ -92,18 +97,30 @@ jobs: if-no-files-found: ignore analyze: - name: PSScriptAnalyzer + name: Code Style, License, Changelog & PSScriptAnalyzer runs-on: windows-latest steps: - name: Checkout uses: actions/checkout@v4 + with: + fetch-depth: 0 - name: Install PSScriptAnalyzer shell: pwsh run: | Install-Module -Name PSScriptAnalyzer -Force -Scope CurrentUser -SkipPublisherCheck; - - name: Analyze code style + - name: Run PSScriptAnalyzer shell: pwsh run: | & .\build\Invoke-ScriptAnalysis.ps1; + + - name: Validate Code Styling & SPDX License Headers + shell: pwsh + run: | + & .\build\Test-ModuleCodeStyling.ps1; + + - name: Validate Changelog Entry on Pull Requests / Feature Branches + shell: pwsh + run: | + & .\build\Test-ModuleChangelog.ps1; diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..fc4ff92 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,18 @@ +# AGENTS.md -- Icinga for Windows AI Agent Entrypoint + +All binding architecture, PowerShell code-style, SPDX licensing, runspace/threading safety, comment-based help, changelog/roadmap governance, testing, and feature task-tracking rules for **Icinga for Windows** are maintained in the central single source of truth: + +- **Binding Ruleset (MUST READ FIRST):** [docs/Agents/guidelines/01-Instruction.md](docs/Agents/guidelines/01-Instruction.md) +- **Changelog & Roadmap Governance:** [docs/General/Changelog.md](docs/General/Changelog.md) · [docs/General/Roadmap.md](docs/General/Roadmap.md) +- **Per-Branch Feature Plans, Todos & Walkthroughs:** [docs/Agents/tasks/](docs/Agents/tasks/) +- **Knowledgebase (`IWKB001xxx`):** [docs/Knowledgebase/index.md](docs/Knowledgebase/index.md) + +## Mandatory Instructions for All Coding Agents + +1. **Read [docs/Agents/guidelines/01-Instruction.md](docs/Agents/guidelines/01-Instruction.md) first** before proposing or applying changes in this repository. +2. **100% English & prose naming:** Write all code, comments, help blocks, Markdown docs, changelogs, roadmaps, and task artifacts 100% in English. Always write **"Icinga for Windows"** in prose and reserve **`IcingaForWindows`** strictly for technical module, file, path, and `$Global:IcingaForWindows` identifiers. +3. **Strict PowerShell formatting & function scope:** UTF-8 without BOM, 4-space indentation, Allman `function Name()` braces, semicolons `;` ending every non-function statement, single-line `if`/`elseif` conditions, vertical `=` alignment across assignment and hashtable blocks, vertical `|` alignment in `.PARAMETER` tables, and at most **one** top-level function with **no** nested functions in `src/` (helper/nested functions are permitted in `build/`, `IcingaForWindows.psm1`, and `Tests/`). +4. **Mandatory `.NOTES` & Icinga SPDX headers:** Every file under `src/`, `build/`, `Tests/`, `IcingaForWindows.psm1`, and compiled `lib/` artifacts must include `.NOTES` ending with `SPDX-FileCopyrightText: 2026 Icinga GmbH ` and `SPDX-License-Identifier: GPL-3.0-or-later` (and `# SPDX-...` when commented outside `<# ... #>`, such as under `PrivateData.SPDX` in `IcingaForWindows.psd1` and in `PSScriptAnalyzerSettings.psd1`). +5. **Threading & class isolation:** Never use PowerShell class literals from `src/Classes` inside functions (`Tests/ClassLiteral.Tests.ps1`), use `Get-GlobalRuntimeVariable` inside worker/daemon contexts, and null per-iteration variables in daemon `finally` blocks (`build/Test-ModuleDaemonMemoryLeak.ps1`). +6. **Validation, Changelog & Roadmap tracking:** Run `.\build\Test-ModuleCodeStyling.ps1` (`0` violations) and `.\build\Test-ModuleChangelog.ps1`, add a bullet entry to `docs/General/Changelog.md` on every non-`main` branch, synchronize `docs/General/Roadmap.md` whenever creating or completing plans under `docs/Agents/tasks//`, and never hand-edit generated files under `lib/` or `docs/Icinga.*.md`. +7. **Do not commit to Git** unless explicitly instructed by the user. diff --git a/CLAUDE.md b/CLAUDE.md index 680339e..f572726 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,294 +1,20 @@ -# CLAUDE.md — IcingaForWindows Code & Documentation Ruleset +# CLAUDE.md -- Icinga for Windows AI Agent Entrypoint -This document defines the **binding code style, project layout and documentation rules** for the Icinga For Windows PowerShell module. It is the single source of truth that AI assistants (Claude, Copilot, …) and human contributors **MUST** follow when editing this repository. +@docs/Agents/guidelines/01-Instruction.md -If something here contradicts a tutorial, blog post or general PowerShell convention — **this file wins**. +All binding architecture, PowerShell code-style, SPDX licensing, runspace/threading safety, comment-based help, changelog/roadmap governance, testing, and feature task-tracking rules for **Icinga for Windows** are maintained in the central single source of truth: ---- +- **Binding Ruleset (MUST READ FIRST):** [docs/Agents/guidelines/01-Instruction.md](docs/Agents/guidelines/01-Instruction.md) +- **Changelog & Roadmap Governance:** [docs/General/Changelog.md](docs/General/Changelog.md) · [docs/General/Roadmap.md](docs/General/Roadmap.md) +- **Per-Branch Feature Plans, Todos & Walkthroughs:** [docs/Agents/tasks/](docs/Agents/tasks/) +- **Knowledgebase (`IWKB001xxx`):** [docs/Knowledgebase/index.md](docs/Knowledgebase/index.md) -## 1. Project Layout +## Mandatory Quick Checklist -``` -IcingaForWindows/ -├── IcingaForWindows.psd1 ← Module manifest, auto-updated by the build script -├── IcingaForWindows.psm1 ← Hand-written runtime bootstrap ($Global:Icinga) -├── build/ -│ ├── Build-ModuleProject.ps1 ← Compiler: src/ → lib/ -│ └── Build-ModuleDocs.ps1 ← Doc generator: src/ → docs/api/ -├── src/ ← Source code (one function per .ps1 file) -│ └── //{Public,Private}/*.ps1 -├── lib/ ← Auto-generated, NEVER edit by hand -│ └── IcingaForWindows...psm1 -├── data/ ← Static runtime assets (prompts, web UI, python daemons) -├── docs/ -│ ├── api/ ← Auto-generated API reference (NEVER edit by hand) -│ ├── Architecture.md ← Hand-written -│ ├── Setup.md ← Hand-written -│ └── Configuration.md ← Hand-written -└── Tests/ ← Pester tests -``` - -**Rules:** -- Every PowerShell function lives in **its own `.ps1` file**, named exactly after the function (e.g. `Add-IcingaFirewallRule.ps1` contains `function Add-IcingaFirewallRule`). -- `Public/` = exported, user-facing. `Private/` = internal helpers, not exported. -- Files in `lib/` and `docs/api/` are **always regenerated** — manual edits will be lost. - ---- - -## 2. PowerShell Code Style - -### 2.1 The semicolon rule - -> **Every non-function statement ends with a semicolon `;`.** - -This includes `param` lines, assignments, pipeline ends, `return` statements, control-flow blocks (`if`, `switch`, `foreach`, `while`) — everything that is *not* the bare `function Name() { … }` declaration. - -```powershell -function Get-IcingaExample() -{ - param ( - [string]$Name = $null, - [int]$Count = 0 - ); - - if ([string]::IsNullOrEmpty($Name)) { - return $null; - } - - [array]$Results = @(); - - for ($i = 0; $i -lt $Count; $i++) { - $Results += "$Name-$i"; - } - - return $Results; -} -``` - -### 2.2 Function declaration - -- Opening brace on its **own line** (Allman style), not K&R. -- Empty parentheses after the name (`function Foo()`), even when there is no positional binding — they make `param()` blocks visually consistent. -- `param()` block always uses one parameter per line with type prefix and default value. -- Param defaults use `= $null` for nullable refs, `= @()` for arrays, `= @{ }` for hashtables, `= $false` for switches. - -### 2.3 Naming - -| Kind | Convention | Example | -|-------------------------|-------------------------------------------------------|---------| -| Public function | `Verb-IcingaNoun` (approved PS verbs only) | `Set-IcingaLogLevel` | -| Private helper | `Verb-ModuleNoun` **or** `Verb-IcingaInternalNoun` | `Read-ModuleAccessControl`, `Write-LoggingEntry` | -| Variable | `PascalCase` with `$` | `$ChatHistory`, `$WorkerId` | -| Loop counter | lowercase | `$i`, `$idx` | -| Type-annotated variable | `[Type]$Name = …` | `[int]$WorkerId = -1` | -| Constants in `$Global:Icinga` | nested hashtables/PSCustomObjects under `Public/Private/Protected` | `$Global:Icinga.Public.AICore.Config` | - -- **Approved PS verbs only** — run `Get-Verb` to check. Avoid `Process-`, `Validate-`, `Execute-`. -- **Never collide with PowerShell built-ins or other modules.** Prefix everything user-facing with `Icinga`. -- Acronyms keep their case: `RestApi`, `IcingaProtocol`, `AccessControl`. - -### 2.4 Indentation and whitespace - -- **4 spaces**, no tabs. -- One blank line between function body sections (init, processing, return). -- No trailing whitespace on any line. -- Files end with a single newline. - -### 2.5 Global state access - -`$Global:Icinga` is the shared runtime state, populated by `New-ModuleBaseEnvironment` in [IcingaForWindows.psm1](IcingaForWindows.psm1). Access patterns: - -```powershell -# Inside a thread / worker — always go through Get-GlobalRuntimeVariable -$GlobalVariable = Get-GlobalRuntimeVariable; -$GlobalVariable.Public.RestApi.Config.ListenPort; - -# Inside a normal function on the main thread, direct access is fine: -$Global:Icinga.Public.IcingaProtocol.Config.Hostname; -``` - -**Rule of thumb:** anything that runs inside `Start-*Daemon` or a worker thread **MUST** go through `Get-GlobalRuntimeVariable`, because thread runspaces receive a snapshot. - -### 2.6 Return values and error handling - -- Public functions: return the structured result the caller expects (object, hashtable, `$null`). -- Private functions that participate in the return-code system: use `Write-FunctionReturnValue -ReturnValue 'SemanticKey' -Data @{…}`. -- Never `throw` for expected error paths inside daemons. Log via `Write-LoggingEntry -Level 'Error'` and return `$null` / a structured error object so the worker can continue. -- `throw` is reserved for **programmer errors** (bad arguments, impossible state). - -### 2.7 Logging - -```powershell -Write-LoggingEntry -Message 'Short, present-tense description' -Level 'Info' -Data @{ - 'ContextKey1' = $value1; - 'ContextKey2' = $value2; -}; -``` - -Levels: `Debug`, `Output`, `Audit`, `Info`, `Success`, `Warning`, `Error`, `Fatal`. Use `Debug` for hot-loop telemetry, `Info` for state transitions, `Warning` for recoverable issues, `Error` for unhandled exceptions. - -### 2.8 Forbidden constructs - -- ❌ `Write-Host` outside of build scripts. Use `Write-LoggingEntry -Level 'Output'`. -- ❌ `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`). -- ❌ 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). - ---- - -## 3. Comment-Based Help (the binding doc format) - -Every function — **public AND private** — must carry a comment-based help block immediately before the `function` keyword. The block uses this exact structure: - -> **Language rule:** All comment-based help — every `.SYNOPSIS`, `.DESCRIPTION`, `.PARAMETER`, `.OUTPUTS`, `.EXAMPLE` and `.NOTES` section — **must be written in English**. No exceptions. - -```powershell -<# -.SYNOPSIS -One-line summary. Imperative voice, no trailing period. - -.DESCRIPTION -Detailed multi-line description. Cover what the function does, how it -fits into the larger workflow, any threading or networking behaviour, -and important side-effects (writes to global state, blocking I/O, -external dependencies). - -.PARAMETER Name -| Name | Type | Description | Default | -|------|---------------|--------------------------------------------|---------| -| Name | System.String | Display name of the resource to act on. | | - -.PARAMETER Count -| Name | Type | Description | Default | -|-------|--------------|-----------------------------------|---------| -| Count | System.Int32 | Number of iterations to perform. | 1 | - -.OUTPUTS -System.Object -- Description of the returned value or object shape. -Use `None` if the function returns nothing. - -.EXAMPLE -PS> Verb-IcingaNoun -Name 'Foo' -Count 3 - -Short prose describing what the example does, when useful. - -.NOTES -Module-level dependencies (external services, credentials, config -files), required privileges, and any non-obvious side-effects. -#> -function Verb-IcingaNoun() -{ - … -} -``` - -### 3.1 Doc rules — strict - -1. **All seven sections** are mandatory on **public** functions: `.SYNOPSIS`, `.DESCRIPTION`, `.PARAMETER` (one per parameter), `.OUTPUTS`, `.EXAMPLE`, `.NOTES`. -2. **Private functions** must have at least `.SYNOPSIS` + `.DESCRIPTION`. `.PARAMETER`, `.OUTPUTS`, `.EXAMPLE`, `.NOTES` are required when the helper has parameters, returns a value, or has non-obvious side-effects — i.e. almost always. -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`. -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. - -### 3.2 What you do **not** comment inline - -- Don't restate what well-named code already says (`# increment counter` above `$i++`). -- Don't reference the current task, fix, or callers (`# used by X`, `# added for the Y flow`). -- Inline comments are reserved for the **why**: hidden constraints, workarounds for specific bugs, invariants that would surprise a future reader. - ---- - -## 4. Build & Generated Artifacts - -### 4.1 Compilation - -`build/Build-ModuleProject.ps1` walks `src/`, concatenates the per-component `Private/` + `Public/` `.ps1` files into `lib/IcingaForWindows..psm1`, and updates `NestedModules` + `FunctionsToExport` in `IcingaForWindows.psd1`. - -Triggering a rebuild: -```powershell -Build-ModuleProject; # compile + run Pester tests -Build-ModuleProject -SkipTests; -``` - -### 4.2 Documentation - -`build/Build-ModuleDocs.ps1` walks `src/`, parses the comment-based help block of every `.ps1` file, and writes one Markdown file per component into `docs/api/`. Triggering: -```powershell -.\build\Build-ModuleDocs.ps1; # default: docs/api/ -.\build\Build-ModuleDocs.ps1 -IncludePrivate:$false; # only Public functions -Build-ModuleProject -GenerateDocs; # compile + docs in one shot -``` - -**If a `.ps1` file is missing required help sections, the generator fails with a non-zero exit code and lists every offending file.** Fix the source — never paper over it in the generator. - ---- - -## 5. Testing - -- Pester ≥ 5 under `Tests/`. -- One `*.Tests.ps1` per public function, named after the function. -- Tests assume `Import-Module IcingaForWindows -Force -Global` has been called. -- Network/IcingaProtocol/ integration tests are **out of scope** for unit tests; mock at the function boundary or stage them separately. - ---- - -## 6. Commits & Branching - -- Default branch: `master`. -- Commit subjects in present-tense imperative ("Fix …", "Add …", "Update …"), one short line. -- Body explains **why**, not **what** — the diff already shows the what. -- Never amend pushed commits. Never force-push to `master`. -- Hooks must not be bypassed (`--no-verify`, `--no-gpg-sign`). - ---- - -## 7. Cross-platform notes - -- Target: PowerShell 7.5 on Windows 11 (primary) and Linux/macOS via the `$env:ProgramData` fallback in `IcingaForWindows.psm1`. -- Use `Join-Path` for every path concatenation. Never hardcode `\` or `/`. -- Path separators in `Build-ModuleProject.ps1` are normalised to `\` for the manifest section that lists nested modules — leave that logic alone. - ---- - -## 8. AI Assistant Etiquette - -When you (Claude, Copilot, etc.) edit this repo: - -- **Match style exactly.** Look at a neighbouring file in the same component first. -- **Don't add backwards-compatibility shims** for code that hasn't shipped yet. -- **Don't introduce new abstractions** for a single caller. Inline beats premature reuse. -- **Don't widen surface area.** If the user asks for a fix, fix that — don't refactor surrounding code. -- **Don't commit unless explicitly asked.** -- **Don't run `Build-ModuleProject`** as part of "verification". It rewrites `lib/` and `IcingaForWindows.psd1` and is the user's call, not yours. -- **When in doubt, ask.** A one-line clarifying question beats a 200-line speculative change. - ---- - -*Last updated: 2026-10-02* +1. **Read [docs/Agents/guidelines/01-Instruction.md](docs/Agents/guidelines/01-Instruction.md) in full** before creating or modifying any file. +2. **100% English & prose naming:** Write all code, inline comments, help blocks, documentation, changelogs, roadmaps, and task plans 100% in English -- regardless of conversation language. Always write **"Icinga for Windows"** in prose and reserve **`IcingaForWindows`** strictly for technical module, file, path, and `$Global:IcingaForWindows` identifiers. +3. **Strict PowerShell house style & function scope:** UTF-8 without BOM, 4-space indentation, Allman braces on `function Name()`, trailing semicolons `;` on every non-function statement, single-line `if (...) {` conditions, vertical `=` alignment in assignment and hashtable blocks, vertical `|` alignment in `.PARAMETER` tables, and strictly one top-level function with zero nested functions per file under `src/` (helper/nested functions are permitted in `build/`, `IcingaForWindows.psm1`, and `Tests/`). +4. **Mandatory `.NOTES` & Icinga SPDX headers:** Every file under `src/`, `build/`, `Tests/`, `IcingaForWindows.psm1`, and compiled `lib/` files must carry `.NOTES` concluding with `SPDX-FileCopyrightText: 2026 Icinga GmbH ` and `SPDX-License-Identifier: GPL-3.0-or-later` (and `# SPDX-...` when commented outside `<# ... #>`, such as under `PrivateData.SPDX` in `IcingaForWindows.psd1` and in `PSScriptAnalyzerSettings.psd1`). +5. **Runspace & daemon safety:** Never use PowerShell class literals from `src/Classes` inside functions (`Tests/ClassLiteral.Tests.ps1`), access runtime state in threads via `Get-GlobalRuntimeVariable`, and null loop variables in `finally` (`build/Test-ModuleDaemonMemoryLeak.ps1`). +6. **Validate & track before finishing:** Run `.\build\Test-ModuleCodeStyling.ps1` (`0` violations) and `.\build\Test-ModuleChangelog.ps1`, add an entry to `docs/General/Changelog.md` on every non-`main` branch, synchronize `docs/General/Roadmap.md` whenever creating or completing plans in `docs/Agents/tasks//`, and persist `implementation_plan.md`, `todo.md`, and `walkthrough.md`. +7. **Never commit to Git** unless explicitly requested by the user. diff --git a/GEMINI.md b/GEMINI.md new file mode 100644 index 0000000..566ef08 --- /dev/null +++ b/GEMINI.md @@ -0,0 +1,18 @@ +# GEMINI.md -- Icinga for Windows AI Agent Entrypoint + +All binding architecture, PowerShell code-style, SPDX licensing, runspace/threading safety, comment-based help, changelog/roadmap governance, testing, and feature task-tracking rules for **Icinga for Windows** are maintained in the central single source of truth: + +- **Binding Ruleset (MUST READ FIRST):** [docs/Agents/guidelines/01-Instruction.md](docs/Agents/guidelines/01-Instruction.md) +- **Changelog & Roadmap Governance:** [docs/General/Changelog.md](docs/General/Changelog.md) · [docs/General/Roadmap.md](docs/General/Roadmap.md) +- **Per-Branch Feature Plans, Todos & Walkthroughs:** [docs/Agents/tasks/](docs/Agents/tasks/) +- **Knowledgebase (`IWKB001xxx`):** [docs/Knowledgebase/index.md](docs/Knowledgebase/index.md) + +## Mandatory Instructions for Gemini / Antigravity Agents + +1. **Read [docs/Agents/guidelines/01-Instruction.md](docs/Agents/guidelines/01-Instruction.md) first** before planning or editing any file in this repository. +2. **100% English & prose naming:** Write all code, comments, help blocks, Markdown docs, changelogs, roadmaps, and `docs/Agents/tasks//{implementation_plan,todo,walkthrough}.md` artifacts 100% in English -- even when the user writes in German or another language. Always write **"Icinga for Windows"** in prose and reserve **`IcingaForWindows`** strictly for technical module, file, path, and `$Global:IcingaForWindows` identifiers. +3. **Enforce PowerShell house style & function scope:** UTF-8 without BOM, 4-space indentation, Allman `function Name()` declarations, semicolons `;` on every non-function statement, single-line `if`/`elseif` conditions, vertically aligned `=` across assignment and hashtable blocks, vertically aligned `|` pipes in `.PARAMETER` help tables, and strictly one top-level function with zero nested functions per file under `src/` (helper/nested functions are permitted under `build/`, `IcingaForWindows.psm1`, and `Tests/`). +4. **Enforce `.NOTES` & Icinga SPDX headers:** Every file under `src/`, `build/`, `Tests/`, `IcingaForWindows.psm1`, and compiled `lib/` artifacts must carry `.NOTES` ending with `SPDX-FileCopyrightText: 2026 Icinga GmbH ` and `SPDX-License-Identifier: GPL-3.0-or-later` (and `# SPDX-...` when commented outside `<# ... #>`, such as under `PrivateData.SPDX` in `IcingaForWindows.psd1` and in `PSScriptAnalyzerSettings.psd1`). +5. **Enforce runspace & memory safety:** Never reference PowerShell classes from `src/Classes` via type literals inside functions (`Tests/ClassLiteral.Tests.ps1`), always use `Get-GlobalRuntimeVariable` in worker/daemon code, and null loop variables in `finally` (`build/Test-ModuleDaemonMemoryLeak.ps1`). +6. **Verify & persist governance artifacts:** Validate with `.\build\Test-ModuleCodeStyling.ps1` (`0` violations) and `.\build\Test-ModuleChangelog.ps1`, add an entry to `docs/General/Changelog.md` on every non-`main` branch, synchronize `docs/General/Roadmap.md` whenever creating or completing plans in `docs/Agents/tasks//`, and maintain `implementation_plan.md`, `todo.md`, and `walkthrough.md`. +7. **Do not create Git commits** unless the user explicitly asks you to commit. diff --git a/IcingaForWindows.psd1 b/IcingaForWindows.psd1 index 108148d..02a73ce 100644 --- a/IcingaForWindows.psd1 +++ b/IcingaForWindows.psd1 @@ -1,30 +1,33 @@ @{ - ModuleVersion = '27.0.0' - GUID = '7e6278de-6948-4180-b1fe-731648db1289' - Author = 'Lord Hepipud' - CompanyName = 'Icinga GmbH' - Copyright = '(c) 2026 Icinga GmbH | MIT' - Description = 'Icinga for Windows monitoring solution.' - PowerShellVersion = '5.1' + ModuleVersion = '27.0.0'; + GUID = '7e6278de-6948-4180-b1fe-731648db1289'; + Author = 'Lord Hepipud'; + CompanyName = 'Icinga GmbH'; + Copyright = '(c) 2026 Icinga GmbH | GPL-3.0-or-later'; + Description = 'Icinga for Windows monitoring solution.'; + PowerShellVersion = '5.1'; NestedModules = @( 'IcingaForWindows.psm1' - ) - FunctionsToExport = '*' - CmdletsToExport = @() - VariablesToExport = '*' - AliasesToExport = '*' + ); + FunctionsToExport = '*'; + CmdletsToExport = @(); + VariablesToExport = '*'; + AliasesToExport = '*'; PrivateData = @{ PSData = @{ Tags = @( 'icinga', 'icinga2', 'windows', 'monitoring', 'opensource', 'Icinga for Windows' ); - LicenseUri = 'https://github.com/Icinga/IcingaForWindows/blob/master/LICENSE' - ProjectUri = 'https://github.com/Icinga/IcingaForWindows' - ReleaseNotes = 'https://github.com/Icinga/IcingaForWindows/releases' + LicenseUri = 'https://github.com/Icinga/IcingaForWindows/blob/main/LICENSE'; + ProjectUri = 'https://github.com/Icinga/IcingaForWindows'; + ReleaseNotes = 'https://github.com/Icinga/IcingaForWindows/releases'; }; Version = 'v27.0.0'; Name = 'Icinga for Windows'; Type = 'core'; Function = ''; Endpoint = ''; - } - HelpInfoURI = 'https://github.com/Icinga/IcingaForWindows' + SPDX = ''; + # SPDX-FileCopyrightText: 2026 Icinga GmbH + # SPDX-License-Identifier: GPL-3.0-or-later + }; + HelpInfoURI = 'https://github.com/Icinga/IcingaForWindows'; } diff --git a/IcingaForWindows.psm1 b/IcingaForWindows.psm1 index 62fc3ae..93b95bf 100644 --- a/IcingaForWindows.psm1 +++ b/IcingaForWindows.psm1 @@ -1,6 +1,6 @@ <# .SYNOPSIS -Initializes the global IcingaForWindows runtime environment and default configuration. +Initialize the global Icinga for Windows runtime environment and default configuration .DESCRIPTION New-ModuleBaseEnvironment creates and assigns a thread-safe, synchronized hashtable to the global variable $Global:IcingaForWindows. @@ -13,44 +13,25 @@ This function is intended to be called once at module initialization to ensure a components to read from and modify. It purposely uses a synchronized hashtable for safe concurrent access from multiple threads or background jobs. -.PARAMETER None -This function does not accept parameters. - .OUTPUTS -System.Collections.Hashtable -The function populates $Global:IcingaForWindows and does not return a value. Consumers should read and manipulate the -global hashtable directly (for example: $Global:IcingaForWindows['Public']['Config']). +None -- Populates $Global:IcingaForWindows in place and does not return a pipeline value. + +.EXAMPLE +PS> New-ModuleBaseEnvironment +PS> $Root = $Global:IcingaForWindows['Public']['Config']['Root'] + +Initializes the base runtime state and reads the configured Icinga for Windows ProgramData root path. .NOTES - Global variable: $Global:IcingaForWindows - The configuration root is set to Join-Path -Path $env:ProgramData -ChildPath 'IcingaForWindows'. - Default theme: 'DefaultDark'. -- Colors are represented as string names intended for console/ANSI color use (Font, Info, Success, Warning, Error, Text). -- TLS protocols: combines SslProtocols.Tls12 and SslProtocols.Tls13 using bitwise OR. Availability of Tls13 depends on - the underlying .NET/Windows runtime; on platforms without Tls13 support you may need to adjust this setting. -- The function overwrites any existing $Global:IcingaForWindows value. - -.EXAMPLE -# Initialize the base environment (run during module import/initialization) -New-ModuleBaseEnvironment - -# Access configuration root path -$root = $Global:IcingaForWindows['Public']['Config']['Root'] - -# Register an Icinga protocol endpoint -$Global:IcingaForWindows['Public']['IcingaProtocol']['Endpoints']['Default'] = @{ - Host = '127.0.0.1' - Port = 5665 - Secure = $true -} +- Colors are represented as string names intended for console/ANSI color use (Debug, Audit, Info, Success, Warning, Error, Fatal, Text, Output). +- Function is idempotent when $Global:IcingaForWindows is already initialized. -# Check TLS protocols configured -$Global:IcingaForWindows['Public']['Config']['TLS']['Protocol'] - -# Note: This function is safe to call multiple times but will reinitialize the global structure, -# so call carefully if other components hold references into the hashtable. +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> - function New-ModuleBaseEnvironment() { if ($null -ne $Global:IcingaForWindows) { @@ -59,7 +40,7 @@ function New-ModuleBaseEnvironment() [string]$OSType = 'Windows'; - # Fix for Linux and MacOS where ProgramData is not set by default, using a .ProgramData folder in the user's home directory as fallback + # Fix for Linux and macOS where ProgramData is not set by default, using a ProgramData folder in the user's home directory as fallback if ($null -eq $env:ProgramData) { $OSType = 'Linux'; $env:ProgramData = Join-Path -Path $env:HOME -ChildPath 'ProgramData'; @@ -257,6 +238,9 @@ Returns the approved Icinga for Windows binaries directory path. .NOTES Created automatically during startup by New-ModuleConfigEnvironment and whitelisted in Get-SecureChildItem. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Get-ModuleBinaryDirectory() { @@ -268,10 +252,10 @@ function Get-ModuleBinaryDirectory() Build and compile the Icinga for Windows module project .DESCRIPTION -`Build-ModuleProject` is the public entry point to compile the Icinga for -Windows module. It consolidates all source files into the kernel artifact -under `lib/`, updates the module manifest, and optionally generates documentation -or executes memory leak tests. +`Build-ModuleProject` is the entry point to compile the Icinga for Windows +module. It consolidates all source files into the classes and kernel artifacts +under `lib/`, reloads the module manifest, and optionally generates API +documentation or executes memory-leak and code-styling checks. .PARAMETER SkipTests | Name | Type | Description | Default | @@ -286,7 +270,12 @@ or executes memory leak tests. .PARAMETER TestDaemonMemoryLeaks | Name | Type | Description | Default | |-----------------------|----------------------------------------------|------------------------------------------------|---------| -| TestDaemonMemoryLeaks | System.Management.Automation.SwitchParameter | When set, run daemon memory leak stress tests. | $false | +| TestDaemonMemoryLeaks | System.Management.Automation.SwitchParameter | When set, run daemon memory leak AST checks. | $false | + +.PARAMETER TestCodeStyling +| Name | Type | Description | Default | +|-----------------|----------------------------------------------|-----------------------------------------------------------|---------| +| TestCodeStyling | System.Management.Automation.SwitchParameter | When set, run repository code-styling and SPDX checks. | $false | .OUTPUTS None -- Side effects only: generates module artifacts under lib/ and docs/. @@ -298,16 +287,20 @@ Compiles the module and generates API documentation. .NOTES Invokes build/Build-ModuleProject.ps1 in the module directory. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Build-ModuleProject() { param ( [switch]$SkipTests = $false, [switch]$GenerateDocs = $false, - [switch]$TestDaemonMemoryLeaks = $false + [switch]$TestDaemonMemoryLeaks = $false, + [switch]$TestCodeStyling = $false ); - & (Join-Path -Path $PSScriptRoot -ChildPath (Join-Path -Path 'build' -ChildPath 'Build-ModuleProject.ps1')) -SkipTests:$SkipTests -GenerateDocs:$GenerateDocs -TestDaemonMemoryLeaks:$TestDaemonMemoryLeaks; + & (Join-Path -Path $PSScriptRoot -ChildPath (Join-Path -Path 'build' -ChildPath 'Build-ModuleProject.ps1')) -SkipTests:$SkipTests -GenerateDocs:$GenerateDocs -TestDaemonMemoryLeaks:$TestDaemonMemoryLeaks -TestCodeStyling:$TestCodeStyling; } <# @@ -339,6 +332,9 @@ Executes only the memory leak test suite. .NOTES Requires the Pester module (5.0 or newer) to be installed and available in the session. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Invoke-IcingaModuleTests() { @@ -361,18 +357,18 @@ function Get-ModuleProjectName() <# .SYNOPSIS -Initialize the IcingaForWindows runtime environment in the current session +Initialize the Icinga for Windows runtime environment in the current session .DESCRIPTION -`Use-IcingaForWindows` performs the necessary startup tasks for the Icinga -PowerShell module. When called without `-NoNewShell` it spawns a new +`Use-IcingaForWindows` performs the necessary startup tasks for the Icinga for +Windows PowerShell module. When called without `-NoNewShell` it spawns a new PowerShell process (preferring pwsh over powershell.exe) and re-invokes itself with `-NoNewShell` in that child process. When called with `-NoNewShell` it initializes the base environment, applies the log level, loads configuration and access control, and starts the standard background -daemon threads (logging, garbage collector, housekeeper, REST API, WebSocket -and Icinga agent). The function is idempotent; repeated calls while already -initialized return immediately. +daemon threads (logging, garbage collector, housekeeper, performance counter, +REST API, WebSocket and Icinga agent). The function is idempotent; repeated +calls while already initialized return immediately. .PARAMETER LogLevel | Name | Type | Description | Default | @@ -401,8 +397,10 @@ Depends on New-ModuleBaseEnvironment, New-ModuleConfigEnvironment, Read-ModuleAccessControl and the daemon functions being available in scope. The alias `ifw` maps to this function. When running without `-NoNewShell` the function blocks until the spawned child process exits. -#> +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> function Use-IcingaForWindows() { param ( @@ -422,7 +420,7 @@ function Use-IcingaForWindows() # Initialize the base environment New-ModuleBaseEnvironment; - # Apply te log level to our environment + # Apply the log level to our environment Set-LoggingLogLevel -Level $LogLevel; # Only apply this for the main, initial call. @@ -456,21 +454,21 @@ function Use-IcingaForWindows() [string]$LogLevel = $args[0]; [bool]$RunBackgroundDaemons = [bool]$args[1]; - # To prevent code duplication, just let this PowerShell session call - # IcingaForWindows, but do not start a new shell. This will ensure we - # have a proper call stack and can manage everything way easier + # To prevent code duplication, let this PowerShell session invoke + # Use-IcingaForWindows directly without spawning another child shell + # so the call stack and runtime state stay cleanly isolated. Use-IcingaForWindows -NoNewShell -LogLevel $LogLevel -RunBackgroundDaemons:$RunBackgroundDaemons; function prompt() { Write-Host -Object 'icinga' -NoNewline; - return '> ' + return '> '; } } -Args $LogLevel, $RunBackgroundDaemons; } } -# Create an alias for us, which allows to simply use 'icinga' in the shell +# Create an alias for us, which allows to simply use 'ifw' in the shell Set-Alias -Name 'ifw' -Value 'Use-IcingaForWindows'; <# diff --git a/PSScriptAnalyzerSettings.psd1 b/PSScriptAnalyzerSettings.psd1 index f5dde17..8cfa7f0 100644 --- a/PSScriptAnalyzerSettings.psd1 +++ b/PSScriptAnalyzerSettings.psd1 @@ -1,3 +1,6 @@ +# SPDX-FileCopyrightText: 2026 Icinga GmbH +# SPDX-License-Identifier: GPL-3.0-or-later + @{ # PSScriptAnalyzer configuration for Icinga for Windows. # @@ -7,12 +10,14 @@ # # The full default rule set runs, EXCEPT the rules below. Each exclusion # reflects a deliberate decision from the documented house style or runtime - # design (see CLAUDE.md) — keeping them on would only produce noise. + # design (see docs/Agents/guidelines/01-Instruction.md) -- keeping them on + # would only produce noise. # # Note: a small set of rules is additionally treated as build-breaking # ERRORS by Invoke-ScriptAnalysis.ps1 (PSUseApprovedVerbs, - # PSAvoidUsingCmdletAliases). PSScriptAnalyzer settings cannot change a - # rule's severity, so that elevation lives in the runner script. + # PSAvoidUsingCmdletAliases, PSAvoidTrailingWhitespace). PSScriptAnalyzer + # settings cannot change a rule's severity, so that elevation lives in the + # runner script. ExcludeRules = @( # House style is UTF-8 *without* BOM (the build writer uses UTF8Encoding($false)). 'PSUseBOMForUnicodeEncodedFile', @@ -33,9 +38,10 @@ 'PSUseSingularNouns', # Write-Host is used by design in the build scripts and the logging console - # formatter. The "no Write-Host in source" rule from CLAUDE.md is enforced by - # review for the remaining source, not by the analyzer. + # formatter. The "no Write-Host in source" rule from 01-Instruction.md is + # enforced by review for the remaining source, not by the analyzer. 'PSAvoidUsingWriteHost', + # OutputType attributes are omitted on build and internal helper functions. 'PSUseOutputTypeCorrectly' ); diff --git a/README.md b/README.md index 121e62e..e576568 100644 --- a/README.md +++ b/README.md @@ -1,72 +1,180 @@ -[![PowerShell Version](https://img.shields.io/badge/PowerShell-5.1-777BB4?logo=PowerSHell)](https://learn.microsoft.com/en-US/powershell/scripting/install/installing-powershell-on-windows?view=powershell-5.1) -[![GitHub Tag](https://img.shields.io/github/tag/Icinga/IcingaForWindows.svg)](https://github.com/Icinga/IcingaForWindows/releases/latest) -[![GitHub Issues](https://img.shields.io/github/issues-search?query=repo%3AIcinga%2FIcingaForWindows%20is%3Aopen%20is%3Aissue&label=Issues&color=red -)](https://github.com/Icinga/IcingaForWindows/issues) -[![GitHub Pull Requests](https://img.shields.io/github/issues-search?query=repo%3AIcinga%2FIcingaForWindows%20is%3Aopen%20is%3Apr&label=Pull%20Requests&color=green -)](https://github.com/Icinga/IcingaForWindows/pulls) +[![PowerShell Version](https://img.shields.io/badge/PowerShell-5.1%2B%20%7C%207.5%2B-5391FE?logo=powershell)](https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell-on-windows) +[![License: GPL-3.0-or-later](https://img.shields.io/badge/License-GPL--3.0--or--later-blue.svg)](LICENSE) +[![CI](https://github.com/Icinga/IcingaForWindows/actions/workflows/ci.yml/badge.svg)](https://github.com/Icinga/IcingaForWindows/actions/workflows/ci.yml) +[![GitHub Release](https://img.shields.io/github/v/release/Icinga/IcingaForWindows?include_prereleases)](https://github.com/Icinga/IcingaForWindows/releases) +[![GitHub Issues](https://img.shields.io/github/issues/Icinga/IcingaForWindows?color=red)](https://github.com/Icinga/IcingaForWindows/issues) +[![GitHub Pull Requests](https://img.shields.io/github/issues-pr/Icinga/IcingaForWindows?color=green)](https://github.com/Icinga/IcingaForWindows/pulls) -IcingaForWindows Documentation -============== +# Icinga for Windows -`IcingaForWindows` is a PowerShell monitoring stack for Windows hosts. Its runtime, configuration layout, threading model and public function surface are built around a single synchronized `$Global:IcingaForWindows` state object that is shared between the main session and every background daemon. +**Icinga for Windows** (`v27.0.0`) is a unified, multi-threaded PowerShell monitoring platform and native Icinga 2 agent runtime for Windows Server and Windows client hosts. -The module is built from small, single-purpose components under `src/`: +All subsystems -- background daemons, the native Icinga 2 JSON-RPC protocol stack, the HTTPS REST API, the performance counter engine, and built-in or custom monitoring plugins -- coordinate through a single synchronized `$Global:IcingaForWindows` runtime state partitioned into `Public` (shared thread-safe queues and configuration), `Private` (runspace-local worker context), and `Protected` (environment metadata). -* **Core.Runtime / Core.Logging / Core.Threading** — the shared runtime, the structured logging queue and the runspace-based thread pool that powers every daemon. -* **Core.TCPStack / Core.RestApi / Core.WebSocket** — the TLS-aware TCP listener, the HTTP/REST worker pipeline and the WebSocket reader/writer pairs. -* **Core.AccessControl** — role-based access roles consumed by the REST API. -* **Core.ErrorHandling** — internal exit-code table and the `Write-FunctionReturnValue` helper used across the module. -* **Api** — the high-level Icinga API endpoint (`Start-IcingaApi`) layered on top of the REST stack. -* **IcingaProtocol** — the native Icinga 2 agent protocol implementation (`Start-IcingaAgent`). -* **Config / Security / Tools** — configuration loading, certificate/security helpers and small reusable utilities. +--- -Compiled module files (`lib/`) and the API reference under `docs/` are **auto-generated** from `src/` by the scripts in `build/`; do not edit them by hand. +## Architecture Overview -Getting started -------------- +**Icinga for Windows** is organized into focused, single-function source files under `src/` that compile into two BOM-less UTF-8 runtime artifacts (`lib/IcingaForWindows.Classes.ps1` and `lib/IcingaForWindows.Kernel.ps1`): -Requirements: PowerShell 5.1+ (PowerShell 7.5 recommended) on Windows. The module also imports on Linux/macOS for development via the `$env:ProgramData` fallback. +* **Core (`Runtime`, `Threading`, `Logging`, `ErrorHandling`)** -- Runspace pool thread management (`New-Thread`, `Start-ThreadHouseKeeper`), structured logging queue (`Write-LoggingEntry`), garbage collection, and semantic internal return codes (`Set-InternalExitCodes`). +* **Core Network (`TCPStack`, `RestApi`, `WebSocket`, `AccessControl`)** -- TLS 1.2+ socket management, multi-worker HTTPS REST API (`Start-RestApiDaemon`), persistent WebSocket client workers (`Start-ModuleWebSocketDaemon`), and role-based access control. +* **Icinga Protocol (`IcingaProtocol`)** -- Native Icinga 2 JSON-RPC netstring listener/connector (`Start-IcingaAgent`) and secure `event::ExecuteCommand` check dispatch for `Invoke-IcingaCheck*` cmdlets and approved external binaries/scripts inside `$env:ProgramData\IcingaForWindows\Binaries`. +* **Performance Counter Engine (`PerformanceCounter`)** -- Dedicated background daemon (`Start-IcingaPerformanceCounterDaemon`), category-level bulk snapshots, static AST counter pre-warming at startup, and automatic inline session fallback. +* **Monitoring Plugins & Public SDK (`Plugins`, `Classes`)** -- Fluent `IcingaPlugin` check/package framework, public `New-IcingaPlugin` SDK cmdlet, `IcingaThresholds` and `IcingaUnit` engines, OS data providers (`Disk`, `FileSystem`, `Process`, `ScheduledTask`), and nine built-in monitoring checks (`CPU`, `Directory`, `Memory`, `PartitionSpace`, `PerfCounter`, `Process`, `ScheduledTask`, `Service`, `Uptime`). +* **Configuration, Security & Tools (`Config`, `Security`, `Tools`)** -- Approved-path filesystem wrappers, Windows PowerShell 5.1 memory-safe JSON serialization (`ConvertFrom-ModuleJson` / `ConvertTo-ModuleJson`), unit conversion, natural sorting, and `SecureString` helpers. + +### Runtime & Check Execution Flow + +```mermaid +flowchart TD + Icinga2["Icinga 2 Parent / Master Node"] <-->|"TLS JSON-RPC Netstrings (5665)"| Proto["IcingaProtocol Daemon & Workers"] + ApiClient["HTTPS / Automation Client"] <-->|"TLS HTTP REST / WebSocket"| Rest["RestApi & WebSocket Workers"] + + subgraph Runtime["Icinga for Windows Runtime ($Global:IcingaForWindows)"] + Proto --> State[("Synchronized State
Public | Private | Protected")] + Rest --> State + Pool["Runspace Thread Pool & HouseKeeper"] --> State + Log["Logging & GC Daemons"] --> State + PerfDaemon["PerformanceCounter Daemon
(Warm Handles & Category Snapshots)"] <--> State + end + + Proto -->|"event::ExecuteCommand"| Dispatcher["Command Resolver & Dispatcher"] + Dispatcher -->|"Invoke-IcingaCheck*"| SDK["New-IcingaPlugin Fluent SDK
(IcingaPlugin + IcingaThresholds)"] + Dispatcher -->|"Approved Binaries Only"| Bin["External .exe / .cmd / .ps1
(ProgramData/IcingaForWindows/Binaries)"] + + SDK --> Providers["OS Data Providers
(Disk, FileSystem, Process, ScheduledTask, CIM)"] + SDK <-->|"Zero-Sleep Counter Reads"| PerfDaemon +``` + +### Build, Documentation & CI Governance Pipeline + +```mermaid +flowchart LR + Src["src/
(Classes, Public, Private)"] --> Compiler["build/Build-ModuleProject.ps1"] + Compiler --> Lib["lib/IcingaForWindows.{Classes,Kernel}.ps1
(UTF-8 without BOM + SPDX)"] + + Src --> DocGen["build/Build-ModuleDocs.ps1
(-Strict $true)"] + DocGen --> ApiDocs["docs/Icinga.*.md & docs/index.md"] + + Src --> Gates["CI Static & Governance Gates"] + Gates --> PSSA["Invoke-ScriptAnalysis.ps1
(PSScriptAnalyzer)"] + Gates --> Style["Test-ModuleCodeStyling.ps1
(Style, Scope & SPDX)"] + Gates --> Changelog["Test-ModuleChangelog.ps1
(PR Changelog & Roadmap)"] + Gates --> Leak["Test-ModuleDaemonMemoryLeak.ps1
(AST Loop & IDisposable)"] + + Lib --> Pester["build/Invoke-ModuleTests.ps1
(Pester 5+ Unit Tests)"] +``` + +--- + +## Quick Start + +**Requirements:** Windows PowerShell 5.1 or PowerShell 7.5+ on Windows Server / Windows 11. For local development and unit testing, the module also imports cleanly on Linux and macOS via the `$env:ProgramData` home-directory fallback. ```powershell +# Import the Icinga for Windows module Import-Module IcingaForWindows -Force -Global; -Use-IcingaForWindows -LogLevel 'Info'; # alias: ifw + +# Initialize the runtime in the current session and start background daemons (alias: ifw) +Use-IcingaForWindows -NoNewShell -LogLevel 'Info' -RunBackgroundDaemons; + +# Run built-in monitoring plugins interactively +Invoke-IcingaCheckCPU -Warning '80' -Critical '95'; +Invoke-IcingaCheckMemory -Warning '85%' -Critical '95%'; +Invoke-IcingaCheckPartitionSpace -Warning '80%' -Critical '90%'; ``` -`Use-IcingaForWindows` initializes the base environment, loads the on-disk configuration and access control, and starts the standard background daemons (logging, housekeeper, REST API, WebSocket, Icinga agent). It is idempotent and can be re-run safely. +--- -Documentation -------------- +## Writing Custom Plugins (`New-IcingaPlugin` SDK) -The API reference and guides live under `docs/`. Start here: +External modules and custom check scripts build checks through the exported `New-IcingaPlugin` cmdlet without referencing internal PowerShell class literals directly: -* [API Reference Index](docs/index.md) — one page per component, lists every public and private function with synopsis, parameters, examples and a source link. -* [Icinga REST API](docs/Icinga.Core.RestApi.md) · [Icinga API endpoint](docs/Icinga.Api.md) -* [Icinga Protocol Stack](docs/Icinga.IcingaProtocol.md) -* [TCP Stack](docs/Icinga.Core.TCPStack.md) · [WebSocket Layer](docs/Icinga.Core.WebSocket.md) -* [Threading Runtime](docs/Icinga.Core.Threading.md) · [Logging](docs/Icinga.Core.Logging.md) · [Error Handling](docs/Icinga.Core.ErrorHandling.md) -* [Access Control](docs/Icinga.Core.AccessControl.md) · [Security Helpers](docs/Icinga.Security.md) -* [Runtime](docs/Icinga.Core.Runtime.md) · [Configuration](docs/Icinga.Config.md) · [Tools](docs/Icinga.Tools.md) +```powershell +function Invoke-IcingaCheckCustomQueue() +{ + param ( + [string]$Warning = $null, + [string]$Critical = $null, + [int]$Verbosity = 0, + [switch]$NoPerfData = $false + ); + + $Package = New-IcingaPlugin -Name 'Message Queues'; + $Package.SetNoPerfData($NoPerfData).SetVerbose($Verbosity).Commit(); + + $QueueCheck = New-IcingaPlugin -Name 'Orders Queue' -Value 42 -Unit 'c'; + $QueueCheck.Warning($Warning).Critical($Critical).CheckRange().Commit(); + $Package.AddCheck($QueueCheck).Commit(); + + return $Package.Compile(); +} +``` -Developer Guide ------------- +See the [Custom Plugin Developer Guide](docs/Developer/Plugins/04-Custom-Plugin-Developer-Guide.md) for full details on composite packages, units, thresholds, error handling, and unit testing. -If you wish to extend the module or write custom integrations against the internal runtime, start with the [Developer Guide](docs/Developer/) — currently focused on the threading model: +--- -* [Threading architecture](docs/Developer/Threading/01-Threading.md) — how `$Global:IcingaForWindows.Public.Threading`, the runspace pool and per-thread `Private` state fit together, and how to spawn your own background threads. +## Developer Build & Validation Commands -The contribution rules, code style and the binding comment-based help format are documented in [CLAUDE.md](CLAUDE.md). Rebuilding the module and regenerating the API reference is done via: +Compiled files under `lib/` and API reference pages (`docs/Icinga.*.md`, `docs/index.md`) are **auto-generated** -- never edit them by hand. ```powershell -Build-ModuleProject; # compile src/ → lib/ and run tests -.\build\Build-ModuleDocs.ps1; # regenerate docs/*.md from comment-based help -Build-ModuleProject -GenerateDocs; # both in one shot +# 1. Compile src/ -> lib/ and run AST daemon memory-leak validation +.\build\Build-ModuleProject.ps1 -SkipTests -TestDaemonMemoryLeaks; + +# 2. Regenerate strict Markdown API documentation (verifies .NOTES + SPDX across all functions) +.\build\Build-ModuleDocs.ps1 -Strict $true; + +# 3. Validate repository-wide PowerShell code styling, function scope, and SPDX headers +.\build\Test-ModuleCodeStyling.ps1; + +# 4. Validate Changelog.md and Roadmap.md (enforces changelog entries on non-main branches) +.\build\Test-ModuleChangelog.ps1; + +# 5. Run PSScriptAnalyzer static analysis +.\build\Invoke-ScriptAnalysis.ps1 -FailOn 'Warning'; + +# 6. Execute the Pester unit test suite +.\build\Invoke-ModuleTests.ps1; ``` -Contributing ------------- +--- + +## Documentation Map + +### General & Governance +* [Changelog](docs/General/Changelog.md) · [Roadmap](docs/General/Roadmap.md) +* [Code, Architecture & Documentation Ruleset (`01-Instruction.md`)](docs/Agents/guidelines/01-Instruction.md) +* [Knowledgebase (`IWKB001xxx`)](docs/Knowledgebase/index.md) + +### Developer Architecture Guides +* [Threading & Runspace Class Isolation](docs/Developer/Threading/01-Threading.md) · [Daemon Memory-Leak Prevention](docs/Developer/CodeQuality/01-MemoryLeaks.md) +* [Icinga 2 Check & Binary Execution Pipeline](docs/Developer/IcingaProtocol/01-Check-and-Binary-Execution.md) +* [Performance Counter Architecture](docs/Developer/PerformanceCounter/01-Technical-Architecture-and-Reference.md) · [Performance Counter Developer Guide](docs/Developer/PerformanceCounter/02-Usability-and-Developer-Guide.md) +* [Plugin Architecture & Concepts](docs/Developer/Plugins/01-Architecture-and-Concepts.md) · [`IcingaPlugin` Reference](docs/Developer/Plugins/02-IcingaPlugin-Reference.md) · [Result & Error Objects](docs/Developer/Plugins/03-Result-and-Error-Objects.md) · [Custom Plugin Developer Guide](docs/Developer/Plugins/04-Custom-Plugin-Developer-Guide.md) + +### Auto-Generated Component API Reference +* **[API Reference Index](docs/index.md)** -- Complete index of all public cmdlets and private helpers +* **Monitoring & Protocol:** [Monitoring Checks](docs/Icinga.Plugins.Checks.md) · [Plugin SDK (`Plugins.Lib`)](docs/Icinga.Plugins.Lib.md) · [Icinga Protocol](docs/Icinga.IcingaProtocol.md) · [Performance Counter](docs/Icinga.PerformanceCounter.md) +* **OS Data Providers:** [Disk](docs/Icinga.Plugins.Provider.Disk.md) · [FileSystem](docs/Icinga.Plugins.Provider.FileSystem.md) · [Process](docs/Icinga.Plugins.Provider.Process.md) · [ScheduledTask](docs/Icinga.Plugins.Provider.ScheduledTask.md) +* **Core Runtime & Network:** [Runtime](docs/Icinga.Core.Runtime.md) · [Threading](docs/Icinga.Core.Threading.md) · [Logging](docs/Icinga.Core.Logging.md) · [Error Handling](docs/Icinga.Core.ErrorHandling.md) · [TCP Stack](docs/Icinga.Core.TCPStack.md) · [REST API](docs/Icinga.Core.RestApi.md) · [WebSocket](docs/Icinga.Core.WebSocket.md) · [Access Control](docs/Icinga.Core.AccessControl.md) +* **Platform Utilities:** [Configuration](docs/Icinga.Config.md) · [Security](docs/Icinga.Security.md) · [Tools](docs/Icinga.Tools.md) + +--- + +## Contributing + +**Icinga for Windows** is an open-source project and welcomes bug reports, feature requests, documentation improvements, and pull requests: + +1. Check the [Issue Tracker](https://github.com/Icinga/IcingaForWindows/issues) and [Roadmap](docs/General/Roadmap.md) before starting work. +2. Follow all code-styling, runspace-isolation, `.NOTES`, and SPDX licensing rules in [`docs/Agents/guidelines/01-Instruction.md`](docs/Agents/guidelines/01-Instruction.md). +3. Add a changelog bullet entry under the current unreleased version in [`docs/General/Changelog.md`](docs/General/Changelog.md) on every pull request / feature branch (`build/Test-ModuleChangelog.ps1`). +4. Verify all build, documentation, styling, memory-leak, and Pester checks pass before opening a [Pull Request](https://github.com/Icinga/IcingaForWindows/pulls). + +--- -IcingaForWindows is an Open Source project (GPLv3) and lives from your contributions — feature requests, issues, documentation or code. +## License -* Please check whether a related issue already exists on our [Issue Tracker](https://github.com/Icinga/IcingaForWindows/issues) -* Send a [Pull Request](https://github.com/Icinga/IcingaForWindows/pulls) -* The master branch shall never be corrupt! +**Icinga for Windows** is licensed under the **GNU General Public License v3.0 or later (`GPL-3.0-or-later`)**. See [LICENSE](LICENSE) for the full license text. diff --git a/Tests/Changelog.Tests.ps1 b/Tests/Changelog.Tests.ps1 new file mode 100644 index 0000000..db61bac --- /dev/null +++ b/Tests/Changelog.Tests.ps1 @@ -0,0 +1,213 @@ +<# +.SYNOPSIS +Fast Pester unit test suite for the Icinga for Windows Changelog and Roadmap validator + +.DESCRIPTION +Validates `build/Test-ModuleChangelog.ps1` against isolated synthetic Git repositories +in `$TestDrive`. Tests `main` branch exemption, non-`main` branch failure when no +bullet entry is added, committed and working-tree bullet detection on feature branches, +GitHub Actions `pull_request` environment detection, and structural validation of +`docs/General/Changelog.md` and `docs/General/Roadmap.md`. + +.NOTES +Executes purely against `$TestDrive` fixtures so CI never runs repository checks twice. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> + +$ModulePath = Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..') -ChildPath 'IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Test-ModuleChangelog Governance Rules' { + BeforeAll { + $script:ModuleRoot = [System.IO.Path]::GetFullPath((Resolve-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..')).ProviderPath); + $script:ChangelogScript = Join-Path -Path (Join-Path -Path $script:ModuleRoot -ChildPath 'build') -ChildPath 'Test-ModuleChangelog.ps1'; + $script:Utf8NoBom = New-Object System.Text.UTF8Encoding($false); + + function Invoke-QuietGit() + { + param ( + [string]$RepoPath = '', + [string[]]$GitArgs = @() + ); + + & git -C $RepoPath @GitArgs | Out-Null; + } + + function New-SyntheticGovernanceRepo() + { + param ( + [string]$RepoName = 'TestRepo' + ); + + [string]$RepoPath = Join-Path -Path $TestDrive -ChildPath $RepoName; + [string]$GeneralDir = Join-Path -Path $RepoPath -ChildPath (Join-Path -Path 'docs' -ChildPath 'General'); + New-Item -Path $GeneralDir -ItemType Directory -Force | Out-Null; + + [string]$BaseChangelog = @( + '# Icinga for Windows Changelog', + '', + '## 27.0.0 (Unreleased)', + '', + '### Enhancements', + '', + '* Initial baseline changelog entry for unit testing', + '' + ) -join "`n"; + + [string]$BaseRoadmap = @( + '# Icinga for Windows Roadmap', + '', + '## Completed Milestones & Subsystems', + '', + '| Status | Subsystem | Summary |', + '| ------ | --------- | ------- |', + '| Completed | Core | Baseline |', + '', + '## Feature List & Planned Work', + '', + '| Priority | Scenario | Description |', + '| -------- | -------- | ----------- |', + '| 1 | Hardening | Planned |', + '' + ) -join "`n"; + + [System.IO.File]::WriteAllText((Join-Path -Path $GeneralDir -ChildPath 'Changelog.md'), $BaseChangelog, $script:Utf8NoBom); + [System.IO.File]::WriteAllText((Join-Path -Path $GeneralDir -ChildPath 'Roadmap.md'), $BaseRoadmap, $script:Utf8NoBom); + + Invoke-QuietGit -RepoPath $RepoPath -GitArgs @( 'init', '-q', '-b', 'main' ); + Invoke-QuietGit -RepoPath $RepoPath -GitArgs @( 'config', 'user.name', 'Icinga Test' ); + Invoke-QuietGit -RepoPath $RepoPath -GitArgs @( 'config', 'user.email', 'test@icinga.com' ); + Invoke-QuietGit -RepoPath $RepoPath -GitArgs @( 'config', 'commit.gpgsign', 'false' ); + Invoke-QuietGit -RepoPath $RepoPath -GitArgs @( 'add', '.' ); + Invoke-QuietGit -RepoPath $RepoPath -GitArgs @( 'commit', '-q', '-m', 'Initial main commit' ); + + return $RepoPath; + } + } + + BeforeEach { + $script:SavedEventName = $env:GITHUB_EVENT_NAME; + $script:SavedRefName = $env:GITHUB_REF_NAME; + $script:SavedBaseRef = $env:GITHUB_BASE_REF; + + $env:GITHUB_EVENT_NAME = $null; + $env:GITHUB_REF_NAME = $null; + $env:GITHUB_BASE_REF = $null; + } + + AfterEach { + $env:GITHUB_EVENT_NAME = $script:SavedEventName; + $env:GITHUB_REF_NAME = $script:SavedRefName; + $env:GITHUB_BASE_REF = $script:SavedBaseRef; + } + + Context 'Branch and Pull Request changelog enforcement' { + It 'passes on main branch without requiring new diff entries' { + [string]$Repo = New-SyntheticGovernanceRepo -RepoName 'MainPassRepo'; + [array]$Violations = & $script:ChangelogScript -ModuleBasePath $Repo -PassThru; + $Violations | Should -BeNullOrEmpty; + } + + It 'fails on a non-main branch when no bullet entry was added to Changelog.md' { + [string]$Repo = New-SyntheticGovernanceRepo -RepoName 'FeatureFailRepo'; + Invoke-QuietGit -RepoPath $Repo -GitArgs @( 'checkout', '-q', '-b', 'feature/missing-changelog' ); + [string]$Dummy = Join-Path -Path $Repo -ChildPath 'dummy.txt'; + [System.IO.File]::WriteAllText($Dummy, "change`n", $script:Utf8NoBom); + Invoke-QuietGit -RepoPath $Repo -GitArgs @( 'add', '.' ); + Invoke-QuietGit -RepoPath $Repo -GitArgs @( 'commit', '-q', '-m', 'Add feature without changelog' ); + + [array]$Violations = & $script:ChangelogScript -ModuleBasePath $Repo -PassThru; + ($Violations -join "`n") | Should -Match 'Missing changelog entry'; + + # Also verify non-PassThru mode throws the expected message + { & $script:ChangelogScript -ModuleBasePath $Repo } | Should -Throw '*Missing changelog entry*'; + } + + It 'rejects non-bullet edits to Changelog.md and passes once a real "* " bullet is added' { + [string]$Repo = New-SyntheticGovernanceRepo -RepoName 'FeatureBulletRepo'; + Invoke-QuietGit -RepoPath $Repo -GitArgs @( 'checkout', '-q', '-b', 'feature/with-bullet' ); + [string]$ClPath = Join-Path -Path $Repo -ChildPath (Join-Path -Path 'docs' -ChildPath (Join-Path -Path 'General' -ChildPath 'Changelog.md')); + + # Prose-only edit without "* " bullet must still fail + [string]$Current = [System.IO.File]::ReadAllText($ClPath, [System.Text.Encoding]::UTF8); + [System.IO.File]::WriteAllText($ClPath, ($Current + "`nSome non-bullet note.`n"), $script:Utf8NoBom); + [array]$BadViolations = & $script:ChangelogScript -ModuleBasePath $Repo -PassThru; + ($BadViolations -join "`n") | Should -Match 'Missing changelog entry'; + + # Uncommitted working-tree "* " bullet passes + [System.IO.File]::WriteAllText($ClPath, ($Current + "* Adds new feature on working tree`n"), $script:Utf8NoBom); + [array]$WtViolations = & $script:ChangelogScript -ModuleBasePath $Repo -PassThru; + $WtViolations | Should -BeNullOrEmpty; + + # Committed "* " bullet continues to pass even after main advances independently + Invoke-QuietGit -RepoPath $Repo -GitArgs @( 'add', '.' ); + Invoke-QuietGit -RepoPath $Repo -GitArgs @( 'commit', '-q', '-m', 'Document feature in Changelog' ); + Invoke-QuietGit -RepoPath $Repo -GitArgs @( 'checkout', '-q', 'main' ); + [System.IO.File]::WriteAllText((Join-Path -Path $Repo -ChildPath 'other.txt'), "main advance`n", $script:Utf8NoBom); + Invoke-QuietGit -RepoPath $Repo -GitArgs @( 'add', '.' ); + Invoke-QuietGit -RepoPath $Repo -GitArgs @( 'commit', '-q', '-m', 'Advance main' ); + Invoke-QuietGit -RepoPath $Repo -GitArgs @( 'checkout', '-q', 'feature/with-bullet' ); + + [array]$CommittedViolations = & $script:ChangelogScript -ModuleBasePath $Repo -PassThru; + $CommittedViolations | Should -BeNullOrEmpty; + } + + It 'enforces changelog entry in simulated GitHub Actions pull_request detached HEAD runs and non-main base refs' { + [string]$Repo = New-SyntheticGovernanceRepo -RepoName 'CiPrRepo'; + Invoke-QuietGit -RepoPath $Repo -GitArgs @( 'branch', 'support/27.0', 'main' ); + Invoke-QuietGit -RepoPath $Repo -GitArgs @( 'checkout', '-q', '-b', 'feature/pr-check', 'support/27.0' ); + [System.IO.File]::WriteAllText((Join-Path -Path $Repo -ChildPath 'pr.txt'), "pr`n", $script:Utf8NoBom); + Invoke-QuietGit -RepoPath $Repo -GitArgs @( 'add', '.' ); + Invoke-QuietGit -RepoPath $Repo -GitArgs @( 'commit', '-q', '-m', 'PR commit without changelog' ); + Invoke-QuietGit -RepoPath $Repo -GitArgs @( 'checkout', '-q', '--detach', 'HEAD' ); + + $env:GITHUB_EVENT_NAME = 'pull_request'; + $env:GITHUB_BASE_REF = 'support/27.0'; + + [array]$Violations = & $script:ChangelogScript -ModuleBasePath $Repo -PassThru; + ($Violations -join "`n") | Should -Match 'Missing changelog entry'; + + # Adding a bullet against support/27.0 passes + [string]$ClPath = Join-Path -Path $Repo -ChildPath (Join-Path -Path 'docs' -ChildPath (Join-Path -Path 'General' -ChildPath 'Changelog.md')); + [string]$Existing = [System.IO.File]::ReadAllText($ClPath, [System.Text.Encoding]::UTF8); + [System.IO.File]::WriteAllText($ClPath, ($Existing + "* Adds backport fix for 27.0`n"), $script:Utf8NoBom); + [array]$PassViolations = & $script:ChangelogScript -ModuleBasePath $Repo -PassThru; + $PassViolations | Should -BeNullOrEmpty; + } + + It 'rejects rewording or deleting existing bullets when no net-new bullet is added' { + [string]$Repo = New-SyntheticGovernanceRepo -RepoName 'RewordBypassRepo'; + Invoke-QuietGit -RepoPath $Repo -GitArgs @( 'checkout', '-q', '-b', 'feature/reword-only' ); + [string]$ClPath = Join-Path -Path $Repo -ChildPath (Join-Path -Path 'docs' -ChildPath (Join-Path -Path 'General' -ChildPath 'Changelog.md')); + [string]$Original = [System.IO.File]::ReadAllText($ClPath, [System.Text.Encoding]::UTF8); + + # Merely rewording the baseline bullet (+1 / -1 = 0 net bullets) must fail + [string]$Reworded = $Original.Replace('* Initial baseline changelog entry for unit testing', '* Initial baseline changelog entry with typo fix'); + [System.IO.File]::WriteAllText($ClPath, $Reworded, $script:Utf8NoBom); + [array]$RewordViolation = & $script:ChangelogScript -ModuleBasePath $Repo -PassThru; + ($RewordViolation -join "`n") | Should -Match 'Missing changelog entry'; + + # Rewording an existing bullet AND adding a new bullet (+2 / -1 = +1 net bullet) passes + [System.IO.File]::WriteAllText($ClPath, ($Reworded + "* Adds genuine branch changelog entry`n"), $script:Utf8NoBom); + [array]$NetNewPass = & $script:ChangelogScript -ModuleBasePath $Repo -PassThru; + $NetNewPass | Should -BeNullOrEmpty; + } + } + + Context 'Document presence and structural validation' { + It 'reports missing Changelog.md or Roadmap.md files' { + [string]$EmptyRepo = Join-Path -Path $TestDrive -ChildPath 'MissingDocsRepo'; + New-Item -Path $EmptyRepo -ItemType Directory -Force | Out-Null; + + [array]$Violations = & $script:ChangelogScript -ModuleBasePath $EmptyRepo -CurrentBranch 'main' -PassThru; + [string]$Joined = ($Violations -join "`n"); + + $Joined | Should -Match 'Missing required file: docs/General/Changelog\.md'; + $Joined | Should -Match 'Missing required file: docs/General/Roadmap\.md'; + } + } +} diff --git a/Tests/ClassLiteral.Tests.ps1 b/Tests/ClassLiteral.Tests.ps1 index e5afed3..f0b8e80 100644 --- a/Tests/ClassLiteral.Tests.ps1 +++ b/Tests/ClassLiteral.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for ClassLiteral in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for ClassLiteral +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; @@ -12,7 +26,7 @@ Describe 'Class literals in functions' { # Functions therefore use New-IcingaPlugin, Test-IcingaError or a runtime # lookup ('Name' -as [type]); only the class files themselves and enums may # use literals. - $script:SourceRoot = [System.IO.Path]::GetFullPath((Join-Path -Path $PSScriptRoot -ChildPath '..\src')); + $script:SourceRoot = [System.IO.Path]::GetFullPath((Resolve-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath (Join-Path -Path '..' -ChildPath 'src'))).ProviderPath); [string[]]$script:ClassNames = @(); foreach ($File in (Get-ChildItem -Path (Join-Path -Path $script:SourceRoot -ChildPath 'Classes') -Filter '*.ps1' -Recurse)) { @@ -39,10 +53,11 @@ Describe 'Class literals in functions' { ); foreach ($File in (Get-ChildItem -Path $script:SourceRoot -Filter '*.ps1' -Recurse)) { - [bool]$Skip = $false; + [string]$FullFilePath = [System.IO.Path]::GetFullPath($File.FullName); + [bool]$Skip = $false; foreach ($Folder in $Skipped) { - if ($File.FullName.StartsWith($Folder + [System.IO.Path]::DirectorySeparatorChar, [System.StringComparison]::OrdinalIgnoreCase)) { + if ($FullFilePath.StartsWith($Folder + [System.IO.Path]::DirectorySeparatorChar, [System.StringComparison]::OrdinalIgnoreCase)) { $Skip = $true; } } @@ -51,7 +66,7 @@ Describe 'Class literals in functions' { continue; } - $Ast = [System.Management.Automation.Language.Parser]::ParseFile($File.FullName, [ref]$null, [ref]$null); + $Ast = [System.Management.Automation.Language.Parser]::ParseFile($FullFilePath, [ref]$null, [ref]$null); $Nodes = $Ast.FindAll({ param ($Node) $Node -is [System.Management.Automation.Language.TypeExpressionAst] -or $Node -is [System.Management.Automation.Language.TypeConstraintAst] }, $true); foreach ($Node in $Nodes) { @@ -62,7 +77,7 @@ Describe 'Class literals in functions' { } if ($script:ClassNames -contains $TypeName.Name) { - $Violations += ('{0}:{1} [{2}]' -f $File.FullName.Substring($script:SourceRoot.Length + 1), $Node.Extent.StartLineNumber, $TypeName.Name); + $Violations += ('{0}:{1} [{2}]' -f $FullFilePath.Substring($script:SourceRoot.Length + 1), $Node.Extent.StartLineNumber, $TypeName.Name); } } } diff --git a/Tests/CodeStyling.Tests.ps1 b/Tests/CodeStyling.Tests.ps1 new file mode 100644 index 0000000..5c7ef76 --- /dev/null +++ b/Tests/CodeStyling.Tests.ps1 @@ -0,0 +1,452 @@ +<# +.SYNOPSIS +Fast Pester unit test suite for the Icinga for Windows code-styling and SPDX validator + +.DESCRIPTION +Validates the parser, AST, function-scope, vertical-alignment, encoding, manifest, +and SPDX license enforcement logic of `build/Test-ModuleCodeStyling.ps1` against +synthetic `$TestDrive` fixtures. Repository-wide scanning executes once via +`build/Test-ModuleCodeStyling.ps1` in the CI `analyze` job so `Invoke-ModuleTests.ps1` +never scans the repository tree a second time. + +.NOTES +Calls `build/Test-ModuleCodeStyling.ps1` with `-PassThru` against `$TestDrive`. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> + +$ModulePath = Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..') -ChildPath 'IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Test-ModuleCodeStyling Validator Rules' { + BeforeAll { + $script:ModuleRoot = [System.IO.Path]::GetFullPath((Resolve-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..')).ProviderPath); + $script:StyleScript = Join-Path -Path (Join-Path -Path $script:ModuleRoot -ChildPath 'build') -ChildPath 'Test-ModuleCodeStyling.ps1'; + $script:Utf8NoBom = New-Object System.Text.UTF8Encoding($false); + } + + Context 'Compliant synthetic files across src/, build/, psd1, and lib/' { + It 'accepts compliant src/ function and class files with .NOTES and SPDX headers' { + [string]$SandboxRoot = Join-Path -Path $TestDrive -ChildPath 'CompliantRepo'; + [string]$SrcPubDir = Join-Path -Path (Join-Path -Path $SandboxRoot -ChildPath 'src') -ChildPath 'Public'; + [string]$SrcClsDir = Join-Path -Path (Join-Path -Path $SandboxRoot -ChildPath 'src') -ChildPath 'Classes'; + [string]$BuildDir = Join-Path -Path $SandboxRoot -ChildPath 'build'; + [string]$LibDir = Join-Path -Path $SandboxRoot -ChildPath 'lib'; + + foreach ($Dir in @( $SrcPubDir, $SrcClsDir, $BuildDir, $LibDir )) { + New-Item -Path $Dir -ItemType Directory -Force | Out-Null; + } + + [string]$GoodFnFile = Join-Path -Path $SrcPubDir -ChildPath 'Get-IcingaSample.ps1'; + [string]$GoodFnBody = @( + '<#', + '.SYNOPSIS', + 'Return a sample value for unit testing', + '', + '.PARAMETER Name', + '| Name | Type | Description | Default |', + '|------|---------------|-----------------|---------|', + '| Name | System.String | Sample name key | $null |', + '', + '.NOTES', + 'Synthetic unit test fixture.', + '', + 'SPDX-FileCopyrightText: 2026 Icinga GmbH ', + 'SPDX-License-Identifier: GPL-3.0-or-later', + '#>', + 'function Get-IcingaSample()', + '{', + ' param (', + ' [string]$Name = $null', + ' );', + '', + ' [int]$Short = 1;', + ' [string]$Long = $Name;', + '', + ' if ([string]::IsNullOrEmpty($Long)) {', + ' return $Short;', + ' }', + '', + ' return $Long;', + '}', + '' + ) -join "`n"; + + [string]$GoodClsFile = Join-Path -Path $SrcClsDir -ChildPath 'SampleStatus.ps1'; + [string]$GoodClsBody = @( + '<#', + '.SYNOPSIS', + 'Sample status enum for unit testing', + '', + '.NOTES', + 'Synthetic enum fixture.', + '', + 'SPDX-FileCopyrightText: 2026 Icinga GmbH ', + 'SPDX-License-Identifier: GPL-3.0-or-later', + '#>', + 'enum SampleStatus', + '{', + ' Ok = 0;', + ' Critical = 2;', + '}', + '' + ) -join "`n"; + + [string]$GoodBldFile = Join-Path -Path $BuildDir -ChildPath 'Invoke-SampleBuild.ps1'; + [string]$GoodBldBody = @( + '<#', + '.SYNOPSIS', + 'Sample build script permitting helper and nested functions', + '', + '.NOTES', + 'Build scripts allow multiple and nested functions.', + '', + 'SPDX-FileCopyrightText: 2026 Icinga GmbH ', + 'SPDX-License-Identifier: GPL-3.0-or-later', + '#>', + 'function Invoke-OuterBuildHelper()', + '{', + ' function Invoke-NestedBuildHelper()', + ' {', + ' return $true;', + ' }', + '', + ' return (Invoke-NestedBuildHelper);', + '}', + '', + 'function Invoke-SecondBuildHelper()', + '{', + ' return (Invoke-OuterBuildHelper);', + '}', + '' + ) -join "`n"; + + [string]$GoodPsd1 = Join-Path -Path $SandboxRoot -ChildPath 'IcingaForWindows.psd1'; + [string]$GoodPsdBody = @( + '@{', + ' ModuleVersion = ''27.0.0'';', + ' Copyright = ''(c) 2026 Icinga GmbH | GPL-3.0-or-later'';', + ' PrivateData = @{', + ' Endpoint = '''';', + ' SPDX = '''';', + ' # SPDX-FileCopyrightText: 2026 Icinga GmbH ', + ' # SPDX-License-Identifier: GPL-3.0-or-later', + ' };', + '}', + '' + ) -join "`n"; + + [string]$GoodLibFile = Join-Path -Path $LibDir -ChildPath 'IcingaForWindows.Kernel.ps1'; + [string]$GoodLibBody = @( + '<#', + '.SYNOPSIS', + ' Icinga for Windows - Kernel Module', + '.NOTES', + ' Source: src', + '', + ' SPDX-FileCopyrightText: 2026 Icinga GmbH ', + ' SPDX-License-Identifier: GPL-3.0-or-later', + '#>', + '' + ) -join "`n"; + + [System.IO.File]::WriteAllText($GoodFnFile, $GoodFnBody, $script:Utf8NoBom); + [System.IO.File]::WriteAllText($GoodClsFile, $GoodClsBody, $script:Utf8NoBom); + [System.IO.File]::WriteAllText($GoodBldFile, $GoodBldBody, $script:Utf8NoBom); + [System.IO.File]::WriteAllText($GoodPsd1, $GoodPsdBody, $script:Utf8NoBom); + [System.IO.File]::WriteAllText($GoodLibFile, $GoodLibBody, $script:Utf8NoBom); + + [array]$Violations = & $script:StyleScript -ModuleBasePath $SandboxRoot -PassThru; + $Violations | Should -BeNullOrEmpty -Because ($Violations -join "`n"); + } + } + + Context 'Function scope enforcement (src/ vs. build/) and SPDX header checks' { + It 'forbids nested functions and multiple top-level functions under src/ and standalone functions under src/Classes/' { + [string]$ScopeRoot = Join-Path -Path $TestDrive -ChildPath 'ScopeRepo'; + [string]$SrcPrvDir = Join-Path -Path (Join-Path -Path $ScopeRoot -ChildPath 'src') -ChildPath 'Private'; + [string]$SrcClsDir = Join-Path -Path (Join-Path -Path $ScopeRoot -ChildPath 'src') -ChildPath 'Classes'; + + New-Item -Path $SrcPrvDir -ItemType Directory -Force | Out-Null; + New-Item -Path $SrcClsDir -ItemType Directory -Force | Out-Null; + + [string]$BadSrcFn = Join-Path -Path $SrcPrvDir -ChildPath 'Invoke-BadSrc.ps1'; + [string]$BadFnBody = @( + '<#', + '.SYNOPSIS', + 'Invalid src file with nested and extra functions', + '', + '.NOTES', + 'SPDX-FileCopyrightText: 2026 Icinga GmbH ', + 'SPDX-License-Identifier: GPL-3.0-or-later', + '#>', + 'function Invoke-BadSrc()', + '{', + ' function Invoke-ForbiddenInner()', + ' {', + ' return 1;', + ' }', + '', + ' return (Invoke-ForbiddenInner);', + '}', + '', + 'function Invoke-SecondTopLevel()', + '{', + ' return 2;', + '}', + '' + ) -join "`n"; + + [string]$BadClsFn = Join-Path -Path $SrcClsDir -ChildPath 'BadClassFile.ps1'; + [string]$BadClsTxt = @( + '<#', + '.SYNOPSIS', + 'Class file with forbidden standalone function', + '', + '.NOTES', + 'SPDX-FileCopyrightText: 2026 Icinga GmbH ', + 'SPDX-License-Identifier: GPL-3.0-or-later', + '#>', + 'class BadClassFile', + '{', + '}', + '', + 'function Get-ForbiddenInClasses()', + '{', + ' return $null;', + '}', + '' + ) -join "`n"; + + [System.IO.File]::WriteAllText($BadSrcFn, $BadFnBody, $script:Utf8NoBom); + [System.IO.File]::WriteAllText($BadClsFn, $BadClsTxt, $script:Utf8NoBom); + + [array]$Violations = & $script:StyleScript -ModuleBasePath $ScopeRoot -Path @( $BadSrcFn, $BadClsFn ) -PassThru; + [string]$Joined = ($Violations -join "`n"); + + $Joined | Should -Match 'Multiple top-level functions'; + $Joined | Should -Match 'Nested function "Invoke-ForbiddenInner"'; + $Joined | Should -Match 'Standalone function "Get-ForbiddenInClasses" is forbidden under src/Classes/'; + } + + It 'rejects missing .NOTES or missing SPDX lines in source, manifest, and compiled lib files' { + [string]$SpdxRoot = Join-Path -Path $TestDrive -ChildPath 'SpdxRepo'; + [string]$SrcDir = Join-Path -Path (Join-Path -Path $SpdxRoot -ChildPath 'src') -ChildPath 'Private'; + [string]$LibDir = Join-Path -Path $SpdxRoot -ChildPath 'lib'; + + New-Item -Path $SrcDir -ItemType Directory -Force | Out-Null; + New-Item -Path $LibDir -ItemType Directory -Force | Out-Null; + + [string]$NoSpdxSrc = Join-Path -Path $SrcDir -ChildPath 'Get-NoSpdx.ps1'; + [string]$NoSpdxBody = @( + '<#', + '.SYNOPSIS', + 'Missing SPDX lines inside .NOTES', + '', + '.NOTES', + 'Only prose notes without SPDX lines.', + '#>', + 'function Get-NoSpdx()', + '{', + ' return $true;', + '}', + '' + ) -join "`n"; + + [string]$BadPsd1 = Join-Path -Path $SpdxRoot -ChildPath 'IcingaForWindows.psd1'; + [string]$BadPsdBody = @( + '@{', + ' ModuleVersion = ''27.0.0'';', + ' Copyright = ''(c) 2026 Icinga GmbH | MIT'';', + ' PrivateData = @{', + ' Endpoint = '''';', + ' };', + '}', + '' + ) -join "`n"; + + [string]$BadLib = Join-Path -Path $LibDir -ChildPath 'IcingaForWindows.Classes.ps1'; + [string]$BadLibBody = @( + '<#', + '.SYNOPSIS', + ' Missing SPDX header at top of lib file', + '#>', + '' + ) -join "`n"; + + [string]$BadSlashSrc = Join-Path -Path $SrcDir -ChildPath 'Get-SlashSpdx.ps1'; + [string]$BadSlashBody = @( + '<#', + '.SYNOPSIS', + 'Rejects C-style double-slash SPDX prefix inside .NOTES', + '', + '.NOTES', + ('/' + '/ SPDX-FileCopyrightText: 2026 Icinga GmbH '), + ('/' + '/ SPDX-License-Identifier: GPL-3.0-or-later'), + '#>', + 'function Get-SlashSpdx()', + '{', + ' return $true;', + '}', + '' + ) -join "`n"; + + [System.IO.File]::WriteAllText($NoSpdxSrc, $NoSpdxBody, $script:Utf8NoBom); + [System.IO.File]::WriteAllText($BadSlashSrc, $BadSlashBody, $script:Utf8NoBom); + [System.IO.File]::WriteAllText($BadPsd1, $BadPsdBody, $script:Utf8NoBom); + [System.IO.File]::WriteAllText($BadLib, $BadLibBody, $script:Utf8NoBom); + + [array]$Violations = & $script:StyleScript -ModuleBasePath $SpdxRoot -Path @( $NoSpdxSrc, $BadSlashSrc, $BadPsd1, $BadLib ) -PassThru; + [string]$Joined = ($Violations -join "`n"); + + $Joined | Should -Match 'Get-NoSpdx\.ps1.*SPDX-FileCopyrightText'; + $Joined | Should -Match 'Get-SlashSpdx\.ps1.*SPDX-FileCopyrightText'; + $Joined | Should -Match 'Copyright must specify GPL-3\.0-or-later'; + $Joined | Should -Match 'PrivateData must include "SPDX = '''';"'; + $Joined | Should -Match 'Compiled lib artifact header block: missing mandatory \.NOTES'; + } + + It 'rejects stray classes or missing functions outside src/Classes/, non-manifest .psd1 without SPDX, and indented build help missing SPDX' { + [string]$GuardRoot = Join-Path -Path $TestDrive -ChildPath 'GuardRepo'; + [string]$SrcPrvDir = Join-Path -Path (Join-Path -Path $GuardRoot -ChildPath 'src') -ChildPath 'Private'; + [string]$BuildDir = Join-Path -Path $GuardRoot -ChildPath 'build'; + + New-Item -Path $SrcPrvDir -ItemType Directory -Force | Out-Null; + New-Item -Path $BuildDir -ItemType Directory -Force | Out-Null; + + [string]$StrayTypeSrc = Join-Path -Path $SrcPrvDir -ChildPath 'StrayType.ps1'; + [string]$StrayBody = @( + 'class MisplacedClass', + '{', + '}', + '' + ) -join "`n"; + + [string]$SettingsPsd1 = Join-Path -Path $GuardRoot -ChildPath 'PSScriptAnalyzerSettings.psd1'; + [string]$SettingsBody = @( + '@{', + ' ExcludeRules = @();', + '}', + '' + ) -join "`n"; + + [string]$IndentedBld = Join-Path -Path $BuildDir -ChildPath 'Invoke-BadHelperDoc.ps1'; + [string]$IndentedBody = @( + '<#', + '.SYNOPSIS', + 'Top-level build script with valid SPDX', + '', + '.NOTES', + 'SPDX-FileCopyrightText: 2026 Icinga GmbH ', + 'SPDX-License-Identifier: GPL-3.0-or-later', + '#>', + 'function Invoke-HelperMissingSpdx()', + '{', + ' <#', + ' .SYNOPSIS', + ' Indented helper help block missing .NOTES and SPDX', + ' #>', + ' return $true;', + '}', + '' + ) -join "`n"; + + [System.IO.File]::WriteAllText($StrayTypeSrc, $StrayBody, $script:Utf8NoBom); + [System.IO.File]::WriteAllText($SettingsPsd1, $SettingsBody, $script:Utf8NoBom); + [System.IO.File]::WriteAllText($IndentedBld, $IndentedBody, $script:Utf8NoBom); + + [array]$Violations = & $script:StyleScript -ModuleBasePath $GuardRoot -PassThru; + [string]$Joined = ($Violations -join "`n"); + + $Joined | Should -Match 'Class or enum "MisplacedClass" is forbidden outside src/Classes/'; + $Joined | Should -Match 'must define a top-level function'; + $Joined | Should -Match 'PowerShell data file \(\.psd1\) must include "# SPDX-FileCopyrightText'; + $Joined | Should -Match 'Invoke-BadHelperDoc\.ps1:11 -- Help block: missing mandatory \.NOTES'; + } + } + + Context 'Encoding, whitespace, AST brace, condition, and alignment violation detection' { + It 'detects UTF-8/UTF-16 BOMs, missing or duplicate trailing newlines, non-4-space indentation, Unicode dashes, and non-ASCII characters' { + [string]$BadFile = Join-Path -Path $TestDrive -ChildPath 'BadBasic.ps1'; + [string]$Body = @( + 'function Test-BadBasic()', + '{', + (' [string]$Dash = ''bad ' + [char]0x2014 + ' dash'';'), + (' [string]$Arrow = ''bad ' + [char]0x2192 + ' arrow'';'), + ' return $Dash;', + '}' + ) -join "`n"; + + # Write WITH UTF-8 BOM and WITHOUT trailing newline + [System.IO.File]::WriteAllText($BadFile, $Body, (New-Object System.Text.UTF8Encoding($true))); + [array]$Violations = & $script:StyleScript -ModuleBasePath $TestDrive -Path @( $BadFile ) -PassThru; + + ($Violations -join "`n") | Should -Match 'UTF-8 BOM'; + ($Violations -join "`n") | Should -Match 'single trailing newline'; + ($Violations -join "`n") | Should -Match 'multiples of 4 spaces'; + ($Violations -join "`n") | Should -Match 'em-dash'; + ($Violations -join "`n") | Should -Match 'U\+2192'; + + # Write WITH two trailing newlines + [System.IO.File]::WriteAllText($BadFile, ($Body + "`n`n"), $script:Utf8NoBom); + [array]$DupNlViolations = & $script:StyleScript -ModuleBasePath $TestDrive -Path @( $BadFile ) -PassThru; + ($DupNlViolations -join "`n") | Should -Match 'multiple trailing blank lines'; + + # Write WITH UTF-16 LE BOM (default of Out-File on Windows PowerShell 5.1) + [System.IO.File]::WriteAllText($BadFile, ($Body + "`n"), [System.Text.Encoding]::Unicode); + [array]$Utf16Violations = & $script:StyleScript -ModuleBasePath $TestDrive -Path @( $BadFile ) -PassThru; + ($Utf16Violations -join "`n") | Should -Match 'UTF-16/UTF-32 BOM'; + } + + It 'detects K&R braces on function/class/enum, multiline if conditions, single-entry hashtable spacing, 4th-row table pipes, and string <# safety' { + [string]$BadAstFile = Join-Path -Path $TestDrive -ChildPath 'BadAst.ps1'; + [string]$AstBody = @( + '<#', + '.PARAMETER Demo', + '| Name | Type | Description | Default |', + '|------|---------------|-------------|---------|', + '| Demo | System.String | First row | $null |', + '| | | Broken row | |', + '', + '.NOTES', + 'SPDX-FileCopyrightText: 2026 Icinga GmbH ', + 'SPDX-License-Identifier: GPL-3.0-or-later', + '#>', + 'enum BadEnum {', + ' First = 1', + '}', + 'class BadClass {', + '}', + 'function Test-BadFunc {', + ' [string]$Marker = ''<# not a real comment'';', + ' [int]$BadAlign = 1;', + ' [hashtable]$Single = @{', + ' ''OnlyKey'' = ''Val'';', + ' };', + ' if (@( 1, 2 ) | Where-Object {', + ' $_ -gt 1;', + ' }) {', + ' return $Single;', + ' }', + ' return $Single;', + '}', + '' + ) -join "`n"; + + [System.IO.File]::WriteAllText($BadAstFile, $AstBody, $script:Utf8NoBom); + [array]$Violations = & $script:StyleScript -ModuleBasePath $TestDrive -Path @( $BadAstFile ) -PassThru; + [string]$Joined = ($Violations -join "`n"); + + $Joined | Should -Match '\.PARAMETER table "\|" pipes'; + $Joined | Should -Match '"enum BadEnum"'; + $Joined | Should -Match '"class BadClass"'; + $Joined | Should -Match 'Function declaration must use "function Name\(\)"'; + $Joined | Should -Match '"if/elseif" condition must be on a single line'; + $Joined | Should -Match 'Single-entry hashtable'; + $Joined | Should -Match 'Assignment "=" alignment'; + } + } +} diff --git a/Tests/ConvertFrom-IcingaProtocolMacros.Tests.ps1 b/Tests/ConvertFrom-IcingaProtocolMacros.Tests.ps1 index 13560f1..2d51552 100644 --- a/Tests/ConvertFrom-IcingaProtocolMacros.Tests.ps1 +++ b/Tests/ConvertFrom-IcingaProtocolMacros.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for ConvertFrom-IcingaProtocolMacros in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for ConvertFrom-IcingaProtocolMacros +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..') -ChildPath 'IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/ConvertFrom-ModuleBoolean.Tests.ps1 b/Tests/ConvertFrom-ModuleBoolean.Tests.ps1 index 198b5b5..529ea2a 100644 --- a/Tests/ConvertFrom-ModuleBoolean.Tests.ps1 +++ b/Tests/ConvertFrom-ModuleBoolean.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for ConvertFrom-ModuleBoolean in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for ConvertFrom-ModuleBoolean +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..') -ChildPath 'IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/ConvertTo-IcingaSortedArray.Tests.ps1 b/Tests/ConvertTo-IcingaSortedArray.Tests.ps1 index 383908f..ddf2609 100644 --- a/Tests/ConvertTo-IcingaSortedArray.Tests.ps1 +++ b/Tests/ConvertTo-IcingaSortedArray.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for ConvertTo-IcingaSortedArray in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for ConvertTo-IcingaSortedArray +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/ConvertTo-IcingaUnit.Tests.ps1 b/Tests/ConvertTo-IcingaUnit.Tests.ps1 index 98c3a57..332f0f0 100644 --- a/Tests/ConvertTo-IcingaUnit.Tests.ps1 +++ b/Tests/ConvertTo-IcingaUnit.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for ConvertTo-IcingaUnit in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for ConvertTo-IcingaUnit +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/ConvertTo-ModuleSecureString.Tests.ps1 b/Tests/ConvertTo-ModuleSecureString.Tests.ps1 index 79da5b5..58d2fee 100644 --- a/Tests/ConvertTo-ModuleSecureString.Tests.ps1 +++ b/Tests/ConvertTo-ModuleSecureString.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for ConvertTo-ModuleSecureString in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for ConvertTo-ModuleSecureString +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..') -ChildPath 'IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/Get-IcingaDirectoryInformation.Tests.ps1 b/Tests/Get-IcingaDirectoryInformation.Tests.ps1 index 315729b..4b33511 100644 --- a/Tests/Get-IcingaDirectoryInformation.Tests.ps1 +++ b/Tests/Get-IcingaDirectoryInformation.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for Get-IcingaDirectoryInformation in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for Get-IcingaDirectoryInformation +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/Get-IcingaDiskInformation.Tests.ps1 b/Tests/Get-IcingaDiskInformation.Tests.ps1 index b8a9ab1..f84419f 100644 --- a/Tests/Get-IcingaDiskInformation.Tests.ps1 +++ b/Tests/Get-IcingaDiskInformation.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for Get-IcingaDiskInformation in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for Get-IcingaDiskInformation +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/Get-IcingaPerformanceCounter.Tests.ps1 b/Tests/Get-IcingaPerformanceCounter.Tests.ps1 index 5390d50..b7cc55c 100644 --- a/Tests/Get-IcingaPerformanceCounter.Tests.ps1 +++ b/Tests/Get-IcingaPerformanceCounter.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for Get-IcingaPerformanceCounter in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for Get-IcingaPerformanceCounter +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/Get-IcingaProcessInformation.Tests.ps1 b/Tests/Get-IcingaProcessInformation.Tests.ps1 index 7d03b28..73a1980 100644 --- a/Tests/Get-IcingaProcessInformation.Tests.ps1 +++ b/Tests/Get-IcingaProcessInformation.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for Get-IcingaProcessInformation in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for Get-IcingaProcessInformation +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/Get-IcingaScheduledTask.Tests.ps1 b/Tests/Get-IcingaScheduledTask.Tests.ps1 index f0cae5d..3608a1e 100644 --- a/Tests/Get-IcingaScheduledTask.Tests.ps1 +++ b/Tests/Get-IcingaScheduledTask.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for Get-IcingaScheduledTask in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for Get-IcingaScheduledTask +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/Get-IcingaWindowsInformation.Tests.ps1 b/Tests/Get-IcingaWindowsInformation.Tests.ps1 index c6d9919..911a35c 100644 --- a/Tests/Get-IcingaWindowsInformation.Tests.ps1 +++ b/Tests/Get-IcingaWindowsInformation.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for Get-IcingaWindowsInformation in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for Get-IcingaWindowsInformation +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/IcingaError.Tests.ps1 b/Tests/IcingaError.Tests.ps1 index 5c20fbc..7a87795 100644 --- a/Tests/IcingaError.Tests.ps1 +++ b/Tests/IcingaError.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for IcingaError in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for IcingaError +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/IcingaPlugin.Tests.ps1 b/Tests/IcingaPlugin.Tests.ps1 index 8d2c0b0..798e69a 100644 --- a/Tests/IcingaPlugin.Tests.ps1 +++ b/Tests/IcingaPlugin.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for IcingaPlugin in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for IcingaPlugin +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/IcingaScheduledTaskStatus.Tests.ps1 b/Tests/IcingaScheduledTaskStatus.Tests.ps1 index ac0b29a..e1fb471 100644 --- a/Tests/IcingaScheduledTaskStatus.Tests.ps1 +++ b/Tests/IcingaScheduledTaskStatus.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for IcingaScheduledTaskStatus in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for IcingaScheduledTaskStatus +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/IcingaServiceStartupType.Tests.ps1 b/Tests/IcingaServiceStartupType.Tests.ps1 index a5f1a14..e1a1df1 100644 --- a/Tests/IcingaServiceStartupType.Tests.ps1 +++ b/Tests/IcingaServiceStartupType.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for IcingaServiceStartupType in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for IcingaServiceStartupType +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/IcingaServiceStatus.Tests.ps1 b/Tests/IcingaServiceStatus.Tests.ps1 index d5d560b..4f1cc70 100644 --- a/Tests/IcingaServiceStatus.Tests.ps1 +++ b/Tests/IcingaServiceStatus.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for IcingaServiceStatus in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for IcingaServiceStatus +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/IcingaThresholds.Tests.ps1 b/Tests/IcingaThresholds.Tests.ps1 index df1942e..b6ff305 100644 --- a/Tests/IcingaThresholds.Tests.ps1 +++ b/Tests/IcingaThresholds.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for IcingaThresholds in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for IcingaThresholds +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; @@ -13,7 +27,8 @@ Describe 'IcingaThresholds' { Where-Object { $_.ModuleType -eq 'Script' } | Select-Object -First 1; - function script:New-Threshold { + function script:New-Threshold() + { param ( [string]$Warning, [string]$Critical, diff --git a/Tests/Invoke-IcingaCheckCPU.Tests.ps1 b/Tests/Invoke-IcingaCheckCPU.Tests.ps1 index 1dc76d4..a5a7420 100644 --- a/Tests/Invoke-IcingaCheckCPU.Tests.ps1 +++ b/Tests/Invoke-IcingaCheckCPU.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for Invoke-IcingaCheckCPU in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for Invoke-IcingaCheckCPU +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/Invoke-IcingaCheckDirectory.Tests.ps1 b/Tests/Invoke-IcingaCheckDirectory.Tests.ps1 index b9e4808..9476ead 100644 --- a/Tests/Invoke-IcingaCheckDirectory.Tests.ps1 +++ b/Tests/Invoke-IcingaCheckDirectory.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for Invoke-IcingaCheckDirectory in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for Invoke-IcingaCheckDirectory +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/Invoke-IcingaCheckMemory.Tests.ps1 b/Tests/Invoke-IcingaCheckMemory.Tests.ps1 index 34ccbc2..f606f32 100644 --- a/Tests/Invoke-IcingaCheckMemory.Tests.ps1 +++ b/Tests/Invoke-IcingaCheckMemory.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for Invoke-IcingaCheckMemory in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for Invoke-IcingaCheckMemory +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/Invoke-IcingaCheckPartitionSpace.Tests.ps1 b/Tests/Invoke-IcingaCheckPartitionSpace.Tests.ps1 index c04afdd..e625012 100644 --- a/Tests/Invoke-IcingaCheckPartitionSpace.Tests.ps1 +++ b/Tests/Invoke-IcingaCheckPartitionSpace.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for Invoke-IcingaCheckPartitionSpace in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for Invoke-IcingaCheckPartitionSpace +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/Invoke-IcingaCheckPerfCounter.Tests.ps1 b/Tests/Invoke-IcingaCheckPerfCounter.Tests.ps1 index 4e17865..1b55f32 100644 --- a/Tests/Invoke-IcingaCheckPerfCounter.Tests.ps1 +++ b/Tests/Invoke-IcingaCheckPerfCounter.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for Invoke-IcingaCheckPerfCounter in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for Invoke-IcingaCheckPerfCounter +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/Invoke-IcingaCheckProcess.Tests.ps1 b/Tests/Invoke-IcingaCheckProcess.Tests.ps1 index 3e331f5..4f5ccd4 100644 --- a/Tests/Invoke-IcingaCheckProcess.Tests.ps1 +++ b/Tests/Invoke-IcingaCheckProcess.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for Invoke-IcingaCheckProcess in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for Invoke-IcingaCheckProcess +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/Invoke-IcingaCheckScheduledTask.Tests.ps1 b/Tests/Invoke-IcingaCheckScheduledTask.Tests.ps1 index fa44c2e..abd92e6 100644 --- a/Tests/Invoke-IcingaCheckScheduledTask.Tests.ps1 +++ b/Tests/Invoke-IcingaCheckScheduledTask.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for Invoke-IcingaCheckScheduledTask in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for Invoke-IcingaCheckScheduledTask +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/Invoke-IcingaCheckService.Tests.ps1 b/Tests/Invoke-IcingaCheckService.Tests.ps1 index 18d4c40..0829737 100644 --- a/Tests/Invoke-IcingaCheckService.Tests.ps1 +++ b/Tests/Invoke-IcingaCheckService.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for Invoke-IcingaCheckService in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for Invoke-IcingaCheckService +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/Invoke-IcingaCheckUptime.Tests.ps1 b/Tests/Invoke-IcingaCheckUptime.Tests.ps1 index 77e465f..c50495b 100644 --- a/Tests/Invoke-IcingaCheckUptime.Tests.ps1 +++ b/Tests/Invoke-IcingaCheckUptime.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for Invoke-IcingaCheckUptime in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for Invoke-IcingaCheckUptime +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/Invoke-IcingaProtocolCheckCommand.Tests.ps1 b/Tests/Invoke-IcingaProtocolCheckCommand.Tests.ps1 index c103ca0..e72060b 100644 --- a/Tests/Invoke-IcingaProtocolCheckCommand.Tests.ps1 +++ b/Tests/Invoke-IcingaProtocolCheckCommand.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for Invoke-IcingaProtocolCheckCommand in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for Invoke-IcingaProtocolCheckCommand +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..') -ChildPath 'IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/Join-WebPath.Tests.ps1 b/Tests/Join-WebPath.Tests.ps1 index 6a71e06..7c0197a 100644 --- a/Tests/Join-WebPath.Tests.ps1 +++ b/Tests/Join-WebPath.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for Join-WebPath in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for Join-WebPath +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/MemoryLeak.Tests.ps1 b/Tests/MemoryLeak.Tests.ps1 index cd31bae..5114de5 100644 --- a/Tests/MemoryLeak.Tests.ps1 +++ b/Tests/MemoryLeak.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for MemoryLeak in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for MemoryLeak +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; @@ -13,7 +27,7 @@ Describe 'Memory Leak Tests for Background Daemons' { $scriptModule = Get-Module -Name 'IcingaForWindows' -All | Where-Object { $_.ModuleType -eq 'Script' } | Select-Object -First 1; - $TestResult = & $scriptModule { + $TestResult = & $scriptModule { # Setup $GlobalVariable = Get-GlobalRuntimeVariable; @@ -144,7 +158,7 @@ Describe 'Memory Leak Tests for Background Daemons' { It 'Should not leak OS handles after processing Icinga Protocol check commands' { $scriptModule = Get-Module -Name 'IcingaForWindows' -All | Where-Object { $_.ModuleType -eq 'Script' } | Select-Object -First 1; - $TestResult = & $scriptModule { + $TestResult = & $scriptModule { # Setup $GlobalVariable = Get-GlobalRuntimeVariable; diff --git a/Tests/ModuleToolsHelpers.Tests.ps1 b/Tests/ModuleToolsHelpers.Tests.ps1 index 47f2fd7..a3e3a26 100644 --- a/Tests/ModuleToolsHelpers.Tests.ps1 +++ b/Tests/ModuleToolsHelpers.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for ModuleToolsHelpers in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for ModuleToolsHelpers +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..') -ChildPath 'IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/New-IcingaPlugin.Tests.ps1 b/Tests/New-IcingaPlugin.Tests.ps1 index 41400e6..d3757af 100644 --- a/Tests/New-IcingaPlugin.Tests.ps1 +++ b/Tests/New-IcingaPlugin.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for New-IcingaPlugin in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for New-IcingaPlugin +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/PerformanceCounter.Tests.ps1 b/Tests/PerformanceCounter.Tests.ps1 index cc0dcb5..ec1fb43 100644 --- a/Tests/PerformanceCounter.Tests.ps1 +++ b/Tests/PerformanceCounter.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for PerformanceCounter in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for PerformanceCounter +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/Resolve-IcingaProtocolCommand.Tests.ps1 b/Tests/Resolve-IcingaProtocolCommand.Tests.ps1 index ac3e83a..f99eb00 100644 --- a/Tests/Resolve-IcingaProtocolCommand.Tests.ps1 +++ b/Tests/Resolve-IcingaProtocolCommand.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for Resolve-IcingaProtocolCommand in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for Resolve-IcingaProtocolCommand +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..') -ChildPath 'IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/Test-IcingaArrayFilter.Tests.ps1 b/Tests/Test-IcingaArrayFilter.Tests.ps1 index 8e9ed6a..66465c7 100644 --- a/Tests/Test-IcingaArrayFilter.Tests.ps1 +++ b/Tests/Test-IcingaArrayFilter.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for Test-IcingaArrayFilter in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for Test-IcingaArrayFilter +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/Tests/Test-IcingaError.Tests.ps1 b/Tests/Test-IcingaError.Tests.ps1 index 9f54a34..27af93a 100644 --- a/Tests/Test-IcingaError.Tests.ps1 +++ b/Tests/Test-IcingaError.Tests.ps1 @@ -1,3 +1,17 @@ +<# +.SYNOPSIS +Pester unit test suite for Test-IcingaError in Icinga for Windows + +.DESCRIPTION +Validates functional behavior, edge cases, and runtime contracts for Test-IcingaError +as part of the Icinga for Windows automated Pester test suite. + +.NOTES +Executed via build/Invoke-ModuleTests.ps1 using Pester 5.0+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> $ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; if (-not (Get-Module -Name 'IcingaForWindows')) { Import-Module -Name $ModulePath -Force -Global; diff --git a/build/Build-ModuleDocs.ps1 b/build/Build-ModuleDocs.ps1 index 71e13eb..5955ebe 100644 --- a/build/Build-ModuleDocs.ps1 +++ b/build/Build-ModuleDocs.ps1 @@ -1,33 +1,35 @@ <# .SYNOPSIS -Generate Markdown API documentation for all Icinga source functions. +Generate Markdown API documentation for all Icinga for Windows source functions .DESCRIPTION -Walks every `*.ps1` file under `src/`, extracts the comment-based help -block that immediately precedes each `function` declaration and emits -one Markdown file per component into `docs/api/`. Also produces an -`index.md` summarising every component and exported function. - -The generator enforces the doc rules defined in `CLAUDE.md`: -- Every public function must have `.SYNOPSIS`, `.DESCRIPTION`, - `.PARAMETER` (one per parameter, Markdown table), `.OUTPUTS`, - `.EXAMPLE`, `.NOTES`. -- Every private function must have at least `.SYNOPSIS` + `.DESCRIPTION`. -- `.PARAMETER` blocks must use the four-column Markdown table format - shown in `CLAUDE.md`. - -When `-Strict` is enabled (default), the generator fails with a non-zero -exit code if any file violates these rules. +Walks every `*.ps1` file under `src/`, extracts the comment-based help block +that immediately precedes each `function` declaration, and emits one Markdown +file per component into `docs/Icinga..md` along with `docs/index.md`. + +The generator enforces the documentation and SPDX rules defined in +`docs/Agents/guidelines/01-Instruction.md`: +- Every public function must have `.SYNOPSIS`, `.DESCRIPTION`, `.PARAMETER` + (one per parameter, four-column Markdown table), `.OUTPUTS`, `.EXAMPLE`, + and `.NOTES`. +- Every private function must have `.SYNOPSIS`, `.DESCRIPTION`, `.PARAMETER` + (for every declared parameter), and `.NOTES`. +- Every function's `.NOTES` block must contain the two Icinga GmbH SPDX lines + (`SPDX-FileCopyrightText` and `SPDX-License-Identifier`), which are stripped + when rendering the human-readable `#### Notes` Markdown section. + +When `-Strict` is enabled (default), the generator fails with a non-zero exit +code if any file violates these rules. .PARAMETER ModuleBasePath -| Name | Type | Description | Default | -|----------------|---------------|--------------------------------------------------------------------|-------------------------------| -| ModuleBasePath | System.String | Absolute path to the Icinga module root (the folder above `src`). | Resolved from the script path | +| Name | Type | Description | Default | +|----------------|---------------|-------------------------------------------------------------------------------|-------------------------------| +| ModuleBasePath | System.String | Absolute path to the Icinga for Windows module root (the folder above `src`). | Resolved from the script path | .PARAMETER OutputPath -| Name | Type | Description | Default | -|------------|---------------|-----------------------------------------------------------|-----------------------------| -| OutputPath | System.String | Directory where the generated Markdown files are written. | `\docs\api` | +| Name | Type | Description | Default | +|------------|---------------|-----------------------------------------------------------|-------------------------| +| OutputPath | System.String | Directory where the generated Markdown files are written. | `\docs` | .PARAMETER IncludePrivate | Name | Type | Description | Default | @@ -46,17 +48,19 @@ System.Int32 -- Number of Markdown files written. Throws on strict violations. .EXAMPLE PS> .\build\Build-ModuleDocs.ps1 -Generates docs/api/*.md for every component, including private helpers. +Generates `docs/Icinga.*.md` and `docs/index.md` for every component, including private helpers. .EXAMPLE PS> .\build\Build-ModuleDocs.ps1 -IncludePrivate:$false -Strict $false -Generate only public API docs, do not fail on missing help sections. +Generates only public API docs without failing on missing help sections. .NOTES -Designed to run on PowerShell 7.5+. Reads source from `src/` and writes -to `docs/api/`. Does NOT modify any `.ps1` source file; if you see -violations, fix the help block in the source file. +Designed for Windows PowerShell 5.1 and PowerShell 7+. Cleans only `Icinga.*.md` +and `index.md` in `OutputPath` so hand-written docs in `docs/` remain untouched. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> [CmdletBinding()] @@ -74,11 +78,15 @@ $ProgressPreference = 'SilentlyContinue'; # Path resolution # --------------------------------------------------------------------------- if ([string]::IsNullOrEmpty($ModuleBasePath)) { - $ModuleBasePath = Resolve-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..') | Select-Object -ExpandProperty Path; + $ModuleBasePath = [System.IO.Path]::GetFullPath((Resolve-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..')).ProviderPath); +} elseif (Test-Path -Path $ModuleBasePath) { + $ModuleBasePath = [System.IO.Path]::GetFullPath((Resolve-Path -Path $ModuleBasePath).ProviderPath); } if ([string]::IsNullOrEmpty($OutputPath)) { - $OutputPath = Join-Path -Path $ModuleBasePath -ChildPath 'docs\'; + $OutputPath = Join-Path -Path $ModuleBasePath -ChildPath 'docs'; +} elseif (Test-Path -Path $OutputPath) { + $OutputPath = [System.IO.Path]::GetFullPath((Resolve-Path -Path $OutputPath).ProviderPath); } $SourcePath = Join-Path -Path $ModuleBasePath -ChildPath 'src'; @@ -94,28 +102,31 @@ function Read-IcingaHelpBlock() { <# .SYNOPSIS - Extract the comment-based help block and function name from a .ps1 file. + Extract the comment-based help block and function name from a .ps1 file .DESCRIPTION Reads the file, locates the comment-based help block that immediately - precedes the first `function` declaration and returns a parsed object + precedes the first `function` declaration, and returns a parsed object with every help section split out. If no help block is present, returns `$null` for the `Help` property so the caller can report it. .PARAMETER Path - | Name | Type | Description | Default | - |------|---------------|-------------------------------------------|---------| - | Path | System.String | Absolute path to a Icinga `.ps1` source. | | + | Name | Type | Description | Default | + |------|---------------|-----------------------------------------------------|---------| + | Path | System.String | Absolute path to an Icinga for Windows `.ps1` file. | | .OUTPUTS System.Collections.Hashtable -- Parsed structure with keys: - Visibility, FunctionName, Synopsis, Description, Parameters, Outputs, Example, Notes. + Visibility, FunctionName, Synopsis, Description, Parameters, Outputs, Examples, Notes. .EXAMPLE PS> Read-IcingaHelpBlock -Path '.\src\Core\Logging\Public\Set-IcingaLogLevel.ps1' .NOTES Pure parser -- does not import or execute the source file. + + SPDX-FileCopyrightText: 2026 Icinga GmbH + SPDX-License-Identifier: GPL-3.0-or-later #> [CmdletBinding()] param ( @@ -123,10 +134,10 @@ function Read-IcingaHelpBlock() [string]$Path ); - $Content = Get-Content -Path $Path -Raw -Encoding UTF8; + $Content = Get-Content -Path $Path -Raw -Encoding UTF8; # Find all comment-based help blocks in the file. - $HelpBlocks = [regex]::Matches($Content, '(?s)<#(.*?)#>'); + $HelpBlocks = [regex]::Matches($Content, '(?s)<#(.*?)#>'); # Build a set of [start, end] ranges covered by comment blocks so the # function-declaration search can skip them. Prose like "the function @@ -134,7 +145,7 @@ function Read-IcingaHelpBlock() # real declaration. $CommentRanges = New-Object System.Collections.ArrayList; foreach ($block in $HelpBlocks) { - [void]$CommentRanges.Add(@{ Start = $block.Index; End = $block.Index + $block.Length }); + [void]$CommentRanges.Add(@{ Start = $block.Index; End = ($block.Index + $block.Length) }); } # Walk every `function NAME` match and accept the first one that does @@ -158,13 +169,17 @@ function Read-IcingaHelpBlock() if ($null -eq $FuncMatch) { return $null; } - $FunctionName = $FuncMatch.Groups[1].Value -replace '^Global:', ''; - # Determine visibility from path - $Visibility = if ($Path -match '[\\/]Public[\\/]') { 'Public' } elseif ($Path -match '[\\/]Private[\\/]') { 'Private' } else { 'Unknown' }; + $FunctionName = $FuncMatch.Groups[1].Value -replace '^Global:', ''; + $Visibility = 'Unknown'; + if ($Path -match '[\\/]Public[\\/]') { + $Visibility = 'Public'; + } elseif ($Path -match '[\\/]Private[\\/]') { + $Visibility = 'Private'; + } # Pick the last help block that ends before the function declaration - $HelpMatch = $null; + $HelpMatch = $null; foreach ($block in $HelpBlocks) { if (($block.Index + $block.Length) -le $FuncMatch.Index) { $HelpMatch = $block; @@ -203,12 +218,27 @@ function Read-IcingaHelpBlock() $Body = $Match.Groups[2].Value.Trim(); switch ($Name) { - 'SYNOPSIS' { $HelpSections.Synopsis = $Body; break; } - 'DESCRIPTION' { $HelpSections.Description = $Body; break; } - 'OUTPUTS' { $HelpSections.Outputs = $Body; break; } - 'NOTES' { $HelpSections.Notes = $Body; break; } - 'EXAMPLE' { $HelpSections.Examples += $Body; break; } - 'PARAMETER' { + 'SYNOPSIS' { + $HelpSections.Synopsis = $Body; + break; + } + 'DESCRIPTION' { + $HelpSections.Description = $Body; + break; + } + 'OUTPUTS' { + $HelpSections.Outputs = $Body; + break; + } + 'NOTES' { + $HelpSections.Notes = $Body; + break; + } + 'EXAMPLE' { + $HelpSections.Examples += $Body; + break; + } + 'PARAMETER' { # Body starts with the parameter name, then the table $ParamMatch = [regex]::Match($Body, '^([a-zA-Z0-9_]+)\s*(.*)$', 'Singleline'); if ($ParamMatch.Success) { @@ -218,7 +248,7 @@ function Read-IcingaHelpBlock() }; } break; - }; + } } } } @@ -232,20 +262,20 @@ function Read-IcingaHelpBlock() } # --------------------------------------------------------------------------- -# Validation per CLAUDE.md +# Validation per docs/Agents/guidelines/01-Instruction.md # --------------------------------------------------------------------------- function Test-IcingaHelpCompleteness() { <# .SYNOPSIS - Validate that a parsed help block meets the rules defined in CLAUDE.md. + Validate that a parsed help block meets the repository documentation and SPDX rules .DESCRIPTION - Public functions require all seven sections. Private functions - require at least Synopsis + Description; if they have parameters - declared in the source file, those must also be documented via the - Markdown table form. Returns a list of human-readable violation - strings (empty when the block is valid). + Public functions require all seven sections. Both public and private + functions require `.SYNOPSIS`, `.DESCRIPTION`, `.PARAMETER` tables for + every declared parameter, and `.NOTES` containing the two Icinga GmbH + SPDX license lines. Returns a list of human-readable violation strings + (empty when the block is valid). .PARAMETER ParsedEntry | Name | Type | Description | Default | @@ -261,10 +291,13 @@ function Test-IcingaHelpCompleteness() System.String[] -- Zero or more violation messages. .EXAMPLE - PS> Test-IcingaHelpCompleteness -ParsedEntry $entry -DeclaredParameters @('Name', 'Count') + PS> Test-IcingaHelpCompleteness -ParsedEntry $Entry -DeclaredParameters @( 'Name', 'Count' ) .NOTES - Internal generator helper. Used by the strict-mode validator. + Internal generator helper used by the strict-mode validator. + + SPDX-FileCopyrightText: 2026 Icinga GmbH + SPDX-License-Identifier: GPL-3.0-or-later #> [CmdletBinding()] param ( @@ -277,28 +310,37 @@ function Test-IcingaHelpCompleteness() $Help = $ParsedEntry.Help; if ($null -eq $Help) { - $Violations += "missing comment-based help block"; + $Violations += 'missing comment-based help block'; return $Violations; } # Synopsis + Description are required for ALL functions if ([string]::IsNullOrWhiteSpace($Help.Synopsis)) { - $Violations += "missing .SYNOPSIS"; + $Violations += 'missing .SYNOPSIS'; } if ([string]::IsNullOrWhiteSpace($Help.Description)) { - $Violations += "missing .DESCRIPTION"; + $Violations += 'missing .DESCRIPTION'; } if ($ParsedEntry.Visibility -eq 'Public') { - # Outputs, Example, Notes are required on public functions + # Outputs and Example are required on public functions if ([string]::IsNullOrWhiteSpace($Help.Outputs)) { - $Violations += "missing .OUTPUTS"; + $Violations += 'missing .OUTPUTS'; } if ($Help.Examples.Count -eq 0) { - $Violations += "missing .EXAMPLE"; + $Violations += 'missing .EXAMPLE'; + } + } + + # .NOTES + Icinga GmbH SPDX lines are mandatory on ALL functions (Public and Private) + if ([string]::IsNullOrWhiteSpace($Help.Notes)) { + $Violations += 'missing .NOTES'; + } else { + if ($Help.Notes -notmatch '(?m)^[ \t]*SPDX-FileCopyrightText: 2026 Icinga GmbH [ \t]*\r?$') { + $Violations += 'missing "SPDX-FileCopyrightText: 2026 Icinga GmbH " in .NOTES'; } - if ([string]::IsNullOrWhiteSpace($Help.Notes)) { - $Violations += "missing .NOTES"; + if ($Help.Notes -notmatch '(?m)^[ \t]*SPDX-License-Identifier: GPL-3\.0-or-later[ \t]*\r?$') { + $Violations += 'missing "SPDX-License-Identifier: GPL-3.0-or-later" in .NOTES'; } } @@ -324,17 +366,17 @@ function Get-IcingaDeclaredParameters() { <# .SYNOPSIS - Extract the parameter names from a .ps1 source file's param block. + Extract the parameter names from a .ps1 source file's param block .DESCRIPTION Reads the file, locates the first `param( ... )` block following the - `function` declaration and returns an array of parameter names. Used + `function` declaration, and returns an array of parameter names. Used by the validator to detect undocumented parameters. .PARAMETER Path - | Name | Type | Description | Default | - |------|---------------|-------------------------------------------|---------| - | Path | System.String | Absolute path to a Icinga `.ps1` source. | | + | Name | Type | Description | Default | + |------|---------------|-----------------------------------------------------|---------| + | Path | System.String | Absolute path to an Icinga for Windows `.ps1` file. | | .OUTPUTS System.String[] -- Parameter names (without `$` prefix). @@ -343,8 +385,11 @@ function Get-IcingaDeclaredParameters() PS> Get-IcingaDeclaredParameters -Path '.\src\Core\Logging\Private\Write-LoggingEntry.ps1' .NOTES - Regex-based; does not use AST. Sufficient for the Icinga house - style where params are one-per-line with explicit types. + Regex-based; sufficient for the Icinga for Windows house style where + parameters are declared one per line with explicit type annotations. + + SPDX-FileCopyrightText: 2026 Icinga GmbH + SPDX-License-Identifier: GPL-3.0-or-later #> [CmdletBinding()] param ( @@ -370,12 +415,9 @@ function Get-IcingaDeclaredParameters() $ParamBody = $ParamMatch.Groups[1].Value; - # A parameter declaration in Icinga always has the shape: + # A parameter declaration in Icinga for Windows always has the shape: # [Type]$Name ...optional default # or [Parameter(...)] [ValidateSet(...)] [Type]$Name ... - # The token immediately before $Name is always a closing bracket of an - # attribute or type annotation. Match exactly that to avoid picking up - # $null / $false / $true used as default values. $Names = [regex]::Matches($ParamBody, '\]\s*\$([a-zA-Z_][a-zA-Z0-9_]*)'); return @($Names | ForEach-Object { $_.Groups[1].Value } | Select-Object -Unique); @@ -386,7 +428,7 @@ function Get-IcingaDeclaredParameters() # --------------------------------------------------------------------------- Write-Host '+---------------------------------------------------------------------+' -ForegroundColor Cyan; Write-Host '| |' -ForegroundColor Cyan; -Write-Host '| Icinga Documentation Builder |' -ForegroundColor Cyan; +Write-Host '| Icinga for Windows - Documentation Builder |' -ForegroundColor Cyan; Write-Host '| |' -ForegroundColor Cyan; Write-Host '+---------------------------------------------------------------------+' -ForegroundColor Cyan; Write-Host '' -ForegroundColor White; @@ -448,15 +490,30 @@ Write-Host '' -ForegroundColor White; Write-Host "[3/4] Writing Markdown into $OutputPath ..." -ForegroundColor Yellow; if (Test-Path -Path $OutputPath) { - Remove-Item -Path (Join-Path -Path $OutputPath -ChildPath '*.md') -Force -ErrorAction SilentlyContinue; + Remove-Item -Path (Join-Path -Path $OutputPath -ChildPath 'Icinga.*.md') -Force -ErrorAction SilentlyContinue; + $ExistingIndex = Join-Path -Path $OutputPath -ChildPath 'index.md'; + if (Test-Path -Path $ExistingIndex) { + Remove-Item -Path $ExistingIndex -Force -ErrorAction SilentlyContinue; + } } else { New-Item -Path $OutputPath -ItemType Directory -Force | Out-Null; } +# Compute relative link prefix from OutputPath back to ModuleBasePath (e.g. '../' for '/docs') +[string]$NormalizedOutDir = ([System.IO.Path]::GetFullPath($OutputPath)).TrimEnd('\', '/') + [System.IO.Path]::DirectorySeparatorChar; +[string]$NormalizedBaseDir = ([System.IO.Path]::GetFullPath($ModuleBasePath)).TrimEnd('\', '/') + [System.IO.Path]::DirectorySeparatorChar; +[System.Uri]$OutDirUri = New-Object System.Uri($NormalizedOutDir); +[System.Uri]$BaseDirUri = New-Object System.Uri($NormalizedBaseDir); +[string]$RepoRelativePrefix = [System.Uri]::UnescapeDataString($OutDirUri.MakeRelativeUri($BaseDirUri).ToString()).Replace('\', '/'); + +if ($RepoRelativePrefix.Length -gt 0 -and -not $RepoRelativePrefix.EndsWith('/')) { + $RepoRelativePrefix += '/'; +} + # Group functions by component (relative path under src/, up to and including the subcomponent) $Grouped = $Parsed | Group-Object -Property { - $rel = $_.File.Substring($SourcePath.Length).TrimStart('\', '/'); - $parts = $rel -split '[\\/]'; + $rel = $_.File.Substring($SourcePath.Length).TrimStart('\', '/'); + $parts = $rel -split '[\\/]'; # parts: , , {Public|Private}, .ps1 if ($parts.Count -ge 3) { return ($parts[0..($parts.Count - 3)] -join '.'); @@ -469,7 +526,6 @@ $WrittenFiles = 0; foreach ($group in ($Grouped | Sort-Object Name)) { $componentName = $group.Name; $outFile = Join-Path -Path $OutputPath -ChildPath ("Icinga.$componentName.md"); - [System.Text.StringBuilder]$md = New-Object System.Text.StringBuilder; [void]$md.AppendLine("# Icinga.$componentName"); @@ -478,7 +534,7 @@ foreach ($group in ($Grouped | Sort-Object Name)) { [void]$md.AppendLine('*Auto-generated from `src/' + $srcDir + '/`. Do not edit by hand -- run `build/Build-ModuleDocs.ps1` to regenerate.*'); [void]$md.AppendLine(); - $publicFns = @($group.Group | Where-Object { $_.Visibility -eq 'Public' } | Sort-Object { $_.FunctionName }); + $publicFns = @($group.Group | Where-Object { $_.Visibility -eq 'Public' } | Sort-Object { $_.FunctionName }); $privateFns = @($group.Group | Where-Object { $_.Visibility -eq 'Private' } | Sort-Object { $_.FunctionName }); if ($publicFns.Count -gt 0) { @@ -555,14 +611,17 @@ foreach ($group in ($Grouped | Sort-Object Name)) { } if (-not [string]::IsNullOrWhiteSpace($fn.Help.Notes)) { - [void]$md.AppendLine('#### Notes'); - [void]$md.AppendLine(); - [void]$md.AppendLine($fn.Help.Notes); - [void]$md.AppendLine(); + [string]$CleanNotes = ([regex]::Replace($fn.Help.Notes, '(?m)^[ \t]*SPDX-(?:FileCopyrightText|License-Identifier):[^\r\n]*(?:\r?\n)?', '')).Trim(); + if (-not [string]::IsNullOrWhiteSpace($CleanNotes)) { + [void]$md.AppendLine('#### Notes'); + [void]$md.AppendLine(); + [void]$md.AppendLine($CleanNotes); + [void]$md.AppendLine(); + } } $srcRel = $fn.File.Substring($ModuleBasePath.Length).TrimStart('\', '/').Replace('\', '/'); - [void]$md.AppendLine("*Source: [$srcRel](../../$srcRel)*"); + [void]$md.AppendLine("*Source: [$srcRel]($($RepoRelativePrefix)$srcRel)*"); [void]$md.AppendLine(); } @@ -573,7 +632,7 @@ foreach ($group in ($Grouped | Sort-Object Name)) { # Index file $indexFile = Join-Path -Path $OutputPath -ChildPath 'index.md'; [System.Text.StringBuilder]$idx = New-Object System.Text.StringBuilder; -[void]$idx.AppendLine('# Icinga API Reference'); +[void]$idx.AppendLine('# Icinga for Windows API Reference'); [void]$idx.AppendLine(); [void]$idx.AppendLine('*Auto-generated on ' + (Get-Date -Format 'yyyy-MM-dd HH:mm:ss') + '.*'); [void]$idx.AppendLine(); @@ -581,7 +640,7 @@ $indexFile = Join-Path -Path $OutputPath -ChildPath 'index. [void]$idx.AppendLine('|-----------|------------------|-----------------|'); foreach ($group in ($Grouped | Sort-Object Name)) { - $pubCount = @($group.Group | Where-Object { $_.Visibility -eq 'Public' }).Count; + $pubCount = @($group.Group | Where-Object { $_.Visibility -eq 'Public' }).Count; $prvCount = @($group.Group | Where-Object { $_.Visibility -eq 'Private' }).Count; [void]$idx.AppendLine("| [Icinga.$($group.Name)](Icinga.$($group.Name).md) | $pubCount | $prvCount |"); } @@ -591,7 +650,7 @@ foreach ($group in ($Grouped | Sort-Object Name)) { [void]$idx.AppendLine(); [void]$idx.AppendLine("- Components: $($Grouped.Count)"); [void]$idx.AppendLine("- Documented functions: $($Parsed.Count)"); -[void]$idx.AppendLine("- Public: $($Parsed | Where-Object { $_.Visibility -eq 'Public' } | Measure-Object | Select-Object -ExpandProperty Count)"); +[void]$idx.AppendLine("- Public: $($Parsed | Where-Object { $_.Visibility -eq 'Public' } | Measure-Object | Select-Object -ExpandProperty Count)"); [void]$idx.AppendLine("- Private: $($Parsed | Where-Object { $_.Visibility -eq 'Private' } | Measure-Object | Select-Object -ExpandProperty Count)"); [System.IO.File]::WriteAllText($indexFile, ($idx.ToString() -replace "`r`n", "`n"), (New-Object System.Text.UTF8Encoding($false))); @@ -606,7 +665,7 @@ Write-Host '' -ForegroundColor White; Write-Host '[4/4] Reporting documentation violations ...' -ForegroundColor Yellow; if ($Violations.Count -eq 0) { - Write-Host ' * No violations -- every function meets the CLAUDE.md doc rules' -ForegroundColor Green; + Write-Host ' * No violations -- every function meets the 01-Instruction.md doc and SPDX rules' -ForegroundColor Green; } else { Write-Host " ! $($Violations.Count) violation(s):" -ForegroundColor Yellow; $Violations | @@ -617,7 +676,7 @@ if ($Violations.Count -eq 0) { } $BuildDuration = (Get-Date) - $BuildStartTime; -$DurationText = "{0:N2}s" -f $BuildDuration.TotalSeconds; +$DurationText = '{0:N2}s' -f $BuildDuration.TotalSeconds; Write-Host '' -ForegroundColor White; Write-Host '+---------------------------------------------------------------------+' -ForegroundColor Green; @@ -626,12 +685,12 @@ Write-Host '| * DOCUMENTATION BUILD DONE Write-Host '| |' -ForegroundColor Green; Write-Host '+---------------------------------------------------------------------+' -ForegroundColor Green; Write-Host '' -ForegroundColor White; -Write-Host " Components: $($Grouped.Count)" -ForegroundColor White; -Write-Host " Functions documented: $($Parsed.Count)" -ForegroundColor White; -Write-Host " Markdown files: $WrittenFiles" -ForegroundColor White; -Write-Host " Violations: $($Violations.Count)" -ForegroundColor White; -Write-Host " Build duration: $DurationText" -ForegroundColor White; -Write-Host " Output: $OutputPath" -ForegroundColor Gray; +Write-Host " Components: $($Grouped.Count)" -ForegroundColor White; +Write-Host " Functions documented: $($Parsed.Count)" -ForegroundColor White; +Write-Host " Markdown files: $WrittenFiles" -ForegroundColor White; +Write-Host " Violations: $($Violations.Count)" -ForegroundColor White; +Write-Host " Build duration: $DurationText" -ForegroundColor White; +Write-Host " Output: $OutputPath" -ForegroundColor Gray; Write-Host '' -ForegroundColor White; if ($Strict -and $Violations.Count -gt 0) { diff --git a/build/Build-ModuleProject.ps1 b/build/Build-ModuleProject.ps1 index c7a1d7d..ee9177c 100644 --- a/build/Build-ModuleProject.ps1 +++ b/build/Build-ModuleProject.ps1 @@ -1,28 +1,109 @@ +<# +.SYNOPSIS +Compile the Icinga for Windows module classes and kernel into lib/ + +.DESCRIPTION +Walks `src/` in the Icinga for Windows repository, minifies PowerShell classes, +enums, and private helper functions, preserves public function help blocks, and +writes two UTF-8 without BOM artifacts under `lib/`: +- `lib/IcingaForWindows.Classes.ps1` (loaded per runspace for PS 5.1 isolation) +- `lib/IcingaForWindows.Kernel.ps1` (consolidated private + public functions) + +Both generated artifacts include the Icinga GmbH SPDX license header at the top +of the file. After compilation, the script reloads `IcingaForWindows.psd1` into +the active session and optionally executes Pester tests, API documentation +generation, daemon memory-leak AST analysis, and code-styling validation. + +.PARAMETER BuildModule +| Name | Type | Description | Default | +|-------------|---------------|--------------------------------------------------------|---------| +| BuildModule | System.String | Target module build mode (currently `'core'` only). | 'core' | + +.PARAMETER ModuleBasePath +| Name | Type | Description | Default | +|----------------|---------------|--------------------------------------------------------------------|-------------------------------| +| ModuleBasePath | System.String | Optional explicit path to the Icinga for Windows repository root. | Resolved from the script path | + +.PARAMETER SkipTests +| Name | Type | Description | Default | +|-----------|----------------------------------------------|-----------------------------------------------------------|---------| +| SkipTests | System.Management.Automation.SwitchParameter | When set, skip running Pester tests after compilation. | $false | + +.PARAMETER GenerateDocs +| Name | Type | Description | Default | +|--------------|----------------------------------------------|------------------------------------------------------------------|---------| +| GenerateDocs | System.Management.Automation.SwitchParameter | When set, regenerate `docs/Icinga.*.md` via Build-ModuleDocs. | $false | + +.PARAMETER TestDaemonMemoryLeaks +| Name | Type | Description | Default | +|-----------------------|----------------------------------------------|----------------------------------------------------------------------|---------| +| TestDaemonMemoryLeaks | System.Management.Automation.SwitchParameter | When set, run AST-based daemon loop and IDisposable leak validation. | $false | + +.PARAMETER TestCodeStyling +| Name | Type | Description | Default | +|-----------------|----------------------------------------------|------------------------------------------------------------------------|---------| +| TestCodeStyling | System.Management.Automation.SwitchParameter | When set, run repository-wide code-styling and SPDX header validation. | $false | + +.OUTPUTS +None -- Compiles `lib/IcingaForWindows.{Classes,Kernel}.ps1` and reloads the module. + +.EXAMPLE +PS> .\build\Build-ModuleProject.ps1 -SkipTests -TestDaemonMemoryLeaks + +Compiles `lib/IcingaForWindows.Classes.ps1` and `lib/IcingaForWindows.Kernel.ps1` +without running Pester and validates daemon memory-leak rules. + +.EXAMPLE +PS> .\build\Build-ModuleProject.ps1 -SkipTests -GenerateDocs -TestCodeStyling + +Compiles the module, regenerates API documentation, and validates code styling. + +.NOTES +Designed for Windows PowerShell 5.1 and PowerShell 7+. Writes compiled files +using UTF-8 without BOM (`UTF8Encoding($false)`). + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> + [CmdletBinding()] param ( [string]$BuildModule = 'core', + [string]$ModuleBasePath = '', [switch]$SkipTests = $false, [switch]$GenerateDocs = $false, - [switch]$TestDaemonMemoryLeaks = $false + [switch]$TestDaemonMemoryLeaks = $false, + [switch]$TestCodeStyling = $false ); -$ErrorActionPreference = 'Stop'; -$ProgressPreference = 'SilentlyContinue'; -[string]$ModuleBasePath = ''; +$ErrorActionPreference = 'Stop'; +$ProgressPreference = 'SilentlyContinue'; if ($BuildModule -eq 'core') { - [array]$InstalledModules = Get-Module -ListAvailable -Name 'IcingaForWindows'; - [string]$BuildScriptLocation = Resolve-Path -Path $PSScriptRoot; + if ([string]::IsNullOrEmpty($ModuleBasePath)) { + [array]$InstalledModules = Get-Module -ListAvailable -Name 'IcingaForWindows'; + [string]$BuildScriptLocation = [System.IO.Path]::GetFullPath((Resolve-Path -Path $PSScriptRoot).ProviderPath); + + foreach ($module in $InstalledModules) { + [string]$CandidateBase = [System.IO.Path]::GetFullPath((Resolve-Path -Path $module.ModuleBase).ProviderPath); + if ($BuildScriptLocation.StartsWith($CandidateBase, [System.StringComparison]::OrdinalIgnoreCase)) { + $ModuleBasePath = $CandidateBase; + break; + } + } + } - foreach ($module in $InstalledModules) { - if ($BuildScriptLocation.StartsWith((Resolve-Path -Path $module.ModuleBase))) { - $ModuleBasePath = $module.ModuleBase; - break; + if ([string]::IsNullOrEmpty($ModuleBasePath)) { + [string]$FallbackBase = [System.IO.Path]::GetFullPath((Resolve-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..')).ProviderPath); + if (Test-Path -Path (Join-Path -Path $FallbackBase -ChildPath 'IcingaForWindows.psd1')) { + $ModuleBasePath = $FallbackBase; } + } elseif (Test-Path -Path $ModuleBasePath) { + $ModuleBasePath = [System.IO.Path]::GetFullPath((Resolve-Path -Path $ModuleBasePath).ProviderPath); } if ([string]::IsNullOrEmpty($ModuleBasePath)) { - throw 'Could not determine module base path for Icinga for Icinga for Windows module.'; + throw 'Could not determine module base path for Icinga for Windows module.'; } } else { # TODO: Implement non-core module builds @@ -36,22 +117,8 @@ function Read-IcingaSourceFile() [string]$Path = $null ); - [System.IO.FileStream]$FileStream = [System.IO.File]::Open( - $Path, - [System.IO.FileMode]::Open, - [System.IO.FileAccess]::Read, - [System.IO.FileShare]::Read - ); - - $ReadArray = New-Object Byte[] $FileStream.Length; - $UTF8Encoding = New-Object System.Text.UTF8Encoding $false; - $FileContent = ''; - - while ($FileStream.Read($ReadArray, 0, $ReadArray.Length)) { - $FileContent = [System.String]::Concat($FileContent, $UTF8Encoding.GetString($ReadArray)); - } - - $FileStream.Dispose(); + $UTF8Encoding = New-Object System.Text.UTF8Encoding($false); + [string]$FileContent = [System.IO.File]::ReadAllText($Path, $UTF8Encoding); return $FileContent.TrimStart([char]0xFEFF); } @@ -104,16 +171,8 @@ function Write-IcingaSourceFile() [string]$Value = '' ); - [System.IO.FileStream]$FileStream = [System.IO.File]::Open( - $Path, - [System.IO.FileMode]::Truncate, - [System.IO.FileAccess]::Write, - [System.IO.FileShare]::Read - ); - - $ContentBytes = [System.Text.Encoding]::UTF8.GetBytes($Value); - $FileStream.Write($ContentBytes, 0, $ContentBytes.Length); - $FileStream.Dispose(); + [System.Text.UTF8Encoding]$Utf8NoBom = New-Object System.Text.UTF8Encoding($false); + [System.IO.File]::WriteAllText($Path, $Value, $Utf8NoBom); } function Get-IcingaModuleStructure() @@ -127,21 +186,21 @@ function Get-IcingaModuleStructure() throw 'Module base path must be provided to analyze the module structure.'; } - [hashtable]$ModuleStructure = @{ + [hashtable]$ModuleStructure = @{ 'Classes' = @(); 'Public' = @(); 'Private' = @(); }; - [int]$FileCount = 0; - - $PowerShellSourcePath = Join-Path -Path $ModuleBasePath -ChildPath 'src\'; - [array]$SourceFiles = Get-ChildItem -Path $PowerShellSourcePath -Recurse -Filter '*.ps1'; + [int]$FileCount = 0; + $PowerShellSourcePath = Join-Path -Path $ModuleBasePath -ChildPath 'src'; + [string]$NormalizedSrcPrefix = $PowerShellSourcePath.Replace('/', '\').TrimEnd('\') + '\'; + [array]$SourceFiles = Get-ChildItem -Path $PowerShellSourcePath -Recurse -Filter '*.ps1'; foreach ($sourceFile in $SourceFiles) { $FileCount += 1; # Make sure to convert to a universal path format, allowing both Unix and Windows style paths in the source files [string]$UniversalPath = $sourceFile.FullName.Replace('/', '\'); - $relativePath = $UniversalPath.Substring($PowerShellSourcePath.Length).TrimStart('\'); + $relativePath = $UniversalPath.Substring($NormalizedSrcPrefix.Length).TrimStart('\'); [System.Collections.ArrayList]$CodeStructure = $relativePath.Split('\'); # Classes must be checked first so they are compiled into the kernel @@ -164,15 +223,15 @@ Write-Host "| Icinga for Windows - Module Compiler Write-Host "| |" -ForegroundColor Cyan; Write-Host "+---------------------------------------------------------------------+`n" -ForegroundColor Cyan; -$BuildStartTime = Get-Date +$BuildStartTime = Get-Date; # First we need to analyze the module structure and gather all components -Write-Host "[1/4] Analyzing module structure..." -ForegroundColor Yellow; +Write-Host '[1/4] Analyzing module structure...' -ForegroundColor Yellow; [hashtable]$Components = Get-IcingaModuleStructure -ModuleBasePath $ModuleBasePath; if ($Components.Public.Count -eq 0) { - throw "No components found in $SourcePath" + throw "No components found in $ModuleBasePath"; } Write-Host " * Found $($Components.Public.Count) public function file(s), $($Components.Private.Count) private function file(s) and $($Components.Classes.Count) class file(s)" -ForegroundColor Green; @@ -182,8 +241,8 @@ Write-Host "`n[2/4] Preparing output directory..." -ForegroundColor Yellow; [string]$OutputPath = Join-Path -Path $ModuleBasePath -ChildPath 'lib'; -if (Test-Path $OutputPath) { - Write-Host " Cleaning existing output directory" -ForegroundColor Yellow +if (Test-Path -Path $OutputPath) { + Write-Host ' Cleaning existing output directory' -ForegroundColor Yellow; Remove-Item -Path (Join-Path -Path $OutputPath -ChildPath '*.psm1') -Force -ErrorAction SilentlyContinue; Remove-Item -Path (Join-Path -Path $OutputPath -ChildPath '*.ps1') -Force -ErrorAction SilentlyContinue; } else { @@ -206,7 +265,7 @@ Write-Host "`n[3/4] Building consolidated classes and kernel modules..." -Foregr [string]$ClassesOutput = Join-Path -Path $OutputPath -ChildPath $ClassesModuleName; [System.Text.StringBuilder]$ClassesContent = New-Object System.Text.StringBuilder; -# Add classes header +# Add classes header with Icinga GmbH SPDX license lines inside .NOTES $ClassesContent.AppendLine('<#') | Out-Null; $ClassesContent.AppendLine('.SYNOPSIS') | Out-Null; $ClassesContent.AppendLine(' Icinga for Windows - Classes Module') | Out-Null; @@ -214,7 +273,10 @@ $ClassesContent.AppendLine('.DESCRIPTION') | Out-Null; $ClassesContent.AppendLine(' Single compiled file containing all Icinga for Windows class definitions') | Out-Null; $ClassesContent.AppendLine(" Auto-generated on $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')") | Out-Null; $ClassesContent.AppendLine('.NOTES') | Out-Null; -$ClassesContent.AppendLine(" Source: $ModuleBasePath\src\Classes") | Out-Null; +$ClassesContent.AppendLine(" Source: $(Join-Path -Path $ModuleBasePath -ChildPath (Join-Path -Path 'src' -ChildPath 'Classes'))") | Out-Null; +$ClassesContent.AppendLine() | Out-Null; +$ClassesContent.AppendLine(' SPDX-FileCopyrightText: 2026 Icinga GmbH ') | Out-Null; +$ClassesContent.AppendLine(' SPDX-License-Identifier: GPL-3.0-or-later') | Out-Null; $ClassesContent.AppendLine('#>') | Out-Null; $ClassesContent.AppendLine() | Out-Null; @@ -229,17 +291,16 @@ foreach ($classFile in ($Components['Classes'] | Sort-Object)) { } } -Set-Content -Path $ClassesOutput -Value $ClassesContent.ToString() -Encoding UTF8 -Force; +Write-IcingaSourceFile -Path $ClassesOutput -Value $ClassesContent.ToString(); Write-Host " * Classes file built successfully: $ClassesModuleName" -ForegroundColor Green; # Build single consolidated kernel module file (functions only) [string]$SingleModuleName = 'IcingaForWindows.Kernel.ps1'; [string]$ModuleOutput = Join-Path -Path $OutputPath -ChildPath $SingleModuleName; [hashtable]$FncCache = @{ }; - [System.Text.StringBuilder]$ModuleContent = New-Object System.Text.StringBuilder; -# Add module header +# Add module header with Icinga GmbH SPDX license lines inside .NOTES $ModuleContent.AppendLine('<#') | Out-Null; $ModuleContent.AppendLine('.SYNOPSIS') | Out-Null; $ModuleContent.AppendLine(' Icinga for Windows - Kernel Module') | Out-Null; @@ -247,13 +308,16 @@ $ModuleContent.AppendLine('.DESCRIPTION') | Out-Null; $ModuleContent.AppendLine(' Single compiled kernel file containing all Icinga for Windows private and public functions') | Out-Null; $ModuleContent.AppendLine(" Auto-generated on $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')") | Out-Null; $ModuleContent.AppendLine('.NOTES') | Out-Null; -$ModuleContent.AppendLine(" Source: $ModuleBasePath\src") | Out-Null; +$ModuleContent.AppendLine(" Source: $(Join-Path -Path $ModuleBasePath -ChildPath 'src')") | Out-Null; +$ModuleContent.AppendLine() | Out-Null; +$ModuleContent.AppendLine(' SPDX-FileCopyrightText: 2026 Icinga GmbH ') | Out-Null; +$ModuleContent.AppendLine(' SPDX-License-Identifier: GPL-3.0-or-later') | Out-Null; $ModuleContent.AppendLine('#>') | Out-Null; $ModuleContent.AppendLine() | Out-Null; -# Append all private functions once (stripped of comments for minimal runtime memory) +# Append all private functions once sorted alphabetically (stripped of comments for minimal runtime memory) Write-Host " * Appending $($Components['Private'].Count) private function file(s) (minified)..." -ForegroundColor White; -foreach ($privateFile in $Components['Private']) { +foreach ($privateFile in ($Components['Private'] | Sort-Object)) { $FileContent = Read-IcingaSourceFile -Path $privateFile; $CleanContent = Remove-IcingaComments -Content $FileContent; if (-not [string]::IsNullOrWhiteSpace($CleanContent)) { @@ -262,11 +326,10 @@ foreach ($privateFile in $Components['Private']) { } } -# Append all public functions once +# Append all public functions once sorted alphabetically Write-Host " * Appending $($Components['Public'].Count) public function file(s)..." -ForegroundColor White; -foreach ($publicFile in $Components['Public']) { +foreach ($publicFile in ($Components['Public'] | Sort-Object)) { $FileContent = Read-IcingaSourceFile -Path $publicFile; - $FunctionMatches = [regex]::Matches($FileContent, '(?m)^\s*function\s+([a-zA-Z0-9_-]+)'); foreach ($match in $FunctionMatches) { @@ -302,18 +365,23 @@ for ($i = 0; $i -lt $PublicFunctionList.Count; $i++) { $ModuleContent.AppendLine(');') | Out-Null; -Set-Content -Path $ModuleOutput -Value $ModuleContent.ToString() -Encoding UTF8 -Force; +Write-IcingaSourceFile -Path $ModuleOutput -Value $ModuleContent.ToString(); Write-Host " * Kernel file built successfully: $SingleModuleName" -ForegroundColor Green; Write-Host "`n[4/4] Module manifest..." -ForegroundColor Yellow; -Write-Host " * Using static manifest (IcingaForWindows.psd1)" -ForegroundColor Green; +Write-Host ' * Using static manifest (IcingaForWindows.psd1)' -ForegroundColor Green; + +[string]$ManifestPath = Join-Path -Path $ModuleBasePath -ChildPath 'IcingaForWindows.psd1'; +if (Test-Path -Path $ManifestPath -PathType Leaf) { + [string]$ModuleParent = Split-Path -Path $ModuleBasePath -Parent; + if (-not ($env:PSModulePath -split [System.IO.Path]::PathSeparator | Where-Object { $_ -eq $ModuleParent })) { + $env:PSModulePath = [string]::Concat($ModuleParent, [System.IO.Path]::PathSeparator, $env:PSModulePath); + } -$ManifestFile = Get-ChildItem -Path $ModuleBasePath -Filter '*.psd1' -File | Select-Object -First 1; -if ($null -ne $ManifestFile) { Get-Module -Name 'IcingaForWindows' | Remove-Module -Force -ErrorAction SilentlyContinue; - Import-Module -Name $ManifestFile.FullName -Force -Global; - Write-Host " * Module loaded successfully into session" -ForegroundColor Green; + Import-Module -Name $ManifestPath -Force -Global; + Write-Host ' * Module loaded successfully into session' -ForegroundColor Green; } # Final step: Run tests unless skipped @@ -322,21 +390,26 @@ if (-not $SkipTests) { $TestPath = Join-Path -Path $ModuleBasePath -ChildPath 'Tests'; - if (Test-Path $TestPath) { - # Check if Pester is installed - if (-not (Get-Module -ListAvailable -Name Pester)) { - Write-Warning " Pester not installed, skipping tests"; + if (Test-Path -Path $TestPath) { + # Check if Pester 5.0+ is installed (avoid built-in Windows PowerShell Pester 3.4.0) + [array]$Pester5 = @(Get-Module -ListAvailable -Name 'Pester' | Where-Object { $_.Version.Major -ge 5 }); + + if ($Pester5.Count -eq 0) { + Write-Warning ' Pester 5.0+ not installed, skipping tests'; } else { try { - $TestResults = Invoke-Pester -Path $TestPath -PassThru; + Import-Module -Name 'Pester' -MinimumVersion '5.0.0' -Force; + $PesterConfig = New-PesterConfiguration; + $PesterConfig.Run.Path = $TestPath; + $PesterConfig.Run.PassThru = $true; + $TestResults = Invoke-Pester -Configuration $PesterConfig; if ($TestResults.FailedCount -gt 0) { throw "Tests failed! Failed: $($TestResults.FailedCount)"; } - Write-Host " * All tests passed" -ForegroundColor Green; + Write-Host ' * All tests passed' -ForegroundColor Green; Write-Host " Total: $($TestResults.TotalCount), Passed: $($TestResults.PassedCount)" -ForegroundColor Gray; - } catch { Write-Error "Test execution failed: $_"; throw; @@ -360,15 +433,19 @@ if ($TestDaemonMemoryLeaks) { & (Join-Path -Path $PSScriptRoot -ChildPath 'Test-ModuleDaemonMemoryLeak.ps1') -ModuleBasePath $ModuleBasePath; } -# Build process is complete +# Optional: Repository-wide Code Styling and SPDX license check +if ($TestCodeStyling) { + & (Join-Path -Path $PSScriptRoot -ChildPath 'Test-ModuleCodeStyling.ps1') -ModuleBasePath $ModuleBasePath; +} +# Build process is complete $BuildDuration = (Get-Date) - $BuildStartTime; -$DurationText = "{0:N2}s" -f $BuildDuration.TotalSeconds; +$DurationText = '{0:N2}s' -f $BuildDuration.TotalSeconds; Write-Host "`n+---------------------------------------------------------------------+" -ForegroundColor Green; -Write-Host "| |" -ForegroundColor Green; -Write-Host "| * BUILD COMPLETED |" -ForegroundColor Green; -Write-Host "| |" -ForegroundColor Green; +Write-Host '| |' -ForegroundColor Green; +Write-Host '| * BUILD COMPLETED |' -ForegroundColor Green; +Write-Host '| |' -ForegroundColor Green; Write-Host "+---------------------------------------------------------------------+`n" -ForegroundColor Green; Write-Host " Components built: $($Components.Public.Count)" -ForegroundColor White; @@ -378,5 +455,5 @@ Write-Host " Output directory: $OutputPath" -ForegroundColor Gray; Write-Host "`n Next steps:" -ForegroundColor Yellow; Write-Host " 1. Review built modules in: $OutputPath" -ForegroundColor Gray; -Write-Host " 2. Sign modules: .\build\Sign-Module.ps1 -CertificateThumbprint " -ForegroundColor Gray; -Write-Host " 3. Test import: Import-Module .\IcingaForWindows.psd1 -Force" -ForegroundColor Gray; +Write-Host ' 2. Sign modules: .\build\Sign-Module.ps1 -CertificateThumbprint ' -ForegroundColor Gray; +Write-Host ' 3. Test import: Import-Module .\IcingaForWindows.psd1 -Force' -ForegroundColor Gray; diff --git a/build/Invoke-ModuleTests.ps1 b/build/Invoke-ModuleTests.ps1 index a8b04cb..9c5a2d7 100644 --- a/build/Invoke-ModuleTests.ps1 +++ b/build/Invoke-ModuleTests.ps1 @@ -1,6 +1,6 @@ <# .SYNOPSIS -Run the Pester test suite for the Icinga for Windows module. +Run the Pester test suite for the Icinga for Windows module .DESCRIPTION Standalone test runner extracted from the module build so the unit @@ -9,7 +9,7 @@ compile and documentation stages. The script ensures the module's parent directory is on `$env:PSModulePath` (so `Import-Module IcingaForWindows` resolves the checked-out copy), verifies that Pester 5 or newer is available, executes every `*.Tests.ps1` file -under `Tests/` and throws when any test fails so the calling shell +under `Tests/`, and throws when any test fails so the calling shell exits with a non-zero code. The compiled `lib/` artifact and an up-to-date manifest must exist @@ -18,9 +18,9 @@ the build job produces those artifacts; locally run `Build-ModuleProject` first. .PARAMETER ModuleBasePath -| Name | Type | Description | Default | -|----------------|---------------|--------------------------------------------------------------------|-------------------------------| -| ModuleBasePath | System.String | Absolute path to the Icinga module root (the folder above `src`). | Resolved from the script path | +| Name | Type | Description | Default | +|----------------|---------------|-------------------------------------------------------------------------------|-------------------------------| +| ModuleBasePath | System.String | Absolute path to the Icinga for Windows module root (the folder above `src`). | Resolved from the script path | .PARAMETER Path | Name | Type | Description | Default | @@ -42,9 +42,12 @@ PS> .\build\Invoke-ModuleTests.ps1 -Path '.\Tests\Join-WebPath.Tests.ps1' Runs a single test file. .NOTES -Requires Pester 5.0+. Imports the IcingaForWindows module, which -initialises `$Global:IcingaForWindows`. Designed for PowerShell 7.5+ -on Windows. +Requires Pester 5.0+. Imports the `IcingaForWindows` module, which +initializes `$Global:IcingaForWindows`. Designed for PowerShell 5.1+ +and PowerShell 7.5+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> [CmdletBinding()] @@ -57,7 +60,9 @@ $ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue'; if ([string]::IsNullOrEmpty($ModuleBasePath)) { - $ModuleBasePath = Resolve-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..') | Select-Object -ExpandProperty Path; + $ModuleBasePath = [System.IO.Path]::GetFullPath((Resolve-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..')).ProviderPath); +} elseif (Test-Path -Path $ModuleBasePath) { + $ModuleBasePath = [System.IO.Path]::GetFullPath((Resolve-Path -Path $ModuleBasePath).ProviderPath); } if ([string]::IsNullOrEmpty($Path)) { @@ -86,11 +91,11 @@ if (-not ($env:PSModulePath -split [System.IO.Path]::PathSeparator | Where-Objec } Write-Host '' -ForegroundColor White; -Write-Host '╔═════════════════════════════════════════════════════════════════════╗' -ForegroundColor Cyan; -Write-Host '║ ║' -ForegroundColor Cyan; -Write-Host '║ Icinga for Windows - Tests ║' -ForegroundColor Cyan; -Write-Host '║ ║' -ForegroundColor Cyan; -Write-Host '╚═════════════════════════════════════════════════════════════════════╝' -ForegroundColor Cyan; +Write-Host '+---------------------------------------------------------------------+' -ForegroundColor Cyan; +Write-Host '| |' -ForegroundColor Cyan; +Write-Host '| Icinga for Windows - Tests |' -ForegroundColor Cyan; +Write-Host '| |' -ForegroundColor Cyan; +Write-Host '+---------------------------------------------------------------------+' -ForegroundColor Cyan; Write-Host '' -ForegroundColor White; # The suite targets Pester 5+. Importing it explicitly avoids silently @@ -120,9 +125,9 @@ $TestResults = Invoke-Pester -Configuration $Pes Write-Host '' -ForegroundColor White; Write-Host '[2/2] Evaluating results ...' -ForegroundColor Yellow; -Write-Host " Total: $($TestResults.TotalCount)" -ForegroundColor White; -Write-Host " Passed: $($TestResults.PassedCount)" -ForegroundColor Green; -Write-Host " Failed: $($TestResults.FailedCount)" -ForegroundColor Red; +Write-Host " Total: $($TestResults.TotalCount)" -ForegroundColor White; +Write-Host " Passed: $($TestResults.PassedCount)" -ForegroundColor Green; +Write-Host " Failed: $($TestResults.FailedCount)" -ForegroundColor Red; Write-Host " Skipped: $($TestResults.SkippedCount)" -ForegroundColor Gray; if ($TestResults.FailedCount -gt 0) { @@ -131,6 +136,6 @@ if ($TestResults.FailedCount -gt 0) { } Write-Host '' -ForegroundColor White; -Write-Host ' ✓ All tests passed' -ForegroundColor Green; +Write-Host ' * All tests passed' -ForegroundColor Green; Exit-Icinga -ExitCode 0; diff --git a/build/Invoke-ScriptAnalysis.ps1 b/build/Invoke-ScriptAnalysis.ps1 index dbd658a..9e313d2 100644 --- a/build/Invoke-ScriptAnalysis.ps1 +++ b/build/Invoke-ScriptAnalysis.ps1 @@ -1,13 +1,13 @@ <# .SYNOPSIS -Run PSScriptAnalyzer over the Icinga for Windows source tree. +Run PSScriptAnalyzer over the Icinga for Windows source tree .DESCRIPTION -Standalone code-style gate for the CI/CD pipeline. Runs +Standalone static-analysis gate for the CI/CD pipeline. Runs PSScriptAnalyzer recursively over the hand-written parts of the -repository (`src/`, `build/` and the root `IcingaForWindows.psm1`) +repository (`src/`, `build/`, and the root `IcingaForWindows.psm1`) and prints every finding grouped into build-breaking and advisory -buckets. The auto-generated `lib/` and `docs/api/` artifacts are +buckets. The auto-generated `lib/` and `docs/Icinga.*.md` artifacts are intentionally excluded because they are never edited by hand. Which rules run is controlled by `PSScriptAnalyzerSettings.psd1` in @@ -19,29 +19,29 @@ editor integrations. On top of the severity model, a small set of rules is treated as build-breaking regardless of the severity PSScriptAnalyzer assigns, -because they map directly onto mandatory CLAUDE.md house rules +because they map directly onto mandatory `01-Instruction.md` house rules (approved verbs only, no aliases in source). A finding fails the run -when it is one of those rules, when its severity is `Error`, or — -with `-FailOn 'Warning'` — when its severity is `Warning`. Everything +when it is one of those rules, when its severity is `Error`, or -- +with `-FailOn 'Warning'` -- when its severity is `Warning`. Everything else is reported as advisory and does not break the build. .PARAMETER ModuleBasePath -| Name | Type | Description | Default | -|----------------|---------------|-------------------------------------------------------------------|-------------------------------| -| ModuleBasePath | System.String | Absolute path to the Icinga module root (the folder above `src`). | Resolved from the script path | +| Name | Type | Description | Default | +|----------------|---------------|-------------------------------------------------------------------------------|-------------------------------| +| ModuleBasePath | System.String | Absolute path to the Icinga for Windows module root (the folder above `src`). | Resolved from the script path | .PARAMETER SettingsPath -| Name | Type | Description | Default | -|--------------|---------------|--------------------------------------------------------------------------|-----------------------------------------------| -| SettingsPath | System.String | PSScriptAnalyzer settings file to apply. | `\PSScriptAnalyzerSettings.psd1` | +| Name | Type | Description | Default | +|--------------|---------------|------------------------------------------|--------------------------------------------------| +| SettingsPath | System.String | PSScriptAnalyzer settings file to apply. | `\PSScriptAnalyzerSettings.psd1` | .PARAMETER FailOn -| Name | Type | Description | Default | -|--------|---------------|------------------------------------------------------------------------------------------|---------| -| FailOn | System.String | Lowest severity that fails the run. One of `Error` or `Warning`. | Error | +| Name | Type | Description | Default | +|--------|---------------|------------------------------------------------------------------|---------| +| FailOn | System.String | Lowest severity that fails the run. One of `Error` or `Warning`. | Error | .OUTPUTS -System.Object[] — All analyzer findings. Throws when any build-breaking +System.Object[] -- All analyzer findings. Throws when any build-breaking finding is present. .EXAMPLE @@ -58,7 +58,10 @@ Treats warnings as build failures as well. .NOTES Requires the PSScriptAnalyzer module. In CI install it with `Install-Module PSScriptAnalyzer -Force -SkipPublisherCheck`. -Designed for PowerShell 7.5+ on Windows. +Designed for PowerShell 7.5+ on Windows, Linux, and macOS. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> [CmdletBinding()] @@ -73,18 +76,20 @@ $ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue'; # Rules elevated to build-breaking errors. They map directly onto mandatory -# CLAUDE.md house rules and currently have zero violations, so they act as +# 01-Instruction.md house rules and currently have zero violations, so they act as # forward guards without flagging existing code. PSScriptAnalyzer settings # cannot reassign rule severity, which is why this lives here and not in the # settings file. -[string[]]$ErrorRules = @( +[string[]]$ErrorRules = @( 'PSUseApprovedVerbs', 'PSAvoidUsingCmdletAliases', 'PSAvoidTrailingWhitespace' ); if ([string]::IsNullOrEmpty($ModuleBasePath)) { - $ModuleBasePath = Resolve-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..') | Select-Object -ExpandProperty Path; + $ModuleBasePath = [System.IO.Path]::GetFullPath((Resolve-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..')).ProviderPath); +} elseif (Test-Path -Path $ModuleBasePath) { + $ModuleBasePath = [System.IO.Path]::GetFullPath((Resolve-Path -Path $ModuleBasePath).ProviderPath); } if ([string]::IsNullOrEmpty($SettingsPath)) { @@ -98,16 +103,16 @@ if ($null -eq (Get-Module -ListAvailable -Name 'PSScriptAnalyzer')) { Import-Module -Name 'PSScriptAnalyzer' -Force; Write-Host '' -ForegroundColor White; -Write-Host '╔═════════════════════════════════════════════════════════════════════╗' -ForegroundColor Cyan; -Write-Host '║ ║' -ForegroundColor Cyan; -Write-Host '║ Icinga for Windows - Code Style ║' -ForegroundColor Cyan; -Write-Host '║ ║' -ForegroundColor Cyan; -Write-Host '╚═════════════════════════════════════════════════════════════════════╝' -ForegroundColor Cyan; +Write-Host '+---------------------------------------------------------------------+' -ForegroundColor Cyan; +Write-Host '| |' -ForegroundColor Cyan; +Write-Host '| Icinga for Windows - Code Style |' -ForegroundColor Cyan; +Write-Host '| |' -ForegroundColor Cyan; +Write-Host '+---------------------------------------------------------------------+' -ForegroundColor Cyan; Write-Host '' -ForegroundColor White; # Only the hand-written parts of the repository are analysed. lib/ and -# docs/api/ are regenerated by the build and must never be edited by hand. -[array]$AnalysisTargets = @( +# docs/Icinga.*.md are regenerated by the build and must never be edited by hand. +[array]$AnalysisTargets = @( (Join-Path -Path $ModuleBasePath -ChildPath 'src'), (Join-Path -Path $ModuleBasePath -ChildPath 'build'), (Join-Path -Path $ModuleBasePath -ChildPath 'IcingaForWindows.psm1') @@ -119,7 +124,7 @@ if (Test-Path -Path $SettingsPath) { $AnalyzerSplat['Settings'] = $SettingsPath; Write-Host " Using settings: $($SettingsPath.Substring($ModuleBasePath.Length).TrimStart('\', '/'))" -ForegroundColor Gray; } else { - Write-Host " ⚠ Settings file not found, running with default rules: $SettingsPath" -ForegroundColor Yellow; + Write-Host " [WARN] Settings file not found, running with default rules: $SettingsPath" -ForegroundColor Yellow; } [array]$Findings = @(); @@ -132,7 +137,7 @@ foreach ($target in $AnalysisTargets) { continue; } - Write-Host " 🔍 $($target.Substring($ModuleBasePath.Length).TrimStart('\', '/'))" -ForegroundColor White; + Write-Host " * $($target.Substring($ModuleBasePath.Length).TrimStart('\', '/'))" -ForegroundColor White; $Findings += Invoke-ScriptAnalyzer -Path $target @AnalyzerSplat; } @@ -140,7 +145,7 @@ Write-Host '' -ForegroundColor White; Write-Host '[2/2] Evaluating findings ...' -ForegroundColor Yellow; # A finding breaks the build when it is one of the elevated house-rule rules, -# when PSScriptAnalyzer flags it as an Error, or — under -FailOn 'Warning' — +# when PSScriptAnalyzer flags it as an Error, or -- under -FailOn 'Warning' -- # when it is a Warning. Anything else is advisory only. [array]$Blocking = @( $Findings | Where-Object { @@ -178,6 +183,6 @@ if ($Blocking.Count -gt 0) { } Write-Host '' -ForegroundColor White; -Write-Host ' ✓ No build-breaking findings' -ForegroundColor Green; +Write-Host ' * No build-breaking findings' -ForegroundColor Green; return $Findings; diff --git a/build/Test-ModuleChangelog.ps1 b/build/Test-ModuleChangelog.ps1 new file mode 100644 index 0000000..856e875 --- /dev/null +++ b/build/Test-ModuleChangelog.ps1 @@ -0,0 +1,254 @@ +<# +.SYNOPSIS +Validate Changelog.md and Roadmap.md governance and require changelog entries on non-main branches + +.DESCRIPTION +Verifies that `docs/General/Changelog.md` and `docs/General/Roadmap.md` exist, use +UTF-8 without BOM encoding, and conform to the Icinga for Windows governance layout +defined in `docs/Agents/guidelines/01-Instruction.md`. + +Whenever execution is NOT on `main` (any local feature/fix/refactoring branch or any +GitHub Actions `pull_request` workflow), the script compares `docs/General/Changelog.md` +against the merge-base with the target base branch (`origin/$env:GITHUB_BASE_REF` in CI +or `main` locally, including uncommitted working-tree changes) and requires at least one +added changelog bullet (`* ...`). Missing changelog entries fail with a clear error. + +.PARAMETER ModuleBasePath +| Name | Type | Description | Default | +|----------------|---------------|-------------------------------------------------------------------------------|-------------------------------| +| ModuleBasePath | System.String | Absolute path to the Icinga for Windows module root (the folder above `src`). | Resolved from the script path | + +.PARAMETER BaseBranch +| Name | Type | Description | Default | +|------------|---------------|------------------------------------------------------------------------|--------------------------------------------| +| BaseBranch | System.String | Optional explicit Git base ref to compare against when not on `main`. | `origin/$env:GITHUB_BASE_REF` or `main` | + +.PARAMETER CurrentBranch +| Name | Type | Description | Default | +|---------------|---------------|---------------------------------------------------------------------------|--------------------------------------| +| CurrentBranch | System.String | Optional explicit branch name override (used by synthetic Pester tests). | Detected from GitHub CI or `git` | + +.PARAMETER PassThru +| Name | Type | Description | Default | +|----------|----------------------------------------------|---------------------------------------------------------------------|---------| +| PassThru | System.Management.Automation.SwitchParameter | Return the array of violation strings instead of throwing on error. | False | + +.OUTPUTS +System.Object -- Returns `$true` when all governance checks pass (or the array of violation strings when `-PassThru` is set). + +.EXAMPLE +PS> .\build\Test-ModuleChangelog.ps1 + +Validates `docs/General/Changelog.md` and `docs/General/Roadmap.md` and enforces a +changelog entry whenever the active branch is not `main`. + +.NOTES +Requires `git` on `PATH` when evaluating branch diffs. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> + +[CmdletBinding()] +param ( + [string]$ModuleBasePath = $null, + [string]$BaseBranch = $null, + [string]$CurrentBranch = $null, + [switch]$PassThru = $false +); + +$ErrorActionPreference = 'Stop'; +$ProgressPreference = 'SilentlyContinue'; + +if ([string]::IsNullOrEmpty($ModuleBasePath)) { + $ModuleBasePath = [System.IO.Path]::GetFullPath((Resolve-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..')).ProviderPath); +} elseif (Test-Path -Path $ModuleBasePath) { + $ModuleBasePath = [System.IO.Path]::GetFullPath((Resolve-Path -Path $ModuleBasePath).ProviderPath); +} + +function Test-GitRefExists() +{ + param ( + [string]$RepoPath = '', + [string]$RefName = '' + ); + + if ([string]::IsNullOrWhiteSpace($RefName)) { + return $false; + } + + $null = & git -C $RepoPath rev-parse --verify --quiet $RefName; + return ($LASTEXITCODE -eq 0); +} + +function Invoke-IcingaChangelogGovernanceCheck() +{ + param ( + [string]$RepoRoot = '', + [string]$ExplicitBase = '', + [string]$ExplicitBranch = '' + ); + + [array]$Violations = @(); + [string]$GeneralDir = Join-Path -Path $RepoRoot -ChildPath (Join-Path -Path 'docs' -ChildPath 'General'); + [string]$ChangelogRel = 'docs/General/Changelog.md'; + [string]$RoadmapRel = 'docs/General/Roadmap.md'; + [string]$ChangelogAbs = Join-Path -Path $GeneralDir -ChildPath 'Changelog.md'; + [string]$RoadmapAbs = Join-Path -Path $GeneralDir -ChildPath 'Roadmap.md'; + + # 1. Verify docs/General/Changelog.md exists and matches structure + if (-not (Test-Path -Path $ChangelogAbs -PathType Leaf)) { + $Violations += ('Missing required file: {0}' -f $ChangelogRel); + } else { + [byte[]]$ClBytes = [System.IO.File]::ReadAllBytes($ChangelogAbs); + if ($ClBytes.Length -ge 3 -and $ClBytes[0] -eq 0xEF -and $ClBytes[1] -eq 0xBB -and $ClBytes[2] -eq 0xBF) { + $Violations += ('{0}:1 -- File contains a UTF-8 BOM; save as UTF-8 without BOM' -f $ChangelogRel); + } + + [string]$ClContent = [System.IO.File]::ReadAllText($ChangelogAbs, [System.Text.Encoding]::UTF8); + if ($ClContent -notmatch '(?mi)^#\s+Icinga for Windows Changelog\b') { + $Violations += ('{0}:1 -- Missing "# Icinga for Windows Changelog" top-level heading' -f $ChangelogRel); + } + if ($ClContent -notmatch '(?m)^##\s+\d+\.\d+\.\d+') { + $Violations += ('{0} -- Missing "## " version section heading' -f $ChangelogRel); + } + if ($ClContent -notmatch '(?m)^\s*\*\s+\S+') { + $Violations += ('{0} -- Changelog must contain at least one "* " bullet entry' -f $ChangelogRel); + } + } + + # 2. Verify docs/General/Roadmap.md exists and matches structure + if (-not (Test-Path -Path $RoadmapAbs -PathType Leaf)) { + $Violations += ('Missing required file: {0}' -f $RoadmapRel); + } else { + [byte[]]$RmBytes = [System.IO.File]::ReadAllBytes($RoadmapAbs); + if ($RmBytes.Length -ge 3 -and $RmBytes[0] -eq 0xEF -and $RmBytes[1] -eq 0xBB -and $RmBytes[2] -eq 0xBF) { + $Violations += ('{0}:1 -- File contains a UTF-8 BOM; save as UTF-8 without BOM' -f $RoadmapRel); + } + + [string]$RmContent = [System.IO.File]::ReadAllText($RoadmapAbs, [System.Text.Encoding]::UTF8); + if ($RmContent -notmatch '(?mi)^#\s+Icinga for Windows Roadmap\b') { + $Violations += ('{0}:1 -- Missing "# Icinga for Windows Roadmap" top-level heading' -f $RoadmapRel); + } + if ($RmContent -notmatch '(?m)^##\s+Completed') { + $Violations += ('{0} -- Missing "## Completed ..." milestones section' -f $RoadmapRel); + } + if ($RmContent -notmatch '(?m)^##\s+Feature List') { + $Violations += ('{0} -- Missing "## Feature List ..." planned work section' -f $RoadmapRel); + } + } + + if ($Violations.Count -gt 0) { + return $Violations; + } + + # 3. Determine whether current execution is on 'main' or on a PR / feature branch + [bool]$IsOnMain = $false; + + if (-not [string]::IsNullOrWhiteSpace($ExplicitBranch)) { + $IsOnMain = ($ExplicitBranch.Trim() -eq 'main'); + } elseif ($env:GITHUB_EVENT_NAME -eq 'pull_request' -or -not [string]::IsNullOrWhiteSpace($env:GITHUB_BASE_REF)) { + $IsOnMain = $false; + } elseif (-not [string]::IsNullOrWhiteSpace($env:GITHUB_REF_NAME)) { + $IsOnMain = ($env:GITHUB_REF_NAME.Trim() -eq 'main'); + } else { + [string]$GitBranch = ((& git -C $RepoRoot rev-parse --abbrev-ref HEAD) -join '').Trim(); + if ($LASTEXITCODE -ne 0) { + $Violations += 'Unable to determine current Git branch via "git rev-parse --abbrev-ref HEAD".'; + return $Violations; + } + $IsOnMain = ($GitBranch -eq 'main'); + } + + if ($IsOnMain) { + return $Violations; + } + + # 4. Resolve base reference to diff against + [string]$ResolvedBase = ''; + + if (-not [string]::IsNullOrWhiteSpace($ExplicitBase)) { + if (Test-GitRefExists -RepoPath $RepoRoot -RefName $ExplicitBase.Trim()) { + $ResolvedBase = $ExplicitBase.Trim(); + } + } elseif (-not [string]::IsNullOrWhiteSpace($env:GITHUB_BASE_REF)) { + [string]$OriginBase = ('origin/{0}' -f $env:GITHUB_BASE_REF.Trim()); + if (Test-GitRefExists -RepoPath $RepoRoot -RefName $OriginBase) { + $ResolvedBase = $OriginBase; + } elseif (Test-GitRefExists -RepoPath $RepoRoot -RefName $env:GITHUB_BASE_REF.Trim()) { + $ResolvedBase = $env:GITHUB_BASE_REF.Trim(); + } + } else { + if (Test-GitRefExists -RepoPath $RepoRoot -RefName 'main') { + $ResolvedBase = 'main'; + } elseif (Test-GitRefExists -RepoPath $RepoRoot -RefName 'origin/main') { + $ResolvedBase = 'origin/main'; + } + } + + if ([string]::IsNullOrEmpty($ResolvedBase)) { + $Violations += 'Unable to resolve base Git branch ("main" or "origin/main") for changelog comparison. Ensure fetch-depth: 0 in CI.'; + return $Violations; + } + + [string]$MergeBase = ((& git -C $RepoRoot merge-base $ResolvedBase HEAD) -join '').Trim(); + if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrEmpty($MergeBase)) { + $Violations += ('Unable to compute Git merge-base between "{0}" and HEAD for changelog comparison.' -f $ResolvedBase); + return $Violations; + } + + # Check whether docs/General/Changelog.md existed in MergeBase without stderr noise + [string]$TreeHit = ((& git -C $RepoRoot ls-tree -r --name-only $MergeBase -- $ChangelogRel) -join '').Trim(); + [bool]$ExistedInBase = (-not [string]::IsNullOrEmpty($TreeHit)); + [bool]$HasAddedBullet = $false; + + if (-not $ExistedInBase) { + # Brand-new Changelog.md introduced on this branch (tracked or untracked in working tree) + [string]$DiskChangelog = [System.IO.File]::ReadAllText($ChangelogAbs, [System.Text.Encoding]::UTF8); + $HasAddedBullet = ($DiskChangelog -match '(?m)^\s*\*\s+\S+'); + } else { + # Compare MergeBase against working-tree file and require at least one net-new bullet + # so rewording or deleting existing bullets cannot bypass the PR changelog requirement + [array]$DiffLines = @(& git -C $RepoRoot diff --unified=0 $MergeBase -- $ChangelogRel); + [int]$AddedBulletCount = 0; + [int]$RemovedBullets = 0; + + foreach ($DiffLine in $DiffLines) { + [string]$LineStr = [string]$DiffLine; + if ($LineStr.StartsWith('+++') -or $LineStr.StartsWith('---')) { + continue; + } + if ($LineStr -match '^\+\s*\*\s+\S+') { + $AddedBulletCount++; + } elseif ($LineStr -match '^-\s*\*\s+\S+') { + $RemovedBullets++; + } + } + + $HasAddedBullet = ($AddedBulletCount -gt $RemovedBullets); + } + + if (-not $HasAddedBullet) { + $Violations += "Missing changelog entry: Every branch and pull request not on 'main' must add an entry to docs/General/Changelog.md."; + } + + return $Violations; +} + +[array]$AllChangelogViolations = Invoke-IcingaChangelogGovernanceCheck -RepoRoot $ModuleBasePath -ExplicitBase $BaseBranch -ExplicitBranch $CurrentBranch; + +if ($PassThru) { + return $AllChangelogViolations; +} + +Write-Host "`n[+] Running Changelog & Roadmap governance checks..." -ForegroundColor Yellow; + +if ($AllChangelogViolations.Count -gt 0) { + foreach ($Issue in $AllChangelogViolations) { + Write-Host ('[ERROR] {0}' -f $Issue) -ForegroundColor Red; + } + throw ($AllChangelogViolations -join "`n"); +} + +Write-Host ' * Changelog & Roadmap governance checks passed' -ForegroundColor Green; +return $true; diff --git a/build/Test-ModuleCodeStyling.ps1 b/build/Test-ModuleCodeStyling.ps1 new file mode 100644 index 0000000..324b0b4 --- /dev/null +++ b/build/Test-ModuleCodeStyling.ps1 @@ -0,0 +1,1042 @@ +<# +.SYNOPSIS +Validate PowerShell files in Icinga for Windows for code-styling and SPDX license compliance + +.DESCRIPTION +Scans the Icinga for Windows repository (`src/`, `build/`, `IcingaForWindows.psm1`, +`IcingaForWindows.psd1`, `Tests/`, and compiled `lib/` SPDX headers by default, or +explicit `-Path` / `-SourceFolder` targets) and verifies compliance with the binding +rules defined in `docs/Agents/guidelines/01-Instruction.md`: + +1. UTF-8 without BOM encoding (no UTF-8, UTF-16, or UTF-32 BOMs and no NUL bytes). +2. Indentation and whitespace (4 spaces per indentation level, no tab characters, + no trailing whitespace, and a single trailing newline at end of file). +3. Strict 7-bit ASCII characters (`0x00`-`0x7F`) across all BOM-less PowerShell files + (no Unicode em-dashes U+2014, en-dashes U+2013, arrows, box-drawing glyphs, or emojis, + which cause Windows-1252 Mojibake or smart-quote lexer parse errors in Windows PowerShell 5.1). +4. Allman brace style on `function`, `class`, and `enum` declarations, explicit empty + parentheses on function declarations (`function Name()`), and single-line `if`/`elseif` + conditions ending with `{`. +5. Function scope rules: files under `src/` (outside `src/Classes/`) may define at most + one top-level `function` and zero nested functions (`src/Classes/` may not define + standalone functions); helper and nested functions are permitted in `build/`, + `IcingaForWindows.psm1`, and `Tests/`. +6. Vertical alignment of `=` (`+=`, `-=`, `*=`, `/=`) across assignment blocks at the + same indentation depth and across contiguous hashtable/enum key-value entries. +7. Vertical alignment of `|` column pipes across all rows of Markdown `.PARAMETER` + tables inside comment-based help blocks. +8. Mandatory `.NOTES` section concluding with the two Icinga GmbH SPDX lines + (`SPDX-FileCopyrightText` and `SPDX-License-Identifier: GPL-3.0-or-later`) across + `src/`, `build/`, `IcingaForWindows.psm1`, and `Tests/`, `PrivateData.SPDX` + + `GPL-3.0-or-later` in `IcingaForWindows.psd1`, and top-of-file SPDX headers in + compiled `lib/IcingaForWindows.{Classes,Kernel}.ps1` files. + +.PARAMETER ModuleBasePath +| Name | Type | Description | Default | +|----------------|---------------|-------------------------------------------------------------------------------|-------------------------------| +| ModuleBasePath | System.String | Absolute path to the Icinga for Windows module root (the folder above `src`). | Resolved from the script path | + +.PARAMETER SourceFolder +| Name | Type | Description | Default | +|--------------|---------------|--------------------------------------------------------------------------|---------| +| SourceFolder | System.String | Optional single folder override to scan when `-Path` is not provided. | '' | + +.PARAMETER Path +| Name | Type | Description | Default | +|------|--------------|-------------------------------------------------------------------------------|---------| +| Path | System.Array | Optional specific file or directory paths to scan instead of the full module. | @() | + +.PARAMETER PassThru +| Name | Type | Description | Default | +|----------|----------------------------------------------|---------------------------------------------------------------------|---------| +| PassThru | System.Management.Automation.SwitchParameter | Return the array of violation strings instead of throwing on error. | False | + +.OUTPUTS +System.Object -- Returns $true when all checks pass (or the array of violation strings when -PassThru is set). + +.EXAMPLE +PS> .\build\Test-ModuleCodeStyling.ps1 + +Scans `src/`, `build/`, `IcingaForWindows.psm1`, `IcingaForWindows.psd1`, `Tests/`, +and compiled `lib/` SPDX headers, throwing if any violation is found. + +.EXAMPLE +PS> .\build\Test-ModuleCodeStyling.ps1 -Path .\src\Classes\Icinga\IcingaPlugin.ps1, .\IcingaForWindows.psd1 + +Scans only the specified files for code-styling and SPDX compliance. + +.NOTES +Designed for Windows PowerShell 5.1 and PowerShell 7+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> + +[CmdletBinding()] +param ( + [string]$ModuleBasePath = $null, + [string]$SourceFolder = $null, + [array]$Path = @(), + [switch]$PassThru = $false +); + +$ErrorActionPreference = 'Stop'; +$ProgressPreference = 'SilentlyContinue'; + +if ([string]::IsNullOrEmpty($ModuleBasePath)) { + $ModuleBasePath = [System.IO.Path]::GetFullPath((Resolve-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..')).ProviderPath); +} elseif (Test-Path -Path $ModuleBasePath) { + $ModuleBasePath = [System.IO.Path]::GetFullPath((Resolve-Path -Path $ModuleBasePath).ProviderPath); +} + +[bool]$HasExplicitSourceFolder = ($PSBoundParameters.ContainsKey('SourceFolder') -and -not [string]::IsNullOrEmpty($SourceFolder)); + +function Test-AssignmentBlockAlignment() +{ + param ( + [string]$RelativePath = '', + [array]$Block = @() + ); + + [array]$BlockViolations = @(); + + if ($null -eq $Block -or $Block.Count -eq 0) { + return $BlockViolations; + } + + [int]$ExpectedEqCol = 0; + + foreach ($Item in $Block) { + [int]$CandidateCol = $Item.LhsEnd + $Item.Op.Length; + if ($CandidateCol -gt $ExpectedEqCol) { + $ExpectedEqCol = $CandidateCol; + } + } + + [bool]$HasMismatch = $false; + + foreach ($Item in $Block) { + if ($Item.EqCol -ne $ExpectedEqCol) { + $HasMismatch = $true; + break; + } + if ($Item.PostSpaces -ne 1 -and -not [string]::IsNullOrWhiteSpace($Item.Rhs)) { + $HasMismatch = $true; + break; + } + } + + if ($HasMismatch) { + [int]$StartLine = $Block[0].Line; + [int]$EndLine = $Block[$Block.Count - 1].Line; + + if ($Block.Count -eq 1) { + $Single = $Block[0]; + $BlockViolations += ('{0}:{1} -- Assignment spacing around "{2}" must have exactly 1 space before (expected "=" at col {3}, found col {4}) and 1 space after: {5}' -f $RelativePath, $Single.Line, $Single.Op, ($ExpectedEqCol + 1), ($Single.EqCol + 1), $Single.Raw.Trim()); + } else { + [array]$Details = @(); + foreach ($Item in $Block) { + $Details += ('L{0}(col {1}, post {2})' -f $Item.Line, ($Item.EqCol + 1), $Item.PostSpaces); + } + $BlockViolations += ('{0}:{1}-{2} -- Assignment "=" alignment or post-"=" spacing mismatch in block (expected col {3} and 1 post-space; found {4})' -f $RelativePath, $StartLine, $EndLine, ($ExpectedEqCol + 1), ($Details -join ', ')); + } + } + + return $BlockViolations; +} + +function Test-KeyValueBlockAlignment() +{ + param ( + [string]$RelativePath = '', + [array]$Block = @(), + [hashtable]$EnumLineNums = @{ } + ); + + [array]$KvViolations = @(); + + if ($null -eq $Block -or $Block.Count -eq 0) { + return $KvViolations; + } + + if ($Block.Count -eq 1) { + $SingleKv = $Block[0]; + if ($EnumLineNums.ContainsKey([int]$SingleKv.Line)) { + [int]$ExpectedEnumEq = $SingleKv.LhsEnd + 1; + if ($SingleKv.EqCol -ne $ExpectedEnumEq -or ($SingleKv.PostSpaces -ne 1 -and -not [string]::IsNullOrWhiteSpace($SingleKv.Rhs))) { + $KvViolations += ('{0}:{1} -- Enum member "=" spacing must have 1 space before and 1 space after "=": {2}' -f $RelativePath, $SingleKv.Line, $SingleKv.Raw.Trim()); + } + } elseif ($SingleKv.PostSpaces -ne 1 -and -not [string]::IsNullOrWhiteSpace($SingleKv.Rhs)) { + $KvViolations += ('{0}:{1} -- Key-value entry must have exactly 1 space after "=": {2}' -f $RelativePath, $SingleKv.Line, $SingleKv.Raw.Trim()); + } + return $KvViolations; + } + + [int]$ExpectedEqCol = 0; + + foreach ($Item in $Block) { + [int]$CandidateCol = $Item.LhsEnd + 1; + if ($CandidateCol -gt $ExpectedEqCol) { + $ExpectedEqCol = $CandidateCol; + } + } + + [bool]$HasMismatch = $false; + + foreach ($Item in $Block) { + if ($Item.EqCol -ne $ExpectedEqCol) { + $HasMismatch = $true; + break; + } + if ($Item.PostSpaces -ne 1 -and -not [string]::IsNullOrWhiteSpace($Item.Rhs)) { + $HasMismatch = $true; + break; + } + } + + if ($HasMismatch) { + [int]$StartLine = $Block[0].Line; + [int]$EndLine = $Block[$Block.Count - 1].Line; + [array]$Details = @(); + + foreach ($Item in $Block) { + $Details += ('L{0}(col {1}, post {2})' -f $Item.Line, ($Item.EqCol + 1), $Item.PostSpaces); + } + + $KvViolations += ('{0}:{1}-{2} -- Hashtable/enum "=" alignment or post-"=" spacing mismatch (expected col {3} and 1 post-space; found {4})' -f $RelativePath, $StartLine, $EndLine, ($ExpectedEqCol + 1), ($Details -join ', ')); + } + + return $KvViolations; +} + +function Get-PipeIndices() +{ + param ( + [string]$Line = '' + ); + + [array]$Indices = @(); + + for ($i = 0; $i -lt $Line.Length; $i++) { + if ($Line[$i] -eq '|') { + $Indices += $i; + } + } + + return ($Indices -join ','); +} + +function Get-TokenDelimiterDelta() +{ + param ( + [array]$LineTokens = @(), + [int]$MinColumn = 1 + ); + + [int]$Delta = 0; + + if ($null -eq $LineTokens) { + return 0; + } + + foreach ($Tok in $LineTokens) { + if ($Tok.Extent.StartColumnNumber -lt $MinColumn) { + continue; + } + + [string]$KindName = [string]$Tok.Kind; + if ($KindName -eq 'LParen' -or $KindName -eq 'AtParen' -or $KindName -eq 'DollarParen' -or $KindName -eq 'LCurly' -or $KindName -eq 'AtCurly') { + $Delta++; + } elseif ($KindName -eq 'RParen' -or $KindName -eq 'RCurly') { + $Delta--; + } + } + + return $Delta; +} + +function Test-BlockCommentNotesAndSpdx() +{ + param ( + [string]$CommentText = '' + ); + + if ([string]::IsNullOrWhiteSpace($CommentText)) { + return 'missing .NOTES section and Icinga GmbH SPDX license lines'; + } + + if ($CommentText -notmatch '(?m)^\s*\.NOTES\b') { + return 'missing mandatory .NOTES section in comment-based help'; + } + + $NotesSplit = [regex]::Split($CommentText, '(?m)^\s*\.NOTES\b'); + [string]$NotesTail = $NotesSplit[$NotesSplit.Count - 1]; + $NotesTail = $NotesTail -replace '\s*#>\z', ''; + # Truncate if another dot-section somehow follows .NOTES + $NextSectionMatch = [regex]::Match($NotesTail, '(?m)^\s*\.[A-Z]{3,}\b'); + if ($NextSectionMatch.Success) { + $NotesTail = $NotesTail.Substring(0, $NextSectionMatch.Index); + } + + [bool]$ConcludesWithSpdx = ($NotesTail -match '(?s)(?:^|\r?\n)[ \t]*SPDX-FileCopyrightText: 2026 Icinga GmbH [ \t]*\r?\n[ \t]*SPDX-License-Identifier: GPL-3\.0-or-later\s*\z'); + + if (-not $ConcludesWithSpdx) { + return '.NOTES must conclude with "SPDX-FileCopyrightText: 2026 Icinga GmbH " followed by "SPDX-License-Identifier: GPL-3.0-or-later"'; + } + + return ''; +} + +function Test-EncodingWithoutBom() +{ + param ( + [string]$RelativePath = '', + [byte[]]$RawBytes = @() + ); + + [array]$EncViolations = @(); + + if ($RawBytes.Length -ge 3 -and $RawBytes[0] -eq 0xEF -and $RawBytes[1] -eq 0xBB -and $RawBytes[2] -eq 0xBF) { + $EncViolations += ('{0}:1 -- File contains a UTF-8 BOM (0xEF 0xBB 0xBF); save as UTF-8 without BOM' -f $RelativePath); + } elseif ($RawBytes.Length -ge 2 -and (($RawBytes[0] -eq 0xFF -and $RawBytes[1] -eq 0xFE) -or ($RawBytes[0] -eq 0xFE -and $RawBytes[1] -eq 0xFF))) { + $EncViolations += ('{0}:1 -- File contains a UTF-16/UTF-32 BOM; save as UTF-8 without BOM' -f $RelativePath); + } elseif ([System.Array]::IndexOf($RawBytes, [byte]0) -ge 0) { + $EncViolations += ('{0}:1 -- File contains NUL bytes (non-UTF-8 encoding); save as UTF-8 without BOM' -f $RelativePath); + } + + return $EncViolations; +} + +function Test-CompiledLibSpdxFile() +{ + param ( + [string]$RelativePath = '', + [string]$FullPath = '' + ); + + [array]$LibViolations = @(); + [byte[]]$RawBytes = [System.IO.File]::ReadAllBytes($FullPath); + $LibViolations += Test-EncodingWithoutBom -RelativePath $RelativePath -RawBytes $RawBytes; + + for ($bIdx = 0; $bIdx -lt $RawBytes.Length; $bIdx++) { + if ($RawBytes[$bIdx] -gt 0x7F) { + $LibViolations += ('{0}:1 -- Compiled lib artifact contains non-ASCII byte 0x{1:X2} at offset {2} (breaks BOM-less Windows-1252 loading in Windows PowerShell 5.1)' -f $RelativePath, $RawBytes[$bIdx], $bIdx); + break; + } + } + + [string]$Content = [System.IO.File]::ReadAllText($FullPath, [System.Text.Encoding]::UTF8); + $LibTokens = $null; + $LibErrors = $null; + [void][System.Management.Automation.Language.Parser]::ParseInput($Content, [ref]$LibTokens, [ref]$LibErrors); + + if ($null -ne $LibErrors -and $LibErrors.Count -gt 0) { + $FirstErr = $LibErrors[0]; + $LibViolations += ('{0}:{1} -- Compiled lib artifact failed PowerShell AST parsing: {2}' -f $RelativePath, $FirstErr.Extent.StartLineNumber, $FirstErr.Message); + } + + $TopHeaderToken = $null; + if ($null -ne $LibTokens) { + foreach ($LibTok in $LibTokens) { + if ([string]$LibTok.Kind -eq 'Comment' -and $LibTok.Text.StartsWith('<#') -and $LibTok.Extent.StartLineNumber -eq 1) { + $TopHeaderToken = $LibTok; + break; + } + } + } + + if ($null -eq $TopHeaderToken) { + $LibViolations += ('{0}:1 -- Compiled lib artifact must start with a top-level <# ... #> header block containing .NOTES and Icinga GmbH SPDX license lines' -f $RelativePath); + } else { + [string]$LibSpdxIssue = Test-BlockCommentNotesAndSpdx -CommentText $TopHeaderToken.Text; + if (-not [string]::IsNullOrEmpty($LibSpdxIssue)) { + $LibViolations += ('{0}:1 -- Compiled lib artifact header block: {1}' -f $RelativePath, $LibSpdxIssue); + } + } + + return $LibViolations; +} + +function Invoke-IcingaCodeStylingCheck() +{ + param ( + [string]$BasePath = '', + [string]$ExplicitSrcRoot = '', + [bool]$UseExplicitSrc = $false, + [array]$TargetPaths = @() + ); + + [array]$FilesToScan = @(); + [array]$LibFilesToScan = @(); + + if ($null -ne $TargetPaths -and $TargetPaths.Count -gt 0) { + foreach ($Target in $TargetPaths) { + [string]$Resolved = [System.IO.Path]::GetFullPath((Resolve-Path -Path $Target).ProviderPath); + if (Test-Path -Path $Resolved -PathType Container) { + $FilesToScan += Get-ChildItem -Path $Resolved -Recurse -Include '*.ps1', '*.psm1', '*.psd1'; + } elseif (Test-Path -Path $Resolved -PathType Leaf) { + [string]$NormTarget = $Resolved.Replace('\', '/'); + if ($NormTarget -match '/lib/IcingaForWindows\.(Classes|Kernel)\.ps1$') { + $LibFilesToScan += Get-Item -Path $Resolved; + } else { + $FilesToScan += Get-Item -Path $Resolved; + } + } + } + } elseif ($UseExplicitSrc) { + if (-not (Test-Path -Path $ExplicitSrcRoot)) { + throw "Source path not found: $ExplicitSrcRoot"; + } + $FilesToScan = Get-ChildItem -Path $ExplicitSrcRoot -Recurse -Include '*.ps1', '*.psm1', '*.psd1'; + } else { + # Full repository governance scope: src/, build/, Tests/, root *.ps1/*.psm1/*.psd1, and compiled lib/ headers + [array]$DefaultDirs = @( + (Join-Path -Path $BasePath -ChildPath 'src'), + (Join-Path -Path $BasePath -ChildPath 'build'), + (Join-Path -Path $BasePath -ChildPath 'Tests') + ); + + foreach ($Dir in $DefaultDirs) { + if (Test-Path -Path $Dir -PathType Container) { + $FilesToScan += Get-ChildItem -Path $Dir -Recurse -Include '*.ps1', '*.psm1', '*.psd1'; + } + } + + if (Test-Path -Path $BasePath -PathType Container) { + $FilesToScan += Get-ChildItem -Path $BasePath -File | Where-Object { $_.Extension -in @( '.ps1', '.psm1', '.psd1' ) }; + } + + [string]$LibDir = Join-Path -Path $BasePath -ChildPath 'lib'; + if (Test-Path -Path $LibDir -PathType Container) { + foreach ($CompiledName in @( 'IcingaForWindows.Classes.ps1', 'IcingaForWindows.Kernel.ps1' )) { + [string]$CompiledPath = Join-Path -Path $LibDir -ChildPath $CompiledName; + if (Test-Path -Path $CompiledPath -PathType Leaf) { + $LibFilesToScan += Get-Item -Path $CompiledPath; + } + } + } + } + + [array]$Violations = @(); + [string]$AssignPattern = '^(\s*)((?:(?:static|hidden)\s+)*(?:\[[A-Za-z0-9_.,\s\[\]]+\])?\s*(?:\$[A-Za-z0-9_:.]+(?:\[[^\]]+\]|\.[A-Za-z0-9_]+)*|\[[A-Za-z0-9_.]+\]::[A-Za-z0-9_]+))(\s*)((?:\+|-|\*|/)?=)(\s*)(.+)$'; + [string]$KvPattern = '^(\s*)([A-Za-z0-9_]+|''[^'']+''|"[^"]+")(\s*)=(\s*)(.+)$'; + + foreach ($LibFile in $LibFilesToScan) { + [string]$LibRelPath = $LibFile.FullName; + if ($LibRelPath.StartsWith($BasePath, [System.StringComparison]::OrdinalIgnoreCase)) { + $LibRelPath = $LibRelPath.Substring($BasePath.Length).TrimStart('\', '/'); + } + $Violations += Test-CompiledLibSpdxFile -RelativePath $LibRelPath -FullPath $LibFile.FullName; + } + + foreach ($File in $FilesToScan) { + [string]$RelPath = $File.FullName; + if ($RelPath.StartsWith($BasePath, [System.StringComparison]::OrdinalIgnoreCase)) { + $RelPath = $RelPath.Substring($BasePath.Length).TrimStart('\', '/'); + } + [string]$NormRelPath = $RelPath.Replace('\', '/'); + [string]$NormFull = $File.FullName.Replace('\', '/'); + + [bool]$IsPsd1File = ($File.Extension -ieq '.psd1'); + [bool]$IsSrcFile = ($NormRelPath -match '^src/' -or $NormFull -match '/src/'); + [bool]$IsClassesFile = ($NormRelPath -match '^src/Classes/' -or $NormFull -match '/src/Classes/'); + + [byte[]]$RawBytes = [System.IO.File]::ReadAllBytes($File.FullName); + + # 1. Check UTF-8 without BOM (reject UTF-8 BOM, UTF-16 LE/BE BOM, UTF-32 BOM and NUL-interleaved encodings) + $Violations += Test-EncodingWithoutBom -RelativePath $RelPath -RawBytes $RawBytes; + + [string]$Content = [System.IO.File]::ReadAllText($File.FullName, [System.Text.Encoding]::UTF8); + [array]$Lines = $Content -split "`r?`n"; + [int]$LineCount = $Lines.Count; + + # 2a. Check single trailing newline at end of file + if ($Content.Length -eq 0 -or -not $Content.EndsWith("`n")) { + $Violations += ('{0}:{1} -- File must end with a single trailing newline' -f $RelPath, [System.Math]::Max(1, $LineCount)); + } elseif ($Content -match '(\r?\n){2}\z') { + $Violations += ('{0}:{1} -- File ends with multiple trailing blank lines; end with a single trailing newline' -f $RelPath, [System.Math]::Max(1, ($LineCount - 1))); + } + + # Strip trailing empty element produced by final newline for line-by-line scan + if ($LineCount -gt 0 -and '' -eq $Lines[$LineCount - 1]) { + $LineCount--; + } + + # Parse PowerShell AST & tokens for comment/string-safe delimiter, block-comment, class/enum and hashtable checks + $Tokens = $null; + $ParseErrors = $null; + $Ast = [System.Management.Automation.Language.Parser]::ParseInput($Content, [ref]$Tokens, [ref]$ParseErrors); + + [hashtable]$BlockCommentLines = @{ }; + [hashtable]$StringInteriorLines = @{ }; + [hashtable]$TokensByLine = @{ }; + [hashtable]$InlineCommentCol = @{ }; + [array]$BlockCommentTokens = @(); + + if ($null -ne $Tokens) { + foreach ($Tok in $Tokens) { + [string]$TokKind = [string]$Tok.Kind; + [int]$TokStartLn = $Tok.Extent.StartLineNumber; + [int]$TokEndLn = $Tok.Extent.EndLineNumber; + + if (-not $TokensByLine.ContainsKey($TokStartLn)) { + $TokensByLine[$TokStartLn] = New-Object System.Collections.ArrayList; + } + [void]$TokensByLine[$TokStartLn].Add($Tok); + + if ($TokKind -eq 'Comment') { + if ($Tok.Text.StartsWith('<#')) { + $BlockCommentTokens += $Tok; + for ($cLn = $TokStartLn; $cLn -le $TokEndLn; $cLn++) { + $BlockCommentLines[$cLn] = $true; + } + } else { + if (-not $InlineCommentCol.ContainsKey($TokStartLn) -or $Tok.Extent.StartColumnNumber -lt $InlineCommentCol[$TokStartLn]) { + $InlineCommentCol[$TokStartLn] = $Tok.Extent.StartColumnNumber; + } + } + } elseif ($TokKind -eq 'StringLiteral' -or $TokKind -eq 'StringExpandable' -or $TokKind -eq 'HereStringLiteral' -or $TokKind -eq 'HereStringExpandable') { + for ($sLn = ($TokStartLn + 1); $sLn -le $TokEndLn; $sLn++) { + $StringInteriorLines[$sLn] = $true; + } + } + } + } + + # 7. Check all rows of Markdown .PARAMETER tables strictly inside AST <# ... #> block comments + foreach ($BlockComment in $BlockCommentTokens) { + [int]$HelpStartIdx = $BlockComment.Extent.StartLineNumber - 1; + [int]$HelpEndIdx = [System.Math]::Min($LineCount, $BlockComment.Extent.EndLineNumber); + + for ($hIdx = $HelpStartIdx; $hIdx -lt $HelpEndIdx; $hIdx++) { + if (($hIdx + 1) -lt $HelpEndIdx -and $Lines[$hIdx] -match '^\s*\|\s*Name\s*\|' -and $Lines[$hIdx + 1] -match '^\s*\|\s*-+\s*\|') { + [string]$ExpectedPipes = Get-PipeIndices -Line $Lines[$hIdx]; + [int]$PipeCount = ($ExpectedPipes -split ',').Count; + [int]$RowCursor = $hIdx + 1; + [bool]$TableMismatch = ($PipeCount -lt 5); + + while ($RowCursor -lt $HelpEndIdx -and $Lines[$RowCursor].TrimStart().StartsWith('|')) { + [string]$RowPipes = Get-PipeIndices -Line $Lines[$RowCursor]; + if ($RowPipes -ne $ExpectedPipes) { + $TableMismatch = $true; + } + $RowCursor++; + } + + [int]$DataRows = $RowCursor - ($hIdx + 2); + if ($DataRows -lt 1 -or $TableMismatch) { + $Violations += ('{0}:{1}-{2} -- Markdown .PARAMETER table "|" pipes must be vertically aligned across header, separator and all value rows' -f $RelPath, ($hIdx + 1), $RowCursor); + } + + $hIdx = $RowCursor - 1; + } + } + } + + # 4a. Check AST class and enum declarations for Allman brace style and record enum member lines + [hashtable]$EnumMemberLines = @{ }; + [array]$TypeDefs = @($Ast.FindAll({ param ($Node) $Node -is [System.Management.Automation.Language.TypeDefinitionAst] }, $true)); + [array]$TopLevelTypeDefs = @(); + + foreach ($TypeDef in $TypeDefs) { + [bool]$HasAncestorType = $false; + $ParentCursor = $TypeDef.Parent; + while ($null -ne $ParentCursor) { + if ($ParentCursor -is [System.Management.Automation.Language.TypeDefinitionAst]) { + $HasAncestorType = $true; + break; + } + $ParentCursor = $ParentCursor.Parent; + } + if (-not $HasAncestorType) { + $TopLevelTypeDefs += $TypeDef; + } + + if ($TypeDef.IsEnum) { + for ($eLn = $TypeDef.Extent.StartLineNumber; $eLn -le $TypeDef.Extent.EndLineNumber; $eLn++) { + $EnumMemberLines[$eLn] = $true; + } + } + + $OpenCurly = $null; + if ($null -ne $Tokens) { + foreach ($CandidateTok in $Tokens) { + if ([string]$CandidateTok.Kind -eq 'LCurly' -and $CandidateTok.Extent.StartOffset -ge $TypeDef.Extent.StartOffset) { + $OpenCurly = $CandidateTok; + break; + } + } + } + + if ($null -ne $OpenCurly) { + [int]$BraceLineIdx = $OpenCurly.Extent.StartLineNumber - 1; + [string]$BraceCode = $Lines[$BraceLineIdx]; + if ($InlineCommentCol.ContainsKey($OpenCurly.Extent.StartLineNumber)) { + $BraceCode = $BraceCode.Substring(0, ($InlineCommentCol[$OpenCurly.Extent.StartLineNumber] - 1)); + } + + if ($OpenCurly.Extent.StartLineNumber -le $TypeDef.Extent.StartLineNumber -or $BraceCode.Trim() -ne '{') { + [string]$KindLabel = 'class'; + if ($TypeDef.IsEnum) { + $KindLabel = 'enum'; + } + $Violations += ('{0}:{1} -- "{2} {3}" declaration must place opening "{{" on its own line (Allman style)' -f $RelPath, $TypeDef.Extent.StartLineNumber, $KindLabel, $TypeDef.Name); + } + } + } + + # 4b & 5. Check AST function/class-method Allman braces and enforce function scope rules in src/ + [array]$FuncDefs = @($Ast.FindAll({ param ($Node) $Node -is [System.Management.Automation.Language.FunctionDefinitionAst] -and -not $Node.IsFilter -and -not $Node.IsWorkflow }, $true)); + [array]$TopStandaloneFns = @(); + [array]$NestedStandalone = @(); + + foreach ($FuncDef in $FuncDefs) { + [bool]$IsClassMethod = ($null -ne $FuncDef.Parent -and $FuncDef.Parent -is [System.Management.Automation.Language.FunctionMemberAst]); + [int]$FuncHeaderLn = $FuncDef.Extent.StartLineNumber; + if ($IsClassMethod) { + $FuncHeaderLn = $FuncDef.Parent.Extent.StartLineNumber; + } else { + [bool]$HasParentFunc = $false; + $FnAncestor = $FuncDef.Parent; + while ($null -ne $FnAncestor) { + if ($FnAncestor -is [System.Management.Automation.Language.FunctionDefinitionAst]) { + $HasParentFunc = $true; + break; + } + $FnAncestor = $FnAncestor.Parent; + } + + if ($HasParentFunc) { + $NestedStandalone += $FuncDef; + } else { + $TopStandaloneFns += $FuncDef; + } + } + + [string]$FuncHdrCode = $Lines[$FuncHeaderLn - 1]; + if ($InlineCommentCol.ContainsKey($FuncHeaderLn)) { + $FuncHdrCode = $FuncHdrCode.Substring(0, ($InlineCommentCol[$FuncHeaderLn] - 1)); + } + + $FuncOpenCurly = $null; + if ($null -ne $Tokens) { + foreach ($CandidateFuncTok in $Tokens) { + if ([string]$CandidateFuncTok.Kind -eq 'LCurly' -and $CandidateFuncTok.Extent.StartOffset -ge $FuncDef.Extent.StartOffset) { + $FuncOpenCurly = $CandidateFuncTok; + break; + } + } + } + + [bool]$ValidFuncBrace = ($null -ne $FuncOpenCurly -and $FuncOpenCurly.Extent.StartLineNumber -gt $FuncHeaderLn); + + if ($ValidFuncBrace) { + [string]$FuncBraceCode = $Lines[$FuncOpenCurly.Extent.StartLineNumber - 1]; + if ($InlineCommentCol.ContainsKey($FuncOpenCurly.Extent.StartLineNumber)) { + $FuncBraceCode = $FuncBraceCode.Substring(0, ($InlineCommentCol[$FuncOpenCurly.Extent.StartLineNumber] - 1)); + } + if ($FuncBraceCode.Trim() -ne '{') { + $ValidFuncBrace = $false; + } + } + + if ($IsClassMethod) { + if (-not $ValidFuncBrace) { + $Violations += ('{0}:{1} -- Class method/constructor declaration must place opening "{{" on its own next line (Allman style): {2}' -f $RelPath, $FuncHeaderLn, $FuncHdrCode.Trim()); + } + } else { + [bool]$ValidFuncHeader = ($FuncHdrCode.Trim() -match '^function\s+(?:[A-Za-z]+:)?[A-Za-z0-9_-]+\(\)\s*$'); + if (-not $ValidFuncHeader -or -not $ValidFuncBrace) { + $Violations += ('{0}:{1} -- Function declaration must use "function Name()" with opening "{{" on its own next line (Allman style): {2}' -f $RelPath, $FuncHeaderLn, $FuncHdrCode.Trim()); + } + } + } + + if ($IsSrcFile) { + if ($IsClassesFile) { + foreach ($ForbiddenFn in ($TopStandaloneFns + $NestedStandalone)) { + $Violations += ('{0}:{1} -- Standalone function "{2}" is forbidden under src/Classes/; define classes and enums only' -f $RelPath, $ForbiddenFn.Extent.StartLineNumber, $ForbiddenFn.Name); + } + } else { + foreach ($ForbiddenType in $TopLevelTypeDefs) { + $Violations += ('{0}:{1} -- Class or enum "{2}" is forbidden outside src/Classes/; move type definitions to src/Classes/' -f $RelPath, $ForbiddenType.Extent.StartLineNumber, $ForbiddenType.Name); + } + if ($TopStandaloneFns.Count -eq 0) { + $Violations += ('{0}:1 -- Source file under src/ (outside src/Classes/) must define a top-level function' -f $RelPath); + } elseif ($TopStandaloneFns.Count -gt 1) { + $Violations += ('{0}:{1} -- Multiple top-level functions ({2}) in a single src/ file are forbidden; place each function in its own .ps1 file' -f $RelPath, $TopStandaloneFns[1].Extent.StartLineNumber, $TopStandaloneFns.Count); + } + foreach ($NestedFn in $NestedStandalone) { + $Violations += ('{0}:{1} -- Nested function "{2}" inside another function is forbidden under src/' -f $RelPath, $NestedFn.Extent.StartLineNumber, $NestedFn.Name); + } + } + } + + # 8. Check mandatory .NOTES and Icinga GmbH SPDX license lines + if ($IsPsd1File) { + if ($Content -match '\bModuleVersion\s*=') { + if ($Content -notmatch 'Copyright\s*=\s*''[^'']*GPL-3\.0-or-later[^'']*''') { + $Violations += ('{0}:1 -- Module manifest Copyright must specify GPL-3.0-or-later matching LICENSE' -f $RelPath); + } + if ($Content -notmatch '(?m)^\s*SPDX\s*=\s*''''\s*;') { + $Violations += ('{0}:1 -- Module manifest PrivateData must include "SPDX = '''';"' -f $RelPath); + } + } + + [bool]$HasPsd1Copy = $false; + [bool]$HasPsd1Lic = $false; + if ($null -ne $Tokens) { + foreach ($PsdTok in $Tokens) { + if ([string]$PsdTok.Kind -eq 'Comment') { + if ($PsdTok.Text -match '^\s*#\s*SPDX-FileCopyrightText: 2026 Icinga GmbH \s*$') { + $HasPsd1Copy = $true; + } elseif ($PsdTok.Text -match '^\s*#\s*SPDX-License-Identifier: GPL-3\.0-or-later\s*$') { + $HasPsd1Lic = $true; + } + } + } + } + if (-not ($HasPsd1Copy -and $HasPsd1Lic)) { + $Violations += ('{0}:1 -- PowerShell data file (.psd1) must include "# SPDX-FileCopyrightText: 2026 Icinga GmbH " and "# SPDX-License-Identifier: GPL-3.0-or-later" comments' -f $RelPath); + } + } elseif ($IsClassesFile) { + if ($TopLevelTypeDefs.Count -eq 0) { + $Violations += ('{0}:1 -- Class/enum file under src/Classes/ must define at least one class or enum with .NOTES and SPDX header' -f $RelPath); + } else { + [int]$PrevTypeEndOffset = 0; + foreach ($TopType in $TopLevelTypeDefs) { + $PrecedingComment = $null; + foreach ($CandComment in $BlockCommentTokens) { + if ($CandComment.Extent.StartOffset -ge $PrevTypeEndOffset -and $CandComment.Extent.EndOffset -le $TopType.Extent.StartOffset) { + $PrecedingComment = $CandComment; + } + } + + if ($null -eq $PrecedingComment) { + $Violations += ('{0}:{1} -- Type "{2}" is missing a preceding <# ... #> help block with .NOTES and Icinga GmbH SPDX lines' -f $RelPath, $TopType.Extent.StartLineNumber, $TopType.Name); + } else { + [string]$SpdxIssue = Test-BlockCommentNotesAndSpdx -CommentText $PrecedingComment.Text; + if (-not [string]::IsNullOrEmpty($SpdxIssue)) { + $Violations += ('{0}:{1} -- Type "{2}" help block: {3}' -f $RelPath, $PrecedingComment.Extent.StartLineNumber, $TopType.Name, $SpdxIssue); + } + } + $PrevTypeEndOffset = $TopType.Extent.EndOffset; + } + } + } elseif ($IsSrcFile) { + if ($TopStandaloneFns.Count -ge 1) { + $PrimaryFn = $TopStandaloneFns[0]; + $FnHelpComment = $null; + foreach ($CandFnComment in $BlockCommentTokens) { + if ($CandFnComment.Extent.EndOffset -le $PrimaryFn.Extent.StartOffset) { + $FnHelpComment = $CandFnComment; + } + } + + if ($null -eq $FnHelpComment) { + $Violations += ('{0}:{1} -- Function "{2}" is missing a preceding <# ... #> help block with .NOTES and Icinga GmbH SPDX lines' -f $RelPath, $PrimaryFn.Extent.StartLineNumber, $PrimaryFn.Name); + } else { + [string]$FnSpdxIssue = Test-BlockCommentNotesAndSpdx -CommentText $FnHelpComment.Text; + if (-not [string]::IsNullOrEmpty($FnSpdxIssue)) { + $Violations += ('{0}:{1} -- Function "{2}" help block: {3}' -f $RelPath, $FnHelpComment.Extent.StartLineNumber, $PrimaryFn.Name, $FnSpdxIssue); + } + } + } + } else { + # build/*.ps1, IcingaForWindows.psm1, Tests/*.ps1, or standalone scripts + [array]$TopLevelHelpBlocks = @($BlockCommentTokens | Where-Object { $_.Extent.StartColumnNumber -eq 1 -and $_.Text -match '(?m)^\s*\.(?:SYNOPSIS|NOTES)\b' }); + [array]$AllDocHelpBlocks = @($BlockCommentTokens | Where-Object { $_.Text -match '(?m)^\s*\.(?:SYNOPSIS|DESCRIPTION|PARAMETER|NOTES)\b' }); + + if ($TopLevelHelpBlocks.Count -eq 0) { + $Violations += ('{0}:1 -- File is missing a top-level <# ... #> help block containing .NOTES and Icinga GmbH SPDX lines' -f $RelPath); + } + foreach ($DocHelpBlock in $AllDocHelpBlocks) { + [string]$HeaderSpdxIssue = Test-BlockCommentNotesAndSpdx -CommentText $DocHelpBlock.Text; + if (-not [string]::IsNullOrEmpty($HeaderSpdxIssue)) { + $Violations += ('{0}:{1} -- Help block: {2}' -f $RelPath, $DocHelpBlock.Extent.StartLineNumber, $HeaderSpdxIssue); + } + } + } + + # 4c. Check AST if / elseif clauses for single-line condition + opening '{' on the same line + [array]$IfAsts = @($Ast.FindAll({ param ($Node) $Node -is [System.Management.Automation.Language.IfStatementAst] }, $true)); + + foreach ($IfAst in $IfAsts) { + foreach ($IfClause in $IfAst.Clauses) { + $ClauseCondAst = $IfClause.Item1; + $ClauseBodyAst = $IfClause.Item2; + [int]$ClauseLn = $ClauseCondAst.Extent.StartLineNumber; + [bool]$SpanCond = ($ClauseCondAst.Extent.StartLineNumber -ne $ClauseCondAst.Extent.EndLineNumber -or $ClauseBodyAst.Extent.StartLineNumber -ne $ClauseLn); + + if ($SpanCond -and $ClauseLn -ge 1 -and $ClauseLn -le $LineCount) { + $Violations += ('{0}:{1} -- "if/elseif" condition must be on a single line ending with "{{" (do not split conditions across lines): {2}' -f $RelPath, $ClauseLn, $Lines[$ClauseLn - 1].Trim()); + } + } + } + + # 6a. Check AST HashtableAst entries for single-entry spacing and post-'=' single space + [array]$HashtableAsts = @($Ast.FindAll({ param ($Node) $Node -is [System.Management.Automation.Language.HashtableAst] }, $true)); + + foreach ($HtAst in $HashtableAsts) { + if ($HtAst.KeyValuePairs.Count -eq 0) { + continue; + } + + if ($HtAst.KeyValuePairs.Count -eq 1) { + $SinglePair = $HtAst.KeyValuePairs[0]; + $SingleKeyAst = $SinglePair.Item1; + $SingleValAst = $SinglePair.Item2; + [int]$SingleKeyLn = $SingleKeyAst.Extent.StartLineNumber; + [string]$KeyLine = $Lines[$SingleKeyLn - 1]; + [int]$KeyEndIdx = $SingleKeyAst.Extent.EndColumnNumber - 1; + [int]$EqPos = $KeyLine.IndexOf('=', $KeyEndIdx); + + if ($EqPos -ge 0) { + [int]$PreEqSpaces = $EqPos - $KeyEndIdx; + [int]$PostEqSpaces = 1; + if ($SingleValAst.Extent.StartLineNumber -eq $SingleKeyLn) { + $PostEqSpaces = ($SingleValAst.Extent.StartColumnNumber - 1) - ($EqPos + 1); + } + + if ($PreEqSpaces -ne 1 -or $PostEqSpaces -ne 1) { + $Violations += ('{0}:{1} -- Single-entry hashtable must have 1 space before and 1 space after "=": {2}' -f $RelPath, $SingleKeyLn, $KeyLine.Trim()); + } + } + } else { + foreach ($MultiPair in $HtAst.KeyValuePairs) { + $MultiKeyAst = $MultiPair.Item1; + $MultiValAst = $MultiPair.Item2; + [int]$MultiKeyLn = $MultiKeyAst.Extent.StartLineNumber; + [string]$MKeyLn = $Lines[$MultiKeyLn - 1]; + [int]$MKeyEndIdx = $MultiKeyAst.Extent.EndColumnNumber - 1; + [int]$MEqPos = $MKeyLn.IndexOf('=', $MKeyEndIdx); + + if ($MEqPos -ge 0) { + [int]$MPreSpaces = $MEqPos - $MKeyEndIdx; + [int]$MPostSpaces = 1; + if ($MultiValAst.Extent.StartLineNumber -eq $MultiKeyLn) { + $MPostSpaces = ($MultiValAst.Extent.StartColumnNumber - 1) - ($MEqPos + 1); + } + + if ($MPreSpaces -lt 1 -or $MPostSpaces -ne 1) { + $Violations += ('{0}:{1} -- Hashtable entry must have at least 1 space before and exactly 1 space after "=": {2}' -f $RelPath, $MultiKeyLn, $MKeyLn.Trim()); + } + } + } + } + } + + [bool]$InMultiline = $false; + [int]$MultilineDepth = 0; + [array]$AssignBlock = @(); + [array]$KvBlock = @(); + + for ($idx = 0; $idx -lt $LineCount; $idx++) { + [int]$LineNumber = $idx + 1; + [string]$Line = $Lines[$idx]; + + # 2b & 3. Check tab characters, trailing whitespace and forbidden em/en-dashes + if ($Line.Contains("`t")) { + $Violations += ('{0}:{1} -- Tab character found; use 4 spaces for indentation' -f $RelPath, $LineNumber); + } + + if ($Line -match '\s+$') { + $Violations += ('{0}:{1} -- Trailing whitespace at end of line' -f $RelPath, $LineNumber); + } + + if ($Line.IndexOf([char]0x2014) -ge 0 -or $Line.IndexOf([char]0x2013) -ge 0) { + $Violations += ('{0}:{1} -- Forbidden Unicode em-dash or en-dash found; use plain ASCII "-" or "--"' -f $RelPath, $LineNumber); + } elseif ($Line -match '[^\x00-\x7F]') { + $NonAsciiMatch = [regex]::Match($Line, '[^\x00-\x7F]'); + [int]$CodePt = [int][char]$Line[$NonAsciiMatch.Index]; + if ([char]::IsSurrogatePair($Line, $NonAsciiMatch.Index)) { + $CodePt = [char]::ConvertToUtf32($Line, $NonAsciiMatch.Index); + } + $Violations += ('{0}:{1} -- Forbidden non-ASCII character U+{2:X4} found in BOM-less PowerShell file (causes Windows-1252 Mojibake or quote-lexer parse errors in Windows PowerShell 5.1); use plain 7-bit ASCII or [char]0xXXXX' -f $RelPath, $LineNumber, $CodePt); + } + + if ($BlockCommentLines.ContainsKey($LineNumber)) { + if ($AssignBlock.Count -gt 0) { + $Violations += Test-AssignmentBlockAlignment -RelativePath $RelPath -Block $AssignBlock; + $AssignBlock = @(); + } + if ($KvBlock.Count -gt 0) { + $Violations += Test-KeyValueBlockAlignment -RelativePath $RelPath -Block $KvBlock -EnumLineNums $EnumMemberLines; + $KvBlock = @(); + } + continue; + } + + if ($StringInteriorLines.ContainsKey($LineNumber)) { + if ($InMultiline) { + [array]$StrLineToks = $TokensByLine[$LineNumber]; + $MultilineDepth += Get-TokenDelimiterDelta -LineTokens $StrLineToks -MinColumn 1; + [string]$StrCode = $Line; + if ($InlineCommentCol.ContainsKey($LineNumber)) { + $StrCode = $StrCode.Substring(0, ($InlineCommentCol[$LineNumber] - 1)); + } + [string]$StrTrimmed = $StrCode.Trim(); + if ($MultilineDepth -le 0 -and ($StrTrimmed.EndsWith(';') -or $StrTrimmed.EndsWith(','))) { + $InMultiline = $false; + $MultilineDepth = 0; + } + } + continue; + } + + [string]$Stripped = $Line.Trim(); + + if ('' -ne $Stripped -and $Line -match '^( +)') { + [int]$LeadingSpaceCount = $Matches[1].Length; + if (($LeadingSpaceCount % 4) -ne 0) { + $Violations += ('{0}:{1} -- Indentation must use multiples of 4 spaces (found {2} leading spaces)' -f $RelPath, $LineNumber, $LeadingSpaceCount); + } + } + + [string]$CodeOnly = $Line; + if ($InlineCommentCol.ContainsKey($LineNumber)) { + $CodeOnly = $Line.Substring(0, ($InlineCommentCol[$LineNumber] - 1)); + } + [string]$CodeStripped = $CodeOnly.Trim(); + + if ('' -eq $CodeStripped -or $CodeStripped -match '^\[Validate[A-Za-z]+\(') { + if ('' -eq $CodeStripped -and $KvBlock.Count -gt 0) { + $Violations += Test-KeyValueBlockAlignment -RelativePath $RelPath -Block $KvBlock -EnumLineNums $EnumMemberLines; + $KvBlock = @(); + } + continue; + } + + # 4c. Check single-line if / elseif conditions (must open '{' on the same line, not wrap across newlines) + if ($CodeStripped -match '^(?:\}\s*)?(?:if|elseif)\s*\(') { + if ($CodeStripped -notmatch '\{\s*$' -and $CodeStripped -notmatch '\}\s*$') { + $Violations += ('{0}:{1} -- "if/elseif" condition must be on a single line ending with "{{" (do not split conditions across lines): {2}' -f $RelPath, $LineNumber, $CodeStripped); + } + } + + # 6b. Check contiguous hashtable / enum key = value blocks + if ($CodeOnly -match $KvPattern -and -not $CodeStripped.StartsWith('$')) { + [string]$KvIndent = $Matches[1]; + [string]$KvKey = $Matches[2]; + [string]$KvPreSpaces = $Matches[3]; + [string]$KvPostSpaces = $Matches[4]; + [string]$KvRhs = $Matches[5]; + [int]$KvLhsEnd = $KvIndent.Length + $KvKey.Length; + [int]$KvEqCol = $KvLhsEnd + $KvPreSpaces.Length; + + if ($KvBlock.Count -gt 0 -and $KvBlock[0].Indent -ne $KvIndent.Length) { + $Violations += Test-KeyValueBlockAlignment -RelativePath $RelPath -Block $KvBlock -EnumLineNums $EnumMemberLines; + $KvBlock = @(); + } + + $KvBlock += [PSCustomObject]@{ + 'Line' = $LineNumber; + 'Indent' = $KvIndent.Length; + 'LhsEnd' = $KvLhsEnd; + 'EqCol' = $KvEqCol; + 'PostSpaces' = $KvPostSpaces.Length; + 'Rhs' = $KvRhs; + 'Raw' = $Line; + }; + } elseif ($KvBlock.Count -gt 0) { + $Violations += Test-KeyValueBlockAlignment -RelativePath $RelPath -Block $KvBlock -EnumLineNums $EnumMemberLines; + $KvBlock = @(); + } + + # 6c. Check variable / property / param assignment alignment across blocks + [array]$CurrentLineTokens = $TokensByLine[$LineNumber]; + + if ($InMultiline) { + $MultilineDepth += Get-TokenDelimiterDelta -LineTokens $CurrentLineTokens -MinColumn 1; + if ($MultilineDepth -le 0 -and ($CodeStripped.EndsWith(';') -or $CodeStripped.EndsWith(','))) { + $InMultiline = $false; + $MultilineDepth = 0; + } + continue; + } + + if ($CodeOnly -match $AssignPattern) { + [string]$IndentStr = $Matches[1]; + [string]$Lhs = $Matches[2]; + [string]$PreSpaces = $Matches[3]; + [string]$Op = $Matches[4]; + [string]$PostSpaces = $Matches[5]; + [string]$Rhs = $Matches[6]; + + if ($AssignBlock.Count -gt 0 -and $AssignBlock[0].Indent -ne $IndentStr.Length) { + $Violations += Test-AssignmentBlockAlignment -RelativePath $RelPath -Block $AssignBlock; + $AssignBlock = @(); + } + + [int]$LhsEnd = $IndentStr.Length + $Lhs.Length; + [int]$EqCol = $LhsEnd + $PreSpaces.Length + ($Op.Length - 1); + + $AssignBlock += [PSCustomObject]@{ + 'Line' = $LineNumber; + 'Indent' = $IndentStr.Length; + 'LhsEnd' = $LhsEnd; + 'Op' = $Op; + 'EqCol' = $EqCol; + 'PostSpaces' = $PostSpaces.Length; + 'Rhs' = $Rhs; + 'Raw' = $Line; + }; + + [int]$NextCheckIdx = $idx + 1; + while ($NextCheckIdx -lt $LineCount) { + [string]$NextCheckCode = $Lines[$NextCheckIdx]; + if ($InlineCommentCol.ContainsKey($NextCheckIdx + 1)) { + $NextCheckCode = $NextCheckCode.Substring(0, ($InlineCommentCol[$NextCheckIdx + 1] - 1)); + } + if ('' -ne $NextCheckCode.Trim()) { + break; + } + $NextCheckIdx++; + } + + [bool]$NextIsParamClose = ($NextCheckIdx -lt $LineCount -and $Lines[$NextCheckIdx].Trim().StartsWith(');')); + [int]$RhsStartCol = $EqCol + 1 + $PostSpaces.Length + 1; + [int]$InitialDepth = Get-TokenDelimiterDelta -LineTokens $CurrentLineTokens -MinColumn $RhsStartCol; + + if ($InitialDepth -gt 0 -or (-not $CodeStripped.EndsWith(';') -and -not $CodeStripped.EndsWith(',') -and -not $NextIsParamClose)) { + $InMultiline = $true; + $MultilineDepth = $InitialDepth; + } + } else { + if ($CodeStripped.Contains('{') -or $CodeStripped.Contains('}') -or $CodeStripped -match '^(if|elseif|else|foreach|for|while|switch|try|catch|finally|param|function|class|enum|return|throw|break|continue)\b') { + if ($AssignBlock.Count -gt 0) { + $Violations += Test-AssignmentBlockAlignment -RelativePath $RelPath -Block $AssignBlock; + $AssignBlock = @(); + } + } + } + } + + if ($AssignBlock.Count -gt 0) { + $Violations += Test-AssignmentBlockAlignment -RelativePath $RelPath -Block $AssignBlock; + } + if ($KvBlock.Count -gt 0) { + $Violations += Test-KeyValueBlockAlignment -RelativePath $RelPath -Block $KvBlock -EnumLineNums $EnumMemberLines; + } + } + + return @($Violations | Select-Object -Unique); +} + +[array]$AllViolations = Invoke-IcingaCodeStylingCheck -BasePath $ModuleBasePath -ExplicitSrcRoot $SourceFolder -UseExplicitSrc $HasExplicitSourceFolder -TargetPaths $Path; + +if ($PassThru) { + return $AllViolations; +} + +Write-Host "`n[+] Running Code Styling & SPDX License tests..." -ForegroundColor Yellow; + +if ($AllViolations.Count -gt 0) { + foreach ($Violation in $AllViolations) { + Write-Host ('[ERROR] {0}' -f $Violation) -ForegroundColor Red; + } + throw ('Code Styling & SPDX License test failed with {0} violation(s).' -f $AllViolations.Count); +} + +Write-Host ' * All Code Styling & SPDX License checks passed' -ForegroundColor Green; +return $true; diff --git a/build/Test-ModuleDaemonMemoryLeak.ps1 b/build/Test-ModuleDaemonMemoryLeak.ps1 index 3d1049f..deca284 100644 --- a/build/Test-ModuleDaemonMemoryLeak.ps1 +++ b/build/Test-ModuleDaemonMemoryLeak.ps1 @@ -1,32 +1,31 @@ <# .SYNOPSIS - Tests background daemons in Icinga for Windows for memory leaks caused by un-nulled local variables inside endless loops, - and ensures that objects implementing IDisposable are properly disposed. +Test background daemons in Icinga for Windows for endless-loop and IDisposable memory leaks .DESCRIPTION - Scans the provided source folder for PowerShell scripts and parses their Abstract Syntax Tree (AST). - It identifies 'while' or 'do-while' loops that run indefinitely (typically checking 'Test-ThreadRunning'). - Inside these loops, it monitors all variable assignments. If a variable is assigned a value but is not - explicitly set to $null anywhere within the same loop (or its finally block), it reports a memory leak. - Native types like [bool], [switch], [int], etc., are exempt because they cannot be set to $null. +Scans the provided source folder for PowerShell scripts and parses their Abstract Syntax Tree (AST). +It identifies 'while' or 'do-while' loops that run indefinitely (typically checking 'Test-ThreadRunning'). +Inside these loops, it monitors all variable assignments. If a variable is assigned a value but is not +explicitly set to `$null` anywhere within the same loop (or its finally block), it reports a memory leak. +Native types like `[bool]`, `[switch]`, `[int]`, etc., are exempt because they cannot be set to `$null`. - Additionally, it tracks assignments of known IDisposable objects (like TcpClient, FileStream, etc.) and - verifies if a corresponding `.Dispose()` method is called on the variable within the loop. - If an IDisposable is passed to another function intentionally, you can suppress the check by adding - `# [IcingaIgnoreDisposeCheck] $VariableName` as a comment inside the loop. +Additionally, it tracks assignments of known IDisposable objects (like TcpClient, FileStream, etc.) and +verifies if a corresponding `.Dispose()` method is called on the variable within the loop. +If an IDisposable is passed to another function intentionally, you can suppress the check by adding +`# [IcingaIgnoreDisposeCheck] $VariableName` as a comment inside the loop. .PARAMETER ModuleBasePath -| Name | Type | Description | Default | -|----------------|---------------|-------------------------------------------------------------------|-------------------------------| -| ModuleBasePath | System.String | Absolute path to the Icinga module root (the folder above `src`). | Resolved from the script path | +| Name | Type | Description | Default | +|----------------|---------------|-------------------------------------------------------------------------------|-------------------------------| +| ModuleBasePath | System.String | Absolute path to the Icinga for Windows module root (the folder above `src`). | Resolved from the script path | .PARAMETER SourceFolder -| Name | Type | Description | Default | -|--------------|---------------|-------------------------------------------------------------------|-------------------------------| -| SourceFolder | System.String | The source folder containing the PowerShell module files to test. | `\src` | +| Name | Type | Description | Default | +|--------------|---------------|-------------------------------------------------------------------|------------------------| +| SourceFolder | System.String | The source folder containing the PowerShell module files to test. | `\src` | .OUTPUTS -System.Boolean — Returns $true if all checks pass. Throws when a memory leak or un-disposed object is detected. +System.Boolean -- Returns $true if all checks pass. Throws when a memory leak or un-disposed object is detected. .EXAMPLE PS> .\build\Test-ModuleDaemonMemoryLeak.ps1 @@ -34,7 +33,10 @@ PS> .\build\Test-ModuleDaemonMemoryLeak.ps1 Scans the src/ directory for daemon memory leaks and undisposed IDisposable objects. .NOTES -Designed for PowerShell 7.5+ on Windows. +Designed for Windows PowerShell 5.1 and PowerShell 7+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> [CmdletBinding()] @@ -47,7 +49,9 @@ $ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue'; if ([string]::IsNullOrEmpty($ModuleBasePath)) { - $ModuleBasePath = Resolve-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..') | Select-Object -ExpandProperty Path; + $ModuleBasePath = [System.IO.Path]::GetFullPath((Resolve-Path -Path (Join-Path -Path $PSScriptRoot -ChildPath '..')).ProviderPath); +} elseif (Test-Path -Path $ModuleBasePath) { + $ModuleBasePath = [System.IO.Path]::GetFullPath((Resolve-Path -Path $ModuleBasePath).ProviderPath); } if ([string]::IsNullOrEmpty($SourceFolder)) { @@ -61,14 +65,14 @@ if (-not (Test-Path -Path $SourceFolder)) { function Test-ModuleDaemonMemoryLeak() { param ( - [string]$SourceFolder = (Join-Path $PSScriptRoot '..\src') - ) + [string]$SourceFolder = (Join-Path -Path $PSScriptRoot -ChildPath (Join-Path -Path '..' -ChildPath 'src')) + ); - [bool]$Success = $true; - $Files = Get-ChildItem -Path $SourceFolder -Recurse -Include *.ps1,*.psm1; + [bool]$Success = $true; + $Files = Get-ChildItem -Path $SourceFolder -Recurse -Include '*.ps1', '*.psm1'; # Native types that do not accept $null or are immediately GCed - $ExemptTypes = @( + $ExemptTypes = @( 'bool', 'System.Boolean', 'switch', 'System.Management.Automation.SwitchParameter', 'int', 'System.Int32', 'long', 'System.Int64', 'double', 'System.Double', 'float', 'System.Single', 'decimal', 'System.Decimal', 'datetime', 'System.DateTime', @@ -89,34 +93,32 @@ function Test-ModuleDaemonMemoryLeak() ); foreach ($File in $Files) { - $Tokens = $null; - $Errors = $null; - $Ast = [System.Management.Automation.Language.Parser]::ParseFile($File.FullName, [ref]$Tokens, [ref]$Errors); + $Tokens = $null; + $Errors = $null; + $Ast = [System.Management.Automation.Language.Parser]::ParseFile($File.FullName, [ref]$Tokens, [ref]$Errors); # Find endless loops used by our daemons $DaemonLoops = $Ast.FindAll({ ($args[0] -is [System.Management.Automation.Language.WhileStatementAst] -or - $args[0] -is [System.Management.Automation.Language.DoWhileStatementAst] -or - $args[0] -is [System.Management.Automation.Language.DoUntilStatementAst]) -and + $args[0] -is [System.Management.Automation.Language.DoWhileStatementAst] -or + $args[0] -is [System.Management.Automation.Language.DoUntilStatementAst]) -and $args[0].Condition.Extent.Text -match 'Test-ThreadRunning' }, $true); foreach ($Loop in $DaemonLoops) { - $AssignedVars = @{}; - $NulledVars = @{}; - - $Assignments = $Loop.FindAll({ $args[0] -is [System.Management.Automation.Language.AssignmentStatementAst] }, $true); + $AssignedVars = @{ }; + $NulledVars = @{ }; + $Assignments = $Loop.FindAll({ $args[0] -is [System.Management.Automation.Language.AssignmentStatementAst] }, $true); foreach ($Assign in $Assignments) { - $Left = $Assign.Left; - $Right = $Assign.Right; - - $VarName = $null; + $Left = $Assign.Left; + $Right = $Assign.Right; + $VarName = $null; $IsExemptType = $false; if ($Left -is [System.Management.Automation.Language.ConvertExpressionAst]) { if ($Left.Child -is [System.Management.Automation.Language.VariableExpressionAst]) { - $VarName = $Left.Child.VariablePath.UserPath; + $VarName = $Left.Child.VariablePath.UserPath; $TypeName = $Left.Type.TypeName.Name; if ($ExemptTypes -contains $TypeName) { $IsExemptType = $true; @@ -127,8 +129,12 @@ function Test-ModuleDaemonMemoryLeak() } if ($null -ne $VarName) { - if ($VarName -match '^(global|script|env|local|private):') { continue; } - if ($VarName -eq '_' -or $VarName -eq 'this' -or $VarName -match '^args$') { continue; } + if ($VarName -match '^(global|script|env|local|private):') { + continue; + } + if ($VarName -eq '_' -or $VarName -eq 'this' -or $VarName -match '^args$') { + continue; + } # Null check tracking if (-not $IsExemptType) { @@ -159,16 +165,15 @@ function Test-ModuleDaemonMemoryLeak() # --------------------------------------------------------- # IDisposable Tracking (Entire File Scope) # --------------------------------------------------------- - $DisposableVars = @{}; - $DisposedVars = @{}; - + $DisposableVars = @{ }; + $DisposedVars = @{ }; $AllAssignments = $Ast.FindAll({ $args[0] -is [System.Management.Automation.Language.AssignmentStatementAst] }, $true); foreach ($Assign in $AllAssignments) { - $Left = $Assign.Left; - $Right = $Assign.Right; - + $Left = $Assign.Left; + $Right = $Assign.Right; $VarName = $null; + if ($Left -is [System.Management.Automation.Language.ConvertExpressionAst]) { if ($Left.Child -is [System.Management.Automation.Language.VariableExpressionAst]) { $VarName = $Left.Child.VariablePath.UserPath; @@ -178,12 +183,15 @@ function Test-ModuleDaemonMemoryLeak() } if ($null -ne $VarName) { - if ($VarName -match '^(global|script|env|local|private):') { continue; } - if ($VarName -eq '_' -or $VarName -eq 'this' -or $VarName -match '^args$') { continue; } + if ($VarName -match '^(global|script|env|local|private):') { + continue; + } + if ($VarName -eq '_' -or $VarName -eq 'this' -or $VarName -match '^args$') { + continue; + } $IsDisposableAssignment = $false; - - $NewObjCmd = $Right.Find({ $args[0] -is [System.Management.Automation.Language.CommandAst] -and $args[0].GetCommandName() -eq 'New-Object' }, $true); + $NewObjCmd = $Right.Find({ $args[0] -is [System.Management.Automation.Language.CommandAst] -and $args[0].GetCommandName() -eq 'New-Object' }, $true); if ($null -ne $NewObjCmd) { foreach ($elem in $NewObjCmd.CommandElements) { if ($elem -is [System.Management.Automation.Language.StringConstantExpressionAst]) { @@ -197,7 +205,7 @@ function Test-ModuleDaemonMemoryLeak() $InvokeMemberCmd = $Right.Find({ $args[0] -is [System.Management.Automation.Language.InvokeMemberExpressionAst] -and $args[0].Member.Extent.Text -match '^new$|^Create$' }, $true); if ($null -ne $InvokeMemberCmd) { - $TypeName = $InvokeMemberCmd.Expression.Extent.Text -replace '\[|\]',''; + $TypeName = $InvokeMemberCmd.Expression.Extent.Text -replace '\[|\]', ''; if ($DisposableTypes -contains $TypeName) { $IsDisposableAssignment = $true; } @@ -223,7 +231,7 @@ function Test-ModuleDaemonMemoryLeak() foreach ($VarName in $DisposableVars.Keys) { if (-not $DisposedVars.ContainsKey($VarName)) { - $StartLine = $DisposableVars[$VarName]; + $StartLine = $DisposableVars[$VarName]; $IsOptedOut = $false; # Check line exactly before the assignment @@ -251,6 +259,7 @@ function Test-ModuleDaemonMemoryLeak() } } } + return $Success; } diff --git a/docs/Agents/guidelines/01-Instruction.md b/docs/Agents/guidelines/01-Instruction.md new file mode 100644 index 0000000..f5e9f91 --- /dev/null +++ b/docs/Agents/guidelines/01-Instruction.md @@ -0,0 +1,434 @@ +# Icinga for Windows -- Code, Architecture & Documentation Ruleset + +This document defines the **binding code style, SPDX licensing, project layout, threading safety, documentation, changelog/roadmap governance, and task-tracking rules** for the **Icinga for Windows** PowerShell module. It is the single source of truth that all AI coding assistants (Claude, Gemini / Antigravity, OpenAI Codex / ChatGPT, GitHub Copilot, Cursor, Windsurf, ...) and human contributors **MUST** follow when editing this repository. + +If anything here contradicts a tutorial, blog post, or general PowerShell convention -- **this file wins**. + +--- + +## 1. Project Layout + +```text +IcingaForWindows/ +├── .github/copilot-instructions.md <- Entrypoint for GitHub Copilot -> points here +├── AGENTS.md <- Entrypoint for Codex / Copilot / Cursor / Windsurf -> points here +├── CLAUDE.md <- Entrypoint for Claude Code -> points here +├── GEMINI.md <- Entrypoint for Gemini / Antigravity -> points here +├── IcingaForWindows.psd1 <- Module manifest (GPL-3.0-or-later + PrivateData.SPDX) +├── IcingaForWindows.psm1 <- Hand-written runtime bootstrap ($Global:IcingaForWindows) +├── build/ +│ ├── Build-ModuleProject.ps1 <- Compiler: src/ -> lib/IcingaForWindows.{Classes,Kernel}.ps1 +│ ├── Build-ModuleDocs.ps1 <- Doc generator: src/ -> docs/Icinga.*.md & docs/index.md +│ ├── Invoke-ModuleTests.ps1 <- Standalone Pester test runner +│ ├── Invoke-ScriptAnalysis.ps1 <- PSScriptAnalyzer runner +│ ├── Test-ModuleChangelog.ps1 <- Non-main PR Changelog.md & Roadmap.md governance gate +│ ├── Test-ModuleCodeStyling.ps1 <- Code-styling, function-scope & SPDX license validator +│ └── Test-ModuleDaemonMemoryLeak.ps1 <- AST daemon loop & IDisposable leak checker +├── src/ <- Source code (strictly one function or class/enum file) +│ ├── Classes/ <- PowerShell classes & enums (compiled per runspace) +│ ├── Config/ <- Environment & configuration directory helpers +│ ├── Core/ <- ErrorHandling, Logging, RestApi, Runtime, TCPStack, Threading, WebSocket +│ ├── IcingaProtocol/ <- Native Icinga 2 JSON-RPC protocol & check execution +│ ├── PerformanceCounter/ <- Background performance counter daemon & readers +│ ├── Plugins/ +│ │ ├── Checks/Public/ <- Exported Invoke-IcingaCheck* monitoring plugins +│ │ ├── Lib/ <- Public/internal plugin SDK helpers (New-IcingaPlugin, ...) +│ │ └── Provider/ <- OS data providers (Disk, FileSystem, Process, ScheduledTask, ...) +│ ├── Security/ <- Approved-path file & directory wrappers +│ └── Tools/ <- JSON, unit conversion, sorting, CIM, boolean & SecureString helpers +├── lib/ <- Auto-generated compiled artifacts, NEVER edit by hand +│ ├── IcingaForWindows.Classes.ps1 +│ └── IcingaForWindows.Kernel.ps1 +├── data/ <- Static runtime assets (Web UI, templates) +├── docs/ +│ ├── Agents/ +│ │ ├── guidelines/ +│ │ │ └── 01-Instruction.md <- This binding ruleset (Single Source of Truth) +│ │ └── tasks/ +│ │ └── / <- Persistent per-branch feature tracking (Section 9) +│ │ ├── implementation_plan.md +│ │ ├── todo.md +│ │ └── walkthrough.md +│ ├── Developer/ <- Hand-written architectural & developer guides +│ ├── General/ +│ │ ├── Changelog.md <- Mandatory PR / feature-branch release changelog +│ │ └── Roadmap.md <- Completed milestones & prioritized future backlog +│ ├── Knowledgebase/ <- Hand-written IWKB001xxx troubleshooting articles +│ ├── Icinga.*.md <- Auto-generated API reference, NEVER edit by hand +│ └── index.md <- Auto-generated API reference index, NEVER edit by hand +└── Tests/ <- Pester unit & static-analysis test suites +``` + +**Function Scope & File Rules (`src/` vs. `build/`):** +- **Under `src/` (outside `src/Classes/`):** Every PowerShell `.ps1` file defines **at most one top-level `function`**, named identically to the `.ps1` file (for example `Invoke-IcingaCheckCPU.ps1` contains `function Invoke-IcingaCheckCPU()`). **Never** place multiple functions in a single `src/` file and **never** nest a `function` inside another `function` under `src/`. +- **Under `src/Classes/`:** Files contain only `class` and `enum` definitions (and their class methods/constructors) -- never standalone `function` declarations. +- **Under `build/`, `IcingaForWindows.psm1`, and `Tests/`:** Internal helper functions and nested functions inside scripts or functions **are permitted**, provided every `function` declaration still follows Allman brace formatting (`function Name()`). +- `Public/` = exported, user-facing. `Private/` = internal helpers, not exported. +- Files in `lib/` and auto-generated `docs/Icinga.*.md` / `docs/index.md` are **always regenerated** -- manual edits will be lost. + +--- + +## 2. PowerShell Code Style + +### 2.1 The semicolon rule + +> **Every non-function statement ends with a semicolon `;`.** + +This includes `param (...)` blocks (`);`), assignments, pipeline ends, `return` statements, and expressions inside control-flow blocks -- everything that is *not* a bare `function Name() { ... }` or block brace. + +```powershell +function Get-IcingaExample() +{ + param ( + [string]$Name = $null, + [int]$Count = 0 + ); + + if ([string]::IsNullOrEmpty($Name)) { + return $null; + } + + [array]$Results = @(); + + for ($i = 0; $i -lt $Count; $i++) { + $Results += "$Name-$i"; + } + + return $Results; +} +``` + +### 2.2 Function & control-flow declaration + +- Opening brace on its **own line** (Allman style) for `function`, `class`, and `enum` declarations, not K&R. +- Explicit empty parentheses after the function name (`function Foo()`), even when parameters are declared inside `param ()`. +- `param ()` block always uses one parameter per line with explicit type prefix and default value (`= $null` for nullable refs, `= @()` for arrays, `= @{ }` for hashtables, `= $false` for switches). +- `if (...) {` and `} elseif (...) {` conditions **must stay on a single line** ending with `{` (do not wrap multi-line conditions across newlines; extract intermediate `[bool]` variables beforehand when a condition grows long). + +### 2.3 Naming & Prose Convention (`"Icinga for Windows"` vs. `IcingaForWindows`) + +| Kind | Convention | Example | +|------|------------|---------| +| Prose product name | **"Icinga for Windows"** (always spaced) | `Icinga for Windows monitoring stack` | +| Technical module / variable name | **`IcingaForWindows`** (no spaces, code only) | `Import-Module IcingaForWindows`, `$Global:IcingaForWindows` | +| Public function | `Verb-IcingaNoun` (approved PS verbs only) | `Invoke-IcingaCheckCPU` | +| Private helper | `Verb-ModuleNoun` **or** `Verb-IcingaInternalNoun` | `ConvertFrom-ModuleBoolean`, `Write-LoggingEntry` | +| Variable | `PascalCase` with `$` | `$CheckResultData`, `$WorkerId` | +| Loop counter | lowercase | `$i`, `$idx` | +| Type-annotated variable | `[Type]$Name = ...` | `[int]$WorkerId = -1` | +| Constants in `$Global:IcingaForWindows` | nested hashtables/PSCustomObjects under `Public/Private/Protected` | `$Global:IcingaForWindows.Public.IcingaProtocol.Config` | + +- **Prose Naming Rule (Binding):** Always write **"Icinga for Windows"** in prose across all Markdown documents (`README.md`, `docs/**`), inline comments, comment-based help blocks, changelogs, roadmaps, implementation plans, todos, and walkthroughs. Reserve **`IcingaForWindows`** exclusively for technical identifiers (`Import-Module IcingaForWindows`, `IcingaForWindows.psd1`, `IcingaForWindows.psm1`, `lib/IcingaForWindows.*.ps1`, directory paths such as `C:\ProgramData\IcingaForWindows`, and `$Global:IcingaForWindows`). +- **Approved PS verbs only** -- run `Get-Verb` to check. Avoid `Process-`, `Validate-`, `Execute-`. +- **Never collide with PowerShell built-ins or other modules.** Prefix everything user-facing with `Icinga`. +- Acronyms keep their case: `RestApi`, `IcingaProtocol`, `AccessControl`, `CPU`. + +### 2.4 Encoding, indentation, whitespace & vertical alignment + +All rules below are automatically enforced by `build/Test-ModuleCodeStyling.ps1`: + +- **UTF-8 without BOM & strict 7-bit ASCII (`0x00`-`0x7F`) in PowerShell files:** UTF-8/UTF-16/UTF-32 byte order marks (`0xEF 0xBB 0xBF`, ...) and literal non-ASCII characters (`> 0x7F`) are strictly forbidden in `.ps1`, `.psm1`, and `.psd1` files. Concatenated `lib/` files break on mid-file BOMs, while Windows PowerShell 5.1 decodes BOM-less scripts as Windows-1252 (turning UTF-8 bytes `0x91`-`0x94` into smart-quote string delimiters that corrupt the AST). Use plain 7-bit ASCII (`--`, `->`, `...`, `*`) or `[char]0xXXXX` when a runtime Unicode glyph is intentionally needed. +- **4 spaces** per indentation level; **no tab characters**. +- One blank line between logical function body sections (initialization, processing, return). +- **No trailing whitespace** on any line; files end with a single trailing newline. +- **Vertical alignment of assignment operators (`=`, `+=`, `-=`, `*=`, `/=`):** + Within any assignment block at the same indentation depth (spanning blank lines, inline comments, and multi-line RHS expressions until interrupted by control-flow keywords or braces), align the `=` character vertically so the widest left-hand side has **exactly one space** before the operator and **one space** after `=`: + ```powershell + [int]$ExitCode = 3; + [string]$CheckOutput = ''; + [array]$CheckPerfData = @(); + ``` +- **Vertical alignment of hashtable & enum entries:** + Single-entry hashtables and enums must use `1` space before and `1` space after `=`; contiguous `'Key' = Value;` or `EnumMember = Value` lines at the same indentation level must align `=` vertically with exactly one space after the widest key and one space after `=`. +- **Vertical alignment of `.PARAMETER` Markdown tables:** + All `|` column separators across header, separator, and every value row of every `.PARAMETER` help table must be vertically aligned at identical column indices. + +### 2.5 Global state access + +`$Global:IcingaForWindows` is the shared runtime state initialized by `New-ModuleBaseEnvironment` in [IcingaForWindows.psm1](../../../IcingaForWindows.psm1). Access patterns: + +```powershell +# Inside a thread / worker / background helper -- ALWAYS go through Get-GlobalRuntimeVariable +$GlobalVariable = Get-GlobalRuntimeVariable; +$GlobalVariable.Public.RestApi.Config.ListenPort; + +# Inside a normal function guaranteed to run only on the main thread, direct access is acceptable: +$Global:IcingaForWindows.Public.IcingaProtocol.Config.Hostname; +``` + +**Rule of thumb:** anything that runs inside `Start-*Daemon`, `Start-*Worker`, or any helper invoked from a background thread **MUST** go through `Get-GlobalRuntimeVariable` so thread-local `Private` and `Protected` state resolves to the active runspace. + +Inside infinite daemon loops (`while (Test-ThreadRunning ...)`), every non-primitive local variable assigned inside the loop **must** be explicitly reset to `$null` in the loop's `finally` block, and every `IDisposable` object must have `.Dispose()` called (`build/Test-ModuleDaemonMemoryLeak.ps1`). + +### 2.6 Return values and error handling + +- Public functions: return the structured result the caller expects (exit code, object, hashtable, `$null`). +- Private functions that participate in the return-code system: register semantic keys in `src/Core/ErrorHandling/Private/Set-InternalExitCodes.ps1` and emit via `Write-FunctionReturnValue -ReturnValue 'SemanticKey' -Data @{ ... }`. +- Never `throw` for expected runtime/configuration error paths inside daemons or checks. Log via `Write-LoggingEntry` / `Write-FunctionReturnValue` and return `$null` or a structured `[UNKNOWN]` result so worker threads stay alive. +- `throw` is reserved for **programmer errors** (impossible state, build/test script failures). + +### 2.7 Logging + +```powershell +Write-LoggingEntry -Message 'Short, present-tense description' -Level 'Info' -Data @{ + 'ContextKey1' = $Value1; + 'ContextKey2' = $Value2; +}; +``` + +Levels: `Debug`, `Output`, `Audit`, `Info`, `Success`, `Warning`, `Error`, `Fatal`. Use `Debug` for hot-loop telemetry, `Info` for state transitions, `Warning` for recoverable issues, `Error` for unhandled exceptions. Never log plain-text passwords or `SecureString` contents; always mask secrets as `'********'`. + +### 2.8 Forbidden constructs + +- ❌ `Write-Host` outside of `build/` scripts (and console prompt/logging formatters). Use `Write-LoggingEntry -Level 'Output'`. +- ❌ `Write-Output` for logging -- use it only when genuinely returning a value to the pipeline. +- ❌ Stream redirects like `2>$null` or `*>&1`. Handle errors explicitly with `try / catch`. +- ❌ Aliases in source code (`%`, `?`, `select`, `where`). Use full cmdlet names (`ForEach-Object`, `Where-Object`, `Select-Object`). +- ❌ Any literal non-ASCII character (`> 0x7F`, including em-dashes U+2014, en-dashes U+2013, arrows `->`, box-drawing glyphs, checkmarks, or emojis) in PowerShell `.ps1` / `.psm1` / `.psd1` files -- Windows PowerShell 5.1 reads BOM-less UTF-8 files as Windows-1252, causing Mojibake and turning UTF-8 bytes `0x91`-`0x94` into smart-quote string delimiters that break compilation. Use plain 7-bit ASCII (`-`, `--`, `->`, `...`, `*`) or `[char]0xXXXX`. +- ❌ `-ErrorAction SilentlyContinue` as a "make the warning go away" shortcut. Use explicit checks or `try / catch` with `-ErrorAction Stop`. +- ❌ Multiple top-level functions or nested functions inside any file under `src/`. +- ❌ Missing `.NOTES` or missing Icinga GmbH SPDX license headers in any `.ps1`, `.psm1`, or `.psd1` file. +- ❌ Editing generated files under `lib/` or `docs/Icinga.*.md` / `docs/index.md` by hand. +- ❌ PowerShell class literals in functions outside `src/Classes` (`[IcingaPlugin]::new()`, `[IcingaSortKey]::FromObject()`, `-is [IcingaError]`). See Section 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 points to the class type of the **main** runspace -- even 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, stalling the thread. 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 PowerShell class literal in a function** -- not to create an object, not for a static member, not for `-is`, casts, or typed variables/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` (loaded per runspace, except `IcingaPerformanceCounter.ps1` which also uses runtime lookups), Pester tests, .NET BCL classes (`[System.Text.StringBuilder]`, `[System.Security.SecureString]`), and enums such as `[IcingaServiceStatus]::Running` (enums carry no script methods and convert by value). +3. **Never pass PowerShell class instances between threads.** Hand over only primitive values, hashtables, and arrays. A plugin result travels as its rendered output, integer exit code, and performance-data string array, never as the `IcingaCheckResult` object. +4. `Tests/ClassLiteral.Tests.ps1` enforces rule 1 and reports the file and line of every offending literal. + +Background and examples: [docs/Developer/Threading/01-Threading.md](../../Developer/Threading/01-Threading.md#classes-and-threads). + +--- + +## 3. Comment-Based Help & Mandatory SPDX Licensing + +Every PowerShell source file -- **public functions, private functions, classes/enums, bootstrap scripts, build scripts, and Pester test files** -- must carry a comment-based help block containing `.NOTES` with the Icinga GmbH SPDX license lines: + +> **Language rule:** All code, inline comments, comment-based help, developer guides, changelogs, roadmaps, knowledgebase entries, implementation plans, todos, and walkthroughs **must be written 100% in English**. No exceptions. + +```powershell +<# +.SYNOPSIS +One-line summary in imperative voice without a trailing period + +.DESCRIPTION +Detailed multi-line description (~80 columns). Cover what the function does, +how it fits into the larger workflow, any threading or networking behavior, +and important side-effects (writes to global state, blocking I/O, external +dependencies). + +.PARAMETER Name +| Name | Type | Description | Default | +|------|---------------|-----------------------------------------|---------| +| Name | System.String | Display name of the resource to act on. | '' | + +.PARAMETER Count +| Name | Type | Description | Default | +|-------|--------------|----------------------------------|---------| +| Count | System.Int32 | Number of iterations to perform. | 1 | + +.OUTPUTS +System.Object -- Description of the returned value or object shape. +Use None if the function returns nothing. + +.EXAMPLE +PS> Verb-IcingaNoun -Name 'Foo' -Count 3 + +Short prose describing what the example does. + +.NOTES +Module-level dependencies (external services, credentials, config files), +required privileges, and threading caveats. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later +#> +function Verb-IcingaNoun() +{ + ... +} +``` + +### 3.1 Strict help & SPDX license rules + +1. **All seven sections** are mandatory on **public** functions: `.SYNOPSIS`, `.DESCRIPTION`, `.PARAMETER` (one per declared parameter), `.OUTPUTS`, `.EXAMPLE`, `.NOTES`. +2. **Private functions** must have `.SYNOPSIS`, `.DESCRIPTION`, a `.PARAMETER` Markdown table for **every** declared parameter in `param ()`, and **`.NOTES`** (including `.OUTPUTS` and `.EXAMPLE` is strongly recommended). +3. **Classes and enums (`src/Classes/`)** must carry a top-level comment-based help block above each top-level `class` / `enum` declaration including `.SYNOPSIS`, `.DESCRIPTION`, and **`.NOTES`**. +4. **Mandatory Icinga GmbH SPDX Footer & Header Comments (Every File):** + - Inside `<# ... #>` comment blocks (specifically concluding every `.NOTES` section across `src/` (`Public/`, `Private/`, `Classes/`), `IcingaForWindows.psm1`, `build/*.ps1`, `Tests/*.Tests.ps1`, and the top-of-file header block of compiled `lib/IcingaForWindows.Classes.ps1` and `lib/IcingaForWindows.Kernel.ps1`), write these exact two lines without any comment prefix: + ```text + SPDX-FileCopyrightText: 2026 Icinga GmbH + SPDX-License-Identifier: GPL-3.0-or-later + ``` + - Outside `<# ... #>` block comments (such as `.psd1` data files), prefix both lines with `# `: + ```powershell + # SPDX-FileCopyrightText: 2026 Icinga GmbH + # SPDX-License-Identifier: GPL-3.0-or-later + ``` + Specifically, `IcingaForWindows.psd1` declares `Copyright = '(c) 2026 Icinga GmbH | GPL-3.0-or-later';`, points `LicenseUri` to `blob/main/LICENSE`, and defines `SPDX = '';` followed by the two `# SPDX-...` lines beneath `Endpoint` inside `PrivateData` (`PSScriptAnalyzerSettings.psd1` likewise carries the two `# SPDX-...` lines at the top of the file). +5. **Every `.PARAMETER` block uses the four-column Markdown table** (`Name | Type | Description | Default`) with vertically aligned `|` pipes. +6. `.SYNOPSIS` is **one line, no trailing period** unless it contains multiple sentences. +7. `.DESCRIPTION` uses plain prose wrapped around ~80 columns. +8. `.OUTPUTS` starts with the .NET type name (`System.Int32`, `System.Collections.Hashtable`, `System.Object`, `None`), followed by `-- Description` (plain ASCII `--`, never an em-dash). +9. `.EXAMPLE` begins with `PS> ` and shows a realistic invocation. + +### 3.2 Inline comments + +- **Always include and preserve helpful inline comments** explaining numbered workflow steps, section boundaries (`Mode A` / `Mode B`), protocol quirks, Windows PowerShell 5.1 compatibility constraints, and security invariants so readers immediately understand what happens and why. Never strip existing explanatory comments during refactoring. +- Avoid noisy filler comments that merely restate a trivial statement (`# increment counter` above `$i++`) or reference transient PR history (`# added for PR #12`). + +--- + +## 4. Build, Validation & Generated Artifacts + +### 4.1 Compilation + +`build/Build-ModuleProject.ps1` walks `src/`, compiles classes into `lib/IcingaForWindows.Classes.ps1` and functions into `lib/IcingaForWindows.Kernel.ps1` (as BOM-less UTF-8 with top-of-file SPDX headers), and reloads the module: + +```powershell +.\build\Build-ModuleProject.ps1 -SkipTests -TestDaemonMemoryLeaks; +``` + +### 4.2 Documentation generation + +`build/Build-ModuleDocs.ps1` parses the comment-based help block of every `.ps1` file under `src/`, enforces `.NOTES` + SPDX completeness across both `Public` and `Private` functions, strips machine-readable `SPDX-...` lines from rendered Markdown notes, and writes component reference files into `docs/Icinga.*.md` and `docs/index.md` without touching hand-written subdirectories (`docs/General/`, `docs/Developer/`, `docs/Knowledgebase/`, `docs/Agents/`): + +```powershell +.\build\Build-ModuleDocs.ps1 -Strict $true; +``` + +**If any `.ps1` file is missing required help sections, parameter tables, `.NOTES`, or SPDX lines, `Build-ModuleDocs.ps1` fails with a non-zero exit code.** Fix the `.ps1` source file -- never weaken the generator. + +### 4.3 Static, style & governance validation + +The entire repository (`src/`, `build/`, `IcingaForWindows.psm1`, `IcingaForWindows.psd1`, `Tests/`, and `lib/` SPDX headers) must pass all validators with **zero** violations: + +```powershell +.\build\Test-ModuleCodeStyling.ps1; +.\build\Test-ModuleChangelog.ps1; +.\build\Test-ModuleDaemonMemoryLeak.ps1; +.\build\Invoke-ScriptAnalysis.ps1 -FailOn 'Warning'; +``` + +In CI (`.github/workflows/ci.yml`), `Invoke-ScriptAnalysis.ps1`, `Test-ModuleCodeStyling.ps1`, and `Test-ModuleChangelog.ps1` execute once inside the `analyze` job. `Tests/CodeStyling.Tests.ps1` and `Tests/Changelog.Tests.ps1` are strictly fast `$TestDrive` unit test suites validating parser/gate behavior so the repository tree is never scanned twice during `Invoke-ModuleTests.ps1`. + +--- + +## 5. Testing + +- Pester test suites live under `Tests/` (`*.Tests.ps1`) and carry a top-level `<# .SYNOPSIS ... .NOTES SPDX-... #>` block. +- Every new public check/cmdlet -- and complex private subsystems such as protocol parsers or providers -- must ship with comprehensive unit tests covering happy paths, boundary conditions, PS 5.1 vs. PS 7 data shapes (`Dictionary[string, object]` vs. `Hashtable`), and error codes. +- Tests import `IcingaForWindows.psd1` and mock external OS/network boundaries (for example shadowing internal provider/directory functions inside `& $script:IcingaModule { ... }`) so unit tests run deterministically offline on Windows, Linux, and macOS. +- Never weaken, skip, or delete an existing test to make a change pass. + +--- + +## 6. Commits, Branching, Changelog & Roadmap Governance + +- Primary integration branch: `main`. +- Commit subjects in present-tense imperative (`Add ...`, `Fix ...`, `Update ...`), concise single line, in English. +- Commit body explains **why**, not **what**. +- Never amend pushed commits, never force-push shared branches, and never bypass Git hooks (`--no-verify`, `--no-gpg-sign`). +- **Mandatory `docs/General/Changelog.md` Entry (Non-`main` Branches & PRs):** + Every branch not on `main` (`feature/*`, `fix/*`, `bugfix/*`, `chore/*`, ...) and every GitHub Pull Request **MUST** add at least one bullet entry (`* ...`) under the current unreleased version section (`### Enhancements`, `### Bugfixes`, `### Security`, or `### Documentation`) in [docs/General/Changelog.md](../../General/Changelog.md). Missing changelog entries fail `build/Test-ModuleChangelog.ps1` in CI. +- **Mandatory `docs/General/Roadmap.md` Synchronization:** + Whenever an implementation plan (`docs/Agents/tasks//implementation_plan.md`) is created or a branch milestone is completed, [docs/General/Roadmap.md](../../General/Roadmap.md) **MUST** be updated in the same branch so completed subsystems and prioritized upcoming work remain accurate. + +--- + +## 7. Cross-Platform & Runtime Compatibility Notes + +- **Primary production target:** Windows PowerShell 5.1 and PowerShell 7.5+ on Windows Server / Windows 11. +- **Development & CI compatibility:** Linux and macOS via the `$env:ProgramData` fallback in `IcingaForWindows.psm1`. +- Always use `Join-Path` for path construction; never hardcode `\` or `/` when building filesystem paths. +- Remember `ConvertFrom-ModuleJson` returns `Dictionary[string, object]` on Windows PowerShell 5.1 and `Hashtable` on PowerShell 7+ -- always accept `[System.Collections.IDictionary]` rather than forcing `[hashtable]` on deserialized JSON objects. + +--- + +## 8. AI Assistant Etiquette + +When you (Claude, Gemini / Antigravity, Codex, Copilot, Cursor, ...) work in this repository: + +- **Match house style & SPDX rules 100%.** Inspect neighboring files in the same component before writing code, include `.NOTES` with the two Icinga GmbH SPDX lines on every PowerShell file, and verify zero violations with `.\build\Test-ModuleCodeStyling.ps1`. +- **Use `"Icinga for Windows"` in all prose** and reserve `IcingaForWindows` strictly for technical module, path, file, and `$Global:IcingaForWindows` identifiers. +- **Write everything 100% in English** -- code, comments, help blocks, changelogs, roadmaps, knowledgebase articles, and task-tracking artifacts (`implementation_plan.md`, `todo.md`, `walkthrough.md`). +- **Maintain `Changelog.md` & `Roadmap.md`.** Add a changelog bullet to `docs/General/Changelog.md` on every non-`main` branch (`.\build\Test-ModuleChangelog.ps1`) and synchronize `docs/General/Roadmap.md` whenever creating or completing task plans under `docs/Agents/tasks/`. +- **Don't add backwards-compatibility shims** for unreleased internal code. +- **Don't introduce premature abstractions** for a single caller. +- **Don't widen surface area.** Keep diffs focused on the requested task. +- **Don't commit to Git unless explicitly instructed by the user.** +- **Persist feature and task documentation** (`implementation_plan.md`, `todo.md`, `walkthrough.md`) in `docs/Agents/tasks//` (see Section 9). +- **When requirements are ambiguous, ask a concise clarifying question** rather than guessing. + +--- + +## 9. Feature & Task Implementation Tracking (`docs/Agents/tasks/`) + +Every non-trivial feature, subsystem enhancement, or major refactoring in **Icinga for Windows** **MUST** maintain a dedicated task documentation folder under: + +```text +docs/Agents/tasks// +├── implementation_plan.md <- Architecture, technical rationale, and proposed file changes +├── todo.md <- Granular checklist (completed items, open points, follow-ups) +└── walkthrough.md <- Post-implementation deep dive, runtime flow & test proof +``` + +Where `` is derived from the Git branch name with prefixes such as `feature/`, `bugfix/`, or `chore/` stripped and underscores normalized to hyphens (for example `feature/plugins-cpu-service-partition` -> `plugins-cpu-service-partition`, `feature/update-code-styling` -> `update-code-styling`), sensibly shortened to ~40-50 characters if a branch name is excessively long. + +### 9.1 Purpose and Technical Rationale + +1. **Persistent Architectural Memory:** In-chat planning and ephemeral agent scratchpads disappear once a session ends or context is compacted. Versioning these three artifacts inside `docs/Agents/tasks//` preserves *why* specific design choices were made, which security or performance trade-offs were evaluated, and how subtle runtime constraints (Windows PowerShell 5.1 vs. PowerShell 7 runspace class isolation, `$Global:IcingaForWindows` state partitioning, `SecureString` lifecycle, daemon memory-leak prevention) were solved. +2. **Seamless Multi-Agent & Incremental Handoffs:** Complex features often span multiple sessions, branches, or different AI tools (Claude, Gemini, Codex, Copilot) and human reviewers. A tracked `todo.md` makes completed work, deliberately deferred items, and next steps immediately visible without reverse-engineering diffs. +3. **Auditability & Roadmap Synchronization:** Provides reviewers and future maintainers with a self-contained architectural blueprint and verification record right beside the code, synchronized with [docs/General/Roadmap.md](../../General/Roadmap.md) and [docs/General/Changelog.md](../../General/Changelog.md). + +### 9.2 The Three Required Artifacts (All in English) + +#### 1. `implementation_plan.md` (Design & Architecture) +Drafted **prior to implementation** (and updated if architectural scope changes): +- **Problem Statement & Objectives:** User requirements, protocol/OS constraints, and security boundaries. +- **Architecture & Design Decisions:** Detailed coverage of: + - Runspace & threading model (`Get-GlobalRuntimeVariable`, class-literal avoidance per Section 2.9, daemon loop cleanup). + - State usage in `$Global:IcingaForWindows` (`Public`, `Private`, `Protected`). + - Internal return codes (`Set-InternalExitCodes`) and user-facing `IWKB001xxx` Knowledgebase mappings where applicable. + - Windows PowerShell 5.1 vs. PowerShell 7+ and cross-platform considerations. +- **Proposed Changes:** Grouped by component with relative repository paths marked `[NEW]`, `[MODIFY]`, or `[DELETE]`. +- **Data Flow:** Mermaid flowcharts or sequence diagrams illustrating execution lifecycles. +- **Verification Plan:** Exact build, code-styling, changelog, static-analysis, Pester, and manual verification steps. + +#### 2. `todo.md` (Task Tracking & Open Points) +Actively maintained throughout implementation: +- **Categorized Checklist:** + - `[x]` Completed items referencing the implemented source, test, and documentation files. + - `[ ]` Open, deferred, or follow-up items for subsequent iterations or branches. +- **Known Limitations & Technical Debt:** Honest documentation of deferred edge cases or Windows-only integration tests requiring live agent verification. +- **Next Steps:** Concrete follow-up actions. + +#### 3. `walkthrough.md` (Implementation Walkthrough & Verification Record) +Completed **after implementation and verification**: +- **Executive Summary:** Concise overview of what was built and why. +- **Under-the-Hood Deep Dive:** Explanation of core algorithms, security checks, type/macro coercion, resource disposal, and error handling. +- **Runtime Flow:** Step-by-step trace from entry point to final output/transmission. +- **Verification Results:** Exact commands executed (`Build-ModuleProject.ps1`, `Build-ModuleDocs.ps1`, `Test-ModuleCodeStyling.ps1`, `Test-ModuleChangelog.ps1`, `Test-ModuleDaemonMemoryLeak.ps1`, `Invoke-ModuleTests.ps1`) with real pass/fail counts. +- **Practical Examples:** Copy-pasteable PowerShell and/or Icinga 2 DSL snippets demonstrating usage. + +### 9.3 Rules for AI Assistants + +- **Mandatory Persistence & Roadmap Sync:** Every non-trivial feature or refactoring task must create or update `implementation_plan.md`, `todo.md`, and `walkthrough.md` under `docs/Agents/tasks//`, update `docs/General/Roadmap.md` when plans are created or completed, and add a changelog entry to `docs/General/Changelog.md` whenever not on `main`. +- **100% English:** Even when the user prompts in German or another language, all repository documentation -- including `docs/Agents/tasks//*.md`, `docs/General/Changelog.md`, and `docs/General/Roadmap.md` -- **must** be written in English. +- **Technical Depth Over Boilerplate:** Write concrete, accurate engineering documentation tied to real file paths, exit codes, and test results -- never vague filler text. + +--- + +*Last updated: 2026-11-17* diff --git a/docs/Agents/tasks/update-code-styling/implementation_plan.md b/docs/Agents/tasks/update-code-styling/implementation_plan.md new file mode 100644 index 0000000..9eb0b4a --- /dev/null +++ b/docs/Agents/tasks/update-code-styling/implementation_plan.md @@ -0,0 +1,73 @@ +# Implementation Plan -- Holistic Code-Styling, SPDX Licensing, Documentation & Governance (`update-code-styling`) + +## 1. Problem Statement & Objectives + +Deliver a single, unified repository governance milestone on `feature/update-code-styling` that brings **100% of PowerShell files, documentation, compiled build artifacts, and CI gates** in **Icinga for Windows** under one binding standard without altering runtime behavior: + +1. **Zero-Exemption Code-Styling Compliance (`255+` PowerShell files):** + Remediate all `506` formatting/alignment/em-dash deviations across `src/` (`208` files), `20` deviations in `build/`, and `3` deviations in `Tests/` without exemptions or path allowlists. Enforce single-function / no-nested-function rules strictly under `src/` while permitting helper and nested functions in `build/`, `IcingaForWindows.psm1`, and `Tests/`. +2. **Mandatory `.NOTES` & Icinga GmbH SPDX License Headers (`GPL-3.0-or-later`):** + Require `.NOTES` concluding with the two Icinga GmbH SPDX lines (`SPDX-FileCopyrightText: 2026 Icinga GmbH ` and `SPDX-License-Identifier: GPL-3.0-or-later`) across every file in `src/` (`Public/`, `Private/`, and `Classes/`), in `IcingaForWindows.psm1`, in every `build/*.ps1` script, and in every `Tests/*.Tests.ps1` file; emit `# SPDX-...` comments at the top of compiled `lib/IcingaForWindows.{Classes,Kernel}.ps1` artifacts (written as BOM-less UTF-8); and update `IcingaForWindows.psd1` from `MIT` to `GPL-3.0-or-later` (`blob/main/LICENSE` + `PrivateData.SPDX` with `# SPDX-...` comments). +3. **`docs/General/Changelog.md` & `docs/General/Roadmap.md` Governance:** + Introduce `docs/General/Changelog.md` and `docs/General/Roadmap.md` modeled on the Icinga documentation structure, enforce via `build/Test-ModuleChangelog.ps1` that every non-`main` branch / Pull Request adds a changelog bullet entry, and require `Roadmap.md` synchronization whenever plans under `docs/Agents/tasks//` are created or completed. +4. **Single-Run CI Integration Alongside `PSScriptAnalyzer` (No Duplicate Scans):** + Wire `build/Test-ModuleCodeStyling.ps1` and `build/Test-ModuleChangelog.ps1` into the `analyze` job of `.github/workflows/ci.yml` alongside `build/Invoke-ScriptAnalysis.ps1` (`fetch-depth: 0`), while keeping `Tests/CodeStyling.Tests.ps1` and `Tests/Changelog.Tests.ps1` strictly to fast `$TestDrive` unit tests so `Invoke-ModuleTests.ps1` never scans the repository tree a second time. +5. **`README.md` Overhaul & Strict `"Icinga for Windows"` Prose Naming:** + Rewrite `README.md` in clear English with Mermaid runtime and CI governance diagrams, and enforce across all prose documentation and help comments that **"Icinga for Windows"** is used in text while **`IcingaForWindows`** is reserved exclusively for technical module, path, file, and `$Global:IcingaForWindows` identifiers. + +--- + +## 2. Architecture & Design Decisions + +```mermaid +flowchart LR + Rules["docs/Agents/guidelines/01-Instruction.md
(AGENTS / CLAUDE / GEMINI / Copilot)"] --> StyleGate["build/Test-ModuleCodeStyling.ps1
(AST + Line + SPDX + Manifest)"] + Rules --> DocGate["build/Build-ModuleDocs.ps1
(Strict .NOTES + SPDX Check)"] + Rules --> ClGate["build/Test-ModuleChangelog.ps1
(Net-New PR Changelog & Roadmap)"] + StyleGate --> CI["GitHub Actions: analyze + build Jobs
(Zero Duplicate Repo Scan)"] + ClGate --> CI + UnitTests["Tests/{CodeStyling,Changelog}.Tests.ps1
(Fast $TestDrive Fixtures Only)"] --> PesterJob["GitHub Actions: test Job"] +``` + +- **Zero Runtime Logic Impact:** All `src/` edits are strictly comment/help additions, Unicode dash replacements inside comments, `.PARAMETER` Markdown pipe alignments, and horizontal `=` / indentation whitespace alignments. Non-comment, non-newline PowerShell AST token streams across all `208` `src/*.ps1` files are verified to match `main` (`3f7fa6e`) 100%. +- **Windows PowerShell 5.1 BOM Safety:** `build/Build-ModuleProject.ps1` writes `lib/IcingaForWindows.Classes.ps1` and `lib/IcingaForWindows.Kernel.ps1` via `[System.IO.File]::WriteAllText(..., [System.Text.UTF8Encoding]::new($false))` rather than `Set-Content -Encoding UTF8` (which emits a 3-byte BOM on Windows PowerShell 5.1). +- **Clean API Reference Output:** `build/Build-ModuleDocs.ps1` validates `.NOTES` + SPDX presence on both `Public` and `Private` functions, strips machine-readable `SPDX-...` lines from rendered `#### Notes` Markdown sections, and restricts cleanup in `docs/` to `Icinga.*.md` and `index.md`. + +--- + +## 3. Proposed File Changes + +### Governance & Agent Entrypoints +- **[MODIFY]** `docs/Agents/guidelines/01-Instruction.md`, `CLAUDE.md`, `AGENTS.md`, `GEMINI.md`, `.github/copilot-instructions.md` +- **[NEW]** `docs/General/Changelog.md` +- **[NEW]** `docs/General/Roadmap.md` +- **[MODIFY]** `README.md`, `docs/Developer/Plugins/04-Custom-Plugin-Developer-Guide.md`, `docs/Developer/Threading/01-Threading.md` + +### Manifest, Bootstrap & Build Tooling +- **[MODIFY]** `IcingaForWindows.psd1` +- **[MODIFY]** `IcingaForWindows.psm1` +- **[MODIFY]** `PSScriptAnalyzerSettings.psd1` +- **[MODIFY]** `build/Build-ModuleProject.ps1` +- **[MODIFY]** `build/Build-ModuleDocs.ps1` +- **[MODIFY]** `build/Invoke-ModuleTests.ps1` +- **[MODIFY]** `build/Invoke-ScriptAnalysis.ps1` +- **[MODIFY]** `build/Test-ModuleDaemonMemoryLeak.ps1` +- **[NEW]** `build/Test-ModuleCodeStyling.ps1` +- **[NEW]** `build/Test-ModuleChangelog.ps1` +- **[MODIFY]** `.github/workflows/ci.yml` + +### Full Source & Test Formatting + SPDX Remediation +- **[MODIFY]** `src/**/*.ps1` (`208` files: formatting alignment + `.NOTES` + SPDX headers; zero AST code token changes) +- **[MODIFY]** `Tests/*.Tests.ps1` (`36` existing test files + `[NEW]` `Tests/CodeStyling.Tests.ps1` + `[NEW]` `Tests/Changelog.Tests.ps1`) +- **[REGENERATE]** `docs/Icinga.*.md` & `docs/index.md` (`20` auto-generated API reference files) + +--- + +## 4. Verification Plan + +1. Verify zero AST non-comment/non-newline token differences across all `208` `src/*.ps1` files compared to `main` (`3f7fa6e`). +2. Run `.\build\Build-ModuleProject.ps1 -SkipTests -TestDaemonMemoryLeaks` and verify BOM-less UTF-8 + top SPDX headers in `lib/IcingaForWindows.{Classes,Kernel}.ps1` and `Test-ModuleManifest -Path .\IcingaForWindows.psd1`. +3. Run `.\build\Build-ModuleDocs.ps1 -Strict $true` (`0` violations across `198` functions). +4. Run `.\build\Test-ModuleCodeStyling.ps1` (`0` violations across `src/`, `build/`, `Tests/`, `IcingaForWindows.psm1`, `IcingaForWindows.psd1`, and `lib/`). +5. Run `.\build\Test-ModuleChangelog.ps1` and `.\build\Invoke-ScriptAnalysis.ps1 -FailOn 'Warning'` (`0` violations). +6. Run `.\build\Invoke-ModuleTests.ps1` and validate all relative Markdown links across `31` hand-written Markdown files. diff --git a/docs/Agents/tasks/update-code-styling/todo.md b/docs/Agents/tasks/update-code-styling/todo.md new file mode 100644 index 0000000..44d0db6 --- /dev/null +++ b/docs/Agents/tasks/update-code-styling/todo.md @@ -0,0 +1,47 @@ +# Task Checklist -- `update-code-styling` + +## Completed Tasks + +- [x] **Branch Setup & Agent Guidelines (`docs/Agents/guidelines/01-Instruction.md`, `CLAUDE.md`, `AGENTS.md`, `GEMINI.md`, `.github/copilot-instructions.md`)** + - Created `feature/update-code-styling` from `main` (`3f7fa6e`) and initialized `docs/Agents/tasks/update-code-styling/`. + - Anchored all five binding rules in `docs/Agents/guidelines/01-Instruction.md` and synchronized `CLAUDE.md`, `AGENTS.md`, `GEMINI.md`, and `.github/copilot-instructions.md`: + 1. `"Icinga for Windows"` prose naming vs. `IcingaForWindows` technical identifiers. + 2. Strictly one top-level function and zero nested functions per file under `src/` (helper/nested functions permitted in `build/`, `IcingaForWindows.psm1`, and `Tests/`). + 3. Mandatory `.NOTES` concluding with the two Icinga GmbH `GPL-3.0-or-later` SPDX lines across all PowerShell files. + 4. Mandatory changelog bullet entry in `docs/General/Changelog.md` on every non-`main` branch / Pull Request. + 5. Mandatory synchronization of `docs/General/Roadmap.md` whenever creating or completing task plans under `docs/Agents/tasks//`. +- [x] **Manifest, Bootstrap, Compiler & Doc Generator (`IcingaForWindows.psd1`, `IcingaForWindows.psm1`, `build/Build-ModuleProject.ps1`, `build/Build-ModuleDocs.ps1`)** + - Updated `IcingaForWindows.psd1` `Copyright` from `MIT` to `GPL-3.0-or-later`, updated `LicenseUri` to `blob/main/LICENSE`, aligned all hashtable `=` columns with trailing semicolons, and added `PrivateData.SPDX` plus the two-line SPDX block comment beneath `Endpoint`. + - Added SPDX lines to `.NOTES` across all documented bootstrap functions in `IcingaForWindows.psm1` and aligned prose naming. + - Added complete comment-based help + SPDX lines and `-TestCodeStyling` support to `build/Build-ModuleProject.ps1`, emitted top-of-file SPDX headers in `lib/IcingaForWindows.{Classes,Kernel}.ps1`, and switched artifact writing to BOM-less `UTF8Encoding($false)`. + - Updated `build/Build-ModuleDocs.ps1` to enforce `.NOTES` + SPDX lines across all `198` `Public` and `Private` functions, strip `SPDX-...` lines from rendered `#### Notes` Markdown, compute accurate relative `*Source:*` links (`../src/...`), and restrict cleanup in `docs/` to `Icinga.*.md` and `index.md`. +- [x] **Full-Repository Code-Styling & SPDX Remediation (`src/`, `build/`, `Tests/`)** + - Upgraded `build/Test-ModuleCodeStyling.ps1` to scan `src/`, `build/`, `Tests/`, root `*.ps1`/`*.psm1`/`*.psd1` (`IcingaForWindows.psm1`, `IcingaForWindows.psd1`, `PSScriptAnalyzerSettings.psd1`), and compiled `lib/` SPDX headers by default, enforcing `src/` vs. `build/` function/type scope rules and mandatory concluding `.NOTES` + SPDX headers. + - Remediated all `208` files in `src/` (`0` violations; verified `0` non-comment/non-newline AST token differences against `main`), all `7` scripts in `build/` (`0` violations), and all `38` test suites in `Tests/` (`0` violations). + - Refactored `Tests/CodeStyling.Tests.ps1` (`6` tests) to fast `$TestDrive` unit tests (~250ms) so CI never scans the repository twice. +- [x] **Changelog, Roadmap & CI Governance (`docs/General/{Changelog,Roadmap}.md`, `build/Test-ModuleChangelog.ps1`, `Tests/Changelog.Tests.ps1`, `.github/workflows/ci.yml`)** + - Created `docs/General/Changelog.md` and `docs/General/Roadmap.md` covering completed `27.0.0` milestones and prioritized (`1` - `4`) planned work. + - Implemented `build/Test-ModuleChangelog.ps1` (enforcing net-new `* ` bullet additions against merge-base) and synthetic Git `$TestDrive` unit tests in `Tests/Changelog.Tests.ps1` (`6` tests). + - Integrated `Test-ModuleCodeStyling.ps1` and `Test-ModuleChangelog.ps1` alongside `Invoke-ScriptAnalysis.ps1` inside the `analyze` job of `.github/workflows/ci.yml` (`fetch-depth: 0`), plus targeted `lib/` SPDX validation in the `build` job. +- [x] **`README.md` Overhaul & Prose Naming Audit** + - Rewrote `README.md` in English with subsystem summaries, Mermaid runtime and CI pipeline diagrams, verified Quick Start and `New-IcingaPlugin` SDK examples, developer validation commands, documentation map, and `GPL-3.0-or-later` licensing. + - Audited all hand-written Markdown docs and source help blocks for strict `"Icinga for Windows"` prose naming and regenerated all `20` `docs/Icinga.*.md` + `docs/index.md` files (`0` broken relative links across all `52` Markdown files). +- [x] **Windows PowerShell 5.1 BOM-Less CP1252 & UNC Share Hardening** + - Eliminated all literal non-ASCII characters (`> 0x7F`, including `U+2192` `->`, box-drawing glyphs, ellipses, and emojis whose UTF-8 continuation bytes `0x91`-`0x94` are lexed as smart-quote string delimiters in Windows PowerShell 5.1 when dot-sourcing BOM-less `.ps1` files) across `src/`, `build/`, and compiled `lib/`. + - Enforced strict 7-bit ASCII (`0x00`-`0x7F`) across all PowerShell source, build, test, manifest, and compiled `lib/` files in `build/Test-ModuleCodeStyling.ps1` and `Tests/CodeStyling.Tests.ps1`. + - Replaced chunk-unsafe `FileStream.Read` in `build/Build-ModuleProject.ps1` with `[System.IO.File]::ReadAllText`, added alphabetical sorting for `Private` and `Public` kernel files, enforced Pester 5.0+ `New-PesterConfiguration` in Step `[5/5]`, and normalized `Resolve-Path` via `.ProviderPath` across `build/` and `Tests/` for UNC paths (`\\Mac\Home\...`). + +--- + +## Open Points & Known Limitations + +- [ ] **Windows-Only OS API Integration Suites (`17` Tests on macOS):** + `Get-IcingaPerformanceCounter.Tests.ps1` (`14` tests using `System.Diagnostics.PerformanceCounter`), `MemoryLeak.Tests.ps1` (`2` tests using `New-SelfSignedCertificate`), and `Get-IcingaDirectoryInformation.Tests.ps1` (`1` test using `WindowsPrincipal::GetCurrent()`) require native Windows APIs and execute in the `windows-latest` GitHub Actions runner (`test` job). All `489` cross-platform Pester tests pass locally on macOS. +- [ ] **Follow-Up Functional & Security Branches:** + Execute queued Priority 1 REST API, approved-path boundary, TLS certificate, and `IcingaProtocol` netstring/socket concurrency milestones tracked in [Roadmap.md](../../../General/Roadmap.md) on dedicated branches after `feature/update-code-styling` is merged. + +--- + +## Next Steps + +1. Merge `feature/update-code-styling` via Pull Request once the `windows-latest` GitHub Actions `analyze`, `build`, `docs`, `memory`, and `test` jobs pass end-to-end. diff --git a/docs/Agents/tasks/update-code-styling/walkthrough.md b/docs/Agents/tasks/update-code-styling/walkthrough.md new file mode 100644 index 0000000..84afc8b --- /dev/null +++ b/docs/Agents/tasks/update-code-styling/walkthrough.md @@ -0,0 +1,71 @@ +# Implementation Walkthrough -- Holistic Code-Styling, SPDX Licensing, Documentation & Governance (`update-code-styling`) + +## 1. Executive Summary + +Delivered complete code-styling, `GPL-3.0-or-later` SPDX licensing, changelog/roadmap governance, CI integration, and English architecture documentation across **Icinga for Windows** on branch `feature/update-code-styling`: + +1. **Zero-Exemption Code Styling Across 255+ PowerShell Files:** Brought all `208` source files in `src/`, `7` build scripts in `build/`, `38` test files in `Tests/`, `IcingaForWindows.psm1`, `IcingaForWindows.psd1`, and `PSScriptAnalyzerSettings.psd1` to **`0` violations** in [build/Test-ModuleCodeStyling.ps1](../../../../build/Test-ModuleCodeStyling.ps1), with mathematically verified **zero** non-comment/non-newline AST token changes across all `208` `src/*.ps1` files compared to `main` (`3f7fa6e`). +2. **End-to-End `GPL-3.0-or-later` SPDX Licensing:** Added mandatory `.NOTES` sections concluding with the two Icinga GmbH SPDX lines across `src/`, `build/`, `Tests/`, and `IcingaForWindows.psm1`; updated [IcingaForWindows.psd1](../../../../IcingaForWindows.psd1) (`Copyright` -> `GPL-3.0-or-later`, `LicenseUri` -> `blob/main/LICENSE`, `PrivateData.SPDX`); and updated [build/Build-ModuleProject.ps1](../../../../build/Build-ModuleProject.ps1) to emit BOM-less UTF-8 `lib/IcingaForWindows.{Classes,Kernel}.ps1` artifacts with top-of-file SPDX headers. +3. **Changelog, Roadmap & Single-Run CI Gates:** Added [docs/General/Changelog.md](../../../General/Changelog.md), [docs/General/Roadmap.md](../../../General/Roadmap.md), [build/Test-ModuleChangelog.ps1](../../../../build/Test-ModuleChangelog.ps1), and fast `$TestDrive` unit suites in [Tests/CodeStyling.Tests.ps1](../../../../Tests/CodeStyling.Tests.ps1) and [Tests/Changelog.Tests.ps1](../../../../Tests/Changelog.Tests.ps1), wiring both repository gates alongside `PSScriptAnalyzer` inside the `analyze` job of [.github/workflows/ci.yml](../../../../.github/workflows/ci.yml) without duplicate scans. +4. **English `README.md` & `"Icinga for Windows"` Prose Naming:** Rewrote [README.md](../../../../README.md) with Mermaid runtime and CI governance diagrams, audited all hand-written documentation and source help blocks for strict `"Icinga for Windows"` prose naming, and regenerated all `20` API reference files via [build/Build-ModuleDocs.ps1](../../../../build/Build-ModuleDocs.ps1). + +--- + +## 2. Under-the-Hood Deep Dive + +### 2.1 Scoped Function Rules & SPDX Enforcement (`build/Test-ModuleCodeStyling.ps1`) +- **Default Repository Scope:** When invoked without `-Path` or `-SourceFolder`, `Test-ModuleCodeStyling.ps1` automatically validates `src/`, `build/`, `Tests/`, all root `*.ps1`/`*.psm1`/`*.psd1` files (`IcingaForWindows.psm1`, `IcingaForWindows.psd1`, `PSScriptAnalyzerSettings.psd1`), and (when `lib/` exists) the BOM-less UTF-8 encoding and top-of-file SPDX header of `lib/IcingaForWindows.{Classes,Kernel}.ps1`. +- **`src/` vs. `build/` Function & Type Scope Rule:** AST inspection of `FunctionDefinitionAst` and `TypeDefinitionAst` nodes enforces exactly **one** top-level function, **zero** nested functions, and **zero** stray `class`/`enum` definitions per file in `src/` outside `src/Classes/` (and zero standalone functions in `src/Classes/`), while permitting internal helper and nested functions in `build/`, `IcingaForWindows.psm1`, and `Tests/`. +- **`.NOTES` & SPDX Validation:** Verifies that every function in `src/`, every top-level `class`/`enum` in `src/Classes/`, every comment-based help block in `IcingaForWindows.psm1`, `build/*.ps1`, and `Tests/*.Tests.ps1`, and the top header block of compiled `lib/IcingaForWindows.{Classes,Kernel}.ps1` artifacts concludes `.NOTES` with `SPDX-FileCopyrightText: 2026 Icinga GmbH ` followed by `SPDX-License-Identifier: GPL-3.0-or-later` (and `# SPDX-...` comments in `.psd1` data files). + +### 2.2 Non-`main` PR Changelog & Roadmap Gate (`build/Test-ModuleChangelog.ps1`) +- Validates UTF-8 without BOM encoding and required Markdown sections in `docs/General/Changelog.md` and `docs/General/Roadmap.md`. +- Detects `main` pushes (`GITHUB_REF_NAME=main` or local `HEAD == main`) vs. feature branches and GitHub Actions `pull_request` runs (`GITHUB_EVENT_NAME=pull_request` / `GITHUB_BASE_REF`, including non-`main` release base branches). +- Computes `git merge-base HEAD` and compares `MergeBase` against the working-tree `docs/General/Changelog.md`, requiring at least one **net-new** `* ...` bullet entry (`AddedBulletCount > RemovedBullets`) so merely rewording or deleting existing bullets cannot bypass the gate. + +### 2.3 Strict Doc Generator & BOM-Free Compiler (`Build-ModuleDocs.ps1` & `Build-ModuleProject.ps1`) +- `Build-ModuleDocs.ps1` requires `.NOTES` + both SPDX lines on all `198` `Public` and `Private` functions in `src/`, strips the machine-readable `SPDX-...` lines when rendering `#### Notes` into `docs/Icinga.*.md`, computes exact relative `*Source:*` links (`../src/...`) from `OutputPath` to `ModuleBasePath`, and cleans only `Icinga.*.md` and `index.md` inside `docs/`. +- `Build-ModuleProject.ps1` writes `lib/IcingaForWindows.Classes.ps1` and `lib/IcingaForWindows.Kernel.ps1` using `System.Text.UTF8Encoding($false)` (preventing Windows PowerShell 5.1 `Set-Content -Encoding UTF8` from inserting UTF-8 BOM bytes) with the two SPDX lines inside `.NOTES` of the top `<# ... #>` header block, sorts `Classes`, `Private`, and `Public` files deterministically across filesystems, reads sources via SMB-safe `[System.IO.File]::ReadAllText`, and explicitly imports Pester 5.0+ with `New-PesterConfiguration`. +- **Windows PowerShell 5.1 CP1252 Quote-Lexer & UNC Path Safeguard:** Because Windows PowerShell 5.1 reads BOM-less `.ps1` files via Windows-1252 (where UTF-8 continuation bytes `0x91`-`0x94` such as `0x92` inside `U+2192` `->` are lexed as closing smart quotes `'`), all `258` PowerShell files across `src/`, `build/`, `Tests/`, root, and `lib/` are strictly 7-bit ASCII (`0x00`-`0x7F`, enforced by `Test-ModuleCodeStyling.ps1`), runtime console tree glyphs use `[char]0x2514` / `[char]0x2500`, and `Resolve-Path` calls combine `[System.IO.Path]::GetFullPath((Resolve-Path ...).ProviderPath)` to strip `FileSystem::` provider prefixes and collapse `\..\` segments on UNC shares (`\\Mac\Home\...`). + +--- + +## 3. Verification Results + +All build, documentation, styling, changelog, static-analysis, AST token-equivalence, link-validation, and Pester checks were executed on PowerShell 7.7.0 / Pester 6.1.0: + +- **AST Executable Token-Stream Equivalence (`src/` vs. `main` `3f7fa6e`):** + `208 / 208` `src/*.ps1` files verified with **`0` non-comment, non-newline PowerShell token differences** and **`0` deleted inline comments** against `main`. +- **Module Compilation & AST Daemon Memory-Leak Check:** + `.\build\Build-ModuleProject.ps1 -SkipTests -TestDaemonMemoryLeaks` -> Compiled `10` classes, `156` private functions, and `42` public functions into BOM-less `lib/IcingaForWindows.{Classes,Kernel}.ps1` with top SPDX headers and **`0` daemon memory leaks**. +- **Module Manifest Validation:** + `Test-ModuleManifest -Path .\IcingaForWindows.psd1` & `Import-PowerShellDataFile` -> `IcingaForWindows v27.0.0`, `Copyright = '(c) 2026 Icinga GmbH | GPL-3.0-or-later'`, `PrivateData.SPDX` present. +- **Strict API Documentation Build:** + `.\build\Build-ModuleDocs.ps1 -Strict $true` -> Parsed `208` files (`198` functions across `19` components), wrote `20` Markdown files with **`0` violations**. +- **Repository-Wide Code-Styling & SPDX Gate:** + `.\build\Test-ModuleCodeStyling.ps1` -> **`0` violations** across all `src/`, `build/`, `Tests/`, `IcingaForWindows.psm1`, `IcingaForWindows.psd1`, `PSScriptAnalyzerSettings.psd1`, and `lib/` files (verified under both LF and simulated Windows CRLF checkouts). +- **Changelog & Roadmap Governance Gate:** + `.\build\Test-ModuleChangelog.ps1` -> **Passed (`0` violations)** on `feature/update-code-styling`. +- **`PSScriptAnalyzer` Static Analysis:** + `.\build\Invoke-ScriptAnalysis.ps1 -FailOn 'Warning'` -> **`0` build-breaking findings**. +- **Pester Unit Test Suite (`38` Test Files / `508` Tests):** + - `Tests/CodeStyling.Tests.ps1`: **`6 / 6` passed** (`$TestDrive` fixtures only; zero duplicate repo scan). + - `Tests/Changelog.Tests.ps1`: **`6 / 6` passed** (`$TestDrive` synthetic Git repos, including net-new bullet and non-`main` `GITHUB_BASE_REF` checks). + - Full suite (`.\build\Invoke-ModuleTests.ps1`): **`491` passed** (`479` baseline + `12` new governance unit tests; `0` regressions; `17` pre-existing Windows-only `PerformanceCounter` / `New-SelfSignedCertificate` / `WindowsPrincipal` OS API tests fail as expected on macOS). +- **Relative Markdown Link Audit:** + Validated all `52` Markdown files across root and `docs/` (both hand-written and generated `docs/Icinga.*.md`) -> **`0` broken relative links**. + +--- + +## 4. Practical Examples + +```powershell +# Run full repository code-styling and SPDX validation +.\build\Test-ModuleCodeStyling.ps1; + +# Validate PR / feature-branch changelog entry and Roadmap structure +.\build\Test-ModuleChangelog.ps1; + +# Run fast unit tests for both governance validators (~2s total) +Invoke-Pester -Path .\Tests\CodeStyling.Tests.ps1, .\Tests\Changelog.Tests.ps1; +``` diff --git a/docs/Developer/Plugins/04-Custom-Plugin-Developer-Guide.md b/docs/Developer/Plugins/04-Custom-Plugin-Developer-Guide.md index d0077e1..8307acb 100644 --- a/docs/Developer/Plugins/04-Custom-Plugin-Developer-Guide.md +++ b/docs/Developer/Plugins/04-Custom-Plugin-Developer-Guide.md @@ -370,4 +370,4 @@ Before submitting a new or migrated plugin, verify the following points: 2. **Every chain ends with `.Commit()` or `.Compile()`:** Never leave an `IcingaPlugin` chain unterminated and never use `| Out-Null`. 3. **Always handle provider errors:** Immediately check provider results with `if (Test-IcingaError -InputObject $Data) { return $CheckPackage.SetError($Data).Compile(); }`. 4. **Set `MetricIndex` and `MetricLabel` on multi-instance checks:** Ensures every instance produces a unique `index::ifw_template::label` metric in `check_multi` format. -5. **Follow `CLAUDE.md` code-styling rules:** UTF-8 without BOM, 4-space indentation, Allman braces with `function Name()`, vertically aligned `=` across assignment blocks, aligned `.PARAMETER` Markdown help tables, and no Unicode em-dashes (`\u2014`) or en-dashes (`\u2013`) (use `--` or `-` instead). Validated by `build/Test-ModuleCodeStyling.ps1`. +5. **Follow `docs/Agents/guidelines/01-Instruction.md` code-styling rules:** UTF-8 without BOM, 4-space indentation, Allman braces with `function Name()`, vertically aligned `=` across assignment blocks, aligned `.PARAMETER` Markdown help tables, and no Unicode em-dashes (`\u2014`) or en-dashes (`\u2013`) (use `--` or `-` instead). Validated by `build/Test-ModuleCodeStyling.ps1`. diff --git a/docs/Developer/Threading/01-Threading.md b/docs/Developer/Threading/01-Threading.md index 571583d..5df30da 100644 --- a/docs/Developer/Threading/01-Threading.md +++ b/docs/Developer/Threading/01-Threading.md @@ -245,7 +245,7 @@ $CheckResultData = @{ }; ``` -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. +The rule applies to all code outside `src/Classes` (see [01-Instruction.md](../../Agents/guidelines/01-Instruction.md#29-classes-and-threads), 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 diff --git a/docs/General/Changelog.md b/docs/General/Changelog.md new file mode 100644 index 0000000..69d8c11 --- /dev/null +++ b/docs/General/Changelog.md @@ -0,0 +1,39 @@ +# Icinga for Windows Changelog + +**The latest release announcements are available on [https://icinga.com/blog/](https://icinga.com/blog/).** + +Please review the [Architecture & Developer Documentation](../Developer/) and [Roadmap](Roadmap.md) for details on subsystem design and upcoming milestones. + +Released closed milestones can be found on [GitHub](https://github.com/Icinga/IcingaForWindows/milestones?state=closed). + +## 27.0.0 (Unreleased) + +[Issues and PRs](https://github.com/Icinga/IcingaForWindows/milestones) + +### Enhancements + +* Enforces zero-exemption PowerShell code-styling compliance, mandatory `.NOTES` sections with Icinga GmbH `GPL-3.0-or-later` SPDX license headers across all source, build, bootstrap, manifest, test, and compiled `lib/` files, automated PR changelog validation (`build/Test-ModuleChangelog.ps1`), `docs/General/Changelog.md` and `docs/General/Roadmap.md` governance, and an updated English `README.md` with Mermaid architecture diagrams (`feature/update-code-styling`) +* Adds nine core monitoring plugins (`Invoke-IcingaCheckCPU`, `Invoke-IcingaCheckDirectory`, `Invoke-IcingaCheckMemory`, `Invoke-IcingaCheckPartitionSpace`, `Invoke-IcingaCheckPerfCounter`, `Invoke-IcingaCheckProcess`, `Invoke-IcingaCheckScheduledTask`, `Invoke-IcingaCheckService`, `Invoke-IcingaCheckUptime`), promotes `New-IcingaPlugin` to a public Plugin SDK cmdlet, and introduces the modular Icinga 2 `event::ExecuteCommand` PowerShell and external binary execution pipeline (`3f7fa6e`) +* Adds the unified `IcingaPlugin` fluent check and package evaluation framework along with `IcingaCheckResult`, `IcingaError`, and `Test-IcingaError` (`be19ae1`) +* Adds the background `IcingaPerformanceCounter` daemon, category snapshot reader, static AST counter discovery, and persistent counter cache (`7e576b1`) +* [#18](https://github.com/Icinga/IcingaForWindows/pull/18) Adds the `IcingaThresholds` evaluation engine supporting Icinga range syntax, units, and percentage thresholds +* [#17](https://github.com/Icinga/IcingaForWindows/pull/17) Adds `IcingaUnit` and `ConvertTo-IcingaUnit` for SI and IEC unit conversion +* [#16](https://github.com/Icinga/IcingaForWindows/pull/16) Enhances `IcingaProtocol` stability, certificate handling, automatic module loading in `Build-ModuleProject.ps1`, and REST API thread inspection endpoints +* [#14](https://github.com/Icinga/IcingaForWindows/pull/14) Adds AST-based daemon endless-loop and `IDisposable` memory-leak detection (`build/Test-ModuleDaemonMemoryLeak.ps1`) +* [#4](https://github.com/Icinga/IcingaForWindows/pull/4) Adds configuration content diffing (`Compare-IcingaTextContent`) and native automation support +* [#3](https://github.com/Icinga/IcingaForWindows/pull/3) Introduces the GitHub Actions CI pipeline for module compilation, strict API documentation generation, `PSScriptAnalyzer`, daemon memory-leak checks, and Pester unit testing +* [#1](https://github.com/Icinga/IcingaForWindows/pull/1) Introduces the synchronized `$Global:IcingaForWindows` runtime architecture, runspace thread pool, structured logging daemon, TLS TCP stack, REST API, WebSocket client layer, and role-based access control + +### Bugfixes + +* Fixes Windows PowerShell 5.1 `lib/IcingaForWindows.Kernel.ps1` parser errors and Mojibake when dot-sourcing BOM-less UTF-8 artifacts by enforcing strict 7-bit ASCII across all PowerShell source, build, test, and compiled `lib/` files, deterministic file sorting and SMB-safe reading in `build/Build-ModuleProject.ps1`, and UNC `ProviderPath` normalization across build and test scripts (`feature/update-code-styling`) +* Fixes infinite exception loop in `Start-IcingaProtocolSocketWriter` when `WriterQueue` is disposed while the writer thread is still active (`c678e4f`) +* [#15](https://github.com/Icinga/IcingaForWindows/pull/15) [#13](https://github.com/Icinga/IcingaForWindows/pull/13) [#10](https://github.com/Icinga/IcingaForWindows/pull/10) [#7](https://github.com/Icinga/IcingaForWindows/pull/7) [#6](https://github.com/Icinga/IcingaForWindows/pull/6) Fixes memory leaks, file locks, and garbage-collection pressure across logging, worker queues, and compiled module loading +* [#12](https://github.com/Icinga/IcingaForWindows/pull/12) [#9](https://github.com/Icinga/IcingaForWindows/pull/9) Fixes `Start-ThreadHouseKeeper` lifecycle handling so completed and unresponsive threads are cleanly recycled +* [#11](https://github.com/Icinga/IcingaForWindows/pull/11) Fixes TCP client connection status verification and ensures `Open-SSLStream` closes the socket when an endpoint handshake fails +* [#8](https://github.com/Icinga/IcingaForWindows/pull/8) Fixes potential freezes on file locks by bounding secure file read and write retries + +### Security + +* Restricts external check binary and `.ps1` script execution in `Resolve-IcingaProtocolCommand` and `Invoke-IcingaProtocolCheckCommand` strictly to the approved `Get-ModuleBinaryDirectory` path (`$env:ProgramData\IcingaForWindows\Binaries`), rejecting path traversal, Alternate Data Streams, and arbitrary PowerShell cmdlet invocation (`IWKB001003`) +* Masks `[securestring]` check arguments as `'********'` in debug telemetry, passes secrets in-memory to PowerShell check plugins, and deterministically disposes temporary `SecureString` instances after execution diff --git a/docs/General/Roadmap.md b/docs/General/Roadmap.md new file mode 100644 index 0000000..8382281 --- /dev/null +++ b/docs/General/Roadmap.md @@ -0,0 +1,59 @@ +# Icinga for Windows Roadmap + +## Overview + +This document outlines the architectural roadmap for **Icinga for Windows** (`v27.0.0` and beyond). It tracks completed core subsystems, monitoring plugins, developer SDK capabilities, and prioritized upcoming engineering work in a single repository-level overview. + +## Milestones + +**Icinga for Windows** is continuously developed on the [`main` branch](https://github.com/Icinga/IcingaForWindows). Every feature, bugfix, security hardening, and refactoring pull request is recorded ahead of release in the [Icinga for Windows Changelog](Changelog.md), and detailed per-branch engineering plans are maintained under [`docs/Agents/tasks/`](../Agents/tasks/). + +## Completed Milestones & Subsystems + +The table below summarizes the foundational subsystems and milestones already delivered on the `27.0.0` architecture: + +| Status | Subsystem / Milestone | Summary & Delivered Capabilities | +| ------ | --------------------- | -------------------------------- | +| Completed | Core Runtime, Threading, Logging & Error Handling | Synchronized `$Global:IcingaForWindows` state (`Public`, `Private`, `Protected`), runspace thread pool (`New-Thread`, `Start-ThreadHouseKeeper`), structured logging queue (`Write-LoggingEntry`), internal return-code registry (`Set-InternalExitCodes`), and AST daemon memory-leak verification (`build/Test-ModuleDaemonMemoryLeak.ps1`) | +| Completed | TLS TCP Stack, REST API, WebSocket & Access Control | TLS 1.2+ socket listener/client helpers, multi-worker HTTP REST API (`Start-RestApiDaemon`), persistent WebSocket reader/writer workers (`Start-ModuleWebSocketDaemon`), approved-path filesystem wrappers (`src/Security/`), and role-based access control | +| Completed | Unit Conversion & Threshold Evaluation Engine | SI/IEC unit conversion (`IcingaUnit`, `ConvertTo-IcingaUnit`), natural sorting (`IcingaSortKey`, `ConvertTo-IcingaSortedArray`), wildcard array filtering (`Test-IcingaArrayFilter`), and full Icinga range/percentage threshold evaluation (`IcingaThresholds`) | +| Completed | Background Performance Counter Subsystem | Dedicated `IcingaPerformanceCounter` daemon (`Start-IcingaPerformanceCounterDaemon`), category-level bulk snapshots, static AST counter discovery at startup, automatic inline fallback, and atomic `PerformanceCounter.json` caching | +| Completed | Unified Plugin Framework & Public Plugin SDK | Fluent `IcingaPlugin` check/container class, `IcingaCheckResult`, `IcingaError`, `Test-IcingaError`, `O(1)` active check command tracking, and the public `New-IcingaPlugin` SDK cmdlet | +| Completed | Core Monitoring Plugins & Icinga 2 Execution Pipeline | Nine core monitoring plugins (`CPU`, `Directory`, `Memory`, `PartitionSpace`, `PerfCounter`, `Process`, `ScheduledTask`, `Service`, `Uptime`), native Icinga 2 `event::ExecuteCommand` dispatch, approved `Binaries` external process/script execution with Job Object / process-group timeout cleanup, and `IWKB001000`-`IWKB001003` Knowledgebase articles | +| Completed | Holistic Code-Styling, SPDX Licensing & Governance | Zero-exemption code-styling enforcement across 250+ PowerShell files (`build/Test-ModuleCodeStyling.ps1`), mandatory `.NOTES` + `GPL-3.0-or-later` SPDX headers across source/build/test/manifest/`lib/` artifacts, non-`main` PR changelog enforcement (`build/Test-ModuleChangelog.ps1`), unified AI agent ruleset (`docs/Agents/guidelines/01-Instruction.md`), and English `README.md` architecture documentation | + +## Issue Triage & Prioritization + +Opened issues, architectural tasks, and feature requests are triaged and prioritized according to operational impact: + +* **Crash / Security:** Unhandled daemon exceptions, runspace deadlocks, memory/handle leaks, and security boundary issues receive top priority (`Priority 1`). +* **Bug / Enhancement:** Functional improvements, protocol extensions, tooling automation, and plugin migrations are scheduled into prioritized milestones (`Priority 2` - `Priority 4`). + +## Feature List & Planned Work + +The following table lists upcoming engineering tasks, architectural enhancements, and planned modules for **Icinga for Windows**. + +> Note: Whenever an implementation plan under `docs/Agents/tasks//implementation_plan.md` is created or completed, this table must be updated in the same branch. + +| Priority\* | Scenario | Status / Task Plan | Description / Notes | +| ---------- | -------- | ------------------ | ------------------- | +| 1 | REST API Execution, Path Boundary & TLS Certificate Fixes | Planned | Integrate shared `ConvertTo-ModuleParameterValue` and `Invoke-ModulePowerShellCommand` helpers in `Invoke-RestApiCommandExecutionField`, mask and dispose `[securestring]` parameters, migrate REST JSON calls to `ConvertFrom-ModuleJson` / `ConvertTo-ModuleJson`, enforce canonical trailing-separator checks in `Test-SecureApprovedPath`, and fix premature `X509Certificate2` disposal in `Get-TlsCertificate` | +| 1 | Icinga Protocol Netstring Framing & Socket Concurrency | Planned | Replace character-based `StringBuilder` netstring slicing with UTF-8 byte-accurate framing in `Start-IcingaProtocolSocketReader` and `Read-IcingaRPCMessage`, pre-initialize per-endpoint `WriterQueue` before spawning socket writer/heartbeat threads, synchronize `Connections`, and harden disconnected-client guards | +| 1 | Pre-Compiled Native C# Helpers | Planned | Compile C# P/Invoke helpers (such as `DeviceIoControl` volume/disk-extent readers) into signed assemblies under `lib/` during `build/Build-ModuleProject.ps1` so runtime code never invokes `Add-Type -TypeDefinition` dynamically | +| 1 | Windows Service Hosting & Installer Packaging | Planned | Native Windows service wrapper, MSI / bootstrap installation and upgrade workflows, automatic Windows Firewall rule management, and configurable Windows service recovery policies | +| 2 | Just Enough Administration (JEA) & Least Privilege | Planned | Automated JEA session configuration compiler, managed least-privilege service account handling, and background SYSTEM task offloading for privileged checks | +| 2 | Metrics over Time (MoT) Background Daemon | Planned | Background time-series metric ring-buffer daemon and `-ThresholdInterval` support across monitoring plugins without blocking check execution | +| 2 | Icinga 2 DSL & Icinga Director Configuration Generator | Planned | Automated generation of Icinga 2 CheckCommand definitions and Icinga Director JSON baskets directly from plugin comment-based help and parameter metadata | +| 2 | Remaining Core Windows Monitoring Plugins | Planned | Migrate and modernize remaining Windows host checks onto `New-IcingaPlugin` (EventLog, X.509 Certificates, Network Adapter / Ping / Port, Time Sync / NTP, Windows Updates, Logged-On Users, Firewall, SMB / UNC Shares) | +| 2 | Static `FunctionsToExport` Manifest Synchronization | Planned | Populate explicit `FunctionsToExport` in `IcingaForWindows.psd1` during `Build-ModuleProject.ps1` for PowerShell module auto-loading (`$PSModuleAutoLoadingPreference`) prior to explicit `Import-Module` | +| 3 | Interactive Management Console & Web UI | Planned | Guided CLI / TUI and local Web UI workflows for configuring `IcingaProtocol` endpoints, TLS certificates, REST API access roles, and live check testing | +| 4 | Enterprise Application Monitoring Modules | Planned | Dedicated extension plugin modules built on the public `New-IcingaPlugin` SDK for Microsoft SQL Server (MSSQL), Hyper-V, Windows Failover Clustering, Active Directory, IIS, and Exchange Server | + +Feature Notes: + +\* Feature Priorities: + +1. Mandatory +2. Beneficial +3. Optional +4. Requires Sponsoring diff --git a/docs/Icinga.Config.md b/docs/Icinga.Config.md index 803d940..d367145 100644 --- a/docs/Icinga.Config.md +++ b/docs/Icinga.Config.md @@ -44,7 +44,7 @@ creating them if necessary, and returns the mapped numeric return code. Uses Get-ModuleConfigDirectory and Get-ModuleBinaryDirectory to resolve target paths. Missing directories are created with -Force. -*Source: [src/Config/Private/New-ModuleConfigEnvironment.ps1](../../src/Config/Private/New-ModuleConfigEnvironment.ps1)* +*Source: [src/Config/Private/New-ModuleConfigEnvironment.ps1](../src/Config/Private/New-ModuleConfigEnvironment.ps1)* --- @@ -68,19 +68,19 @@ callers receive $null on failure. **`$Config`** -| Name | Type | Description | Default | -|--------|---------------|-----------------------------------|---------| -| Config | System.String | Filename of the config to read. | $null | +| Name | Type | Description | Default | +|--------|---------------|---------------------------------|---------| +| Config | System.String | Filename of the config to read. | $null | **`$IncludeSubConfig`** -| Name | Type | Description | Default | -|------------------|---------------------------------------------|-----------------------------------------------------------|---------| +| Name | Type | Description | Default | +|------------------|----------------------------------------------|---------------------------------------------------------------|---------| | IncludeSubConfig | System.Management.Automation.SwitchParameter | When set, recursively reads sub-configs referenced by Config. | $false | #### Outputs -System.Object — Parsed JSON object on success, or $null on error. +System.Object -- Parsed JSON object on success, or $null on error. #### Examples @@ -97,5 +97,5 @@ Relies on Get-ModuleConfigDirectory and Read-SecureFile for file I/O. Returns $null via -OverrideReturn $null on error to match calling conventions elsewhere in the module. -*Source: [src/Config/Private/Read-ModuleConfigFile.ps1](../../src/Config/Private/Read-ModuleConfigFile.ps1)* +*Source: [src/Config/Private/Read-ModuleConfigFile.ps1](../src/Config/Private/Read-ModuleConfigFile.ps1)* diff --git a/docs/Icinga.Core.AccessControl.md b/docs/Icinga.Core.AccessControl.md index 6ffb814..d1680ff 100644 --- a/docs/Icinga.Core.AccessControl.md +++ b/docs/Icinga.Core.AccessControl.md @@ -1,347 +1,346 @@ -# Icinga.Core.AccessControl - -*Auto-generated from `src/Core/AccessControl/`. Do not edit by hand -- run `build/Build-ModuleDocs.ps1` to regenerate.* - -## Public functions - -- [New-IcingaAccessRole](#new-icingaaccessrole) -- [Remove-IcingaAccessRole](#remove-icingaaccessrole) -- [Show-IcingaAccessRoles](#show-icingaaccessroles) - -## Private helpers - -- [New-ModuleAccessRole](#new-moduleaccessrole) -- [Read-ModuleAccessControl](#read-moduleaccesscontrol) -- [Remove-ModuleAccessRole](#remove-moduleaccessrole) -- [Show-ModuleAccessRoles](#show-moduleaccessroles) - ---- - -### New-IcingaAccessRole - -*Public function* - -**Synopsis:** Public wrapper to create an Icinga access role - -#### Description - +# Icinga.Core.AccessControl + +*Auto-generated from `src/Core/AccessControl/`. Do not edit by hand -- run `build/Build-ModuleDocs.ps1` to regenerate.* + +## Public functions + +- [New-IcingaAccessRole](#new-icingaaccessrole) +- [Remove-IcingaAccessRole](#remove-icingaaccessrole) +- [Show-IcingaAccessRoles](#show-icingaaccessroles) + +## Private helpers + +- [New-ModuleAccessRole](#new-moduleaccessrole) +- [Read-ModuleAccessControl](#read-moduleaccesscontrol) +- [Remove-ModuleAccessRole](#remove-moduleaccessrole) +- [Show-ModuleAccessRoles](#show-moduleaccessroles) + +--- + +### New-IcingaAccessRole + +*Public function* + +**Synopsis:** Public wrapper to create an Icinga access role + +#### Description + Exposes a stable public API that delegates to `New-ModuleAccessRole` to create and persist an access role. Validates parameters are handled by the underlying implementation; this wrapper simply forwards arguments and returns the same -standardized return values. - -#### Parameters - -**`$RoleName`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| RoleName | System.String | Friendly name for the access role. | '' | - -**`$Users`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Users | System.String[] | List of usernames (or identifiers) assigned to the role. | @() | - -**`$AccessControlObject`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| AccessControlObject | System.PSCustomObject[] | Array of access control objects (ACLs) to attach to the role. | @() | - -**`$InheritedRoles`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| InheritedRoles | System.String[] | Roles whose permissions are inherited by this role. | @() | - -**`$Force`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Force | System.Management.Automation.SwitchParameter | Overwrite existing role file if present. | $false | - -#### Outputs - -PSCustomObject — Forwarded return value from `New-ModuleAccessRole`. - -#### Examples - -```powershell +standardized return values. + +#### Parameters + +**`$RoleName`** + +| Name | Type | Description | Default | +|----------|---------------|------------------------------------|---------| +| RoleName | System.String | Friendly name for the access role. | '' | + +**`$Users`** + +| Name | Type | Description | Default | +|-------|-----------------|----------------------------------------------------------|---------| +| Users | System.String[] | List of usernames (or identifiers) assigned to the role. | @() | + +**`$AccessControlObject`** + +| Name | Type | Description | Default | +|---------------------|-------------------------|---------------------------------------------------------------|---------| +| AccessControlObject | System.PSCustomObject[] | Array of access control objects (ACLs) to attach to the role. | @() | + +**`$InheritedRoles`** + +| Name | Type | Description | Default | +|----------------|-----------------|-----------------------------------------------------|---------| +| InheritedRoles | System.String[] | Roles whose permissions are inherited by this role. | @() | + +**`$Force`** + +| Name | Type | Description | Default | +|-------|----------------------------------------------|------------------------------------------|---------| +| Force | System.Management.Automation.SwitchParameter | Overwrite existing role file if present. | $false | + +#### Outputs + +PSCustomObject -- Forwarded return value from `New-ModuleAccessRole`. + +#### Examples + +```powershell PS> New-IcingaAccessRole -RoleName 'admin' -Users @('alice') -AccessControlObject $acl Creates the access role named admin for user alice using the provided access -control object and persists it via the private implementation. -``` - -#### Notes - +control object and persists it via the private implementation. +``` + +#### Notes + This function is intentionally thin and exists to expose a public command surface while the implementation and persistence logic remain in the module -private helper. - -*Source: [src/Core/AccessControl/Public/New-IcingaAccessRole.ps1](../../src/Core/AccessControl/Public/New-IcingaAccessRole.ps1)* - ---- - -### Remove-IcingaAccessRole - -*Public function* - -**Synopsis:** Public wrapper to remove a persisted Icinga access role - -#### Description - +private helper. + +*Source: [src/Core/AccessControl/Public/New-IcingaAccessRole.ps1](../src/Core/AccessControl/Public/New-IcingaAccessRole.ps1)* + +--- + +### Remove-IcingaAccessRole + +*Public function* + +**Synopsis:** Public wrapper to remove a persisted Icinga access role + +#### Description + Deletes a persisted access role by delegating to the private `Remove-ModuleAccessRole` implementation. Returns the underlying function's -return value or status codes in case of error. - -#### Parameters - -**`$RoleName`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| RoleName | System.String | Name of the role to remove. | '' | - -#### Outputs - -PSCustomObject — Forwarded return value from `Remove-ModuleAccessRole`. - -#### Examples - -```powershell +return value or status codes in case of error. + +#### Parameters + +**`$RoleName`** + +| Name | Type | Description | Default | +|----------|---------------|-----------------------------|---------| +| RoleName | System.String | Name of the role to remove. | '' | + +#### Outputs + +PSCustomObject -- Forwarded return value from `Remove-ModuleAccessRole`. + +#### Examples + +```powershell PS> Remove-IcingaAccessRole -RoleName 'admin' Removes the persisted access role named admin and refreshes the in-memory -access control definitions via the private implementation. -``` - -#### Notes - +access control definitions via the private implementation. +``` + +#### Notes + This wrapper keeps the public module API distinct from the private -implementation which performs the file deletion and reloads access control data. - -*Source: [src/Core/AccessControl/Public/Remove-IcingaAccessRole.ps1](../../src/Core/AccessControl/Public/Remove-IcingaAccessRole.ps1)* - ---- - -### Show-IcingaAccessRoles - -*Public function* - -**Synopsis:** Show loaded Icinga access roles - -#### Description - +implementation which performs the file deletion and reloads access control data. + +*Source: [src/Core/AccessControl/Public/Remove-IcingaAccessRole.ps1](../src/Core/AccessControl/Public/Remove-IcingaAccessRole.ps1)* + +--- + +### Show-IcingaAccessRoles + +*Public function* + +**Synopsis:** Show loaded Icinga access roles + +#### Description + Public wrapper that emits the current in-memory access role definitions via -the module logging system by delegating to `Show-ModuleAccessRoles`. - -#### Outputs - -None — Emits the current access role list to the logging system at Output level. - -#### Examples - -```powershell +the module logging system by delegating to `Show-ModuleAccessRoles`. + +#### Outputs + +None -- Emits the current access role list to the logging system at Output level. + +#### Examples + +```powershell PS> Show-IcingaAccessRoles -Writes all currently loaded Icinga access roles to the logging output channel. -``` - -#### Notes - +Writes all currently loaded Icinga access roles to the logging output channel. +``` + +#### Notes + This command does not modify state; it is purely informational and relies on -Read-ModuleAccessControl having been run previously to populate the in-memory list. - -*Source: [src/Core/AccessControl/Public/Show-IcingaAccessRoles.ps1](../../src/Core/AccessControl/Public/Show-IcingaAccessRoles.ps1)* - ---- - -### New-ModuleAccessRole - -*Private function* - -**Synopsis:** Create and persist a module access role with allowed users and ACLs - -#### Description - +Read-ModuleAccessControl having been run previously to populate the in-memory list. + +*Source: [src/Core/AccessControl/Public/Show-IcingaAccessRoles.ps1](../src/Core/AccessControl/Public/Show-IcingaAccessRoles.ps1)* + +--- + +### New-ModuleAccessRole + +*Private function* + +**Synopsis:** Create and persist a module access role with allowed users and ACLs + +#### Description + Constructs an access role object that contains the role name, users, access control objects and inherited roles. Persists the role as a JSON file under the module config `AccessRoles` directory using secure file helpers -and reloads the module access control definitions. - -#### Parameters - -**`$RoleName`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| RoleName | System.String | Friendly name for the access role. | '' | - -**`$Users`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Users | System.String[] | List of usernames (or identifiers) assigned to the role. | @() | - -**`$AccessControlObject`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| AccessControlObject | System.PSCustomObject[] | Array of access control objects (ACLs) to attach to the role. | @() | - -**`$InheritedRoles`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| InheritedRoles | System.String[] | Roles whose permissions are inherited by this role. | @() | - -**`$Force`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Force | System.Management.Automation.SwitchParameter | Overwrite existing role file if present. | $false | - -#### Outputs - -System.Object — Structured return object from Write-FunctionReturnValue. Returns +and reloads the module access control definitions. + +#### Parameters + +**`$RoleName`** + +| Name | Type | Description | Default | +|----------|---------------|------------------------------------|---------| +| RoleName | System.String | Friendly name for the access role. | '' | + +**`$Users`** + +| Name | Type | Description | Default | +|-------|-----------------|----------------------------------------------------------|---------| +| Users | System.String[] | List of usernames (or identifiers) assigned to the role. | @() | + +**`$AccessControlObject`** + +| Name | Type | Description | Default | +|---------------------|-------------------------|---------------------------------------------------------------|---------| +| AccessControlObject | System.PSCustomObject[] | Array of access control objects (ACLs) to attach to the role. | @() | + +**`$InheritedRoles`** + +| Name | Type | Description | Default | +|----------------|-----------------|-----------------------------------------------------|---------| +| InheritedRoles | System.String[] | Roles whose permissions are inherited by this role. | @() | + +**`$Force`** + +| Name | Type | Description | Default | +|-------|----------------------------------------------|------------------------------------------|---------| +| Force | System.Management.Automation.SwitchParameter | Overwrite existing role file if present. | $false | + +#### Outputs + +System.Object -- Structured return object from Write-FunctionReturnValue. Returns AccessRoleCreated on success (Data contains RoleName and AccessRole) or one of -several error return codes for validation or file errors. - -#### Examples - -```powershell +several error return codes for validation or file errors. + +#### Examples + +```powershell PS> New-ModuleAccessRole -RoleName 'admin' -Users @('alice','bob') -AccessControlObject $acl Creates the access role named admin, assigns it to alice and bob, and -persists the role file under the AccessRoles config directory. -``` - -#### Notes - +persists the role file under the AccessRoles config directory. +``` + +#### Notes + Role files are saved under the AccessRoles subfolder of Get-ModuleConfigDirectory. Write-SecureFile and New-SecureItem are used to persist files securely. Read-ModuleAccessControl is called after writing to reload the in-memory -access control definitions for the current session. - -*Source: [src/Core/AccessControl/Private/New-ModuleAccessRole.ps1](../../src/Core/AccessControl/Private/New-ModuleAccessRole.ps1)* - ---- - -### Read-ModuleAccessControl - -*Private function* - -**Synopsis:** Load and parse module access role files from the config directory - -#### Description - +access control definitions for the current session. + +*Source: [src/Core/AccessControl/Private/New-ModuleAccessRole.ps1](../src/Core/AccessControl/Private/New-ModuleAccessRole.ps1)* + +--- + +### Read-ModuleAccessControl + +*Private function* + +**Synopsis:** Load and parse module access role files from the config directory + +#### Description + Scans the module `AccessRoles` configuration folder for JSON role files, reads them using secure file helpers and parses them into PSCustomObjects which are stored in the global runtime variable `Protected.AccessControl` for runtime use. -Parsing and IO errors are logged and reported via `Write-FunctionReturnValue`. - -#### Outputs - -System.Object — Structured return object from Write-FunctionReturnValue when the +Parsing and IO errors are logged and reported via `Write-FunctionReturnValue`. + +#### Outputs + +System.Object -- Structured return object from Write-FunctionReturnValue when the AccessRoles folder is not found; otherwise None (populates -(Get-GlobalRuntimeVariable).Protected.AccessControl as a side effect). - -#### Examples - -```powershell +(Get-GlobalRuntimeVariable).Protected.AccessControl as a side effect). + +#### Examples + +```powershell PS> Read-ModuleAccessControl Scans the AccessRoles config folder, parses all role JSON files and stores the -resulting objects in the global runtime variable. -``` - -#### Notes - +resulting objects in the global runtime variable. +``` + +#### Notes + Role files are expected to be valid JSON and are read with Read-SecureFile. Parsing errors for individual files do not abort the overall loading process; -they are logged and the loader continues with the remaining files. - -*Source: [src/Core/AccessControl/Private/Read-ModuleAccessControl.ps1](../../src/Core/AccessControl/Private/Read-ModuleAccessControl.ps1)* - ---- - -### Remove-ModuleAccessRole - -*Private function* - -**Synopsis:** Remove a persisted module access role by name - -#### Description - +they are logged and the loader continues with the remaining files. + +*Source: [src/Core/AccessControl/Private/Read-ModuleAccessControl.ps1](../src/Core/AccessControl/Private/Read-ModuleAccessControl.ps1)* + +--- + +### Remove-ModuleAccessRole + +*Private function* + +**Synopsis:** Remove a persisted module access role by name + +#### Description + Deletes the role JSON file from the module `AccessRoles` folder after sanitizing the role name into a safe filename. Reloads module access control -definitions to reflect the deletion in the current runtime. - -#### Parameters - -**`$RoleName`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| RoleName | System.String | Name of the role to remove. | '' | - -#### Outputs - -System.Object — Structured return object from Write-FunctionReturnValue when the -role name is empty; otherwise None. - -#### Examples - -```powershell +definitions to reflect the deletion in the current runtime. + +#### Parameters + +**`$RoleName`** + +| Name | Type | Description | Default | +|----------|---------------|-----------------------------|---------| +| RoleName | System.String | Name of the role to remove. | '' | + +#### Outputs + +System.Object -- Structured return object from Write-FunctionReturnValue when the +role name is empty; otherwise None. + +#### Examples + +```powershell PS> Remove-ModuleAccessRole -RoleName 'admin' Removes the persisted access role file for admin and reloads the in-memory -access control definitions. -``` - -#### Notes - +access control definitions. +``` + +#### Notes + Uses Remove-SecureItem to safely delete the role file and then calls Read-ModuleAccessControl to refresh the in-memory role list for the current -session. - -*Source: [src/Core/AccessControl/Private/Remove-ModuleAccessRole.ps1](../../src/Core/AccessControl/Private/Remove-ModuleAccessRole.ps1)* - ---- - -### Show-ModuleAccessRoles - -*Private function* - -**Synopsis:** Output loaded module access roles to the logging system - -#### Description - +session. + +*Source: [src/Core/AccessControl/Private/Remove-ModuleAccessRole.ps1](../src/Core/AccessControl/Private/Remove-ModuleAccessRole.ps1)* + +--- + +### Show-ModuleAccessRoles + +*Private function* + +**Synopsis:** Output loaded module access roles to the logging system + +#### Description + Writes a formatted access role summary to the module logging system at the `Output` level. The function reads the in-memory access control objects from -the global runtime variable and emits them as structured log data. - -#### Outputs - -None — Emits structured log output at the Output level as a side effect. - -#### Examples - -```powershell +the global runtime variable and emits them as structured log data. + +#### Outputs + +None -- Emits structured log output at the Output level as a side effect. + +#### Examples + +```powershell PS> Show-ModuleAccessRoles -Writes the currently loaded access roles to the logging system at Output level. -``` - -#### Notes - +Writes the currently loaded access roles to the logging system at Output level. +``` + +#### Notes + This helper does not modify state; it only emits the current (Get-GlobalRuntimeVariable).Protected.AccessControl via Write-LoggingEntry. -Read-ModuleAccessControl must have been called previously to populate the list. - -*Source: [src/Core/AccessControl/Private/Show-ModuleAccessRoles.ps1](../../src/Core/AccessControl/Private/Show-ModuleAccessRoles.ps1)* - - +Read-ModuleAccessControl must have been called previously to populate the list. + +*Source: [src/Core/AccessControl/Private/Show-ModuleAccessRoles.ps1](../src/Core/AccessControl/Private/Show-ModuleAccessRoles.ps1)* + diff --git a/docs/Icinga.Core.ErrorHandling.md b/docs/Icinga.Core.ErrorHandling.md index 20b52fe..3dae6eb 100644 --- a/docs/Icinga.Core.ErrorHandling.md +++ b/docs/Icinga.Core.ErrorHandling.md @@ -31,9 +31,9 @@ for $null, for collections and for every other value. **`$InputObject`** -| Name | Type | Description | Default | -|-------------|---------------|------------------------------------------------|---------| -| InputObject | System.Object | Result of a data collection function to test. | $null | +| Name | Type | Description | Default | +|-------------|---------------|-----------------------------------------------|---------| +| InputObject | System.Object | Result of a data collection function to test. | $null | #### Outputs @@ -54,7 +54,7 @@ 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. -*Source: [src/Core/ErrorHandling/Public/Test-IcingaError.ps1](../../src/Core/ErrorHandling/Public/Test-IcingaError.ps1)* +*Source: [src/Core/ErrorHandling/Public/Test-IcingaError.ps1](../src/Core/ErrorHandling/Public/Test-IcingaError.ps1)* --- @@ -90,7 +90,7 @@ is already populated. Private helper used by error-handling and logging routines; safe to call multiple times because it will not overwrite an existing table. -*Source: [src/Core/ErrorHandling/Private/Set-InternalExitCodes.ps1](../../src/Core/ErrorHandling/Private/Set-InternalExitCodes.ps1)* +*Source: [src/Core/ErrorHandling/Private/Set-InternalExitCodes.ps1](../src/Core/ErrorHandling/Private/Set-InternalExitCodes.ps1)* --- @@ -111,33 +111,33 @@ Supports returning an override value instead of the mapped code. **`$ReturnValue`** -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ReturnValue | System.String | Semantic key of the return-code entry to emit (for example: 'TlsHandshakeSuccessful'). | | +| Name | Type | Description | Default | +|-------------|---------------|----------------------------------------------------------------------------------------|---------| +| ReturnValue | System.String | Semantic key of the return-code entry to emit (for example: 'TlsHandshakeSuccessful'). | | **`$Data`** -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Data | System.Collections.Hashtable | Additional contextual data to attach to the log entry. | @{} | +| Name | Type | Description | Default | +|------|------------------------------|--------------------------------------------------------|---------| +| Data | System.Collections.Hashtable | Additional contextual data to attach to the log entry. | @{} | **`$OverrideReturn`** -| Name | Type | Description | Default | -|------|------|-------------|---------| +| Name | Type | Description | Default | +|----------------|---------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------| | OverrideReturn | System.Object | If provided (not 'Core::IgnoreOverride'), this value is returned instead of the mapped numeric code. Booleans are returned via explicit cast to preserve type. | Core::IgnoreOverride | **`$AutomationRun`** -| Name | Type | Description | Default | -|------|------|-------------|---------| -| AutomationRun | System.Management.Automation.SwitchParameter | When set, returns @{ ExitCode; Output } instead of the numeric code. ExitCode is 0 for Info/Audit/Debug severities, 2 for all others. | $false | +| Name | Type | Description | Default | +|---------------|----------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------|---------| +| AutomationRun | System.Management.Automation.SwitchParameter | When set, returns @{ ExitCode; Output } instead of the numeric code. ExitCode is 0 for Info/Audit/Debug severities, 2 for all others. | $false | #### Outputs -System.Int32 — Numeric code from the return-code table when neither -OverrideReturn nor -AutomationRun is active. -System.Collections.Hashtable — @{ ExitCode = System.Int32; Output = System.String } when -AutomationRun is set. -System.Object — The -OverrideReturn value as-is when provided, taking precedence over both the numeric code and -AutomationRun. +System.Int32 -- Numeric code from the return-code table when neither -OverrideReturn nor -AutomationRun is active. +System.Collections.Hashtable -- @{ ExitCode = System.Int32; Output = System.String } when -AutomationRun is set. +System.Object -- The -OverrideReturn value as-is when provided, taking precedence over both the numeric code and -AutomationRun. #### Examples @@ -152,5 +152,5 @@ Enqueues a log entry via Write-LoggingEntry only when the entry's severity is en current logging configuration and is not 'Audit'. Must be called from the main thread or via Get-GlobalRuntimeVariable in daemon context. -*Source: [src/Core/ErrorHandling/Private/Write-FunctionReturnValue.ps1](../../src/Core/ErrorHandling/Private/Write-FunctionReturnValue.ps1)* +*Source: [src/Core/ErrorHandling/Private/Write-FunctionReturnValue.ps1](../src/Core/ErrorHandling/Private/Write-FunctionReturnValue.ps1)* diff --git a/docs/Icinga.Core.Logging.md b/docs/Icinga.Core.Logging.md index ced7add..9669510 100644 --- a/docs/Icinga.Core.Logging.md +++ b/docs/Icinga.Core.Logging.md @@ -1,950 +1,949 @@ -# Icinga.Core.Logging - -*Auto-generated from `src/Core/Logging/`. Do not edit by hand -- run `build/Build-ModuleDocs.ps1` to regenerate.* - -## Public functions - -- [Set-IcingaLogLevel](#set-icingaloglevel) - -## Private helpers - -- [Format-LoggingConsoleException](#format-loggingconsoleexception) -- [Format-LoggingConsoleMessage](#format-loggingconsolemessage) -- [Format-LoggingConsoleNullValue](#format-loggingconsolenullvalue) -- [Format-LoggingConsoleObjectProperties](#format-loggingconsoleobjectproperties) -- [Format-LoggingConsoleObjects](#format-loggingconsoleobjects) -- [Format-LoggingConsoleScalar](#format-loggingconsolescalar) -- [Format-LoggingConsoleSslStream](#format-loggingconsolesslstream) -- [Format-LoggingConsoleTcpClient](#format-loggingconsoletcpclient) -- [Format-LoggingConsoleTcpListener](#format-loggingconsoletcplistener) -- [Format-LoggingConsoleTlsCertificate](#format-loggingconsoletlscertificate) -- [Get-LoggingConsoleColorForObjectType](#get-loggingconsolecolorforobjecttype) -- [Get-LoggingConsoleColorForValue](#get-loggingconsolecolorforvalue) -- [Get-LoggingConsoleNestedProperty](#get-loggingconsolenestedproperty) -- [Get-LoggingEventLogSeverity](#get-loggingeventlogseverity) -- [Register-LoggingWindowsEventLog](#register-loggingwindowseventlog) -- [Set-LoggingLogLevel](#set-loggingloglevel) -- [Start-LoggingDaemon](#start-loggingdaemon) -- [Test-LoggingConsoleNextObjectIterable](#test-loggingconsolenextobjectiterable) -- [Test-LoggingWriteLog](#test-loggingwritelog) -- [Update-LoggingThreadLoggingId](#update-loggingthreadloggingid) -- [Write-LoggingEntry](#write-loggingentry) - ---- - -### Set-IcingaLogLevel - -*Public function* - -**Synopsis:** Set the global logging level for Icinga - -#### Description - +# Icinga.Core.Logging + +*Auto-generated from `src/Core/Logging/`. Do not edit by hand -- run `build/Build-ModuleDocs.ps1` to regenerate.* + +## Public functions + +- [Set-IcingaLogLevel](#set-icingaloglevel) + +## Private helpers + +- [Format-LoggingConsoleException](#format-loggingconsoleexception) +- [Format-LoggingConsoleMessage](#format-loggingconsolemessage) +- [Format-LoggingConsoleNullValue](#format-loggingconsolenullvalue) +- [Format-LoggingConsoleObjectProperties](#format-loggingconsoleobjectproperties) +- [Format-LoggingConsoleObjects](#format-loggingconsoleobjects) +- [Format-LoggingConsoleScalar](#format-loggingconsolescalar) +- [Format-LoggingConsoleSslStream](#format-loggingconsolesslstream) +- [Format-LoggingConsoleTcpClient](#format-loggingconsoletcpclient) +- [Format-LoggingConsoleTcpListener](#format-loggingconsoletcplistener) +- [Format-LoggingConsoleTlsCertificate](#format-loggingconsoletlscertificate) +- [Get-LoggingConsoleColorForObjectType](#get-loggingconsolecolorforobjecttype) +- [Get-LoggingConsoleColorForValue](#get-loggingconsolecolorforvalue) +- [Get-LoggingConsoleNestedProperty](#get-loggingconsolenestedproperty) +- [Get-LoggingEventLogSeverity](#get-loggingeventlogseverity) +- [Register-LoggingWindowsEventLog](#register-loggingwindowseventlog) +- [Set-LoggingLogLevel](#set-loggingloglevel) +- [Start-LoggingDaemon](#start-loggingdaemon) +- [Test-LoggingConsoleNextObjectIterable](#test-loggingconsolenextobjectiterable) +- [Test-LoggingWriteLog](#test-loggingwritelog) +- [Update-LoggingThreadLoggingId](#update-loggingthreadloggingid) +- [Write-LoggingEntry](#write-loggingentry) + +--- + +### Set-IcingaLogLevel + +*Public function* + +**Synopsis:** Set the global logging level for Icinga + +#### Description + `Set-IcingaLogLevel` updates the module-wide logging threshold stored in `$Global:Icinga.Public.Logging.Level`. The logging subsystem uses this value to decide which messages should be enqueued and processed. Use one of the -predefined levels to control verbosity. - -#### Parameters - -**`$Level`** - -| Name | Type | Description | Default | -|-------|---------------|-------------------------------|----------| -| Level | System.String | Desired minimum logging level | 'Info' | - -#### Outputs - -None — This function sets a global variable and does not emit pipeline output. - -#### Examples - -```powershell -PS> Set-IcingaLogLevel -Level 'Warning' -``` - -#### Notes - +predefined levels to control verbosity. + +#### Parameters + +**`$Level`** + +| Name | Type | Description | Default | +|-------|---------------|-------------------------------|---------| +| Level | System.String | Desired minimum logging level | 'Info' | + +#### Outputs + +None -- This function sets a global variable and does not emit pipeline output. + +#### Examples + +```powershell +PS> Set-IcingaLogLevel -Level 'Warning' +``` + +#### Notes + Valid levels are `Debug`, `Audit`, `Info`, `Success`, `Warning`, `Error` and `Fatal`. `Test-LoggingWriteLog` consults the global level to decide whether a message -at a given severity should be emitted. - -*Source: [src/Core/Logging/Public/Set-IcingaLogLevel.ps1](../../src/Core/Logging/Public/Set-IcingaLogLevel.ps1)* - ---- - -### Format-LoggingConsoleException - -*Private function* - -**Synopsis:** Format an exception object for console output. - -#### Description - +at a given severity should be emitted. + +*Source: [src/Core/Logging/Public/Set-IcingaLogLevel.ps1](../src/Core/Logging/Public/Set-IcingaLogLevel.ps1)* + +--- + +### Format-LoggingConsoleException + +*Private function* + +**Synopsis:** Format an exception object for console output. + +#### Description + `Format-LoggingConsoleException` returns a formatted representation of an exception -using `Format-LoggingConsoleObjectProperties` and a predefined set of properties. - -#### Parameters - -**`$Exception`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Exception | System.Exception | The exception to format | | - -**`$Indent`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Indent | System.String | Optional indentation string for nested formatting | '' | - -#### Outputs - -System.String — A formatted multiline string describing the exception. - -#### Examples - -```powershell -PS> Format-LoggingConsoleException -Exception $ex -Indent ' ' -``` - -#### Notes - -Uses `Format-LoggingConsoleObjectProperties` to extract common exception details. - -*Source: [src/Core/Logging/Private/Format-LoggingConsoleException.ps1](../../src/Core/Logging/Private/Format-LoggingConsoleException.ps1)* - ---- - -### Format-LoggingConsoleMessage - -*Private function* - -**Synopsis:** Format a markup-colored logging message for console output. - -#### Description - +using `Format-LoggingConsoleObjectProperties` and a predefined set of properties. + +#### Parameters + +**`$Exception`** + +| Name | Type | Description | Default | +|-----------|------------------|-------------------------|---------| +| Exception | System.Exception | The exception to format | | + +**`$Indent`** + +| Name | Type | Description | Default | +|--------|---------------|---------------------------------------------------|---------| +| Indent | System.String | Optional indentation string for nested formatting | '' | + +#### Outputs + +System.String -- A formatted multiline string describing the exception. + +#### Examples + +```powershell +PS> Format-LoggingConsoleException -Exception $ex -Indent ' ' +``` + +#### Notes + +Uses `Format-LoggingConsoleObjectProperties` to extract common exception details. + +*Source: [src/Core/Logging/Private/Format-LoggingConsoleException.ps1](../src/Core/Logging/Private/Format-LoggingConsoleException.ps1)* + +--- + +### Format-LoggingConsoleMessage + +*Private function* + +**Synopsis:** Format a markup-colored logging message for console output. + +#### Description + `Format-LoggingConsoleMessage` parses simple color markup tokens (e.g. [Red]...[/Red]) -and returns either a formatted string or writes the colored message to the host. - -#### Parameters - -**`$Message`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Message | System.String | Message containing optional color tags | | - -**`$GetMsgObj`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| GetMsgObj | System.SwitchParameter | When set the function returns the formatted string instead of writing to host | `$false` | - -#### Outputs - -System.String — The formatted message string when `-GetMsgObj` is set; otherwise None, the message is written directly to the host. - -#### Examples - -```powershell -PS> Format-LoggingConsoleMessage -Message '[Green]OK[/Green] Completed' -GetMsgObj -``` - -#### Notes - -Supports escaping and validates color names against `System.ConsoleColor`. - -*Source: [src/Core/Logging/Private/Format-LoggingConsoleMessage.ps1](../../src/Core/Logging/Private/Format-LoggingConsoleMessage.ps1)* - ---- - -### Format-LoggingConsoleNullValue - -*Private function* - -**Synopsis:** Return a formatted representation for null values in console output. - -#### Description - +and returns either a formatted string or writes the colored message to the host. + +#### Parameters + +**`$Message`** + +| Name | Type | Description | Default | +|---------|---------------|----------------------------------------|---------| +| Message | System.String | Message containing optional color tags | | + +**`$GetMsgObj`** + +| Name | Type | Description | Default | +|-----------|------------------------|-------------------------------------------------------------------------------|----------| +| GetMsgObj | System.SwitchParameter | When set the function returns the formatted string instead of writing to host | `$false` | + +#### Outputs + +System.String -- The formatted message string when `-GetMsgObj` is set; otherwise None, the message is written directly to the host. + +#### Examples + +```powershell +PS> Format-LoggingConsoleMessage -Message '[Green]OK[/Green] Completed' -GetMsgObj +``` + +#### Notes + +Supports escaping and validates color names against `System.ConsoleColor`. + +*Source: [src/Core/Logging/Private/Format-LoggingConsoleMessage.ps1](../src/Core/Logging/Private/Format-LoggingConsoleMessage.ps1)* + +--- + +### Format-LoggingConsoleNullValue + +*Private function* + +**Synopsis:** Return a formatted representation for null values in console output. + +#### Description + `Format-LoggingConsoleNullValue` returns a short, colored string representation -for null values used throughout logging output formatting helpers. - -#### Parameters - -**`$Indent`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Indent | System.String | Optional prefix indentation for the returned string | '' | - -#### Outputs - -System.String — A one-line formatted representation of a null value. - -#### Examples - -```powershell -PS> Format-LoggingConsoleNullValue -Indent ' ' -``` - -#### Notes - -Used by multiple formatting helpers to ensure consistent null rendering. - -*Source: [src/Core/Logging/Private/Format-LoggingConsoleNullValue.ps1](../../src/Core/Logging/Private/Format-LoggingConsoleNullValue.ps1)* - ---- - -### Format-LoggingConsoleObjectProperties - -*Private function* - -**Synopsis:** Format selected properties of an object for console logging. - -#### Description - +for null values used throughout logging output formatting helpers. + +#### Parameters + +**`$Indent`** + +| Name | Type | Description | Default | +|--------|---------------|-----------------------------------------------------|---------| +| Indent | System.String | Optional prefix indentation for the returned string | '' | + +#### Outputs + +System.String -- A one-line formatted representation of a null value. + +#### Examples + +```powershell +PS> Format-LoggingConsoleNullValue -Indent ' ' +``` + +#### Notes + +Used by multiple formatting helpers to ensure consistent null rendering. + +*Source: [src/Core/Logging/Private/Format-LoggingConsoleNullValue.ps1](../src/Core/Logging/Private/Format-LoggingConsoleNullValue.ps1)* + +--- + +### Format-LoggingConsoleObjectProperties + +*Private function* + +**Synopsis:** Format selected properties of an object for console logging. + +#### Description + `Format-LoggingConsoleObjectProperties` extracts named properties (including nested) -from an object and returns a colorized string suitable for console logging. - -#### Parameters - -**`$Object`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Object | System.Object | The input object to inspect | | - -**`$Properties`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Properties | System.Array | List of property paths to extract (e.g. 'Client.Address') | @() | - -**`$Indent`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Indent | System.String | Indentation prefix for each formatted line | '' | - -#### Outputs - -System.String — A multi-line formatted string with property:value pairs. - -#### Examples - -```powershell -PS> Format-LoggingConsoleObjectProperties -Object $resp -Properties @('Status','Body') -``` - -#### Notes - +from an object and returns a colorized string suitable for console logging. + +#### Parameters + +**`$Object`** + +| Name | Type | Description | Default | +|--------|---------------|-----------------------------|---------| +| Object | System.Object | The input object to inspect | | + +**`$Properties`** + +| Name | Type | Description | Default | +|------------|--------------|-----------------------------------------------------------|---------| +| Properties | System.Array | List of property paths to extract (e.g. 'Client.Address') | @() | + +**`$Indent`** + +| Name | Type | Description | Default | +|--------|---------------|--------------------------------------------|---------| +| Indent | System.String | Indentation prefix for each formatted line | '' | + +#### Outputs + +System.String -- A multi-line formatted string with property:value pairs. + +#### Examples + +```powershell +PS> Format-LoggingConsoleObjectProperties -Object $resp -Properties @('Status','Body') +``` + +#### Notes + Relies on `Get-LoggingConsoleNestedProperty`, `Get-LoggingConsoleColorForObjectType`, -and `Get-LoggingConsoleColorForValue` for nested access and color selection. - -*Source: [src/Core/Logging/Private/Format-LoggingConsoleObjectProperties.ps1](../../src/Core/Logging/Private/Format-LoggingConsoleObjectProperties.ps1)* - ---- - -### Format-LoggingConsoleObjects - -*Private function* - -**Synopsis:** Render complex objects into a readable, colorized console representation. - -#### Description - +and `Get-LoggingConsoleColorForValue` for nested access and color selection. + +*Source: [src/Core/Logging/Private/Format-LoggingConsoleObjectProperties.ps1](../src/Core/Logging/Private/Format-LoggingConsoleObjectProperties.ps1)* + +--- + +### Format-LoggingConsoleObjects + +*Private function* + +**Synopsis:** Render complex objects into a readable, colorized console representation. + +#### Description + `Format-LoggingConsoleObjects` handles arrays, hashtables, PSCustomObjects and several special CLR types (TcpClient, SslStream, X509Certificate2, TcpListener) -and returns a string with structured, colorized output for logging. - -#### Parameters - -**`$Object`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Object | System.Object | The object to format for console output | | - -**`$Level`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Level | System.Int32 | Indentation/nesting level for pretty printing | 0 | - -#### Outputs - -System.String — A formatted multi-line representation of the object. - -#### Examples - -```powershell -PS> Format-LoggingConsoleObjects -Object $response -Level 1 -``` - -#### Notes - +and returns a string with structured, colorized output for logging. + +#### Parameters + +**`$Object`** + +| Name | Type | Description | Default | +|--------|---------------|-----------------------------------------|---------| +| Object | System.Object | The object to format for console output | | + +**`$Level`** + +| Name | Type | Description | Default | +|-------|--------------|-----------------------------------------------|---------| +| Level | System.Int32 | Indentation/nesting level for pretty printing | 0 | + +#### Outputs + +System.String -- A formatted multi-line representation of the object. + +#### Examples + +```powershell +PS> Format-LoggingConsoleObjects -Object $response -Level 1 +``` + +#### Notes + This function delegates to other helpers (scalar, properties, nested access) -and is the central place for human-friendly logging formatting. - -*Source: [src/Core/Logging/Private/Format-LoggingConsoleObjects.ps1](../../src/Core/Logging/Private/Format-LoggingConsoleObjects.ps1)* - ---- - -### Format-LoggingConsoleScalar - -*Private function* - -**Synopsis:** Format a scalar value with color for console logging. - -#### Description - +and is the central place for human-friendly logging formatting. + +*Source: [src/Core/Logging/Private/Format-LoggingConsoleObjects.ps1](../src/Core/Logging/Private/Format-LoggingConsoleObjects.ps1)* + +--- + +### Format-LoggingConsoleScalar + +*Private function* + +**Synopsis:** Format a scalar value with color for console logging. + +#### Description + `Format-LoggingConsoleScalar` returns a one-line colored string for scalar values -using `Get-LoggingConsoleColorForValue` to determine an appropriate color. - -#### Parameters - -**`$Object`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Object | System.Object | The value to format | | - -**`$Indent`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Indent | System.String | Optional indentation prefix | '' | - -#### Outputs - -System.String — A formatted single-line representation of the scalar value. - -#### Examples - -```powershell -PS> Format-LoggingConsoleScalar -Object 123 -Indent ' ' -``` - -#### Notes - -Used internally by `Format-LoggingConsoleObjects` for fallback scalar formatting. - -*Source: [src/Core/Logging/Private/Format-LoggingConsoleScalar.ps1](../../src/Core/Logging/Private/Format-LoggingConsoleScalar.ps1)* - ---- - -### Format-LoggingConsoleSslStream - -*Private function* - -**Synopsis:** Format `SslStream` properties for console output. - -#### Description - +using `Get-LoggingConsoleColorForValue` to determine an appropriate color. + +#### Parameters + +**`$Object`** + +| Name | Type | Description | Default | +|--------|---------------|---------------------|---------| +| Object | System.Object | The value to format | | + +**`$Indent`** + +| Name | Type | Description | Default | +|--------|---------------|-----------------------------|---------| +| Indent | System.String | Optional indentation prefix | '' | + +#### Outputs + +System.String -- A formatted single-line representation of the scalar value. + +#### Examples + +```powershell +PS> Format-LoggingConsoleScalar -Object 123 -Indent ' ' +``` + +#### Notes + +Used internally by `Format-LoggingConsoleObjects` for fallback scalar formatting. + +*Source: [src/Core/Logging/Private/Format-LoggingConsoleScalar.ps1](../src/Core/Logging/Private/Format-LoggingConsoleScalar.ps1)* + +--- + +### Format-LoggingConsoleSslStream + +*Private function* + +**Synopsis:** Format `SslStream` properties for console output. + +#### Description + `Format-LoggingConsoleSslStream` extracts and formats commonly useful properties -from a `System.Net.Security.SslStream` and returns a colorized string. - -#### Parameters - -**`$Stream`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Stream | System.Net.Security.SslStream | The SSL stream to inspect | | - -**`$Indent`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Indent | System.String | Optional indentation prefix | $null | - -#### Outputs - -System.String — A multi-line formatted representation of the stream properties. - -#### Examples - -```powershell -PS> Format-LoggingConsoleSslStream -Stream $sslStream -Indent ' ' -``` - -#### Notes - -Delegates property extraction to `Format-LoggingConsoleObjectProperties`. - -*Source: [src/Core/Logging/Private/Format-LoggingConsoleSslStream.ps1](../../src/Core/Logging/Private/Format-LoggingConsoleSslStream.ps1)* - ---- - -### Format-LoggingConsoleTcpClient - -*Private function* - -**Synopsis:** Format a `TcpClient` for console logging. - -#### Description - +from a `System.Net.Security.SslStream` and returns a colorized string. + +#### Parameters + +**`$Stream`** + +| Name | Type | Description | Default | +|--------|-------------------------------|---------------------------|---------| +| Stream | System.Net.Security.SslStream | The SSL stream to inspect | | + +**`$Indent`** + +| Name | Type | Description | Default | +|--------|---------------|-----------------------------|---------| +| Indent | System.String | Optional indentation prefix | $null | + +#### Outputs + +System.String -- A multi-line formatted representation of the stream properties. + +#### Examples + +```powershell +PS> Format-LoggingConsoleSslStream -Stream $sslStream -Indent ' ' +``` + +#### Notes + +Delegates property extraction to `Format-LoggingConsoleObjectProperties`. + +*Source: [src/Core/Logging/Private/Format-LoggingConsoleSslStream.ps1](../src/Core/Logging/Private/Format-LoggingConsoleSslStream.ps1)* + +--- + +### Format-LoggingConsoleTcpClient + +*Private function* + +**Synopsis:** Format a `TcpClient` for console logging. + +#### Description + `Format-LoggingConsoleTcpClient` returns a formatted representation of a -`System.Net.Sockets.TcpClient`, including connection status and endpoints. - -#### Parameters - -**`$Client`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Client | System.Net.Sockets.TcpClient | The TCP client instance to format | | - -**`$Indent`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Indent | System.String | Optional indentation prefix | '' | - -#### Outputs - -System.String — A formatted multi-line description of the `TcpClient`. - -#### Examples - -```powershell -PS> Format-LoggingConsoleTcpClient -Client $client -``` - -#### Notes - -This helper uses `Format-LoggingConsoleObjectProperties` for property extraction. - -*Source: [src/Core/Logging/Private/Format-LoggingConsoleTcpClient.ps1](../../src/Core/Logging/Private/Format-LoggingConsoleTcpClient.ps1)* - ---- - -### Format-LoggingConsoleTcpListener - -*Private function* - -**Synopsis:** Format a `TcpListener` object for console logging. - -#### Description - +`System.Net.Sockets.TcpClient`, including connection status and endpoints. + +#### Parameters + +**`$Client`** + +| Name | Type | Description | Default | +|--------|------------------------------|-----------------------------------|---------| +| Client | System.Net.Sockets.TcpClient | The TCP client instance to format | | + +**`$Indent`** + +| Name | Type | Description | Default | +|--------|---------------|-----------------------------|---------| +| Indent | System.String | Optional indentation prefix | '' | + +#### Outputs + +System.String -- A formatted multi-line description of the `TcpClient`. + +#### Examples + +```powershell +PS> Format-LoggingConsoleTcpClient -Client $client +``` + +#### Notes + +This helper uses `Format-LoggingConsoleObjectProperties` for property extraction. + +*Source: [src/Core/Logging/Private/Format-LoggingConsoleTcpClient.ps1](../src/Core/Logging/Private/Format-LoggingConsoleTcpClient.ps1)* + +--- + +### Format-LoggingConsoleTcpListener + +*Private function* + +**Synopsis:** Format a `TcpListener` object for console logging. + +#### Description + `Format-LoggingConsoleTcpListener` extracts and formats selected properties of a -`System.Net.Sockets.TcpListener` and returns a colorized string for logging. - -#### Parameters - -**`$TcpListener`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| TcpListener | System.Net.Sockets.TcpListener | The listener to format | | - -**`$Indent`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Indent | System.String | Optional indentation prefix | '' | - -#### Outputs - -System.String — A formatted string describing listener properties. - -#### Examples - -```powershell -PS> Format-LoggingConsoleTcpListener -TcpListener $listener -``` - -#### Notes - -Used to present network listener details consistently in logs. - -*Source: [src/Core/Logging/Private/Format-LoggingConsoleTcpListener.ps1](../../src/Core/Logging/Private/Format-LoggingConsoleTcpListener.ps1)* - ---- - -### Format-LoggingConsoleTlsCertificate - -*Private function* - -**Synopsis:** Format an X509 certificate for console logging. - -#### Description - +`System.Net.Sockets.TcpListener` and returns a colorized string for logging. + +#### Parameters + +**`$TcpListener`** + +| Name | Type | Description | Default | +|-------------|--------------------------------|------------------------|---------| +| TcpListener | System.Net.Sockets.TcpListener | The listener to format | | + +**`$Indent`** + +| Name | Type | Description | Default | +|--------|---------------|-----------------------------|---------| +| Indent | System.String | Optional indentation prefix | '' | + +#### Outputs + +System.String -- A formatted string describing listener properties. + +#### Examples + +```powershell +PS> Format-LoggingConsoleTcpListener -TcpListener $listener +``` + +#### Notes + +Used to present network listener details consistently in logs. + +*Source: [src/Core/Logging/Private/Format-LoggingConsoleTcpListener.ps1](../src/Core/Logging/Private/Format-LoggingConsoleTcpListener.ps1)* + +--- + +### Format-LoggingConsoleTlsCertificate + +*Private function* + +**Synopsis:** Format an X509 certificate for console logging. + +#### Description + `Format-LoggingConsoleTlsCertificate` extracts a set of useful properties from a `System.Security.Cryptography.X509Certificates.X509Certificate2` and returns -them as a colorized multi-line string for inclusion in logs. - -#### Parameters - -**`$Certificate`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Certificate | System.Security.Cryptography.X509Certificates.X509Certificate2 | Certificate to format | | - -**`$Indent`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Indent | System.String | Optional indentation prefix | '' | - -#### Outputs - -System.String — A formatted representation of the certificate. - -#### Examples - -```powershell -PS> Format-LoggingConsoleTlsCertificate -Certificate $cert -``` - -#### Notes - -Useful when logging TLS connection metadata. - -*Source: [src/Core/Logging/Private/Format-LoggingConsoleTlsCertificate.ps1](../../src/Core/Logging/Private/Format-LoggingConsoleTlsCertificate.ps1)* - ---- - -### Get-LoggingConsoleColorForObjectType - -*Private function* - -**Synopsis:** Select a console color name for a given object type or parameter. - -#### Description - +them as a colorized multi-line string for inclusion in logs. + +#### Parameters + +**`$Certificate`** + +| Name | Type | Description | Default | +|-------------|----------------------------------------------------------------|-----------------------|---------| +| Certificate | System.Security.Cryptography.X509Certificates.X509Certificate2 | Certificate to format | | + +**`$Indent`** + +| Name | Type | Description | Default | +|--------|---------------|-----------------------------|---------| +| Indent | System.String | Optional indentation prefix | '' | + +#### Outputs + +System.String -- A formatted representation of the certificate. + +#### Examples + +```powershell +PS> Format-LoggingConsoleTlsCertificate -Certificate $cert +``` + +#### Notes + +Useful when logging TLS connection metadata. + +*Source: [src/Core/Logging/Private/Format-LoggingConsoleTlsCertificate.ps1](../src/Core/Logging/Private/Format-LoggingConsoleTlsCertificate.ps1)* + +--- + +### Get-LoggingConsoleColorForObjectType + +*Private function* + +**Synopsis:** Select a console color name for a given object type or parameter. + +#### Description + `Get-LoggingConsoleColorForObjectType` returns a string matching a `System.ConsoleColor` name appropriate for the provided object name or -for special cases like parameters and null values. - -#### Parameters - -**`$ObjectName`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ObjectName | System.String | The CLR type name or friendly name to evaluate | | - -**`$IsParameter`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| IsParameter | System.SwitchParameter | When set returns the color used for parameter names | $false | - -**`$IsNullValue`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| IsNullValue | System.SwitchParameter | When set returns the color used for null values | $false | - -#### Outputs - -System.String — The name of a `System.ConsoleColor` value. - -#### Examples - -```powershell -PS> Get-LoggingConsoleColorForObjectType -ObjectName 'String' -``` - -#### Notes - -Color choices are mapped to common CLR type names and special flags. - -*Source: [src/Core/Logging/Private/Get-LoggingConsoleColorForObjectType.ps1](../../src/Core/Logging/Private/Get-LoggingConsoleColorForObjectType.ps1)* - ---- - -### Get-LoggingConsoleColorForValue - -*Private function* - -**Synopsis:** Return the console color name for an arbitrary value. - -#### Description - +for special cases like parameters and null values. + +#### Parameters + +**`$ObjectName`** + +| Name | Type | Description | Default | +|------------|---------------|------------------------------------------------|---------| +| ObjectName | System.String | The CLR type name or friendly name to evaluate | | + +**`$IsParameter`** + +| Name | Type | Description | Default | +|-------------|------------------------|-----------------------------------------------------|---------| +| IsParameter | System.SwitchParameter | When set returns the color used for parameter names | $false | + +**`$IsNullValue`** + +| Name | Type | Description | Default | +|-------------|------------------------|-------------------------------------------------|---------| +| IsNullValue | System.SwitchParameter | When set returns the color used for null values | $false | + +#### Outputs + +System.String -- The name of a `System.ConsoleColor` value. + +#### Examples + +```powershell +PS> Get-LoggingConsoleColorForObjectType -ObjectName 'String' +``` + +#### Notes + +Color choices are mapped to common CLR type names and special flags. + +*Source: [src/Core/Logging/Private/Get-LoggingConsoleColorForObjectType.ps1](../src/Core/Logging/Private/Get-LoggingConsoleColorForObjectType.ps1)* + +--- + +### Get-LoggingConsoleColorForValue + +*Private function* + +**Synopsis:** Return the console color name for an arbitrary value. + +#### Description + `Get-LoggingConsoleColorForValue` inspects the input value and returns an appropriate `System.ConsoleColor` name by delegating to -`Get-LoggingConsoleColorForObjectType` with the value's CLR type name. - -#### Parameters - -**`$Value`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Value | System.Object | The value to choose a color for | | - -#### Outputs - -System.String — The chosen console color name. - -#### Examples - -```powershell -PS> Get-LoggingConsoleColorForValue -Value 42 -``` - -#### Notes - -Returns a special color for `$null` values. - -*Source: [src/Core/Logging/Private/Get-LoggingConsoleColorForValue.ps1](../../src/Core/Logging/Private/Get-LoggingConsoleColorForValue.ps1)* - ---- - -### Get-LoggingConsoleNestedProperty - -*Private function* - -**Synopsis:** Resolve a nested property path on an object safely. - -#### Description - +`Get-LoggingConsoleColorForObjectType` with the value's CLR type name. + +#### Parameters + +**`$Value`** + +| Name | Type | Description | Default | +|-------|---------------|---------------------------------|---------| +| Value | System.Object | The value to choose a color for | | + +#### Outputs + +System.String -- The chosen console color name. + +#### Examples + +```powershell +PS> Get-LoggingConsoleColorForValue -Value 42 +``` + +#### Notes + +Returns a special color for `$null` values. + +*Source: [src/Core/Logging/Private/Get-LoggingConsoleColorForValue.ps1](../src/Core/Logging/Private/Get-LoggingConsoleColorForValue.ps1)* + +--- + +### Get-LoggingConsoleNestedProperty + +*Private function* + +**Synopsis:** Resolve a nested property path on an object safely. + +#### Description + `Get-LoggingConsoleNestedProperty` walks a dot-separated property path (for example 'Client.Address') on an input object and returns the resolved value or `$null` if -any segment cannot be resolved. - -#### Parameters - -**`$InputObject`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| InputObject | System.Object | The object to query | | - -**`$PropertyPath`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| PropertyPath | System.String | Dot-separated property path to resolve | | - -#### Outputs - -System.Object — The resolved property value or `$null` when not found. - -#### Examples - -```powershell -PS> Get-LoggingConsoleNestedProperty -InputObject $resp -PropertyPath 'Client.Address' -``` - -#### Notes - -This helper intentionally swallows property access errors and returns `$null` on failure. - -*Source: [src/Core/Logging/Private/Get-LoggingConsoleNestedProperty.ps1](../../src/Core/Logging/Private/Get-LoggingConsoleNestedProperty.ps1)* - ---- - -### Get-LoggingEventLogSeverity - -*Private function* - -**Synopsis:** Map internal log severity to Windows EventLog entry types. - -#### Description - +any segment cannot be resolved. + +#### Parameters + +**`$InputObject`** + +| Name | Type | Description | Default | +|-------------|---------------|---------------------|---------| +| InputObject | System.Object | The object to query | | + +**`$PropertyPath`** + +| Name | Type | Description | Default | +|--------------|---------------|----------------------------------------|---------| +| PropertyPath | System.String | Dot-separated property path to resolve | | + +#### Outputs + +System.Object -- The resolved property value or `$null` when not found. + +#### Examples + +```powershell +PS> Get-LoggingConsoleNestedProperty -InputObject $resp -PropertyPath 'Client.Address' +``` + +#### Notes + +This helper intentionally swallows property access errors and returns `$null` on failure. + +*Source: [src/Core/Logging/Private/Get-LoggingConsoleNestedProperty.ps1](../src/Core/Logging/Private/Get-LoggingConsoleNestedProperty.ps1)* + +--- + +### Get-LoggingEventLogSeverity + +*Private function* + +**Synopsis:** Map internal log severity to Windows EventLog entry types. + +#### Description + `Get-LoggingEventLogSeverity` converts module logging severity labels to -Windows EventLog entry types such as 'Information' or 'Error'. - -#### Parameters - -**`$Severity`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Severity | System.String | Internal severity string (e.g. 'Debug', 'Info') | | - -#### Outputs - -System.String — The Windows EventLog entry type name. - -#### Examples - -```powershell -PS> Get-LoggingEventLogSeverity -Severity 'Error' -``` - -#### Notes - -Unknown severities default to 'Information'. - -*Source: [src/Core/Logging/Private/Get-LoggingEventLogSeverity.ps1](../../src/Core/Logging/Private/Get-LoggingEventLogSeverity.ps1)* - ---- - -### Register-LoggingWindowsEventLog - -*Private function* - -**Synopsis:** Create and configure Windows Event Log sources for this module. - -#### Description - +Windows EventLog entry types such as 'Information' or 'Error'. + +#### Parameters + +**`$Severity`** + +| Name | Type | Description | Default | +|----------|---------------|-------------------------------------------------|---------| +| Severity | System.String | Internal severity string (e.g. 'Debug', 'Info') | | + +#### Outputs + +System.String -- The Windows EventLog entry type name. + +#### Examples + +```powershell +PS> Get-LoggingEventLogSeverity -Severity 'Error' +``` + +#### Notes + +Unknown severities default to 'Information'. + +*Source: [src/Core/Logging/Private/Get-LoggingEventLogSeverity.ps1](../src/Core/Logging/Private/Get-LoggingEventLogSeverity.ps1)* + +--- + +### Register-LoggingWindowsEventLog + +*Private function* + +**Synopsis:** Create and configure Windows Event Log sources for this module. + +#### Description + `Register-LoggingWindowsEventLog` registers event sources under the provided -namespace and ensures the log maximum size is configured. - -#### Outputs - -None — Registers event sources under the module name and configures the maximum log size. - -#### Examples - -```powershell -PS> Register-LoggingWindowsEventLog -``` - -#### Notes - +namespace and ensures the log maximum size is configured. + +#### Outputs + +None -- Registers event sources under the module name and configures the maximum log size. + +#### Examples + +```powershell +PS> Register-LoggingWindowsEventLog +``` + +#### Notes + Requires administrative privileges to create Windows EventLog sources and modify log settings. The module name is resolved via `Get-ModuleProjectName`. Return codes are read from -`(Get-GlobalRuntimeVariable).Public.ReturnCodes` to derive the full list of source names. - -*Source: [src/Core/Logging/Private/Register-LoggingWindowsEventLog.ps1](../../src/Core/Logging/Private/Register-LoggingWindowsEventLog.ps1)* - ---- - -### Set-LoggingLogLevel - -*Private function* - -**Synopsis:** Set the global logging level for this module. - -#### Description - +`(Get-GlobalRuntimeVariable).Public.ReturnCodes` to derive the full list of source names. + +*Source: [src/Core/Logging/Private/Register-LoggingWindowsEventLog.ps1](../src/Core/Logging/Private/Register-LoggingWindowsEventLog.ps1)* + +--- + +### Set-LoggingLogLevel + +*Private function* + +**Synopsis:** Set the global logging level for this module. + +#### Description + `Set-LoggingLogLevel` updates the runtime logging level in the global -runtime variable so subsequent log writes follow the desired verbosity. - -#### Parameters - -**`$Level`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Level | System.String | One of 'Debug','Audit','Info','Success','Warning','Error','Fatal' | 'Info' | - -#### Outputs - -None — Updates `(Get-GlobalRuntimeVariable).Public.Logging.Level`. - -#### Examples - -```powershell -PS> Set-LoggingLogLevel -Level 'Debug' -``` - -#### Notes - -Use `Test-LoggingWriteLog` to determine whether a message at a given level will be emitted. - -*Source: [src/Core/Logging/Private/Set-LoggingLogLevel.ps1](../../src/Core/Logging/Private/Set-LoggingLogLevel.ps1)* - ---- - -### Start-LoggingDaemon - -*Private function* - -**Synopsis:** Background logging daemon that consumes the logging queue. - -#### Description - +runtime variable so subsequent log writes follow the desired verbosity. + +#### Parameters + +**`$Level`** + +| Name | Type | Description | Default | +|-------|---------------|-------------------------------------------------------------------|---------| +| Level | System.String | One of 'Debug','Audit','Info','Success','Warning','Error','Fatal' | 'Info' | + +#### Outputs + +None -- Updates `(Get-GlobalRuntimeVariable).Public.Logging.Level`. + +#### Examples + +```powershell +PS> Set-LoggingLogLevel -Level 'Debug' +``` + +#### Notes + +Use `Test-LoggingWriteLog` to determine whether a message at a given level will be emitted. + +*Source: [src/Core/Logging/Private/Set-LoggingLogLevel.ps1](../src/Core/Logging/Private/Set-LoggingLogLevel.ps1)* + +--- + +### Start-LoggingDaemon + +*Private function* + +**Synopsis:** Background logging daemon that consumes the logging queue. + +#### Description + `Start-LoggingDaemon` runs in a loop while `Test-ThreadRunning` is true and processes objects from the global logging queue. It formats messages, -writes Windows EventLog entries and prints colorized output to the console. - -#### Outputs - -None — Operates for side effects (writes logs and event entries). - -#### Examples - -```powershell -PS> Start-LoggingDaemon -``` - -#### Notes - +writes Windows EventLog entries and prints colorized output to the console. + +#### Outputs + +None -- Operates for side effects (writes logs and event entries). + +#### Examples + +```powershell +PS> Start-LoggingDaemon +``` + +#### Notes + This function must be executed inside a dedicated background runspace. It blocks indefinitely by calling `BlockingCollection.Take()` on the logging queue, so it must never run on the main thread. All access to shared state goes through `Get-GlobalRuntimeVariable` because the runspace receives only a snapshot of `$Global:Icinga` at startup. The daemon exits cleanly when `Test-ThreadRunning` -returns `$false`. - -*Source: [src/Core/Logging/Private/Start-LoggingDaemon.ps1](../../src/Core/Logging/Private/Start-LoggingDaemon.ps1)* - ---- - -### Test-LoggingConsoleNextObjectIterable - -*Private function* - -**Synopsis:** Determine whether an object should be treated as iterable for logging. - -#### Description - +returns `$false`. + +*Source: [src/Core/Logging/Private/Start-LoggingDaemon.ps1](../src/Core/Logging/Private/Start-LoggingDaemon.ps1)* + +--- + +### Test-LoggingConsoleNextObjectIterable + +*Private function* + +**Synopsis:** Determine whether an object should be treated as iterable for logging. + +#### Description + `Test-LoggingConsoleNextObjectIterable` inspects the provided value and returns `$true` if the logging formatter should iterate its child elements, or `$false` -for scalar values such as strings. - -#### Parameters - -**`$Value`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Value | System.Object | The value to test for iterable printing | | - -#### Outputs - -System.Boolean — `$true` when the value is considered iterable for logging. - -#### Examples - -```powershell -PS> Test-LoggingConsoleNextObjectIterable -Value $arr -``` - -#### Notes - -Strings and certain CLR types are intentionally excluded from iteration. - -*Source: [src/Core/Logging/Private/Test-LoggingConsoleNextObjectIterable.ps1](../../src/Core/Logging/Private/Test-LoggingConsoleNextObjectIterable.ps1)* - ---- - -### Test-LoggingWriteLog - -*Private function* - -**Synopsis:** Decide if a message at a given level should be emitted by the logger. - -#### Description - +for scalar values such as strings. + +#### Parameters + +**`$Value`** + +| Name | Type | Description | Default | +|-------|---------------|-----------------------------------------|---------| +| Value | System.Object | The value to test for iterable printing | | + +#### Outputs + +System.Boolean -- `$true` when the value is considered iterable for logging. + +#### Examples + +```powershell +PS> Test-LoggingConsoleNextObjectIterable -Value $arr +``` + +#### Notes + +Strings and certain CLR types are intentionally excluded from iteration. + +*Source: [src/Core/Logging/Private/Test-LoggingConsoleNextObjectIterable.ps1](../src/Core/Logging/Private/Test-LoggingConsoleNextObjectIterable.ps1)* + +--- + +### Test-LoggingWriteLog + +*Private function* + +**Synopsis:** Decide if a message at a given level should be emitted by the logger. + +#### Description + `Test-LoggingWriteLog` compares the requested message level against the currently configured global logging level and returns `$true` when the message -should be written. - -#### Parameters - -**`$Level`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Level | System.String | The severity of the message to evaluate | 'Info' | - -#### Outputs - -System.Boolean — `$true` if the message should be written given the current logging level. - -#### Examples - -```powershell -PS> Test-LoggingWriteLog -Level 'Debug' -``` - -#### Notes - -Logging level hierarchy is implemented by explicit membership checks per level. - -*Source: [src/Core/Logging/Private/Test-LoggingWriteLog.ps1](../../src/Core/Logging/Private/Test-LoggingWriteLog.ps1)* - ---- - -### Update-LoggingThreadLoggingId - -*Private function* - -**Synopsis:** Set or renew the current per-thread logging identifier. - -#### Description - +should be written. + +#### Parameters + +**`$Level`** + +| Name | Type | Description | Default | +|-------|---------------|-----------------------------------------|---------| +| Level | System.String | The severity of the message to evaluate | 'Info' | + +#### Outputs + +System.Boolean -- `$true` if the message should be written given the current logging level. + +#### Examples + +```powershell +PS> Test-LoggingWriteLog -Level 'Debug' +``` + +#### Notes + +Logging level hierarchy is implemented by explicit membership checks per level. + +*Source: [src/Core/Logging/Private/Test-LoggingWriteLog.ps1](../src/Core/Logging/Private/Test-LoggingWriteLog.ps1)* + +--- + +### Update-LoggingThreadLoggingId + +*Private function* + +**Synopsis:** Set or renew the current per-thread logging identifier. + +#### Description + `Update-LoggingThreadLoggingId` assigns a unique logging GUID for tracing logs -generated by a thread. If a `ThreadId` is provided it is used; otherwise a new GUID is created. - -#### Parameters - -**`$ThreadId`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ThreadId | System.String | Optional GUID to use as the current logging id | $null | - -#### Outputs - -None — Updates `(Get-GlobalRuntimeVariable).Private.Logging.CurrentLoggingId`. - -#### Examples - -```powershell -PS> Update-LoggingThreadLoggingId -ThreadId (New-Guid).ToString() -``` - -#### Notes - -This id helps correlate logs produced during the lifetime of a thread. - -*Source: [src/Core/Logging/Private/Update-LoggingThreadLoggingId.ps1](../../src/Core/Logging/Private/Update-LoggingThreadLoggingId.ps1)* - ---- - -### Write-LoggingEntry - -*Private function* - -**Synopsis:** Queue a structured log entry for asynchronous processing. - -#### Description - +generated by a thread. If a `ThreadId` is provided it is used; otherwise a new GUID is created. + +#### Parameters + +**`$ThreadId`** + +| Name | Type | Description | Default | +|----------|---------------|------------------------------------------------|---------| +| ThreadId | System.String | Optional GUID to use as the current logging id | $null | + +#### Outputs + +None -- Updates `(Get-GlobalRuntimeVariable).Private.Logging.CurrentLoggingId`. + +#### Examples + +```powershell +PS> Update-LoggingThreadLoggingId -ThreadId (New-Guid).ToString() +``` + +#### Notes + +This id helps correlate logs produced during the lifetime of a thread. + +*Source: [src/Core/Logging/Private/Update-LoggingThreadLoggingId.ps1](../src/Core/Logging/Private/Update-LoggingThreadLoggingId.ps1)* + +--- + +### Write-LoggingEntry + +*Private function* + +**Synopsis:** Queue a structured log entry for asynchronous processing. + +#### Description + `Write-LoggingEntry` constructs a logging object (message, level, event id, area, and additional data) and enqueues it into the global logging queue for processing -by the logging daemon. It also assigns a per-message logging id for correlation. - -#### Parameters - -**`$Message`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Message | System.String | The log message text | | - -**`$Level`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Level | System.String | Severity (Debug,Output,Audit,Info,Success,Warning,Error,Fatal) | 'Info' | - -**`$EventId`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| EventId | System.Int32 | Numeric event identifier for the log entry | 15 | - -**`$Data`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Data | System.Hashtable | Additional structured data to include with the log entry | @{} | - -#### Outputs - -System.Management.Automation.PSCustomObject — The enqueued log object when called from a background daemon with Level 'Output'; None otherwise. - -#### Examples - -```powershell -PS> Write-LoggingEntry -Message 'Started processing' -Level 'Info' -EventId 100 -``` - -#### Notes - +by the logging daemon. It also assigns a per-message logging id for correlation. + +#### Parameters + +**`$Message`** + +| Name | Type | Description | Default | +|---------|---------------|----------------------|---------| +| Message | System.String | The log message text | | + +**`$Level`** + +| Name | Type | Description | Default | +|-------|---------------|----------------------------------------------------------------|---------| +| Level | System.String | Severity (Debug,Output,Audit,Info,Success,Warning,Error,Fatal) | 'Info' | + +**`$EventId`** + +| Name | Type | Description | Default | +|---------|--------------|--------------------------------------------|---------| +| EventId | System.Int32 | Numeric event identifier for the log entry | 15 | + +**`$Data`** + +| Name | Type | Description | Default | +|------|------------------|----------------------------------------------------------|---------| +| Data | System.Hashtable | Additional structured data to include with the log entry | @{} | + +#### Outputs + +System.Management.Automation.PSCustomObject -- The enqueued log object when called from a background daemon with Level 'Output'; None otherwise. + +#### Examples + +```powershell +PS> Write-LoggingEntry -Message 'Started processing' -Level 'Info' -EventId 100 +``` + +#### Notes + This function is intentionally non-blocking: it enqueues messages for a background -consumer. It uses `(Get-GlobalRuntimeVariable).Private.Logging.CurrentLoggingId` to tag messages. - -*Source: [src/Core/Logging/Private/Write-LoggingEntry.ps1](../../src/Core/Logging/Private/Write-LoggingEntry.ps1)* - - +consumer. It uses `(Get-GlobalRuntimeVariable).Private.Logging.CurrentLoggingId` to tag messages. + +*Source: [src/Core/Logging/Private/Write-LoggingEntry.ps1](../src/Core/Logging/Private/Write-LoggingEntry.ps1)* + diff --git a/docs/Icinga.Core.RestApi.md b/docs/Icinga.Core.RestApi.md index cd32254..224072f 100644 --- a/docs/Icinga.Core.RestApi.md +++ b/docs/Icinga.Core.RestApi.md @@ -1,1198 +1,1197 @@ -# Icinga.Core.RestApi - -*Auto-generated from `src/Core/RestApi/`. Do not edit by hand -- run `build/Build-ModuleDocs.ps1` to regenerate.* - -## Public functions - -- [New-IcingaRestApiAccessControlObject](#new-icingarestapiaccesscontrolobject) -- [Send-IcingaRestApiRequest](#send-icingarestapirequest) -- [Set-IcingaRestApiConfig](#set-icingarestapiconfig) - -## Private helpers - -- [Add-RestApiClientToWorker](#add-restapiclienttoworker) -- [Expand-RestApiHeader](#expand-restapiheader) -- [Expand-RestApiQueryString](#expand-restapiquerystring) -- [Expand-RestApiWebPath](#expand-restapiwebpath) -- [Invoke-RestApiCall](#invoke-restapicall) -- [Invoke-RestApiCommandExecutionField](#invoke-restapicommandexecutionfield) -- [New-RestApiAccessControlObject](#new-restapiaccesscontrolobject) -- [New-RestApiEnvironment](#new-restapienvironment) -- [New-RestApiFaviconResponse](#new-restapifaviconresponse) -- [New-RestApiResponse](#new-restapiresponse) -- [Read-RestApiBody](#read-restapibody) -- [Read-RestApiConfig](#read-restapiconfig) -- [Read-RestApiHeader](#read-restapiheader) -- [Read-RestApiSpacesConfig](#read-restapispacesconfig) -- [Send-RestApiHtmlEndpointResponse](#send-restapihtmlendpointresponse) -- [Send-RestApiRequest](#send-restapirequest) -- [Set-RestApiConfig](#set-restapiconfig) -- [Start-RestApiDaemon](#start-restapidaemon) -- [Start-RestApiListener](#start-restapilistener) -- [Start-RestApiWorker](#start-restapiworker) -- [Test-RestApiAccessControl](#test-restapiaccesscontrol) -- [Test-RestApiCommandExecutionField](#test-restapicommandexecutionfield) - ---- - -### New-IcingaRestApiAccessControlObject - -*Public function* - -**Synopsis:** Create a RestApi access control object for use in Icinga role definitions - -#### Description - +# Icinga.Core.RestApi + +*Auto-generated from `src/Core/RestApi/`. Do not edit by hand -- run `build/Build-ModuleDocs.ps1` to regenerate.* + +## Public functions + +- [New-IcingaRestApiAccessControlObject](#new-icingarestapiaccesscontrolobject) +- [Send-IcingaRestApiRequest](#send-icingarestapirequest) +- [Set-IcingaRestApiConfig](#set-icingarestapiconfig) + +## Private helpers + +- [Add-RestApiClientToWorker](#add-restapiclienttoworker) +- [Expand-RestApiHeader](#expand-restapiheader) +- [Expand-RestApiQueryString](#expand-restapiquerystring) +- [Expand-RestApiWebPath](#expand-restapiwebpath) +- [Invoke-RestApiCall](#invoke-restapicall) +- [Invoke-RestApiCommandExecutionField](#invoke-restapicommandexecutionfield) +- [New-RestApiAccessControlObject](#new-restapiaccesscontrolobject) +- [New-RestApiEnvironment](#new-restapienvironment) +- [New-RestApiFaviconResponse](#new-restapifaviconresponse) +- [New-RestApiResponse](#new-restapiresponse) +- [Read-RestApiBody](#read-restapibody) +- [Read-RestApiConfig](#read-restapiconfig) +- [Read-RestApiHeader](#read-restapiheader) +- [Read-RestApiSpacesConfig](#read-restapispacesconfig) +- [Send-RestApiHtmlEndpointResponse](#send-restapihtmlendpointresponse) +- [Send-RestApiRequest](#send-restapirequest) +- [Set-RestApiConfig](#set-restapiconfig) +- [Start-RestApiDaemon](#start-restapidaemon) +- [Start-RestApiListener](#start-restapilistener) +- [Start-RestApiWorker](#start-restapiworker) +- [Test-RestApiAccessControl](#test-restapiaccesscontrol) +- [Test-RestApiCommandExecutionField](#test-restapicommandexecutionfield) + +--- + +### New-IcingaRestApiAccessControlObject + +*Public function* + +**Synopsis:** Create a RestApi access control object for use in Icinga role definitions + +#### Description + Public wrapper around `New-RestApiAccessControlObject` that constructs a reusable access control descriptor for the RestApi subsystem. The returned object specifies which HTTP methods, resources and client origins are permitted for a role, whether credentials are required and the maximum allowed request body size. Pass the returned object to `New-AccessRole` -to attach it to a user or group. - -#### Parameters - -**`$AllowedMethods`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| AllowedMethods | System.String[] | List of allowed HTTP methods (case-insensitive). Use `*` to allow all. | @('GET') | - -**`$AllowedResources`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| AllowedResources | System.String[] | Glob-style patterns of resources that are explicitly allowed. Use `*` to allow all. | @() | - -**`$BlockedResources`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| BlockedResources | System.String[] | Glob-style patterns of resources that are explicitly blocked. Use `*` to block all. | @('*') | - -**`$AllowedOrigins`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| AllowedOrigins | System.String[] | Client IP or hostname patterns that may access the API. Use `*` to allow all origins. | @('*') | - -**`$RequireCredentials`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| RequireCredentials | System.Boolean | When true, the access control entry requires credentials. | $false | - -**`$RequestBodySizeLimitKB`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| RequestBodySizeLimitKB | System.Int32 | Maximum allowed request body size in kilobytes. Negative values are normalized to 0. | 1024 | - -#### Outputs - -PSCustomObject — access control object with `AllowedMethods`, `AllowedResources`, +to attach it to a user or group. + +#### Parameters + +**`$AllowedMethods`** + +| Name | Type | Description | Default | +|----------------|-----------------|------------------------------------------------------------------------|----------| +| AllowedMethods | System.String[] | List of allowed HTTP methods (case-insensitive). Use `*` to allow all. | @('GET') | + +**`$AllowedResources`** + +| Name | Type | Description | Default | +|------------------|-----------------|-------------------------------------------------------------------------------------|---------| +| AllowedResources | System.String[] | Glob-style patterns of resources that are explicitly allowed. Use `*` to allow all. | @() | + +**`$BlockedResources`** + +| Name | Type | Description | Default | +|------------------|-----------------|-------------------------------------------------------------------------------------|---------| +| BlockedResources | System.String[] | Glob-style patterns of resources that are explicitly blocked. Use `*` to block all. | @('*') | + +**`$AllowedOrigins`** + +| Name | Type | Description | Default | +|----------------|-----------------|---------------------------------------------------------------------------------------|---------| +| AllowedOrigins | System.String[] | Client IP or hostname patterns that may access the API. Use `*` to allow all origins. | @('*') | + +**`$RequireCredentials`** + +| Name | Type | Description | Default | +|--------------------|----------------|-----------------------------------------------------------|---------| +| RequireCredentials | System.Boolean | When true, the access control entry requires credentials. | $false | + +**`$RequestBodySizeLimitKB`** + +| Name | Type | Description | Default | +|------------------------|--------------|--------------------------------------------------------------------------------------|---------| +| RequestBodySizeLimitKB | System.Int32 | Maximum allowed request body size in kilobytes. Negative values are normalized to 0. | 1024 | + +#### Outputs + +PSCustomObject -- access control object with `AllowedMethods`, `AllowedResources`, `BlockedResources`, `AllowedOrigins`, `RequireCredentials`, -`RequestBodySizeLimit` (bytes) and `Scope` set to `RestApi`. - -#### Examples - -```powershell -PS> New-IcingaRestApiAccessControlObject -AllowedMethods @('GET','POST') -AllowedResources @('/v1/*') -RequestBodySizeLimitKB 512 -``` - -#### Notes - +`RequestBodySizeLimit` (bytes) and `Scope` set to `RestApi`. + +#### Examples + +```powershell +PS> New-IcingaRestApiAccessControlObject -AllowedMethods @('GET','POST') -AllowedResources @('/v1/*') -RequestBodySizeLimitKB 512 +``` + +#### Notes + The `RequireCredentials` flag is informational in the current implementation; credential enforcement must be added in the request handling logic. The KB limit is converted to bytes internally. At least one allowed method -must be specified; passing an empty array causes the function to return `$null`. - -*Source: [src/Core/RestApi/Public/New-IcingaRestApiAccessControlObject.ps1](../../src/Core/RestApi/Public/New-IcingaRestApiAccessControlObject.ps1)* - ---- - -### Send-IcingaRestApiRequest - -*Public function* - -**Synopsis:** Send an HTTP(S) request to the local Icinga RestApi endpoint - -#### Description - +must be specified; passing an empty array causes the function to return `$null`. + +*Source: [src/Core/RestApi/Public/New-IcingaRestApiAccessControlObject.ps1](../src/Core/RestApi/Public/New-IcingaRestApiAccessControlObject.ps1)* + +--- + +### Send-IcingaRestApiRequest + +*Public function* + +**Synopsis:** Send an HTTP(S) request to the local Icinga RestApi endpoint + +#### Description + Public wrapper around `Send-RestApiRequest` that sends an HTTP or HTTPS request to the locally running RestApi daemon. The function loads the RestApi configuration to determine the listen port, constructs the full URI and forwards the call using `Invoke-RestMethod` with TLS certificate checking disabled for self-signed certificates. Non-GET methods serialize -the `Body` hashtable as JSON. Non-200 responses are returned as failures. - -#### Parameters - -**`$WebPath`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| WebPath | System.String | Relative web path or endpoint (e.g. '/v1/status'). Leading slash is optional. | '' | - -**`$Method`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Method | System.String | HTTP method to use (GET, POST, PUT, DELETE, etc.). | 'GET' | - -**`$Headers`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Headers | System.Collections.Hashtable | Additional HTTP headers to include in the request. | @{ 'Content-Type' = 'application/json'; } | - -**`$Body`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Body | System.Collections.Hashtable | Request body serialized as JSON for non-GET methods. | @{ } | - -#### Outputs - -PSCustomObject — structured return value from `Write-FunctionReturnValue`. +the `Body` hashtable as JSON. Non-200 responses are returned as failures. + +#### Parameters + +**`$WebPath`** + +| Name | Type | Description | Default | +|---------|---------------|-------------------------------------------------------------------------------|---------| +| WebPath | System.String | Relative web path or endpoint (e.g. '/v1/status'). Leading slash is optional. | '' | + +**`$Method`** + +| Name | Type | Description | Default | +|--------|---------------|----------------------------------------------------|---------| +| Method | System.String | HTTP method to use (GET, POST, PUT, DELETE, etc.). | 'GET' | + +**`$Headers`** + +| Name | Type | Description | Default | +|---------|------------------------------|----------------------------------------------------|-------------------------------------------| +| Headers | System.Collections.Hashtable | Additional HTTP headers to include in the request. | @{ 'Content-Type' = 'application/json'; } | + +**`$Body`** + +| Name | Type | Description | Default | +|------|------------------------------|------------------------------------------------------|---------| +| Body | System.Collections.Hashtable | Request body serialized as JSON for non-GET methods. | @{ } | + +#### Outputs + +PSCustomObject -- structured return value from `Write-FunctionReturnValue`. `RestApiRequestSuccessful` with `Response` in Data on success; -`RestApiRequestFailed` with `StatusCode` and `Response` or `Exception` on failure. - -#### Examples - -```powershell +`RestApiRequestFailed` with `StatusCode` and `Response` or `Exception` on failure. + +#### Examples + +```powershell PS> Send-IcingaRestApiRequest -WebPath '/v1/status' -Method 'GET' -PS> Send-IcingaRestApiRequest -WebPath '/v1/items' -Method 'POST' -Body @{ name = 'test' } -``` - -#### Notes - +PS> Send-IcingaRestApiRequest -WebPath '/v1/items' -Method 'POST' -Body @{ name = 'test' } +``` + +#### Notes + Requires a valid `restapi.json` configuration file to be present in the module config directory. The request always targets `https://localhost:`. Certificate validation is skipped via `-SkipCertificateCheck` to support -self-signed TLS certificates. - -*Source: [src/Core/RestApi/Public/Send-IcingaRestApiRequest.ps1](../../src/Core/RestApi/Public/Send-IcingaRestApiRequest.ps1)* - ---- - -### Set-IcingaRestApiConfig - -*Public function* - -**Synopsis:** Public wrapper to configure the Icinga RestApi settings. - -#### Description - +self-signed TLS certificates. + +*Source: [src/Core/RestApi/Public/Send-IcingaRestApiRequest.ps1](../src/Core/RestApi/Public/Send-IcingaRestApiRequest.ps1)* + +--- + +### Set-IcingaRestApiConfig + +*Public function* + +**Synopsis:** Public wrapper to configure the Icinga RestApi settings. + +#### Description + Public function that validates and applies RestApi configuration by delegating to the private `Set-RestApiConfig` function. This is the supported public API for module consumers to update the RestApi listen address, port, TLS configuration and worker count. The function returns the same standardized -return objects as the underlying private implementation. - -#### Parameters - -**`$ListenAddress`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ListenAddress | System.String | IP address or hostname to bind the RestApi listener. Use '0.0.0.0' to bind all interfaces. | '0.0.0.0' | - -**`$ListenPort`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ListenPort | System.Int32 | TCP port to listen on (1-65535). | 5668 | - -**`$TlsCertConfig`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| TlsCertConfig | System.PSCustomObject | TLS certificate configuration created by `New-IcingaTlsCertConfig`. | $null | - -**`$WorkerCount`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| WorkerCount | System.Int32 | Number of worker threads to spawn for handling connections. | 5 | - -**`$DryRun`** - -| Name | Type | Description | Default | -|--------|----------------------------------------------|---------------------------------------------------------------------------------------------------|---------| -| DryRun | System.Management.Automation.SwitchParameter | When set, returns a unified diff of the pending configuration versus the persisted restapi.json instead of writing the change. | $false | - -#### Outputs - -PSCustomObject — Function return value forwarded from `Set-RestApiConfig`. - -#### Examples - -```powershell -PS> Set-IcingaRestApiConfig -ListenAddress '127.0.0.1' -ListenPort 10443 -WorkerCount 8 -``` - -#### Notes - +return objects as the underlying private implementation. + +#### Parameters + +**`$ListenAddress`** + +| Name | Type | Description | Default | +|---------------|---------------|--------------------------------------------------------------------------------------------|-----------| +| ListenAddress | System.String | IP address or hostname to bind the RestApi listener. Use '0.0.0.0' to bind all interfaces. | '0.0.0.0' | + +**`$ListenPort`** + +| Name | Type | Description | Default | +|------------|--------------|----------------------------------|---------| +| ListenPort | System.Int32 | TCP port to listen on (1-65535). | 5668 | + +**`$TlsCertConfig`** + +| Name | Type | Description | Default | +|---------------|-----------------------|---------------------------------------------------------------------|---------| +| TlsCertConfig | System.PSCustomObject | TLS certificate configuration created by `New-IcingaTlsCertConfig`. | $null | + +**`$WorkerCount`** + +| Name | Type | Description | Default | +|-------------|--------------|-------------------------------------------------------------|---------| +| WorkerCount | System.Int32 | Number of worker threads to spawn for handling connections. | 5 | + +**`$DryRun`** + +| Name | Type | Description | Default | +|--------|----------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------|---------| +| DryRun | System.Management.Automation.SwitchParameter | When set, returns a unified diff of the pending configuration versus the persisted restapi.json instead of writing the change. | $false | + +#### Outputs + +PSCustomObject -- Function return value forwarded from `Set-RestApiConfig`. + +#### Examples + +```powershell +PS> Set-IcingaRestApiConfig -ListenAddress '127.0.0.1' -ListenPort 10443 -WorkerCount 8 +``` + +#### Notes + This public wrapper exists to expose a stable module API while keeping the implementation in `Set-RestApiConfig` (private) where validation and persistence -logic is implemented. - -*Source: [src/Core/RestApi/Public/Set-IcingaRestApiConfig.ps1](../../src/Core/RestApi/Public/Set-IcingaRestApiConfig.ps1)* - ---- - -### Add-RestApiClientToWorker - -*Private function* - -**Synopsis:** Assign a new TCP client to a RestApi worker queue. - -#### Description - +logic is implemented. + +*Source: [src/Core/RestApi/Public/Set-IcingaRestApiConfig.ps1](../src/Core/RestApi/Public/Set-IcingaRestApiConfig.ps1)* + +--- + +### Add-RestApiClientToWorker + +*Private function* + +**Synopsis:** Assign a new TCP client to a RestApi worker queue. + +#### Description + Performs a simple round-robin assignment of an accepted `TcpClient` to one of the RestApi worker queues managed in the global runtime state. Logs the -assignment and validates the input client. - -#### Parameters - -**`$TcpClient`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| TcpClient | System.Net.Sockets.TcpClient | Accepted TCP client to assign to a worker queue. | | - -#### Outputs - -None - -#### Examples - -```powershell -PS> Add-RestApiClientToWorker -TcpClient $acceptedClient -``` - -#### Notes - +assignment and validates the input client. + +#### Parameters + +**`$TcpClient`** + +| Name | Type | Description | Default | +|-----------|------------------------------|--------------------------------------------------|---------| +| TcpClient | System.Net.Sockets.TcpClient | Accepted TCP client to assign to a worker queue. | | + +#### Outputs + +None + +#### Examples + +```powershell +PS> Add-RestApiClientToWorker -TcpClient $acceptedClient +``` + +#### Notes + This helper expects RestApi worker queues to be initialized under `(Get-GlobalRuntimeVariable).Public.RestApi.WorkerQueue` and a -`WorkerCount` value in the RestApi configuration. - -*Source: [src/Core/RestApi/Private/Add-RestApiClientToWorker.ps1](../../src/Core/RestApi/Private/Add-RestApiClientToWorker.ps1)* - ---- - -### Expand-RestApiHeader - -*Private function* - -**Synopsis:** Parse raw HTTP header text into structured header data. - -#### Description - +`WorkerCount` value in the RestApi configuration. + +*Source: [src/Core/RestApi/Private/Add-RestApiClientToWorker.ps1](../src/Core/RestApi/Private/Add-RestApiClientToWorker.ps1)* + +--- + +### Expand-RestApiHeader + +*Private function* + +**Synopsis:** Parse raw HTTP header text into structured header data. + +#### Description + Parses a raw HTTP request header string into a hashtable containing the request method, path, HTTP version and a dictionary of headers. Returns -the parsed structure or logs an error and returns `$null` on parse failure. - -#### Parameters - -**`$HeaderString`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| HeaderString | System.String | Raw HTTP header string including request line and headers. | | - -#### Outputs - -System.Collections.Hashtable — parsed header hashtable with `Method`, `Path`, `HttpVersion` and `Headers`. - -#### Examples - -```powershell -PS> Expand-RestApiHeader -HeaderString $rawHeader -``` - -#### Notes - -Used by RestApi worker processing to interpret incoming HTTP requests. - -*Source: [src/Core/RestApi/Private/Expand-RestApiHeader.ps1](../../src/Core/RestApi/Private/Expand-RestApiHeader.ps1)* - ---- - -### Expand-RestApiQueryString - -*Private function* - -**Synopsis:** Parse a URL query string into a hashtable of parameters. - -#### Description - +the parsed structure or logs an error and returns `$null` on parse failure. + +#### Parameters + +**`$HeaderString`** + +| Name | Type | Description | Default | +|--------------|---------------|------------------------------------------------------------|---------| +| HeaderString | System.String | Raw HTTP header string including request line and headers. | | + +#### Outputs + +System.Collections.Hashtable -- parsed header hashtable with `Method`, `Path`, `HttpVersion` and `Headers`. + +#### Examples + +```powershell +PS> Expand-RestApiHeader -HeaderString $rawHeader +``` + +#### Notes + +Used by RestApi worker processing to interpret incoming HTTP requests. + +*Source: [src/Core/RestApi/Private/Expand-RestApiHeader.ps1](../src/Core/RestApi/Private/Expand-RestApiHeader.ps1)* + +--- + +### Expand-RestApiQueryString + +*Private function* + +**Synopsis:** Parse a URL query string into a hashtable of parameters. + +#### Description + Parses a query string into key/value pairs while respecting quoted values and percent-encoding. Multiple occurrences of the same key -are converted into arrays. - -#### Parameters - -**`$QueryString`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| QueryString | System.String | Raw query string (may include leading '?'). | | - -**`$QueryParams`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| QueryParams | System.Collections.Hashtable | Hashtable to populate with parsed parameters. | @{} | - -#### Outputs - -None — modifies the provided `QueryParams` hashtable in place. - -#### Examples - -```powershell -PS> Expand-RestApiQueryString -QueryString '?q=hello%20world&tags=one&tags=two' -QueryParams $params -``` - -#### Notes - +are converted into arrays. + +#### Parameters + +**`$QueryString`** + +| Name | Type | Description | Default | +|-------------|---------------|---------------------------------------------|---------| +| QueryString | System.String | Raw query string (may include leading '?'). | | + +**`$QueryParams`** + +| Name | Type | Description | Default | +|-------------|------------------------------|-----------------------------------------------|---------| +| QueryParams | System.Collections.Hashtable | Hashtable to populate with parsed parameters. | @{} | + +#### Outputs + +None -- modifies the provided `QueryParams` hashtable in place. + +#### Examples + +```powershell +PS> Expand-RestApiQueryString -QueryString '?q=hello%20world&tags=one&tags=two' -QueryParams $params +``` + +#### Notes + This function is tolerant to quoted parameter values and retains array -semantics for repeated keys. - -*Source: [src/Core/RestApi/Private/Expand-RestApiQueryString.ps1](../../src/Core/RestApi/Private/Expand-RestApiQueryString.ps1)* - ---- - -### Expand-RestApiWebPath - -*Private function* - -**Synopsis:** Normalize and split an HTTP path into segments. - -#### Description - +semantics for repeated keys. + +*Source: [src/Core/RestApi/Private/Expand-RestApiQueryString.ps1](../src/Core/RestApi/Private/Expand-RestApiQueryString.ps1)* + +--- + +### Expand-RestApiWebPath + +*Private function* + +**Synopsis:** Normalize and split an HTTP path into segments. + +#### Description + Normalizes a web path by collapsing consecutive slashes, trimming trailing slashes (except for root) and returning an object with the normalized path -and an array of path segments. - -#### Parameters - -**`$WebPath`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| WebPath | System.String | The HTTP path to normalize (e.g. '/api/v1/resource/'). | | - -#### Outputs - -System.Collections.Hashtable — parsed path object with keys `Segments`, `QueryParams`, `WebPath`, -`HasQuery`, `SegmentCount` and optional `Version`, `Space`, `Action`, `Resource`. - -#### Examples - -```powershell -PS> Expand-RestApiWebPath -Path '/api//v1/resource/' -``` - -#### Notes - +and an array of path segments. + +#### Parameters + +**`$WebPath`** + +| Name | Type | Description | Default | +|---------|---------------|--------------------------------------------------------|---------| +| WebPath | System.String | The HTTP path to normalize (e.g. '/api/v1/resource/'). | | + +#### Outputs + +System.Collections.Hashtable -- parsed path object with keys `Segments`, `QueryParams`, `WebPath`, +`HasQuery`, `SegmentCount` and optional `Version`, `Space`, `Action`, `Resource`. + +#### Examples + +```powershell +PS> Expand-RestApiWebPath -Path '/api//v1/resource/' +``` + +#### Notes + This helper is used when routing incoming requests to configured RestApi -spaces and handlers. - -*Source: [src/Core/RestApi/Private/Expand-RestApiWebPath.ps1](../../src/Core/RestApi/Private/Expand-RestApiWebPath.ps1)* - ---- - -### Invoke-RestApiCall - -*Private function* - -**Synopsis:** Resolve the REST API path to a configured handler and execute it. - -#### Description - +spaces and handlers. + +*Source: [src/Core/RestApi/Private/Expand-RestApiWebPath.ps1](../src/Core/RestApi/Private/Expand-RestApiWebPath.ps1)* + +--- + +### Invoke-RestApiCall + +*Private function* + +**Synopsis:** Resolve the REST API path to a configured handler and execute it. + +#### Description + Core dispatcher of the Icinga for Windows REST API. Reads the parsed web-path and headers from `$Global.Private.RestApi.*`, walks the configured -spaces hashtable (Space → Action → Resource) to locate an +spaces hashtable (Space -> Action -> Resource) to locate an `ApiCommandExecution` field and invokes the bound PowerShell function via `Invoke-RestApiCommandExecutionField`. Emits the appropriate JSON response on success and well-formed error responses on failure -(missing space → 404, invalid path depth → 400, command error → 500, -no spaces configured → 500, no command at all → HTML endpoint listing -or 200 / 404 for JSON callers). - -#### Outputs - -System.Int32 — A semantic return code resolved through +(missing space -> 404, invalid path depth -> 400, command error -> 500, +no spaces configured -> 500, no command at all -> HTML endpoint listing +or 200 / 404 for JSON callers). + +#### Outputs + +System.Int32 -- A semantic return code resolved through `Write-FunctionReturnValue` for downstream diagnostics. The HTTP -response is sent directly over the worker's TCP stream. - -#### Examples - -```powershell +response is sent directly over the worker's TCP stream. + +#### Examples + +```powershell PS> Invoke-RestApiCall Called by `Start-RestApiWorker` after the request line and body have -been parsed; arguments are taken from worker-private state. -``` - -#### Notes - +been parsed; arguments are taken from worker-private state. +``` + +#### Notes + Path schema is `/v1///`. The actual `ApiCommandExecution` lookup supports 2, 3 or 4 segments (segment -count is checked before the handler runs). - -*Source: [src/Core/RestApi/Private/Invoke-RestApiCall.ps1](../../src/Core/RestApi/Private/Invoke-RestApiCall.ps1)* - ---- - -### Invoke-RestApiCommandExecutionField - -*Private function* - -**Synopsis:** Invoke the function defined in an ApiCommandExecution space configuration - -#### Description - +count is checked before the handler runs). + +*Source: [src/Core/RestApi/Private/Invoke-RestApiCall.ps1](../src/Core/RestApi/Private/Invoke-RestApiCall.ps1)* + +--- + +### Invoke-RestApiCommandExecutionField + +*Private function* + +**Synopsis:** Invoke the function defined in an ApiCommandExecution space configuration + +#### Description + Validates the provided space object, resolves the configured PowerShell function name, verifies the HTTP method is permitted, maps query or body parameters to the expected types defined in the space configuration and then calls the function via splatting. Web path, header and body context are read from `(Get-GlobalRuntimeVariable).Private.RestApi`. Returns the -function result or a structured error object on failure. - -#### Parameters - -**`$Space`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Space | PSCustomObject | ApiCommandExecution configuration object with `Function`, `Method` and `Parameters` properties. | $null | - -#### Outputs - -System.Object — the return value of the invoked function, or a hashtable -with an `error` key when the invocation fails or is not permitted. - -#### Examples - -```powershell -PS> Invoke-RestApiCommandExecutionField -Space $spaceObj.ApiCommandExecution -``` - -#### Notes - +function result or a structured error object on failure. + +#### Parameters + +**`$Space`** + +| Name | Type | Description | Default | +|-------|----------------|-------------------------------------------------------------------------------------------------|---------| +| Space | PSCustomObject | ApiCommandExecution configuration object with `Function`, `Method` and `Parameters` properties. | $null | + +#### Outputs + +System.Object -- the return value of the invoked function, or a hashtable +with an `error` key when the invocation fails or is not permitted. + +#### Examples + +```powershell +PS> Invoke-RestApiCommandExecutionField -Space $spaceObj.ApiCommandExecution +``` + +#### Notes + Parameter type mapping supports `int`, `string`, `bool` and `array`. Array values in GET query strings are split on commas while respecting quoted strings. Must only be called from within a RestApi worker thread -after `Private.RestApi.WebPath` and `Private.RestApi.Header` are set. - -*Source: [src/Core/RestApi/Private/Invoke-RestApiCommandExecutionField.ps1](../../src/Core/RestApi/Private/Invoke-RestApiCommandExecutionField.ps1)* - ---- - -### New-RestApiAccessControlObject - -*Private function* - -**Synopsis:** Create a RestApi access control object describing allowed methods and resources. - -#### Description - +after `Private.RestApi.WebPath` and `Private.RestApi.Header` are set. + +*Source: [src/Core/RestApi/Private/Invoke-RestApiCommandExecutionField.ps1](../src/Core/RestApi/Private/Invoke-RestApiCommandExecutionField.ps1)* + +--- + +### New-RestApiAccessControlObject + +*Private function* + +**Synopsis:** Create a RestApi access control object describing allowed methods and resources. + +#### Description + Helps construct a reusable access control object for RestApi spaces. The object contains allowed HTTP methods, allowed/blocked resources, allowed client origins, credentials requirement and a request body size limit. It is intended to be embedded in system access roles or used directly by -the RestApi access control evaluation routines. - -#### Parameters - -**`$AllowedMethods`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| AllowedMethods | System.String[] | List of allowed HTTP methods (case-insensitive). Use `*` to allow all. | @('GET') | - -**`$AllowedResources`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| AllowedResources | System.String[] | Glob-style patterns of resources that are explicitly allowed. Use `*` to allow all. | @() | - -**`$BlockedResources`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| BlockedResources | System.String[] | Glob-style patterns of resources that are explicitly blocked. Use `*` to block all. | @('*') | - -**`$AllowedOrigins`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| AllowedOrigins | System.String[] | Client IP/hostname patterns that are allowed to access the API. Use `*` to allow all origins. | @('*') | - -**`$RequireCredentials`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| RequireCredentials | System.Boolean | When true, the ACL requires credentials (not implemented in this helper). | $false | - -**`$RequestBodySizeLimitKB`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| RequestBodySizeLimitKB | System.Int32 | Maximum allowed request body size in kilobytes. Negative values are normalized to 0. | 1024 | - -#### Outputs - -PSCustomObject — access control object ready for inclusion in role definitions. - -#### Examples - -```powershell -PS> New-RestApiAccessControlObject -AllowedMethods @('GET','POST') -AllowedResources @('/v1/*') -RequestBodySizeLimitKB 512 -``` - -#### Notes - +the RestApi access control evaluation routines. + +#### Parameters + +**`$AllowedMethods`** + +| Name | Type | Description | Default | +|----------------|-----------------|------------------------------------------------------------------------|----------| +| AllowedMethods | System.String[] | List of allowed HTTP methods (case-insensitive). Use `*` to allow all. | @('GET') | + +**`$AllowedResources`** + +| Name | Type | Description | Default | +|------------------|-----------------|-------------------------------------------------------------------------------------|---------| +| AllowedResources | System.String[] | Glob-style patterns of resources that are explicitly allowed. Use `*` to allow all. | @() | + +**`$BlockedResources`** + +| Name | Type | Description | Default | +|------------------|-----------------|-------------------------------------------------------------------------------------|---------| +| BlockedResources | System.String[] | Glob-style patterns of resources that are explicitly blocked. Use `*` to block all. | @('*') | + +**`$AllowedOrigins`** + +| Name | Type | Description | Default | +|----------------|-----------------|-----------------------------------------------------------------------------------------------|---------| +| AllowedOrigins | System.String[] | Client IP/hostname patterns that are allowed to access the API. Use `*` to allow all origins. | @('*') | + +**`$RequireCredentials`** + +| Name | Type | Description | Default | +|--------------------|----------------|---------------------------------------------------------------------------|---------| +| RequireCredentials | System.Boolean | When true, the ACL requires credentials (not implemented in this helper). | $false | + +**`$RequestBodySizeLimitKB`** + +| Name | Type | Description | Default | +|------------------------|--------------|--------------------------------------------------------------------------------------|---------| +| RequestBodySizeLimitKB | System.Int32 | Maximum allowed request body size in kilobytes. Negative values are normalized to 0. | 1024 | + +#### Outputs + +PSCustomObject -- access control object ready for inclusion in role definitions. + +#### Examples + +```powershell +PS> New-RestApiAccessControlObject -AllowedMethods @('GET','POST') -AllowedResources @('/v1/*') -RequestBodySizeLimitKB 512 +``` + +#### Notes + The returned object converts KB limit to bytes and normalizes string -arrays. The `RequireCredentials` flag is informational — credential -enforcement must be implemented in the request handling logic. - -*Source: [src/Core/RestApi/Private/New-RestApiAccessControlObject.ps1](../../src/Core/RestApi/Private/New-RestApiAccessControlObject.ps1)* - ---- - -### New-RestApiEnvironment - -*Private function* - -**Synopsis:** Initialize RestApi runtime environment structures - -#### Description - +arrays. The `RequireCredentials` flag is informational -- credential +enforcement must be implemented in the request handling logic. + +*Source: [src/Core/RestApi/Private/New-RestApiAccessControlObject.ps1](../src/Core/RestApi/Private/New-RestApiAccessControlObject.ps1)* + +--- + +### New-RestApiEnvironment + +*Private function* + +**Synopsis:** Initialize RestApi runtime environment structures + +#### Description + Loads the RestApi configuration from disk via `Read-RestApiConfig`, reads all space definitions via `Read-RestApiSpacesConfig`, loads the TLS certificate and then creates the blocking worker queues and spawns one `Start-RestApiWorker` thread per configured worker. Finally, it starts the `Start-RestApiListener` thread. The function reads worker count from `(Get-GlobalRuntimeVariable).Public.RestApi.Config.WorkerCount` which must -be populated before this function runs. - -#### Outputs - -None — populates `(Get-GlobalRuntimeVariable).Public.RestApi.WorkerQueue` -and starts all worker and listener threads. - -#### Examples - -```powershell -PS> New-RestApiEnvironment -``` - -#### Notes - +be populated before this function runs. + +#### Outputs + +None -- populates `(Get-GlobalRuntimeVariable).Public.RestApi.WorkerQueue` +and starts all worker and listener threads. + +#### Examples + +```powershell +PS> New-RestApiEnvironment +``` + +#### Notes + Must be called after `Set-RestApiConfig` has been executed so that a valid `restapi.json` configuration file exists. All threads started here rely on the global runtime variable rather than parameters, so thread-safety -depends on the blocking collections used for the worker queues. - -*Source: [src/Core/RestApi/Private/New-RestApiEnvironment.ps1](../../src/Core/RestApi/Private/New-RestApiEnvironment.ps1)* - ---- - -### New-RestApiFaviconResponse - -*Private function* - -**Synopsis:** Build an HTTP response object for a favicon.ico request. - -#### Description - +depends on the blocking collections used for the worker queues. + +*Source: [src/Core/RestApi/Private/New-RestApiEnvironment.ps1](../src/Core/RestApi/Private/New-RestApiEnvironment.ps1)* + +--- + +### New-RestApiFaviconResponse + +*Private function* + +**Synopsis:** Build an HTTP response object for a favicon.ico request. + +#### Description + Constructs a simple response object containing the provided icon bytes and correct `Content-Type` header for `image/x-icon`. Returns the response -structure or logs an error when no data is supplied. - -#### Outputs - -System.Collections.Hashtable — response object with `Message` (byte[]) and -`Length` (int), ready to pass to `Send-TCPMessage`. - -#### Examples - -```powershell -PS> New-RestApiFaviconResponse -``` - -#### Notes - +structure or logs an error when no data is supplied. + +#### Outputs + +System.Collections.Hashtable -- response object with `Message` (byte[]) and +`Length` (int), ready to pass to `Send-TCPMessage`. + +#### Examples + +```powershell +PS> New-RestApiFaviconResponse +``` + +#### Notes + The favicon is read from `assets\restapi\favicon.png` under the module root directory. The function selects the correct MIME type (`image/x-icon` or -`image/png`) based on the file extension found at that path. - -*Source: [src/Core/RestApi/Private/New-RestApiFaviconResponse.ps1](../../src/Core/RestApi/Private/New-RestApiFaviconResponse.ps1)* - ---- - -### New-RestApiResponse - -*Private function* - -**Synopsis:** Build a full HTTP response byte array from status and body. - -#### Description - +`image/png`) based on the file extension found at that path. + +*Source: [src/Core/RestApi/Private/New-RestApiFaviconResponse.ps1](../src/Core/RestApi/Private/New-RestApiFaviconResponse.ps1)* + +--- + +### New-RestApiResponse + +*Private function* + +**Synopsis:** Build a full HTTP response byte array from status and body. + +#### Description + Converts a status code, status message, content type and response body into a single byte array suitable for sending over a TCP socket. When the -`Content-Type` is JSON the body is serialized with `ConvertTo-Json`. - -#### Parameters - -**`$StatusCode`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| StatusCode | System.Int32 | HTTP status code to send (e.g. 200). | 200 | - -**`$StatusMessage`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| StatusMessage | System.String | Short HTTP status message (e.g. 'OK'). | 'OK' | - -**`$ContentType`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ContentType | System.String | MIME type for the response body. | 'application/json; charset=utf-8' | - -**`$ResponseBody`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ResponseBody | Object | Body payload; may be byte[], string or object (serialized to JSON). | | - -#### Outputs - -Hashtable with `Message` (byte[]) and `Length` (int) keys. - -#### Examples - -```powershell -PS> New-RestApiResponse -StatusCode 200 -ResponseBody @{ success = $true } -``` - -#### Notes - -The returned `Message` is ready to be written to a TCP stream. - -*Source: [src/Core/RestApi/Private/New-RestApiResponse.ps1](../../src/Core/RestApi/Private/New-RestApiResponse.ps1)* - ---- - -### Read-RestApiBody - -*Private function* - -**Synopsis:** Read the HTTP request body from the TCP stream based on Content-Length. - -#### Description - +`Content-Type` is JSON the body is serialized with `ConvertTo-Json`. + +#### Parameters + +**`$StatusCode`** + +| Name | Type | Description | Default | +|------------|--------------|--------------------------------------|---------| +| StatusCode | System.Int32 | HTTP status code to send (e.g. 200). | 200 | + +**`$StatusMessage`** + +| Name | Type | Description | Default | +|---------------|---------------|----------------------------------------|---------| +| StatusMessage | System.String | Short HTTP status message (e.g. 'OK'). | 'OK' | + +**`$ContentType`** + +| Name | Type | Description | Default | +|-------------|---------------|----------------------------------|-----------------------------------| +| ContentType | System.String | MIME type for the response body. | 'application/json; charset=utf-8' | + +**`$ResponseBody`** + +| Name | Type | Description | Default | +|--------------|--------|---------------------------------------------------------------------|---------| +| ResponseBody | Object | Body payload; may be byte[], string or object (serialized to JSON). | | + +#### Outputs + +Hashtable with `Message` (byte[]) and `Length` (int) keys. + +#### Examples + +```powershell +PS> New-RestApiResponse -StatusCode 200 -ResponseBody @{ success = $true } +``` + +#### Notes + +The returned `Message` is ready to be written to a TCP stream. + +*Source: [src/Core/RestApi/Private/New-RestApiResponse.ps1](../src/Core/RestApi/Private/New-RestApiResponse.ps1)* + +--- + +### Read-RestApiBody + +*Private function* + +**Synopsis:** Read the HTTP request body from the TCP stream based on Content-Length. + +#### Description + Reads the request body for an HTTP request already parsed into headers. Honors `Content-Length`, enforces access control via `Test-RestApiAccessControl` and returns a structured object with raw -bytes, string and parsed JSON (if applicable). - -#### Parameters - -**`$ParsedHeaders`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ParsedHeaders | System.Collections.Hashtable | Parsed header object produced by `Expand-RestApiHeader`. | @{ } | - -**`$PreReadBodyBytes`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| PreReadBodyBytes | byte[] | Any body bytes that were read along with the headers. | @() | - -#### Outputs - -Hashtable with keys `RawBytes`, `RawString`, `JsonObj`, `ContentLength`. - -#### Examples - -```powershell -PS> Read-RestApiBody -ParsedHeaders $parsed -PreReadBodyBytes $extraBytes -``` - -#### Notes - +bytes, string and parsed JSON (if applicable). + +#### Parameters + +**`$ParsedHeaders`** + +| Name | Type | Description | Default | +|---------------|------------------------------|----------------------------------------------------------|---------| +| ParsedHeaders | System.Collections.Hashtable | Parsed header object produced by `Expand-RestApiHeader`. | @{ } | + +**`$PreReadBodyBytes`** + +| Name | Type | Description | Default | +|------------------|--------|-------------------------------------------------------|---------| +| PreReadBodyBytes | byte[] | Any body bytes that were read along with the headers. | @() | + +#### Outputs + +Hashtable with keys `RawBytes`, `RawString`, `JsonObj`, `ContentLength`. + +#### Examples + +```powershell +PS> Read-RestApiBody -ParsedHeaders $parsed -PreReadBodyBytes $extraBytes +``` + +#### Notes + Closes the TCP connection and returns `$null` if access control denies -the request or a timeout occurs while reading. - -*Source: [src/Core/RestApi/Private/Read-RestApiBody.ps1](../../src/Core/RestApi/Private/Read-RestApiBody.ps1)* - ---- - -### Read-RestApiConfig - -*Private function* - -**Synopsis:** Load RestApi configuration from disk. - -#### Description - +the request or a timeout occurs while reading. + +*Source: [src/Core/RestApi/Private/Read-RestApiBody.ps1](../src/Core/RestApi/Private/Read-RestApiBody.ps1)* + +--- + +### Read-RestApiConfig + +*Private function* + +**Synopsis:** Load RestApi configuration from disk. + +#### Description + Reads the `restapi.json` configuration file from the module config directory and stores the parsed object into the global runtime variable -under `(Get-GlobalRuntimeVariable).Public.RestApi.Config`. - -#### Outputs - -PSCustomObject — the loaded RestApi configuration on success, or a -structured return code object when the file is missing or corrupt. - -#### Examples - -```powershell -PS> Read-RestApiConfig -``` - -#### Notes - +under `(Get-GlobalRuntimeVariable).Public.RestApi.Config`. + +#### Outputs + +PSCustomObject -- the loaded RestApi configuration on success, or a +structured return code object when the file is missing or corrupt. + +#### Examples + +```powershell +PS> Read-RestApiConfig +``` + +#### Notes + Logs structured return codes using `Write-FunctionReturnValue` when the -file is missing or cannot be parsed. - -*Source: [src/Core/RestApi/Private/Read-RestApiConfig.ps1](../../src/Core/RestApi/Private/Read-RestApiConfig.ps1)* - ---- - -### Read-RestApiHeader - -*Private function* - -**Synopsis:** Read raw HTTP header bytes from the TCP stream and return parsed header data. - -#### Description - +file is missing or cannot be parsed. + +*Source: [src/Core/RestApi/Private/Read-RestApiConfig.ps1](../src/Core/RestApi/Private/Read-RestApiConfig.ps1)* + +--- + +### Read-RestApiHeader + +*Private function* + +**Synopsis:** Read raw HTTP header bytes from the TCP stream and return parsed header data. + +#### Description + Reads from the TCP stream until the HTTP header terminator (`\r\n\r\n`) is encountered or a timeout occurs. Returns a hashtable with raw header string, -raw bytes and any extra body bytes that were read alongside the headers. - -#### Outputs - -Hashtable with `RawString`, `RawBytes`, and `ExtraBodyBytes`. - -#### Examples - -```powershell -PS> Read-RestApiHeader -``` - -#### Notes - -This function reads directly from `(Get-GlobalRuntimeVariable).Private.TCP.Stream`. - -*Source: [src/Core/RestApi/Private/Read-RestApiHeader.ps1](../../src/Core/RestApi/Private/Read-RestApiHeader.ps1)* - ---- - -### Read-RestApiSpacesConfig - -*Private function* - -**Synopsis:** Load RestApi space definitions from the data directory. - -#### Description - +raw bytes and any extra body bytes that were read alongside the headers. + +#### Outputs + +Hashtable with `RawString`, `RawBytes`, and `ExtraBodyBytes`. + +#### Examples + +```powershell +PS> Read-RestApiHeader +``` + +#### Notes + +This function reads directly from `(Get-GlobalRuntimeVariable).Private.TCP.Stream`. + +*Source: [src/Core/RestApi/Private/Read-RestApiHeader.ps1](../src/Core/RestApi/Private/Read-RestApiHeader.ps1)* + +--- + +### Read-RestApiSpacesConfig + +*Private function* + +**Synopsis:** Load RestApi space definitions from the data directory. + +#### Description + Reads all JSON files under `data/restapi/` and populates the global private RestApi `Spaces` hashtable with parsed space configurations keyed -by filename (lowercase). Logs per-file parse results using `Write-FunctionReturnValue`. - -#### Outputs - -None — populates `(Get-GlobalRuntimeVariable).Private.RestApi.Spaces`. - -#### Examples - -```powershell -PS> Read-RestApiSpacesConfig -``` - -#### Notes - +by filename (lowercase). Logs per-file parse results using `Write-FunctionReturnValue`. + +#### Outputs + +None -- populates `(Get-GlobalRuntimeVariable).Private.RestApi.Spaces`. + +#### Examples + +```powershell +PS> Read-RestApiSpacesConfig +``` + +#### Notes + Each space file must contain a valid JSON object describing routes, -handlers and optional access control for that API space. - -*Source: [src/Core/RestApi/Private/Read-RestApiSpacesConfig.ps1](../../src/Core/RestApi/Private/Read-RestApiSpacesConfig.ps1)* - ---- - -### Send-RestApiHtmlEndpointResponse - -*Private function* - -**Synopsis:** Return an HTML listing of available RestApi endpoints for a space. - -#### Description - +handlers and optional access control for that API space. + +*Source: [src/Core/RestApi/Private/Read-RestApiSpacesConfig.ps1](../src/Core/RestApi/Private/Read-RestApiSpacesConfig.ps1)* + +--- + +### Send-RestApiHtmlEndpointResponse + +*Private function* + +**Synopsis:** Return an HTML listing of available RestApi endpoints for a space. + +#### Description + Generates a simple HTML document listing available endpoints for the provided space object or, if no space is given, lists all configured -spaces. The HTML is returned to the client as an HTTP response. - -#### Parameters - -**`$SpaceObj`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| SpaceObj | PSCustomObject | Optional space configuration object to enumerate endpoints for. | | - -#### Outputs - -None — sends an HTTP response with `Content-Type: text/html` via `Send-TCPMessage`. - -#### Examples - -```powershell -PS> Send-RestApiHtmlEndpointResponse -SpaceObj $space -``` - -#### Notes - -Intended to be used by browser-based exploration of the RestApi. - -*Source: [src/Core/RestApi/Private/Send-RestApiHtmlEndpointResponse.ps1](../../src/Core/RestApi/Private/Send-RestApiHtmlEndpointResponse.ps1)* - ---- - -### Send-RestApiRequest - -*Private function* - -**Synopsis:** Send an HTTPS request to the local RestApi. - -#### Description - +spaces. The HTML is returned to the client as an HTTP response. + +#### Parameters + +**`$SpaceObj`** + +| Name | Type | Description | Default | +|----------|----------------|-----------------------------------------------------------------|---------| +| SpaceObj | PSCustomObject | Optional space configuration object to enumerate endpoints for. | | + +#### Outputs + +None -- sends an HTTP response with `Content-Type: text/html` via `Send-TCPMessage`. + +#### Examples + +```powershell +PS> Send-RestApiHtmlEndpointResponse -SpaceObj $space +``` + +#### Notes + +Intended to be used by browser-based exploration of the RestApi. + +*Source: [src/Core/RestApi/Private/Send-RestApiHtmlEndpointResponse.ps1](../src/Core/RestApi/Private/Send-RestApiHtmlEndpointResponse.ps1)* + +--- + +### Send-RestApiRequest + +*Private function* + +**Synopsis:** Send an HTTPS request to the local RestApi. + +#### Description + Sends an HTTP(S) request to the local RestApi endpoint configured in the runtime. Ensures the RestApi configuration is loaded, constructs the request URI and forwards the request using `Invoke-RestMethod`. JSON bodies are serialized for non-GET methods. The function returns standardized return values using -`Write-FunctionReturnValue`. - -#### Parameters - -**`$WebPath`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| WebPath | System.String | Relative web path or endpoint (for example '/v1/status'). Leading slash optional. | '' | - -**`$Method`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Method | System.String | HTTP method to use (GET, POST, PUT, DELETE, etc.). | 'GET' | - -**`$Headers`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Headers | System.Collections.Hashtable | Additional HTTP headers to include. | @{ 'Content-Type' = 'application/json'; } | - -**`$Body`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Body | System.Hashtable | Request body to be serialized as JSON for non-GET methods. | @{ } | - -#### Outputs - -PSCustomObject — Function return value produced by `Write-FunctionReturnValue`. +`Write-FunctionReturnValue`. + +#### Parameters + +**`$WebPath`** + +| Name | Type | Description | Default | +|---------|---------------|-----------------------------------------------------------------------------------|---------| +| WebPath | System.String | Relative web path or endpoint (for example '/v1/status'). Leading slash optional. | '' | + +**`$Method`** + +| Name | Type | Description | Default | +|--------|---------------|----------------------------------------------------|---------| +| Method | System.String | HTTP method to use (GET, POST, PUT, DELETE, etc.). | 'GET' | + +**`$Headers`** + +| Name | Type | Description | Default | +|---------|------------------------------|-------------------------------------|-------------------------------------------| +| Headers | System.Collections.Hashtable | Additional HTTP headers to include. | @{ 'Content-Type' = 'application/json'; } | + +**`$Body`** + +| Name | Type | Description | Default | +|------|------------------|------------------------------------------------------------|---------| +| Body | System.Hashtable | Request body to be serialized as JSON for non-GET methods. | @{ } | + +#### Outputs + +PSCustomObject -- Function return value produced by `Write-FunctionReturnValue`. - `RestApiRequestSuccessful`: Data contains `Response`. -- `RestApiRequestFailed`: Data contains `Exception`, `Uri`, `Method`, `Headers`, `Body` or `StatusCode` and `Response`. - -#### Examples - -```powershell +- `RestApiRequestFailed`: Data contains `Exception`, `Uri`, `Method`, `Headers`, `Body` or `StatusCode` and `Response`. + +#### Examples + +```powershell PS> Send-RestApiRequest -WebPath '/v1/status' -Method 'GET' -PS> Send-RestApiRequest -WebPath '/v1/items' -Method 'POST' -Body @{ name = 'test' } -``` - -#### Notes - +PS> Send-RestApiRequest -WebPath '/v1/items' -Method 'POST' -Body @{ name = 'test' } +``` + +#### Notes + Uses `Read-RestApiConfig` to ensure RestApi is configured and `Invoke-RestMethod` with `-SkipCertificateCheck` for local/self-signed certificates. Non-200 status -codes are treated as failures and returned via `Write-FunctionReturnValue`. - -*Source: [src/Core/RestApi/Private/Send-RestApiRequest.ps1](../../src/Core/RestApi/Private/Send-RestApiRequest.ps1)* - ---- - -### Set-RestApiConfig - -*Private function* - -**Synopsis:** Configure RestApi listener, TLS and worker count and persist to restapi.json. - -#### Description - +codes are treated as failures and returned via `Write-FunctionReturnValue`. + +*Source: [src/Core/RestApi/Private/Send-RestApiRequest.ps1](../src/Core/RestApi/Private/Send-RestApiRequest.ps1)* + +--- + +### Set-RestApiConfig + +*Private function* + +**Synopsis:** Configure RestApi listener, TLS and worker count and persist to restapi.json. + +#### Description + Validates listen address, port and worker count, updates the global RestApi configuration and writes the configuration to the module config directory as `restapi.json`. Returns standardized function return values via -`Write-FunctionReturnValue`. - -#### Parameters - -**`$ListenAddress`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ListenAddress | System.String | IP address or hostname to bind the RestApi listener. Use '0.0.0.0' to bind all interfaces. | '0.0.0.0' | - -**`$ListenPort`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ListenPort | System.Int32 | TCP port to listen on (1-65535). | 10000 | - -**`$TlsCertConfig`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| TlsCertConfig | System.PSCustomObject | TLS certificate configuration created by `New-TlsCertConfig`. | $null | - -**`$WorkerCount`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| WorkerCount | System.Int32 | Number of worker threads to spawn for handling connections. | 5 | - -**`$DryRun`** - -| Name | Type | Description | Default | -|--------|----------------------------------------------|---------------------------------------------------------------------------------------------------|---------| -| DryRun | System.Management.Automation.SwitchParameter | When set, returns a unified diff of the pending configuration versus the persisted restapi.json instead of writing the change. | $false | - -#### Outputs - -PSCustomObject — Function return value via `Write-FunctionReturnValue`. +`Write-FunctionReturnValue`. + +#### Parameters + +**`$ListenAddress`** + +| Name | Type | Description | Default | +|---------------|---------------|--------------------------------------------------------------------------------------------|-----------| +| ListenAddress | System.String | IP address or hostname to bind the RestApi listener. Use '0.0.0.0' to bind all interfaces. | '0.0.0.0' | + +**`$ListenPort`** + +| Name | Type | Description | Default | +|------------|--------------|----------------------------------|---------| +| ListenPort | System.Int32 | TCP port to listen on (1-65535). | 10000 | + +**`$TlsCertConfig`** + +| Name | Type | Description | Default | +|---------------|-----------------------|---------------------------------------------------------------|---------| +| TlsCertConfig | System.PSCustomObject | TLS certificate configuration created by `New-TlsCertConfig`. | $null | + +**`$WorkerCount`** + +| Name | Type | Description | Default | +|-------------|--------------|-------------------------------------------------------------|---------| +| WorkerCount | System.Int32 | Number of worker threads to spawn for handling connections. | 5 | + +**`$DryRun`** + +| Name | Type | Description | Default | +|--------|----------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------|---------| +| DryRun | System.Management.Automation.SwitchParameter | When set, returns a unified diff of the pending configuration versus the persisted restapi.json instead of writing the change. | $false | + +#### Outputs + +PSCustomObject -- Function return value via `Write-FunctionReturnValue`. - `RestApiConfigConfigured`: Data contains `Config`. - `NoRestApiListenAddressProvided`: invalid listen address. - `NoRestApiListenPortProvided`: invalid port. -- `InvalidRestApiWorkerCountProvided`: invalid worker count (Data contains `WorkerCount` and `MaxThreads`). - -#### Examples - -```powershell -PS> Set-RestApiConfig -ListenAddress '127.0.0.1' -ListenPort 10443 -WorkerCount 8 -``` - -#### Notes - +- `InvalidRestApiWorkerCountProvided`: invalid worker count (Data contains `WorkerCount` and `MaxThreads`). + +#### Examples + +```powershell +PS> Set-RestApiConfig -ListenAddress '127.0.0.1' -ListenPort 10443 -WorkerCount 8 +``` + +#### Notes + Persists the configuration to `restapi.json` under the module config directory using `Write-SecureFile` and `Get-ModuleConfigDirectory`. `WorkerCount` is -bounded by the global `Threading.MaxThreads` setting. - -*Source: [src/Core/RestApi/Private/Set-RestApiConfig.ps1](../../src/Core/RestApi/Private/Set-RestApiConfig.ps1)* - ---- - -### Start-RestApiDaemon - -*Private function* - -**Synopsis:** Start the RestApi daemon by initializing the RestApi environment. - -#### Description - +bounded by the global `Threading.MaxThreads` setting. + +*Source: [src/Core/RestApi/Private/Set-RestApiConfig.ps1](../src/Core/RestApi/Private/Set-RestApiConfig.ps1)* + +--- + +### Start-RestApiDaemon + +*Private function* + +**Synopsis:** Start the RestApi daemon by initializing the RestApi environment. + +#### Description + Creates a background thread that initializes the RestApi runtime environment. This is a lightweight helper that delegates to -`New-RestApiEnvironment` on a new thread. - -#### Outputs - -None — starts a background thread and returns immediately. - -#### Examples - -```powershell -PS> Start-RestApiDaemon -``` - -#### Notes - +`New-RestApiEnvironment` on a new thread. + +#### Outputs + +None -- starts a background thread and returns immediately. + +#### Examples + +```powershell +PS> Start-RestApiDaemon +``` + +#### Notes + This function starts a thread but does not wait for the environment to be fully initialized. Use `New-RestApiEnvironment` directly when synchronous -initialization is required. - -*Source: [src/Core/RestApi/Private/Start-RestApiDaemon.ps1](../../src/Core/RestApi/Private/Start-RestApiDaemon.ps1)* - ---- - -### Start-RestApiListener - -*Private function* - -**Synopsis:** Start the RestApi TCP listener and accept incoming connections. - -#### Description - +initialization is required. + +*Source: [src/Core/RestApi/Private/Start-RestApiDaemon.ps1](../src/Core/RestApi/Private/Start-RestApiDaemon.ps1)* + +--- + +### Start-RestApiListener + +*Private function* + +**Synopsis:** Start the RestApi TCP listener and accept incoming connections. + +#### Description + Opens a TCP socket according to the RestApi configuration, then accepts incoming connections and assigns them to worker queues via -`Add-RestApiClientToWorker`. - -#### Outputs - -None - -#### Examples - -```powershell -PS> Start-RestApiListener -``` - -#### Notes - +`Add-RestApiClientToWorker`. + +#### Outputs + +None + +#### Examples + +```powershell +PS> Start-RestApiListener +``` + +#### Notes + This function runs on a dedicated thread and uses global runtime state -for configuration and worker management. - -*Source: [src/Core/RestApi/Private/Start-RestApiListener.ps1](../../src/Core/RestApi/Private/Start-RestApiListener.ps1)* - ---- - -### Start-RestApiWorker - -*Private function* - -**Synopsis:** Worker loop that processes assigned RestApi TCP clients. - -#### Description - +for configuration and worker management. + +*Source: [src/Core/RestApi/Private/Start-RestApiListener.ps1](../src/Core/RestApi/Private/Start-RestApiListener.ps1)* + +--- + +### Start-RestApiWorker + +*Private function* + +**Synopsis:** Worker loop that processes assigned RestApi TCP clients. + +#### Description + Executes the worker loop for a single RestApi worker. The worker waits for accepted `TcpClient` instances from its queue, performs TLS handshake, access control checks, reads the request and dispatches it to -the appropriate handler. - -#### Parameters - -**`$WorkerId`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| WorkerId | System.Int32 | Numeric identifier for this worker. | -1 | - -**`$Spaces`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Spaces | System.Collections.Hashtable | Hashtable of RestApi space configurations. | @{ } | - -#### Outputs - -None — sends responses over the TCP connection and logs results. - -#### Examples - -```powershell -PS> Start-RestApiWorker -WorkerId 0 -Spaces $spaces -``` - -#### Notes - +the appropriate handler. + +#### Parameters + +**`$WorkerId`** + +| Name | Type | Description | Default | +|----------|--------------|-------------------------------------|---------| +| WorkerId | System.Int32 | Numeric identifier for this worker. | -1 | + +**`$Spaces`** + +| Name | Type | Description | Default | +|--------|------------------------------|--------------------------------------------|---------| +| Spaces | System.Collections.Hashtable | Hashtable of RestApi space configurations. | @{ } | + +#### Outputs + +None -- sends responses over the TCP connection and logs results. + +#### Examples + +```powershell +PS> Start-RestApiWorker -WorkerId 0 -Spaces $spaces +``` + +#### Notes + This function is designed to run as a long-lived thread and relies on -global runtime variables for TCP streams and timeouts. - -*Source: [src/Core/RestApi/Private/Start-RestApiWorker.ps1](../../src/Core/RestApi/Private/Start-RestApiWorker.ps1)* - ---- - -### Test-RestApiAccessControl - -*Private function* - -**Synopsis:** Evaluate access control rules for an incoming RestApi request. - -#### Description - +global runtime variables for TCP streams and timeouts. + +*Source: [src/Core/RestApi/Private/Start-RestApiWorker.ps1](../src/Core/RestApi/Private/Start-RestApiWorker.ps1)* + +--- + +### Test-RestApiAccessControl + +*Private function* + +**Synopsis:** Evaluate access control rules for an incoming RestApi request. + +#### Description + Checks configured access control entries for the RestApi subsystem and determines whether the current request is permitted. Supports checking -origins (client IP) and request body size limits. - -#### Parameters - -**`$TestOrigins`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| TestOrigins | SwitchParameter | If set, evaluates allowed client origins for the request. | $false | - -**`$TestContentLength`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| TestContentLength | SwitchParameter | If set, enforces configured request body size limits. | $false | - -#### Outputs - -System.Int32 — structured return code from `Write-FunctionReturnValue` indicating -permission granted, denied, origin blocked or content length exceeded. - -#### Examples - -```powershell -PS> Test-RestApiAccessControl -TestOrigins -``` - -#### Notes - +origins (client IP) and request body size limits. + +#### Parameters + +**`$TestOrigins`** + +| Name | Type | Description | Default | +|-------------|-----------------|-----------------------------------------------------------|---------| +| TestOrigins | SwitchParameter | If set, evaluates allowed client origins for the request. | $false | + +**`$TestContentLength`** + +| Name | Type | Description | Default | +|-------------------|-----------------|-------------------------------------------------------|---------| +| TestContentLength | SwitchParameter | If set, enforces configured request body size limits. | $false | + +#### Outputs + +System.Int32 -- structured return code from `Write-FunctionReturnValue` indicating +permission granted, denied, origin blocked or content length exceeded. + +#### Examples + +```powershell +PS> Test-RestApiAccessControl -TestOrigins +``` + +#### Notes + This function uses the protected `AccessControl` configuration stored in -the global runtime variable and the current RestApi context. - -*Source: [src/Core/RestApi/Private/Test-RestApiAccessControl.ps1](../../src/Core/RestApi/Private/Test-RestApiAccessControl.ps1)* - ---- - -### Test-RestApiCommandExecutionField - -*Private function* - -**Synopsis:** Check whether a RestApi space exposes an ApiCommandExecution field. - -#### Description - +the global runtime variable and the current RestApi context. + +*Source: [src/Core/RestApi/Private/Test-RestApiAccessControl.ps1](../src/Core/RestApi/Private/Test-RestApiAccessControl.ps1)* + +--- + +### Test-RestApiCommandExecutionField + +*Private function* + +**Synopsis:** Check whether a RestApi space exposes an ApiCommandExecution field. + +#### Description + Validates that a provided space configuration contains an `ApiCommandExecution` entry which indicates that an executable API command is configured for the space. Returns boolean-like structured return codes via -`Write-FunctionReturnValue`. - -#### Parameters - -**`$Space`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Space | PSCustomObject | Space configuration object to inspect. | | - -#### Outputs - -System.Boolean — `$true` when `ApiCommandExecution` is present, `$false` otherwise, -wrapped via `Write-FunctionReturnValue`. - -#### Examples - -```powershell -PS> Test-RestApiCommandExecutionField -Space $space -``` - -#### Notes - +`Write-FunctionReturnValue`. + +#### Parameters + +**`$Space`** + +| Name | Type | Description | Default | +|-------|----------------|----------------------------------------|---------| +| Space | PSCustomObject | Space configuration object to inspect. | | + +#### Outputs + +System.Boolean -- `$true` when `ApiCommandExecution` is present, `$false` otherwise, +wrapped via `Write-FunctionReturnValue`. + +#### Examples + +```powershell +PS> Test-RestApiCommandExecutionField -Space $space +``` + +#### Notes + Used by routing logic to decide whether to invoke a command or render -sub-endpoints for a space. - -*Source: [src/Core/RestApi/Private/Test-RestApiCommandExecutionField.ps1](../../src/Core/RestApi/Private/Test-RestApiCommandExecutionField.ps1)* - - +sub-endpoints for a space. + +*Source: [src/Core/RestApi/Private/Test-RestApiCommandExecutionField.ps1](../src/Core/RestApi/Private/Test-RestApiCommandExecutionField.ps1)* + diff --git a/docs/Icinga.Core.Runtime.md b/docs/Icinga.Core.Runtime.md index 1a9461d..3ca1664 100644 --- a/docs/Icinga.Core.Runtime.md +++ b/docs/Icinga.Core.Runtime.md @@ -1,80 +1,79 @@ -# Icinga.Core.Runtime - -*Auto-generated from `src/Core/Runtime/`. Do not edit by hand -- run `build/Build-ModuleDocs.ps1` to regenerate.* - -## Public functions - -- [Exit-Icinga](#exit-icinga) - -## Private helpers - -- [Start-ModuleGarbageCollector](#start-modulegarbagecollector) - ---- - -### Exit-Icinga - -*Public function* - -**Synopsis:** Forcibly terminate the current PowerShell process used by Icinga - -#### Description - +# Icinga.Core.Runtime + +*Auto-generated from `src/Core/Runtime/`. Do not edit by hand -- run `build/Build-ModuleDocs.ps1` to regenerate.* + +## Public functions + +- [Exit-Icinga](#exit-icinga) + +## Private helpers + +- [Start-ModuleGarbageCollector](#start-modulegarbagecollector) + +--- + +### Exit-Icinga + +*Public function* + +**Synopsis:** Forcibly terminate the current PowerShell process used by Icinga + +#### Description + `Exit-Icinga` stops the current PowerShell process immediately to avoid the shell freezing due to background threads that do not terminate on a normal -exit. - -#### Parameters - -**`$ExitCode`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ExitCode | System.Int32 | Process exit code to return | 0 | - -#### Outputs - -None — The process is terminated immediately; no value is returned. - -#### Examples - -```powershell -PS> Exit-Icinga -``` - -#### Notes - -Uses `[System.Environment]::Exit($ExitCode)` to ensure the process exits cleanly with the desired exit code. - -*Source: [src/Core/Runtime/Public/Exit-Icinga.ps1](../../src/Core/Runtime/Public/Exit-Icinga.ps1)* - ---- - -### Start-ModuleGarbageCollector - -*Private function* - -**Synopsis:** Background garbage collector loop used by the runtime subsystem. - -#### Description - +exit. + +#### Parameters + +**`$ExitCode`** + +| Name | Type | Description | Default | +|----------|--------------|-----------------------------|---------| +| ExitCode | System.Int32 | Process exit code to return | 0 | + +#### Outputs + +None -- The process is terminated immediately; no value is returned. + +#### Examples + +```powershell +PS> Exit-Icinga +``` + +#### Notes + +Uses `[System.Environment]::Exit($ExitCode)` to ensure the process exits cleanly with the desired exit code. + +*Source: [src/Core/Runtime/Public/Exit-Icinga.ps1](../src/Core/Runtime/Public/Exit-Icinga.ps1)* + +--- + +### Start-ModuleGarbageCollector + +*Private function* + +**Synopsis:** Background garbage collector loop used by the runtime subsystem. + +#### Description + Periodically forces a full .NET garbage collection and clears the `$Error` buffer -while the runtime thread is running. Intended to run as a background helper thread. - -#### Outputs - -None — Periodically runs garbage collection and clears the error buffer in the background. - -#### Examples - -```powershell -PS> Start-ModuleGarbageCollector -``` - -#### Notes - -This helper should be run in a dedicated thread and relies on `Test-ThreadRunning`. - -*Source: [src/Core/Runtime/Private/Start-ModuleGarbageCollector.ps1](../../src/Core/Runtime/Private/Start-ModuleGarbageCollector.ps1)* - - +while the runtime thread is running. Intended to run as a background helper thread. + +#### Outputs + +None -- Periodically runs garbage collection and clears the error buffer in the background. + +#### Examples + +```powershell +PS> Start-ModuleGarbageCollector +``` + +#### Notes + +This helper should be run in a dedicated thread and relies on `Test-ThreadRunning`. + +*Source: [src/Core/Runtime/Private/Start-ModuleGarbageCollector.ps1](../src/Core/Runtime/Private/Start-ModuleGarbageCollector.ps1)* + diff --git a/docs/Icinga.Core.TCPStack.md b/docs/Icinga.Core.TCPStack.md index c316736..ed00da2 100644 --- a/docs/Icinga.Core.TCPStack.md +++ b/docs/Icinga.Core.TCPStack.md @@ -1,517 +1,516 @@ -# Icinga.Core.TCPStack - -*Auto-generated from `src/Core/TCPStack/`. Do not edit by hand -- run `build/Build-ModuleDocs.ps1` to regenerate.* - -## Public functions - -- [New-IcingaTlsCertConfig](#new-icingatlscertconfig) - -## Private helpers - -- [Close-TCPConnection](#close-tcpconnection) -- [Close-TCPSocket](#close-tcpsocket) -- [Get-TlsCertificate](#get-tlscertificate) -- [New-TlsCertConfig](#new-tlscertconfig) -- [Open-SSLStream](#open-sslstream) -- [Open-TCPSocket](#open-tcpsocket) -- [Send-TCPMessage](#send-tcpmessage) -- [Set-TCPClientAndStream](#set-tcpclientandstream) -- [Test-TCPConnection](#test-tcpconnection) -- [Update-TCPConnection](#update-tcpconnection) - ---- - -### New-IcingaTlsCertConfig - -*Public function* - -**Synopsis:** Create an Icinga TLS certificate configuration object - -#### Description - +# Icinga.Core.TCPStack + +*Auto-generated from `src/Core/TCPStack/`. Do not edit by hand -- run `build/Build-ModuleDocs.ps1` to regenerate.* + +## Public functions + +- [New-IcingaTlsCertConfig](#new-icingatlscertconfig) + +## Private helpers + +- [Close-TCPConnection](#close-tcpconnection) +- [Close-TCPSocket](#close-tcpsocket) +- [Get-TlsCertificate](#get-tlscertificate) +- [New-TlsCertConfig](#new-tlscertconfig) +- [Open-SSLStream](#open-sslstream) +- [Open-TCPSocket](#open-tcpsocket) +- [Send-TCPMessage](#send-tcpmessage) +- [Set-TCPClientAndStream](#set-tcpclientandstream) +- [Test-TCPConnection](#test-tcpconnection) +- [Update-TCPConnection](#update-tcpconnection) + +--- + +### New-IcingaTlsCertConfig + +*Public function* + +**Synopsis:** Create an Icinga TLS certificate configuration object + +#### Description + Returns a standardized TLS certificate configuration object by delegating to `New-TlsCertConfig`. This wrapper supplies Icinga-specific defaults for the certificate store and store location while allowing callers to specify a -certificate file, thumbprint, CN, issuer, or alternative store settings. - -#### Parameters - -**`$CertPath`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CertPath | System.String | Path to a PKCS#12/PFX certificate file to load. | | - -**`$CertThumbprint`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CertThumbprint | System.String | Thumbprint of a certificate to locate in a certificate store. | | - -**`$CertCN`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CertCN | System.String | Common Name (CN) to match when searching certificate stores. | | - -**`$CertStore`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CertStore | System.String | Certificate store name (for example: My, Root). | My | - -**`$CertStoreLocation`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CertStoreLocation | System.String | Certificate store location (for example: LocalMachine, CurrentUser). | LocalMachine | - -**`$CertIssuer`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CertIssuer | System.Array | Array of issuer names to match when searching certificate stores. | | - -#### Outputs - -System.Object — TLS certificate configuration object for the TCP stack, returned from `New-TlsCertConfig`. - -#### Examples - -```powershell -PS> New-IcingaTlsCertConfig -CertPath 'C:\certs\icinga.pfx' -``` - -#### Notes - +certificate file, thumbprint, CN, issuer, or alternative store settings. + +#### Parameters + +**`$CertPath`** + +| Name | Type | Description | Default | +|----------|---------------|-------------------------------------------------|---------| +| CertPath | System.String | Path to a PKCS#12/PFX certificate file to load. | | + +**`$CertThumbprint`** + +| Name | Type | Description | Default | +|----------------|---------------|---------------------------------------------------------------|---------| +| CertThumbprint | System.String | Thumbprint of a certificate to locate in a certificate store. | | + +**`$CertCN`** + +| Name | Type | Description | Default | +|--------|---------------|--------------------------------------------------------------|---------| +| CertCN | System.String | Common Name (CN) to match when searching certificate stores. | | + +**`$CertStore`** + +| Name | Type | Description | Default | +|-----------|---------------|-------------------------------------------------|---------| +| CertStore | System.String | Certificate store name (for example: My, Root). | My | + +**`$CertStoreLocation`** + +| Name | Type | Description | Default | +|-------------------|---------------|----------------------------------------------------------------------|--------------| +| CertStoreLocation | System.String | Certificate store location (for example: LocalMachine, CurrentUser). | LocalMachine | + +**`$CertIssuer`** + +| Name | Type | Description | Default | +|------------|--------------|-------------------------------------------------------------------|---------| +| CertIssuer | System.Array | Array of issuer names to match when searching certificate stores. | | + +#### Outputs + +System.Object -- TLS certificate configuration object for the TCP stack, returned from `New-TlsCertConfig`. + +#### Examples + +```powershell +PS> New-IcingaTlsCertConfig -CertPath 'C:\certs\icinga.pfx' +``` + +#### Notes + This function is a thin Icinga-specific wrapper around `New-TlsCertConfig`. Refer to `New-TlsCertConfig` for full validation rules and additional options. At least one of -CertPath, CertThumbprint, CertCN or CertIssuer must be supplied. - -*Source: [src/Core/TCPStack/Public/New-IcingaTlsCertConfig.ps1](../../src/Core/TCPStack/Public/New-IcingaTlsCertConfig.ps1)* - ---- - -### Close-TCPConnection - -*Private function* - -**Synopsis:** Close and dispose the active TCP client and SSL stream - -#### Description - +CertPath, CertThumbprint, CertCN or CertIssuer must be supplied. + +*Source: [src/Core/TCPStack/Public/New-IcingaTlsCertConfig.ps1](../src/Core/TCPStack/Public/New-IcingaTlsCertConfig.ps1)* + +--- + +### Close-TCPConnection + +*Private function* + +**Synopsis:** Close and dispose the active TCP client and SSL stream + +#### Description + `Close-TCPConnection` safely closes and disposes the current TCP client and -associated SSL stream stored in the global runtime variable, if present. - -#### Outputs - -None — Clears the SSL stream, TCP client and their references in the global state. - -#### Examples - -```powershell -PS> Close-TCPConnection -``` - -#### Notes - -This is idempotent and swallows disposal exceptions. - -*Source: [src/Core/TCPStack/Private/Close-TCPConnection.ps1](../../src/Core/TCPStack/Private/Close-TCPConnection.ps1)* - ---- - -### Close-TCPSocket - -*Private function* - -**Synopsis:** Stop and release the TCP listener socket - -#### Description - +associated SSL stream stored in the global runtime variable, if present. + +#### Outputs + +None -- Clears the SSL stream, TCP client and their references in the global state. + +#### Examples + +```powershell +PS> Close-TCPConnection +``` + +#### Notes + +This is idempotent and swallows disposal exceptions. + +*Source: [src/Core/TCPStack/Private/Close-TCPConnection.ps1](../src/Core/TCPStack/Private/Close-TCPConnection.ps1)* + +--- + +### Close-TCPSocket + +*Private function* + +**Synopsis:** Stop and release the TCP listener socket + +#### Description + `Close-TCPSocket` stops the active `TcpListener` (if any), logs the action -and clears the listener reference in the global runtime variable. - -#### Outputs - -None — Stops the listener and clears its reference in the global state. - -#### Examples - -```powershell -PS> Close-TCPSocket -``` - -#### Notes - -Requires privileges sufficient to stop the listener; exceptions are logged. - -*Source: [src/Core/TCPStack/Private/Close-TCPSocket.ps1](../../src/Core/TCPStack/Private/Close-TCPSocket.ps1)* - ---- - -### Get-TlsCertificate - -*Private function* - -**Synopsis:** Load a TLS certificate from path or certificate store according to config. - -#### Description - +and clears the listener reference in the global runtime variable. + +#### Outputs + +None -- Stops the listener and clears its reference in the global state. + +#### Examples + +```powershell +PS> Close-TCPSocket +``` + +#### Notes + +Requires privileges sufficient to stop the listener; exceptions are logged. + +*Source: [src/Core/TCPStack/Private/Close-TCPSocket.ps1](../src/Core/TCPStack/Private/Close-TCPSocket.ps1)* + +--- + +### Get-TlsCertificate + +*Private function* + +**Synopsis:** Load a TLS certificate from path or certificate store according to config. + +#### Description + `Get-TlsCertificate` attempts to load a certificate based on the provided TLS configuration object. It supports loading from a file path or by searching -the specified certificate store using thumbprint, common name or issuer filters. - -#### Parameters - -**`$TlsCertConfig`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| TlsCertConfig | System.PSCustomObject | Configuration describing how to locate the certificate | | - -#### Outputs - -System.Security.Cryptography.X509Certificates.X509Certificate2 — The loaded certificate, or $null on failure. - -#### Examples - -```powershell -PS> Get-TlsCertificate -TlsCertConfig $cfg -``` - -#### Notes - -Uses `Write-FunctionReturnValue` to report detailed result codes for callers. - -*Source: [src/Core/TCPStack/Private/Get-TlsCertificate.ps1](../../src/Core/TCPStack/Private/Get-TlsCertificate.ps1)* - ---- - -### New-TlsCertConfig - -*Private function* - -**Synopsis:** Create a TLS certificate configuration object - -#### Description - +the specified certificate store using thumbprint, common name or issuer filters. + +#### Parameters + +**`$TlsCertConfig`** + +| Name | Type | Description | Default | +|---------------|-----------------------|--------------------------------------------------------|---------| +| TlsCertConfig | System.PSCustomObject | Configuration describing how to locate the certificate | | + +#### Outputs + +System.Security.Cryptography.X509Certificates.X509Certificate2 -- The loaded certificate, or $null on failure. + +#### Examples + +```powershell +PS> Get-TlsCertificate -TlsCertConfig $cfg +``` + +#### Notes + +Uses `Write-FunctionReturnValue` to report detailed result codes for callers. + +*Source: [src/Core/TCPStack/Private/Get-TlsCertificate.ps1](../src/Core/TCPStack/Private/Get-TlsCertificate.ps1)* + +--- + +### New-TlsCertConfig + +*Private function* + +**Synopsis:** Create a TLS certificate configuration object + +#### Description + `New-TlsCertConfig` builds a PSCustomObject that describes how to locate a TLS certificate, either by file path, thumbprint or search filters (CN/Issuer). -It validates that at least one selector is provided. - -#### Parameters - -**`$CertPath`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CertPath | System.String | Optional filesystem path to a certificate file | $null | - -**`$CertThumbprint`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CertThumbprint | System.String | Thumbprint to locate certificate in store | $null | - -**`$CertCN`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CertCN | System.String | Common Name filter for certificate store search | $null | - -**`$CertStore`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CertStore | System.String | Certificate store name (e.g. 'My') | 'My' | - -**`$CertStoreLocation`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CertStoreLocation | System.String | Store location (e.g. 'LocalMachine') | 'LocalMachine' | - -**`$CertIssuer`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CertIssuer | System.Array | Array of issuer names to match when searching certificate stores | $null | - -#### Outputs - -System.Management.Automation.PSCustomObject — Constructed TLS configuration object, returned via `Write-FunctionReturnValue`. - -#### Examples - -```powershell -PS> New-TlsCertConfig -CertThumbprint 'ABCDEF...' -``` - -#### Notes - -At least one of `CertPath`, `CertThumbprint`, `CertCN` or `CertIssuer` must be provided. - -*Source: [src/Core/TCPStack/Private/New-TlsCertConfig.ps1](../../src/Core/TCPStack/Private/New-TlsCertConfig.ps1)* - ---- - -### Open-SSLStream - -*Private function* - -**Synopsis:** Create and authenticate an SSL stream for the active TCP client. - -#### Description - +It validates that at least one selector is provided. + +#### Parameters + +**`$CertPath`** + +| Name | Type | Description | Default | +|----------|---------------|------------------------------------------------|---------| +| CertPath | System.String | Optional filesystem path to a certificate file | $null | + +**`$CertThumbprint`** + +| Name | Type | Description | Default | +|----------------|---------------|-------------------------------------------|---------| +| CertThumbprint | System.String | Thumbprint to locate certificate in store | $null | + +**`$CertCN`** + +| Name | Type | Description | Default | +|--------|---------------|-------------------------------------------------|---------| +| CertCN | System.String | Common Name filter for certificate store search | $null | + +**`$CertStore`** + +| Name | Type | Description | Default | +|-----------|---------------|------------------------------------|---------| +| CertStore | System.String | Certificate store name (e.g. 'My') | 'My' | + +**`$CertStoreLocation`** + +| Name | Type | Description | Default | +|-------------------|---------------|--------------------------------------|----------------| +| CertStoreLocation | System.String | Store location (e.g. 'LocalMachine') | 'LocalMachine' | + +**`$CertIssuer`** + +| Name | Type | Description | Default | +|------------|--------------|------------------------------------------------------------------|---------| +| CertIssuer | System.Array | Array of issuer names to match when searching certificate stores | $null | + +#### Outputs + +System.Management.Automation.PSCustomObject -- Constructed TLS configuration object, returned via `Write-FunctionReturnValue`. + +#### Examples + +```powershell +PS> New-TlsCertConfig -CertThumbprint 'ABCDEF...' +``` + +#### Notes + +At least one of `CertPath`, `CertThumbprint`, `CertCN` or `CertIssuer` must be provided. + +*Source: [src/Core/TCPStack/Private/New-TlsCertConfig.ps1](../src/Core/TCPStack/Private/New-TlsCertConfig.ps1)* + +--- + +### Open-SSLStream + +*Private function* + +**Synopsis:** Create and authenticate an SSL stream for the active TCP client. + +#### Description + `Open-SSLStream` wraps the active TCP client's network stream in an `SslStream`, configures timeouts, and performs client or server authentication -using the thread-local TLS certificate. On failure it closes the TCP connection. - -#### Parameters - -**`$Endpoint`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Endpoint | System.String | Expected remote endpoint name (required for client auth) | $null | - -**`$IsClient`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| IsClient | System.SwitchParameter | When set perform client-side authentication | $false | - -#### Outputs - -None — Stores the opened SslStream in the global state; result codes are reported via `Write-FunctionReturnValue`. - -#### Examples - -```powershell -PS> Open-SSLStream -Endpoint 'example.com' -IsClient -``` - -#### Notes - -Requires a valid certificate in `(Get-GlobalRuntimeVariable).Private.TCP.Certificate`. - -*Source: [src/Core/TCPStack/Private/Open-SSLStream.ps1](../../src/Core/TCPStack/Private/Open-SSLStream.ps1)* - ---- - -### Open-TCPSocket - -*Private function* - -**Synopsis:** Create and (optionally) start a TCP listener socket - -#### Description - +using the thread-local TLS certificate. On failure it closes the TCP connection. + +#### Parameters + +**`$Endpoint`** + +| Name | Type | Description | Default | +|----------|---------------|----------------------------------------------------------|---------| +| Endpoint | System.String | Expected remote endpoint name (required for client auth) | $null | + +**`$IsClient`** + +| Name | Type | Description | Default | +|----------|------------------------|---------------------------------------------|---------| +| IsClient | System.SwitchParameter | When set perform client-side authentication | $false | + +#### Outputs + +None -- Stores the opened SslStream in the global state; result codes are reported via `Write-FunctionReturnValue`. + +#### Examples + +```powershell +PS> Open-SSLStream -Endpoint 'example.com' -IsClient +``` + +#### Notes + +Requires a valid certificate in `(Get-GlobalRuntimeVariable).Private.TCP.Certificate`. + +*Source: [src/Core/TCPStack/Private/Open-SSLStream.ps1](../src/Core/TCPStack/Private/Open-SSLStream.ps1)* + +--- + +### Open-TCPSocket + +*Private function* + +**Synopsis:** Create and (optionally) start a TCP listener socket + +#### Description + `Open-TCPSocket` creates a `TcpListener` bound to the provided address and port, stores it in the global runtime variable and optionally starts listening. -An optional TLS certificate can be associated for incoming connections. - -#### Parameters - -**`$Address`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Address | System.String | IP address to bind or empty for loopback | '' | - -**`$Port`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Port | System.Int32 | TCP port to bind | 0 | - -**`$Start`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Start | System.SwitchParameter | When set, immediately start the listener | $false | - -**`$TlsCertificate`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| TlsCertificate | System.Security.Cryptography.X509Certificates.X509Certificate2 | Optional server certificate to attach | $null | - -#### Outputs - -None. Stores listener and certificate in global runtime state. - -#### Examples - -```powershell -PS> Open-TCPSocket -Port 8080 -Start -``` - -#### Notes - -Use `Close-TCPSocket` to stop and clear the listener. - -*Source: [src/Core/TCPStack/Private/Open-TCPSocket.ps1](../../src/Core/TCPStack/Private/Open-TCPSocket.ps1)* - ---- - -### Send-TCPMessage - -*Private function* - -**Synopsis:** Write a prepared message buffer to the active TCP/SSL stream - -#### Description - +An optional TLS certificate can be associated for incoming connections. + +#### Parameters + +**`$Address`** + +| Name | Type | Description | Default | +|---------|---------------|------------------------------------------|---------| +| Address | System.String | IP address to bind or empty for loopback | '' | + +**`$Port`** + +| Name | Type | Description | Default | +|------|--------------|------------------|---------| +| Port | System.Int32 | TCP port to bind | 0 | + +**`$Start`** + +| Name | Type | Description | Default | +|-------|------------------------|------------------------------------------|---------| +| Start | System.SwitchParameter | When set, immediately start the listener | $false | + +**`$TlsCertificate`** + +| Name | Type | Description | Default | +|----------------|----------------------------------------------------------------|---------------------------------------|---------| +| TlsCertificate | System.Security.Cryptography.X509Certificates.X509Certificate2 | Optional server certificate to attach | $null | + +#### Outputs + +None. Stores listener and certificate in global runtime state. + +#### Examples + +```powershell +PS> Open-TCPSocket -Port 8080 -Start +``` + +#### Notes + +Use `Close-TCPSocket` to stop and clear the listener. + +*Source: [src/Core/TCPStack/Private/Open-TCPSocket.ps1](../src/Core/TCPStack/Private/Open-TCPSocket.ps1)* + +--- + +### Send-TCPMessage + +*Private function* + +**Synopsis:** Write a prepared message buffer to the active TCP/SSL stream + +#### Description + `Send-TCPMessage` takes a message object containing the buffer and length and writes it to the active SSL stream of the current TCP client. It logs -an error if no valid stream is available. - -#### Parameters - -**`$MsgObj`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| MsgObj | System.Object | Object with `message` (buffer) and `length` properties | $null | - -#### Outputs - -None — Writes the message buffer to the SSL stream and flushes it; logs an error if no valid stream is available. - -#### Examples - -```powershell -PS> Send-TCPMessage -MsgObj $msg -``` - -#### Notes - -This helper assumes the active stream is an `SslStream` exposing `Write` and `Flush`. - -*Source: [src/Core/TCPStack/Private/Send-TCPMessage.ps1](../../src/Core/TCPStack/Private/Send-TCPMessage.ps1)* - ---- - -### Set-TCPClientAndStream - -*Private function* - -**Synopsis:** Set the global TCP client and SSL stream references - -#### Description - +an error if no valid stream is available. + +#### Parameters + +**`$MsgObj`** + +| Name | Type | Description | Default | +|--------|---------------|--------------------------------------------------------|---------| +| MsgObj | System.Object | Object with `message` (buffer) and `length` properties | $null | + +#### Outputs + +None -- Writes the message buffer to the SSL stream and flushes it; logs an error if no valid stream is available. + +#### Examples + +```powershell +PS> Send-TCPMessage -MsgObj $msg +``` + +#### Notes + +This helper assumes the active stream is an `SslStream` exposing `Write` and `Flush`. + +*Source: [src/Core/TCPStack/Private/Send-TCPMessage.ps1](../src/Core/TCPStack/Private/Send-TCPMessage.ps1)* + +--- + +### Set-TCPClientAndStream + +*Private function* + +**Synopsis:** Set the global TCP client and SSL stream references + +#### Description + `Set-TCPClientAndStream` assigns the provided `TcpClient` and `SslStream` -instances into the runtime private TCP container so other helpers can access them. - -#### Parameters - -**`$TcpClient`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| TcpClient | System.Net.Sockets.TcpClient | The connected TCP client instance | $null | - -**`$SslStream`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| SslStream | System.Net.Security.SslStream | The SSL stream wrapping the client's network stream | $null | - -#### Outputs - -None — Updates the `TcpClient` and `SslStream` references in `(Get-GlobalRuntimeVariable).Private.TCP`. - -#### Examples - -```powershell -PS> Set-TCPClientAndStream -TcpClient $c -SslStream $s -``` - -#### Notes - -This is a trivial assignment helper used after connection establishment. - -*Source: [src/Core/TCPStack/Private/Set-TCPClientAndStream.ps1](../../src/Core/TCPStack/Private/Set-TCPClientAndStream.ps1)* - ---- - -### Test-TCPConnection - -*Private function* - -**Synopsis:** Check whether the current TCP client and stream are connected. - -#### Description - +instances into the runtime private TCP container so other helpers can access them. + +#### Parameters + +**`$TcpClient`** + +| Name | Type | Description | Default | +|-----------|------------------------------|-----------------------------------|---------| +| TcpClient | System.Net.Sockets.TcpClient | The connected TCP client instance | $null | + +**`$SslStream`** + +| Name | Type | Description | Default | +|-----------|-------------------------------|-----------------------------------------------------|---------| +| SslStream | System.Net.Security.SslStream | The SSL stream wrapping the client's network stream | $null | + +#### Outputs + +None -- Updates the `TcpClient` and `SslStream` references in `(Get-GlobalRuntimeVariable).Private.TCP`. + +#### Examples + +```powershell +PS> Set-TCPClientAndStream -TcpClient $c -SslStream $s +``` + +#### Notes + +This is a trivial assignment helper used after connection establishment. + +*Source: [src/Core/TCPStack/Private/Set-TCPClientAndStream.ps1](../src/Core/TCPStack/Private/Set-TCPClientAndStream.ps1)* + +--- + +### Test-TCPConnection + +*Private function* + +**Synopsis:** Check whether the current TCP client and stream are connected. + +#### Description + `Test-TCPConnection` validates that both the TCP client and its associated -stream are present and returns the client's `Connected` state. - -#### Outputs - -System.Boolean — $true when connected and a valid client and stream are present; $false otherwise. - -#### Examples - -```powershell -PS> Test-TCPConnection -``` - -#### Notes - -Used by thread health checks and higher-level network monitors. - -*Source: [src/Core/TCPStack/Private/Test-TCPConnection.ps1](../../src/Core/TCPStack/Private/Test-TCPConnection.ps1)* - ---- - -### Update-TCPConnection - -*Private function* - -**Synopsis:** Register a new TcpClient and open its SSL stream. - -#### Description - +stream are present and returns the client's `Connected` state. + +#### Outputs + +System.Boolean -- $true when connected and a valid client and stream are present; $false otherwise. + +#### Examples + +```powershell +PS> Test-TCPConnection +``` + +#### Notes + +Used by thread health checks and higher-level network monitors. + +*Source: [src/Core/TCPStack/Private/Test-TCPConnection.ps1](../src/Core/TCPStack/Private/Test-TCPConnection.ps1)* + +--- + +### Update-TCPConnection + +*Private function* + +**Synopsis:** Register a new TcpClient and open its SSL stream. + +#### Description + `Update-TCPConnection` sets the provided `TcpClient` into the runtime private TCP container and calls `Open-SSLStream` to wrap and authenticate the connection -as client or server depending on the `IsClient` flag. - -#### Parameters - -**`$Client`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Client | System.Net.Sockets.TcpClient | Connected TCP client instance to register | $null | - -**`$Endpoint`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Endpoint | System.String | Remote endpoint name (used for client SSL auth) | $null | - -**`$IsClient`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| IsClient | System.SwitchParameter | When set perform client-side SSL authentication | $false | - -#### Outputs - -None — Result codes from `Open-SSLStream` are forwarded via `Write-FunctionReturnValue`. - -#### Examples - -```powershell -PS> Update-TCPConnection -Client $c -Endpoint 'example.com' -IsClient -``` - -#### Notes - -Validates `$Client` and returns `UpdateTcpClientInvalid` when missing. - -*Source: [src/Core/TCPStack/Private/Update-TCPConnection.ps1](../../src/Core/TCPStack/Private/Update-TCPConnection.ps1)* - - +as client or server depending on the `IsClient` flag. + +#### Parameters + +**`$Client`** + +| Name | Type | Description | Default | +|--------|------------------------------|-------------------------------------------|---------| +| Client | System.Net.Sockets.TcpClient | Connected TCP client instance to register | $null | + +**`$Endpoint`** + +| Name | Type | Description | Default | +|----------|---------------|-------------------------------------------------|---------| +| Endpoint | System.String | Remote endpoint name (used for client SSL auth) | $null | + +**`$IsClient`** + +| Name | Type | Description | Default | +|----------|------------------------|-------------------------------------------------|---------| +| IsClient | System.SwitchParameter | When set perform client-side SSL authentication | $false | + +#### Outputs + +None -- Result codes from `Open-SSLStream` are forwarded via `Write-FunctionReturnValue`. + +#### Examples + +```powershell +PS> Update-TCPConnection -Client $c -Endpoint 'example.com' -IsClient +``` + +#### Notes + +Validates `$Client` and returns `UpdateTcpClientInvalid` when missing. + +*Source: [src/Core/TCPStack/Private/Update-TCPConnection.ps1](../src/Core/TCPStack/Private/Update-TCPConnection.ps1)* + diff --git a/docs/Icinga.Core.Threading.md b/docs/Icinga.Core.Threading.md index 8ff41ec..57b1d8b 100644 --- a/docs/Icinga.Core.Threading.md +++ b/docs/Icinga.Core.Threading.md @@ -1,296 +1,296 @@ -# Icinga.Core.Threading - -*Auto-generated from `src/Core/Threading/`. Do not edit by hand -- run `build/Build-ModuleDocs.ps1` to regenerate.* - -## Public functions - -- [Set-ThreadData](#set-threaddata) -- [Show-IcingaThreads](#show-icingathreads) - -## Private helpers - -- [Get-ThreadCallStack](#get-threadcallstack) -- [Get-ThreadId](#get-threadid) -- [Get-ThreadLastSeen](#get-threadlastseen) -- [Get-ThreadState](#get-threadstate) -- [Get-ThreadTree](#get-threadtree) -- [New-Thread](#new-thread) -- [New-ThreadPool](#new-threadpool) -- [Set-ThreadFrozen](#set-threadfrozen) -- [Set-ThreadProcessing](#set-threadprocessing) -- [Show-Threads](#show-threads) -- [Start-ThreadHouseKeeper](#start-threadhousekeeper) -- [Stop-Thread](#stop-thread) -- [Test-ThreadRunning](#test-threadrunning) -- [Write-ThreadTree](#write-threadtree) - ---- - -### Set-ThreadData - -*Public function* - -**Synopsis:** Initialize thread-local runtime state inside a new runspace. - -#### Description - +# Icinga.Core.Threading + +*Auto-generated from `src/Core/Threading/`. Do not edit by hand -- run `build/Build-ModuleDocs.ps1` to regenerate.* + +## Public functions + +- [Set-ThreadData](#set-threaddata) +- [Show-IcingaThreads](#show-icingathreads) + +## Private helpers + +- [Get-ThreadCallStack](#get-threadcallstack) +- [Get-ThreadId](#get-threadid) +- [Get-ThreadLastSeen](#get-threadlastseen) +- [Get-ThreadState](#get-threadstate) +- [Get-ThreadTree](#get-threadtree) +- [New-Thread](#new-thread) +- [New-ThreadPool](#new-threadpool) +- [Set-ThreadFrozen](#set-threadfrozen) +- [Set-ThreadProcessing](#set-threadprocessing) +- [Show-Threads](#show-threads) +- [Start-ThreadHouseKeeper](#start-threadhousekeeper) +- [Stop-Thread](#stop-thread) +- [Test-ThreadRunning](#test-threadrunning) +- [Write-ThreadTree](#write-threadtree) + +--- + +### Set-ThreadData + +*Public function* + +**Synopsis:** Initialize thread-local runtime state inside a new runspace. + +#### Description + `Set-ThreadData` is invoked inside threads created by `New-Thread`. It sets up the base environment, configures the public and protected runtime containers, registers the thread id, validates the requested command and finally invokes it -with the supplied parameters. - -#### Parameters - -**`$PublicSpace`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| PublicSpace | System.Object | Shared public runtime object to attach to the thread | $null | - -**`$AccessControl`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| AccessControl | System.Object | Access control descriptor to attach to protected runtime area | $null | - -**`$ThreadId`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ThreadId | System.String | The thread id assigned by the creator | $null | - -**`$Command`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Command | System.String | The command/function name to execute in the thread | $null | - -**`$Parameters`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Parameters | System.Hashtable | Named parameters to pass to `Command` | @{} | - -#### Outputs - -Varies. The invoked `Command` determines output; error conditions return structured cmdlet returns. - -#### Examples - -```powershell -PS> Set-ThreadData -PublicSpace $GlobalPublic -AccessControl $ac -ThreadId $tid -Command 'RunWorker' -Parameters @{ 'Queue' = $q } -``` - -#### Notes - +with the supplied parameters. + +#### Parameters + +**`$PublicSpace`** + +| Name | Type | Description | Default | +|-------------|---------------|------------------------------------------------------|---------| +| PublicSpace | System.Object | Shared public runtime object to attach to the thread | $null | + +**`$AccessControl`** + +| Name | Type | Description | Default | +|---------------|---------------|---------------------------------------------------------------|---------| +| AccessControl | System.Object | Access control descriptor to attach to protected runtime area | $null | + +**`$ThreadId`** + +| Name | Type | Description | Default | +|----------|---------------|---------------------------------------|---------| +| ThreadId | System.String | The thread id assigned by the creator | $null | + +**`$Command`** + +| Name | Type | Description | Default | +|---------|---------------|----------------------------------------------------|---------| +| Command | System.String | The command/function name to execute in the thread | $null | + +**`$Parameters`** + +| Name | Type | Description | Default | +|------------|------------------|---------------------------------------|---------| +| Parameters | System.Hashtable | Named parameters to pass to `Command` | @{} | + +#### Outputs + +Varies. The invoked `Command` determines output; error conditions return structured cmdlet returns. + +#### Examples + +```powershell +PS> Set-ThreadData -PublicSpace $GlobalPublic -AccessControl $ac -ThreadId $tid -Command 'RunWorker' -Parameters @{ 'Queue' = $q } +``` + +#### Notes + Called exclusively by New-Thread; do not invoke directly. Calls New-ModuleBaseEnvironment to set up the runspace and sets (Get-GlobalRuntimeVariable).Protected.IsBackgroundDaemon to $true so that downstream functions know they are executing in a background context. Thread identity is -tracked via Update-LoggingThreadLoggingId for log correlation. - -*Source: [src/Core/Threading/Public/Set-ThreadData.ps1](../../src/Core/Threading/Public/Set-ThreadData.ps1)* - ---- - -### Show-IcingaThreads - -*Public function* - -**Synopsis:** Display the Icinga thread hierarchy. - -#### Description - +tracked via Update-LoggingThreadLoggingId for log correlation. + +*Source: [src/Core/Threading/Public/Set-ThreadData.ps1](../src/Core/Threading/Public/Set-ThreadData.ps1)* + +--- + +### Show-IcingaThreads + +*Public function* + +**Synopsis:** Display the Icinga thread hierarchy. + +#### Description + `Show-IcingaThreads` is a small public wrapper that renders the current -thread hierarchy for the Icinga application by delegating to `Show-Threads`. - -#### Parameters - -**`$AsObject`** - -| Name | Type | Description | Default | -|----------|-------------------------|----------------------------------------------------|---------| -| AsObject | System.SwitchParameter | Return the tree as PSObjects instead of rendering | $false | - -#### Outputs - +thread hierarchy for the Icinga application by delegating to `Show-Threads`. + +#### Parameters + +**`$AsObject`** + +| Name | Type | Description | Default | +|----------|------------------------|---------------------------------------------------|---------| +| AsObject | System.SwitchParameter | Return the tree as PSObjects instead of rendering | $false | + +#### Outputs + System.Array when `-AsObject` is set. Returns the root-level thread nodes with a nested `Children` array representing the full hierarchy. -None otherwise. Writes a formatted thread tree to the logging system. - -#### Examples - -```powershell -PS> Show-IcingaThreads -``` - -```powershell +None otherwise. Writes a formatted thread tree to the logging system. + +#### Examples + +```powershell +PS> Show-IcingaThreads +``` + +```powershell PS> $tree = Show-IcingaThreads -AsObject -PS> $tree | Select-Object Name, State, LastSeen -``` - -#### Notes - +PS> $tree | Select-Object Name, State, LastSeen +``` + +#### Notes + This wrapper calls `Show-Threads` and exists to provide a user-facing -command name for convenience. - -*Source: [src/Core/Threading/Public/Show-IcingaThreads.ps1](../../src/Core/Threading/Public/Show-IcingaThreads.ps1)* - ---- - -### Get-ThreadCallStack - -*Private function* - -**Synopsis:** Get a readable breadcrumb-style name for the current thread call stack. - -#### Description - +command name for convenience. + +*Source: [src/Core/Threading/Public/Show-IcingaThreads.ps1](../src/Core/Threading/Public/Show-IcingaThreads.ps1)* + +--- + +### Get-ThreadCallStack + +*Private function* + +**Synopsis:** Get a readable breadcrumb-style name for the current thread call stack. + +#### Description + `Get-ThreadCallStack` inspects the PowerShell call stack to construct a compact, human-readable thread name by joining function names with '`::`'. It normalizes -scriptblock entries and removes internal `Set-ThreadData` frames. - -#### Outputs - -System.String — A single-line thread name derived from the call stack. - -#### Examples - -```powershell -PS> Get-ThreadCallStack -``` - -#### Notes - -Used for naming threads created with `New-Thread` to aid diagnostics and tracing. - -*Source: [src/Core/Threading/Private/Get-ThreadCallStack.ps1](../../src/Core/Threading/Private/Get-ThreadCallStack.ps1)* - ---- - -### Get-ThreadId - -*Private function* - -**Synopsis:** Return the current thread identifier used by our runtime. - -#### Description - +scriptblock entries and removes internal `Set-ThreadData` frames. + +#### Outputs + +System.String -- A single-line thread name derived from the call stack. + +#### Examples + +```powershell +PS> Get-ThreadCallStack +``` + +#### Notes + +Used for naming threads created with `New-Thread` to aid diagnostics and tracing. + +*Source: [src/Core/Threading/Private/Get-ThreadCallStack.ps1](../src/Core/Threading/Private/Get-ThreadCallStack.ps1)* + +--- + +### Get-ThreadId + +*Private function* + +**Synopsis:** Return the current thread identifier used by our runtime. + +#### Description + `Get-ThreadId` returns the thread id stored in the runtime private threading -container. It is a convenience helper to avoid repeating the global variable path. - -#### Outputs - -System.String — The current thread GUID string, or $null if not set. - -#### Examples - -```powershell -PS> Get-ThreadId -``` - -#### Notes - -The value is read from `(Get-GlobalRuntimeVariable).Private.Threading.ThreadId`. - -*Source: [src/Core/Threading/Private/Get-ThreadId.ps1](../../src/Core/Threading/Private/Get-ThreadId.ps1)* - ---- - -### Get-ThreadLastSeen - -*Private function* - -**Synopsis:** Return seconds since the thread was last seen (heartbeat). - -#### Description - +container. It is a convenience helper to avoid repeating the global variable path. + +#### Outputs + +System.String -- The current thread GUID string, or $null if not set. + +#### Examples + +```powershell +PS> Get-ThreadId +``` + +#### Notes + +The value is read from `(Get-GlobalRuntimeVariable).Private.Threading.ThreadId`. + +*Source: [src/Core/Threading/Private/Get-ThreadId.ps1](../src/Core/Threading/Private/Get-ThreadId.ps1)* + +--- + +### Get-ThreadLastSeen + +*Private function* + +**Synopsis:** Return seconds since the thread was last seen (heartbeat). + +#### Description + `Get-ThreadLastSeen` reads a thread's `LastSeen` timestamp from the global thread registry and returns the elapsed seconds (rounded) since that timestamp. -If the thread or timestamp is missing, `$null` is returned. - -#### Parameters - -**`$ThreadId`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ThreadId | System.String | The thread id to query. Defaults to current thread. | (Get-ThreadId) | - -#### Outputs - -System.Double — Seconds since the last heartbeat, or $null if the thread is unknown. - -#### Examples - -```powershell -PS> Get-ThreadLastSeen -ThreadId $tid -``` - -#### Notes - -Used by health checks and thread state transitions in the housekeeper. - -*Source: [src/Core/Threading/Private/Get-ThreadLastSeen.ps1](../../src/Core/Threading/Private/Get-ThreadLastSeen.ps1)* - ---- - -### Get-ThreadState - -*Private function* - -**Synopsis:** Evaluate and normalize the runtime state of a thread. - -#### Description - +If the thread or timestamp is missing, `$null` is returned. + +#### Parameters + +**`$ThreadId`** + +| Name | Type | Description | Default | +|----------|---------------|-----------------------------------------------------|----------------| +| ThreadId | System.String | The thread id to query. Defaults to current thread. | (Get-ThreadId) | + +#### Outputs + +System.Double -- Seconds since the last heartbeat, or $null if the thread is unknown. + +#### Examples + +```powershell +PS> Get-ThreadLastSeen -ThreadId $tid +``` + +#### Notes + +Used by health checks and thread state transitions in the housekeeper. + +*Source: [src/Core/Threading/Private/Get-ThreadLastSeen.ps1](../src/Core/Threading/Private/Get-ThreadLastSeen.ps1)* + +--- + +### Get-ThreadState + +*Private function* + +**Synopsis:** Evaluate and normalize the runtime state of a thread. + +#### Description + `Get-ThreadState` inspects a thread's stored state and returns a normalized status such as 'RUNNING', 'IDLE', 'BLOCKED', or the raw stored state when unmodified. It uses the thread's `LastSeen` timestamp and `KeepAlive` flag to -differentiate between active and idle conditions. - -#### Parameters - -**`$ThreadId`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ThreadId | System.String | The thread id to evaluate. Defaults to current thread. | (Get-ThreadId) | - -#### Outputs - -System.String — Normalisierter Thread-State (z.B. RUNNING, IDLE, BLOCKED). - -#### Examples - -```powershell -PS> Get-ThreadState -ThreadId $tid -``` - -#### Notes - -Relies on configuration values such as `(Get-GlobalRuntimeVariable).Public.Threading.IdleTime`. - -*Source: [src/Core/Threading/Private/Get-ThreadState.ps1](../../src/Core/Threading/Private/Get-ThreadState.ps1)* - ---- - -### Get-ThreadTree - -*Private function* - -**Synopsis:** Build a hierarchical tree of all registered threads as PSObjects. - -#### Description - +differentiate between active and idle conditions. + +#### Parameters + +**`$ThreadId`** + +| Name | Type | Description | Default | +|----------|---------------|--------------------------------------------------------|----------------| +| ThreadId | System.String | The thread id to evaluate. Defaults to current thread. | (Get-ThreadId) | + +#### Outputs + +System.String -- Normalisierter Thread-State (z.B. RUNNING, IDLE, BLOCKED). + +#### Examples + +```powershell +PS> Get-ThreadState -ThreadId $tid +``` + +#### Notes + +Relies on configuration values such as `(Get-GlobalRuntimeVariable).Public.Threading.IdleTime`. + +*Source: [src/Core/Threading/Private/Get-ThreadState.ps1](../src/Core/Threading/Private/Get-ThreadState.ps1)* + +--- + +### Get-ThreadTree + +*Private function* + +**Synopsis:** Build a hierarchical tree of all registered threads as PSObjects. + +#### Description + `Get-ThreadTree` collects every thread from the global thread registry and assembles it into a list of root-level tree nodes. Each node holds the resolved thread state, last-seen age, parameters and a `Children` array that -contains the child nodes in the same format — forming a complete, self-contained +contains the child nodes in the same format -- forming a complete, self-contained representation of the thread hierarchy without requiring further registry -lookups. - -#### Outputs - +lookups. + +#### Outputs + System.Array. Sorted array of root-level thread nodes. Each node is a PSObject with the following properties: @@ -299,435 +299,434 @@ PSObject with the following properties: | Id | System.String | Unique thread GUID | | Name | System.String | Display name of the thread | | Command | System.String | Entry-point command name | -| State | System.String | Resolved state (RUNNING, IDLE, …) | +| State | System.String | Resolved state (RUNNING, IDLE, ...) | | LastSeen | System.Double | Seconds since last heartbeat | | KeepAlive | System.Boolean | Whether the thread is kept alive | | Parameters | System.Hashtable | Parameters passed to the command | | ParentId | System.String | Parent thread GUID or $null | -| Children | System.Array | Ordered child nodes (same structure) | - -#### Examples - -```powershell +| Children | System.Array | Ordered child nodes (same structure) | + +#### Examples + +```powershell PS> $tree = Get-ThreadTree -PS> $tree[0].Children -``` - -#### Notes - +PS> $tree[0].Children +``` + +#### Notes + The function resolves state and last-seen values at call time via -`Get-ThreadState` and `Get-ThreadLastSeen`. - -*Source: [src/Core/Threading/Private/Get-ThreadTree.ps1](../../src/Core/Threading/Private/Get-ThreadTree.ps1)* - ---- - -### New-Thread - -*Private function* - -**Synopsis:** Create and (optionally) start a managed background PowerShell thread. - -#### Description - +`Get-ThreadState` and `Get-ThreadLastSeen`. + +*Source: [src/Core/Threading/Private/Get-ThreadTree.ps1](../src/Core/Threading/Private/Get-ThreadTree.ps1)* + +--- + +### New-Thread + +*Private function* + +**Synopsis:** Create and (optionally) start a managed background PowerShell thread. + +#### Description + `New-Thread` creates a PowerShell runspace with a thread-local environment, registers the thread in the global threading registry and optionally starts it. -The function supports keep-alive semantics and parent/child relationships. - -#### Parameters - -**`$Command`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Command | System.String | The command (function) name to execute in the thread | | - -**`$Parameters`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Parameters | System.Hashtable | Named parameters passed to the command | @{} | - -**`$ParentThread`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ParentThread | System.String | Optional parent thread id (defaults to current thread) | $null | - -**`$OverrideName`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| OverrideName | System.String | Optional explicit display name for the created thread | $null | - -**`$Start`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Start | System.SwitchParameter | When set, start the thread immediately after creation | $false | - -**`$KeepAlive`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| KeepAlive | System.SwitchParameter | When set, the housekeeper may restart the thread on failure | $false | - -**`$WaitForJobs`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| WaitForJobs | System.SwitchParameter | When set the thread is expected to wait for queued jobs | $false | - -#### Outputs - -System.String. The newly created thread id. - -#### Examples - -```powershell -PS> New-Thread -Command 'Start-Worker' -Parameters @{ 'Queue' = $q } -Start -``` - -#### Notes - -This helper uses `Set-ThreadData` in the created runspace to initialize thread-local state. - -*Source: [src/Core/Threading/Private/New-Thread.ps1](../../src/Core/Threading/Private/New-Thread.ps1)* - ---- - -### New-ThreadPool - -*Private function* - -**Synopsis:** Create or return a shared PowerShell runspace pool for threads. - -#### Description - +The function supports keep-alive semantics and parent/child relationships. + +#### Parameters + +**`$Command`** + +| Name | Type | Description | Default | +|---------|---------------|------------------------------------------------------|---------| +| Command | System.String | The command (function) name to execute in the thread | | + +**`$Parameters`** + +| Name | Type | Description | Default | +|------------|------------------|----------------------------------------|---------| +| Parameters | System.Hashtable | Named parameters passed to the command | @{} | + +**`$ParentThread`** + +| Name | Type | Description | Default | +|--------------|---------------|--------------------------------------------------------|---------| +| ParentThread | System.String | Optional parent thread id (defaults to current thread) | $null | + +**`$OverrideName`** + +| Name | Type | Description | Default | +|--------------|---------------|-------------------------------------------------------|---------| +| OverrideName | System.String | Optional explicit display name for the created thread | $null | + +**`$Start`** + +| Name | Type | Description | Default | +|-------|------------------------|-------------------------------------------------------|---------| +| Start | System.SwitchParameter | When set, start the thread immediately after creation | $false | + +**`$KeepAlive`** + +| Name | Type | Description | Default | +|-----------|------------------------|-------------------------------------------------------------|---------| +| KeepAlive | System.SwitchParameter | When set, the housekeeper may restart the thread on failure | $false | + +**`$WaitForJobs`** + +| Name | Type | Description | Default | +|-------------|------------------------|---------------------------------------------------------|---------| +| WaitForJobs | System.SwitchParameter | When set the thread is expected to wait for queued jobs | $false | + +#### Outputs + +System.String. The newly created thread id. + +#### Examples + +```powershell +PS> New-Thread -Command 'Start-Worker' -Parameters @{ 'Queue' = $q } -Start +``` + +#### Notes + +This helper uses `Set-ThreadData` in the created runspace to initialize thread-local state. + +*Source: [src/Core/Threading/Private/New-Thread.ps1](../src/Core/Threading/Private/New-Thread.ps1)* + +--- + +### New-ThreadPool + +*Private function* + +**Synopsis:** Create or return a shared PowerShell runspace pool for threads. + +#### Description + `New-ThreadPool` creates a `RunspacePool` with the given minimum and maximum instances and caches it on the global runtime variable. If a pool already -exists, the cached instance is returned. - -#### Parameters - -**`$MinInstances`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| MinInstances | System.Int32 | Minimum number of runspaces in the pool | 1 | - -**`$MaxInstances`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| MaxInstances | System.Int32 | Maximum number of runspaces in the pool | `(Get-GlobalRuntimeVariable).Public.Threading.MaxThreads` | - -#### Outputs - -System.Management.Automation.Runspaces.RunspacePool — The newly created or cached runspace pool. - -#### Examples - -```powershell -PS> New-ThreadPool -MinInstances 2 -MaxInstances 8 -``` - -#### Notes - -The function currently uses the default `InitialSessionState`. Future work may enable JEA. - -*Source: [src/Core/Threading/Private/New-ThreadPool.ps1](../../src/Core/Threading/Private/New-ThreadPool.ps1)* - ---- - -### Set-ThreadFrozen - -*Private function* - -**Synopsis:** Mark a thread as FROZEN if it appears unresponsive. - -#### Description - +exists, the cached instance is returned. + +#### Parameters + +**`$MinInstances`** + +| Name | Type | Description | Default | +|--------------|--------------|-----------------------------------------|---------| +| MinInstances | System.Int32 | Minimum number of runspaces in the pool | 1 | + +**`$MaxInstances`** + +| Name | Type | Description | Default | +|--------------|--------------|-----------------------------------------|-----------------------------------------------------------| +| MaxInstances | System.Int32 | Maximum number of runspaces in the pool | `(Get-GlobalRuntimeVariable).Public.Threading.MaxThreads` | + +#### Outputs + +System.Management.Automation.Runspaces.RunspacePool -- The newly created or cached runspace pool. + +#### Examples + +```powershell +PS> New-ThreadPool -MinInstances 2 -MaxInstances 8 +``` + +#### Notes + +The function currently uses the default `InitialSessionState`. Future work may enable JEA. + +*Source: [src/Core/Threading/Private/New-ThreadPool.ps1](../src/Core/Threading/Private/New-ThreadPool.ps1)* + +--- + +### Set-ThreadFrozen + +*Private function* + +**Synopsis:** Mark a thread as FROZEN if it appears unresponsive. + +#### Description + `Set-ThreadFrozen` checks the last-seen timestamp for a given thread and, if it exceeds the configured keep-alive threshold, sets the thread state to -`FROZEN` and emits a warning log entry. - -#### Parameters - -**`$ThreadId`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ThreadId | System.String | The thread id to inspect. Defaults to current thread. | (Get-ThreadId) | - -#### Outputs - -None — Updates the thread state in the global registry and emits a warning log entry when frozen. - -#### Examples - -```powershell -PS> Set-ThreadFrozen -ThreadId $tid -``` - -#### Notes - -This helper is used by the housekeeper loop to detect and flag unresponsive threads. - -*Source: [src/Core/Threading/Private/Set-ThreadFrozen.ps1](../../src/Core/Threading/Private/Set-ThreadFrozen.ps1)* - ---- - -### Set-ThreadProcessing - -*Private function* - -**Synopsis:** Mark the current thread as processing and refresh its heartbeat. - -#### Description - +`FROZEN` and emits a warning log entry. + +#### Parameters + +**`$ThreadId`** + +| Name | Type | Description | Default | +|----------|---------------|-------------------------------------------------------|----------------| +| ThreadId | System.String | The thread id to inspect. Defaults to current thread. | (Get-ThreadId) | + +#### Outputs + +None -- Updates the thread state in the global registry and emits a warning log entry when frozen. + +#### Examples + +```powershell +PS> Set-ThreadFrozen -ThreadId $tid +``` + +#### Notes + +This helper is used by the housekeeper loop to detect and flag unresponsive threads. + +*Source: [src/Core/Threading/Private/Set-ThreadFrozen.ps1](../src/Core/Threading/Private/Set-ThreadFrozen.ps1)* + +--- + +### Set-ThreadProcessing + +*Private function* + +**Synopsis:** Mark the current thread as processing and refresh its heartbeat. + +#### Description + `Set-ThreadProcessing` updates the current thread's state to `PROCESSING` -and records the current timestamp in `LastSeen` to indicate activity. - -#### Outputs - -None — Modifies `(Get-GlobalRuntimeVariable).Public.Threading.Threads` for the current thread. - -#### Examples - -```powershell -PS> Set-ThreadProcessing -``` - -#### Notes - -Typically called by worker loops when they start handling a job. - -*Source: [src/Core/Threading/Private/Set-ThreadProcessing.ps1](../../src/Core/Threading/Private/Set-ThreadProcessing.ps1)* - ---- - -### Show-Threads - -*Private function* - -**Synopsis:** Render or return the current thread hierarchy and status. - -#### Description - +and records the current timestamp in `LastSeen` to indicate activity. + +#### Outputs + +None -- Modifies `(Get-GlobalRuntimeVariable).Public.Threading.Threads` for the current thread. + +#### Examples + +```powershell +PS> Set-ThreadProcessing +``` + +#### Notes + +Typically called by worker loops when they start handling a job. + +*Source: [src/Core/Threading/Private/Set-ThreadProcessing.ps1](../src/Core/Threading/Private/Set-ThreadProcessing.ps1)* + +--- + +### Show-Threads + +*Private function* + +**Synopsis:** Render or return the current thread hierarchy and status. + +#### Description + `Show-Threads` builds a complete thread tree via `Get-ThreadTree` and either returns the structured tree objects or renders them as a formatted hierarchy -string and emits it to the logging system — depending on the `-AsObject` -switch. - -#### Parameters - -**`$AsObject`** - -| Name | Type | Description | Default | -|----------|-------------------------|----------------------------------------------------|---------| -| AsObject | System.SwitchParameter | Return the tree as PSObjects instead of rendering | $false | - -#### Outputs - +string and emits it to the logging system -- depending on the `-AsObject` +switch. + +#### Parameters + +**`$AsObject`** + +| Name | Type | Description | Default | +|----------|------------------------|---------------------------------------------------|---------| +| AsObject | System.SwitchParameter | Return the tree as PSObjects instead of rendering | $false | + +#### Outputs + System.Array when `-AsObject` is set. Returns the root-level thread nodes produced by `Get-ThreadTree`, each with a `Children` array for the full hierarchy. None otherwise. Writes a formatted thread hierarchy string to the logging -queue. - -#### Examples - -```powershell -PS> Show-Threads -``` - -```powershell +queue. + +#### Examples + +```powershell +PS> Show-Threads +``` + +```powershell PS> $tree = Show-Threads -AsObject -PS> $tree[0].Children -``` - -#### Notes - +PS> $tree[0].Children +``` + +#### Notes + Relies on `Get-ThreadTree` to build the hierarchy and `Write-ThreadTree` to -render individual branches. - -*Source: [src/Core/Threading/Private/Show-Threads.ps1](../../src/Core/Threading/Private/Show-Threads.ps1)* - ---- - -### Start-ThreadHouseKeeper - -*Private function* - -**Synopsis:** Periodic housekeeper that monitors and manages thread lifecycle. - -#### Description - +render individual branches. + +*Source: [src/Core/Threading/Private/Show-Threads.ps1](../src/Core/Threading/Private/Show-Threads.ps1)* + +--- + +### Start-ThreadHouseKeeper + +*Private function* + +**Synopsis:** Periodic housekeeper that monitors and manages thread lifecycle. + +#### Description + `Start-ThreadHouseKeeper` runs a loop that inspects all registered threads, marks unresponsive threads as `FROZEN`, cleans up terminated or dead threads, and attempts restarts for keep-alive threads. It sleeps between cycles to -reduce resource usage. - -#### Outputs - -None — Performs side-effect operations on the global thread registry and logs actions. - -#### Examples - -```powershell -PS> Start-ThreadHouseKeeper -``` - -#### Notes - -This function is intended to run as a background supervisory thread. - -*Source: [src/Core/Threading/Private/Start-ThreadHouseKeeper.ps1](../../src/Core/Threading/Private/Start-ThreadHouseKeeper.ps1)* - ---- - -### Stop-Thread - -*Private function* - -**Synopsis:** Request termination for a registered thread. - -#### Description - +reduce resource usage. + +#### Outputs + +None -- Performs side-effect operations on the global thread registry and logs actions. + +#### Examples + +```powershell +PS> Start-ThreadHouseKeeper +``` + +#### Notes + +This function is intended to run as a background supervisory thread. + +*Source: [src/Core/Threading/Private/Start-ThreadHouseKeeper.ps1](../src/Core/Threading/Private/Start-ThreadHouseKeeper.ps1)* + +--- + +### Stop-Thread + +*Private function* + +**Synopsis:** Request termination for a registered thread. + +#### Description + `Stop-Thread` marks a thread's state as `TERMINATED` in the global thread registry. It validates the provided thread id and returns structured results -using `Write-FunctionReturnValue` when errors occur. - -#### Parameters - -**`$ThreadId`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ThreadId | System.String | The id of the thread to stop | $null | - -#### Outputs - -System.Management.Automation.PSCustomObject — Strukturierter Rueckgabewert bei Fehler (via Write-FunctionReturnValue); None bei Erfolg. - -#### Examples - -```powershell -PS> Stop-Thread -ThreadId $tid -``` - -#### Notes - -The actual runspace shutdown and cleanup is handled by the housekeeper loop. - -*Source: [src/Core/Threading/Private/Stop-Thread.ps1](../../src/Core/Threading/Private/Stop-Thread.ps1)* - ---- - -### Test-ThreadRunning - -*Private function* - -**Synopsis:** Core loop gate to determine whether a thread should continue running. - -#### Description - +using `Write-FunctionReturnValue` when errors occur. + +#### Parameters + +**`$ThreadId`** + +| Name | Type | Description | Default | +|----------|---------------|------------------------------|---------| +| ThreadId | System.String | The id of the thread to stop | $null | + +#### Outputs + +System.Management.Automation.PSCustomObject -- Strukturierter Rueckgabewert bei Fehler (via Write-FunctionReturnValue); None bei Erfolg. + +#### Examples + +```powershell +PS> Stop-Thread -ThreadId $tid +``` + +#### Notes + +The actual runspace shutdown and cleanup is handled by the housekeeper loop. + +*Source: [src/Core/Threading/Private/Stop-Thread.ps1](../src/Core/Threading/Private/Stop-Thread.ps1)* + +--- + +### Test-ThreadRunning + +*Private function* + +**Synopsis:** Core loop gate to determine whether a thread should continue running. + +#### Description + `Test-ThreadRunning` is invoked by thread loops to decide if the thread should continue executing. It updates heartbeats, refreshes logging ids, checks the thread state and optionally validates TCP/WebSocket connectivity. -It also enforces lightweight sleeps to reduce CPU usage. - -#### Parameters - -**`$CheckTcpConnection`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CheckTcpConnection | System.SwitchParameter | When set test the global TCP connection status | $false | - -**`$CheckWebSocket`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CheckWebSocket | System.SwitchParameter | When set test the WebSocket connectivity | $false | - -**`$NoSleep`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| NoSleep | System.SwitchParameter | When set skip the default short sleep at loop start | $false | - -#### Outputs - -System.Boolean — $true when the thread should continue, $false otherwise. - -#### Examples - -```powershell -while (Test-ThreadRunning) { Do-Work } -``` - -#### Notes - +It also enforces lightweight sleeps to reduce CPU usage. + +#### Parameters + +**`$CheckTcpConnection`** + +| Name | Type | Description | Default | +|--------------------|------------------------|------------------------------------------------|---------| +| CheckTcpConnection | System.SwitchParameter | When set test the global TCP connection status | $false | + +**`$CheckWebSocket`** + +| Name | Type | Description | Default | +|----------------|------------------------|------------------------------------------|---------| +| CheckWebSocket | System.SwitchParameter | When set test the WebSocket connectivity | $false | + +**`$NoSleep`** + +| Name | Type | Description | Default | +|---------|------------------------|-----------------------------------------------------|---------| +| NoSleep | System.SwitchParameter | When set skip the default short sleep at loop start | $false | + +#### Outputs + +System.Boolean -- $true when the thread should continue, $false otherwise. + +#### Examples + +```powershell +while (Test-ThreadRunning) { Do-Work } +``` + +#### Notes + This function performs multiple side effects (timestamp updates, logging id rotation) -and is central to thread lifecycle management. - -*Source: [src/Core/Threading/Private/Test-ThreadRunning.ps1](../../src/Core/Threading/Private/Test-ThreadRunning.ps1)* - ---- - -### Write-ThreadTree - -*Private function* - -**Synopsis:** Append a formatted tree entry for a thread node to a StringBuilder. - -#### Description - +and is central to thread lifecycle management. + +*Source: [src/Core/Threading/Private/Test-ThreadRunning.ps1](../src/Core/Threading/Private/Test-ThreadRunning.ps1)* + +--- + +### Write-ThreadTree + +*Private function* + +**Synopsis:** Append a formatted tree entry for a thread node to a StringBuilder. + +#### Description + `Write-ThreadTree` renders a single thread line (with name, id, state, age, and parameters) into a supplied `System.Text.StringBuilder` and recursively renders child nodes from the pre-built tree to produce the full hierarchical -view. The node is a PSObject as returned by `Get-ThreadTree`. - -#### Parameters - -**`$Node`** - -| Name | Type | Description | Default | -|------|---------------|------------------------------------------|---------| -| Node | PSObject | Tree node as returned by `Get-ThreadTree` | $null | - -**`$StringBuilder`** - -| Name | Type | Description | Default | -|---------------|-----------------------------|---------------------------------|---------| -| StringBuilder | System.Text.StringBuilder | The builder to append lines to | $null | - -**`$Level`** - -| Name | Type | Description | Default | -|-------|---------------|-------------------------------------|---------| -| Level | System.Int32 | Nesting level for indentation | 0 | - -#### Outputs - -None. Appends formatted lines to the provided `StringBuilder` instance. - -#### Examples - -```powershell +view. The node is a PSObject as returned by `Get-ThreadTree`. + +#### Parameters + +**`$Node`** + +| Name | Type | Description | Default | +|------|----------|-------------------------------------------|---------| +| Node | PSObject | Tree node as returned by `Get-ThreadTree` | $null | + +**`$StringBuilder`** + +| Name | Type | Description | Default | +|---------------|---------------------------|--------------------------------|---------| +| StringBuilder | System.Text.StringBuilder | The builder to append lines to | $null | + +**`$Level`** + +| Name | Type | Description | Default | +|-------|--------------|-------------------------------|---------| +| Level | System.Int32 | Nesting level for indentation | 0 | + +#### Outputs + +None. Appends formatted lines to the provided `StringBuilder` instance. + +#### Examples + +```powershell $sb = [System.Text.StringBuilder]::new() -Get-ThreadTree | ForEach-Object { Write-ThreadTree -Node $_ -StringBuilder $sb } -``` - -#### Notes - +Get-ThreadTree | ForEach-Object { Write-ThreadTree -Node $_ -StringBuilder $sb } +``` + +#### Notes + This function does not return a value; it operates by side-effects on the -supplied builder. Child nodes are read directly from `$Node.Children` — no -additional registry lookups are performed. - -*Source: [src/Core/Threading/Private/Write-ThreadTree.ps1](../../src/Core/Threading/Private/Write-ThreadTree.ps1)* - - +supplied builder. Child nodes are read directly from `$Node.Children` -- no +additional registry lookups are performed. + +*Source: [src/Core/Threading/Private/Write-ThreadTree.ps1](../src/Core/Threading/Private/Write-ThreadTree.ps1)* + diff --git a/docs/Icinga.Core.WebSocket.md b/docs/Icinga.Core.WebSocket.md index dde3801..e8ec63a 100644 --- a/docs/Icinga.Core.WebSocket.md +++ b/docs/Icinga.Core.WebSocket.md @@ -1,855 +1,884 @@ -# Icinga.Core.WebSocket - -*Auto-generated from `src/Core/WebSocket/`. Do not edit by hand -- run `build/Build-ModuleDocs.ps1` to regenerate.* - -## Public functions - -- [Add-IcingaWebSocketConfig](#add-icingawebsocketconfig) -- [Remove-IcingaWebSocketConfig](#remove-icingawebsocketconfig) -- [Show-IcingaWebSockets](#show-icingawebsockets) - -## Private helpers - -- [Add-ModuleWebSocketConfig](#add-modulewebsocketconfig) -- [Add-ModuleWebSocketMessageToQueue](#add-modulewebsocketmessagetoqueue) -- [Connect-ModuleWebSocket](#connect-modulewebsocket) -- [Disconnect-ModuleWebSocket](#disconnect-modulewebsocket) -- [Get-ModuleCurrentWebSocketConfig](#get-modulecurrentwebsocketconfig) -- [New-ModuleWebSocketEnvironment](#new-modulewebsocketenvironment) -- [Read-ModuleWebSocket](#read-modulewebsocket) -- [Read-ModuleWebSocketConfig](#read-modulewebsocketconfig) -- [Remove-ModuleWebSocketConfig](#remove-modulewebsocketconfig) -- [Show-ModuleWebSockets](#show-modulewebsockets) -- [Start-ModuleWebSocketDaemon](#start-modulewebsocketdaemon) -- [Start-ModuleWebSocketHandler](#start-modulewebsockethandler) -- [Start-ModuleWebSocketReaderWorker](#start-modulewebsocketreaderworker) -- [Test-ModuleWebSocket](#test-modulewebsocket) -- [Update-ModuleWebSocketThread](#update-modulewebsocketthread) -- [Write-ModuleWebSocket](#write-modulewebsocket) - ---- - -### Add-IcingaWebSocketConfig - -*Public function* - -**Synopsis:** Register and persist a WebSocket configuration. - -#### Description - +# Icinga.Core.WebSocket + +*Auto-generated from `src/Core/WebSocket/`. Do not edit by hand -- run `build/Build-ModuleDocs.ps1` to regenerate.* + +## Public functions + +- [Add-IcingaWebSocketConfig](#add-icingawebsocketconfig) +- [Remove-IcingaWebSocketConfig](#remove-icingawebsocketconfig) +- [Show-IcingaWebSockets](#show-icingawebsockets) + +## Private helpers + +- [Add-ModuleWebSocketConfig](#add-modulewebsocketconfig) +- [Add-ModuleWebSocketMessageToQueue](#add-modulewebsocketmessagetoqueue) +- [Connect-ModuleWebSocket](#connect-modulewebsocket) +- [Disconnect-ModuleWebSocket](#disconnect-modulewebsocket) +- [Get-ModuleCurrentWebSocketConfig](#get-modulecurrentwebsocketconfig) +- [New-ModuleWebSocketEnvironment](#new-modulewebsocketenvironment) +- [Read-ModuleWebSocket](#read-modulewebsocket) +- [Read-ModuleWebSocketConfig](#read-modulewebsocketconfig) +- [Remove-ModuleWebSocketConfig](#remove-modulewebsocketconfig) +- [Show-ModuleWebSockets](#show-modulewebsockets) +- [Start-ModuleWebSocketDaemon](#start-modulewebsocketdaemon) +- [Start-ModuleWebSocketHandler](#start-modulewebsockethandler) +- [Start-ModuleWebSocketReaderWorker](#start-modulewebsocketreaderworker) +- [Test-ModuleWebSocket](#test-modulewebsocket) +- [Update-ModuleWebSocketThread](#update-modulewebsocketthread) +- [Write-ModuleWebSocket](#write-modulewebsocket) + +--- + +### Add-IcingaWebSocketConfig + +*Public function* + +**Synopsis:** Register and persist a WebSocket configuration. + +#### Description + `Add-IcingaWebSocketConfig` is the public wrapper for `Add-ModuleWebSocketConfig`. It validates a WebSocket configuration payload, stores it in the runtime configuration (`$Global:Icinga.Public.WebSocket.Config`), and persists a pointer file under the Icinga config directory. The function reads the referenced type-specific config via `Read-ModuleConfigFile` and only writes a path pointer -to disk. - -#### Parameters - -**`$Name`** - -| Name | Type | Description | Default | -|------|---------------|----------------------------------------|---------| -| Name | System.String | Logical name for the WebSocket config | | - -**`$Address`** - -| Name | Type | Description | Default | -|---------|---------------|------------------------------------|---------| -| Address | System.String | Remote WebSocket URI (wss://...) | | - -**`$Config`** - -| Name | Type | Description | Default | -|--------|---------------|----------------------------------------------------|---------| -| Config | System.String | Path or pointer to the type-specific config file | | - -**`$Type`** - +to disk. + +#### Parameters + +**`$Name`** + | Name | Type | Description | Default | |------|---------------|---------------------------------------|---------| -| Type | System.String | Logical type for the WebSocket config | | - -**`$Force`** - -| Name | Type | Description | Default | -|-------|-------------------------|------------------------------------------------|---------| -| Force | System.Management.Automation.SwitchParameter | Overwrite an existing config with the same name | $false | - -#### Outputs - -System.Object — Returns a structured Icinga return indicating success or the -validation failure. - -#### Examples - -```powershell -PS> Add-IcingaWebSocketConfig -Name 'MyWebSocket' -Address 'wss://mywebsocket.example.com:443' -Config 'configs\mywebsocket.json' -Type MyWebSocket -``` - -#### Notes - +| Name | System.String | Logical name for the WebSocket config | | + +**`$Address`** + +| Name | Type | Description | Default | +|---------|---------------|----------------------------------|---------| +| Address | System.String | Remote WebSocket URI (wss://...) | | + +**`$Config`** + +| Name | Type | Description | Default | +|--------|---------------|--------------------------------------------------|---------| +| Config | System.String | Path or pointer to the type-specific config file | | + +**`$Type`** + +| Name | Type | Description | Default | +|------|---------------|---------------------------------------|---------| +| Type | System.String | Logical type for the WebSocket config | | + +**`$Force`** + +| Name | Type | Description | Default | +|-------|----------------------------------------------|-------------------------------------------------|---------| +| Force | System.Management.Automation.SwitchParameter | Overwrite an existing config with the same name | $false | + +#### Outputs + +System.Object -- Returns a structured Icinga return indicating success or the +validation failure. + +#### Examples + +```powershell +PS> Add-IcingaWebSocketConfig -Name 'MyWebSocket' -Address 'wss://mywebsocket.example.com:443' -Config 'configs\mywebsocket.json' -Type MyWebSocket +``` + +#### Notes + The persisted file under the Icinga config directory contains only the path pointer to the type-specific config, not the full in-memory object. Requires read access to the type-specific configuration file referenced by `Config`. -Configuration is stored in `$Global:Icinga.Public.WebSocket.Config`. - -*Source: [src/Core/WebSocket/Public/Add-IcingaWebSocketConfig.ps1](../../src/Core/WebSocket/Public/Add-IcingaWebSocketConfig.ps1)* - ---- - -### Remove-IcingaWebSocketConfig - -*Public function* - -**Synopsis:** Remove a persisted WebSocket configuration file. - -#### Description - +Configuration is stored in `$Global:Icinga.Public.WebSocket.Config`. + +*Source: [src/Core/WebSocket/Public/Add-IcingaWebSocketConfig.ps1](../src/Core/WebSocket/Public/Add-IcingaWebSocketConfig.ps1)* + +--- + +### Remove-IcingaWebSocketConfig + +*Public function* + +**Synopsis:** Remove a persisted WebSocket configuration file. + +#### Description + `Remove-IcingaWebSocketConfig` is the public wrapper for `Remove-ModuleWebSocketConfig`. It removes the persisted pointer file for a named WebSocket configuration from the Icinga config directory. The function does not modify in-memory runtime structures; a running WebSocket environment -must be restarted separately to reflect the removal. - -#### Parameters - -**`$Name`** - +must be restarted separately to reflect the removal. + +#### Parameters + +**`$Name`** + | Name | Type | Description | Default | |------|---------------|------------------------------------------------|---------| -| Name | System.String | Logical name of the WebSocket config to remove | | - -#### Outputs - -System.Object — Emits a structured return value when no name is provided; -otherwise removes the file and returns quietly. - -#### Examples - -```powershell -PS> Remove-IcingaWebSocketConfig -Name 'MyWebSocket' -``` - -#### Notes - +| Name | System.String | Logical name of the WebSocket config to remove | | + +#### Outputs + +System.Object -- Emits a structured return value when no name is provided; +otherwise removes the file and returns quietly. + +#### Examples + +```powershell +PS> Remove-IcingaWebSocketConfig -Name 'MyWebSocket' +``` + +#### Notes + Only the persisted pointer file on disk is removed. The in-memory configuration in `$Global:Icinga.Public.WebSocket.Config` is not modified. No special -permissions beyond write access to the Icinga config directory are required. - -*Source: [src/Core/WebSocket/Public/Remove-IcingaWebSocketConfig.ps1](../../src/Core/WebSocket/Public/Remove-IcingaWebSocketConfig.ps1)* - ---- - -### Show-IcingaWebSockets - -*Public function* - -**Synopsis:** Display the currently configured WebSocket endpoints. - -#### Description - +permissions beyond write access to the Icinga config directory are required. + +*Source: [src/Core/WebSocket/Public/Remove-IcingaWebSocketConfig.ps1](../src/Core/WebSocket/Public/Remove-IcingaWebSocketConfig.ps1)* + +--- + +### Show-IcingaWebSockets + +*Public function* + +**Synopsis:** Display the currently configured WebSocket endpoints. + +#### Description + `Show-IcingaWebSockets` is the public wrapper for `Show-ModuleWebSockets`. It reads all WebSocket configurations from `$Global:Icinga.Public.WebSocket.Config` and emits them as a formatted output message via `Write-LoggingEntry` at the `Output` level. The function is intended for interactive inspection during -runtime and produces no return value. - -#### Outputs - -None — Writes the WebSocket configurations as a formatted output entry via -`Write-LoggingEntry`. - -#### Examples - -```powershell -PS> Show-IcingaWebSockets -``` - -#### Notes - +runtime and produces no return value. + +#### Outputs + +None -- Writes the WebSocket configurations as a formatted output entry via +`Write-LoggingEntry`. + +#### Examples + +```powershell +PS> Show-IcingaWebSockets +``` + +#### Notes + No parameters are required. The output is written through `Write-LoggingEntry` and is not returned to the pipeline. Requires the WebSocket environment to have -been initialized via `Start-ModuleWebSocketDaemon` for meaningful output. - -*Source: [src/Core/WebSocket/Public/Show-IcingaWebSockets.ps1](../../src/Core/WebSocket/Public/Show-IcingaWebSockets.ps1)* - ---- - -### Add-ModuleWebSocketConfig - -*Private function* - -**Synopsis:** Register and persist a WebSocket configuration. - -#### Description - +been initialized via `Start-ModuleWebSocketDaemon` for meaningful output. + +*Source: [src/Core/WebSocket/Public/Show-IcingaWebSockets.ps1](../src/Core/WebSocket/Public/Show-IcingaWebSockets.ps1)* + +--- + +### Add-ModuleWebSocketConfig + +*Private function* + +**Synopsis:** Register and persist a WebSocket configuration. + +#### Description + `Add-ModuleWebSocketConfig` validates a WebSocket configuration payload, stores it in the runtime configuration (`$Global:ModuleName.Public.WebSocket.Config`), and persists a pointer file under the module config directory. The function reads the referenced type-specific config via `Read-ModuleConfigFile` and -only writes a path pointer to disk. - -#### Parameters - -**`$Name`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Name | System.String | Logical name for the WebSocket config | | - -**`$Address`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Address | System.String | Remote WebSocket URI (wss://...) | | - -**`$Config`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Config | System.String | Path or pointer to the type-specific config | | - -**`$Type`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Type | System.String | Logical type for the WebSocket config | | - -**`$Force`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Force | System.SwitchParameter | Overwrite an existing config with the same name | false | - -#### Outputs - -System.Object — Returns a structured module return indicating success or the validation failure. - -#### Examples - -```powershell -PS> Add-ModuleWebSocketConfig -Name 'MyWebSocket' -Address 'wss://example.com' -Config 'configs\mywebsocket.json' -Type MyWebSocket -``` - -#### Notes - +only writes a path pointer to disk. + +#### Parameters + +**`$Name`** + +| Name | Type | Description | Default | +|------|---------------|---------------------------------------|---------| +| Name | System.String | Logical name for the WebSocket config | | + +**`$Address`** + +| Name | Type | Description | Default | +|---------|---------------|----------------------------------|---------| +| Address | System.String | Remote WebSocket URI (wss://...) | | + +**`$Config`** + +| Name | Type | Description | Default | +|--------|---------------|---------------------------------------------|---------| +| Config | System.String | Path or pointer to the type-specific config | | + +**`$Type`** + +| Name | Type | Description | Default | +|------|---------------|---------------------------------------|---------| +| Type | System.String | Logical type for the WebSocket config | | + +**`$Force`** + +| Name | Type | Description | Default | +|-------|------------------------|-------------------------------------------------|---------| +| Force | System.SwitchParameter | Overwrite an existing config with the same name | false | + +#### Outputs + +System.Object -- Returns a structured module return indicating success or the validation failure. + +#### Examples + +```powershell +PS> Add-ModuleWebSocketConfig -Name 'MyWebSocket' -Address 'wss://example.com' -Config 'configs\mywebsocket.json' -Type MyWebSocket +``` + +#### Notes + The persisted file under the config directory contains only the path pointer to the type-specific config (not the full in-memory object). The configuration is stored in `$Global:ModuleName.Public.WebSocket.Config` and accessed via -`Get-GlobalRuntimeVariable`. - -*Source: [src/Core/WebSocket/Private/Add-ModuleWebSocketConfig.ps1](../../src/Core/WebSocket/Private/Add-ModuleWebSocketConfig.ps1)* - ---- - -### Add-ModuleWebSocketMessageToQueue - -*Private function* - -**Synopsis:** Enqueue a message for a WebSocket writer worker. - -#### Description - +`Get-GlobalRuntimeVariable`. + +*Source: [src/Core/WebSocket/Private/Add-ModuleWebSocketConfig.ps1](../src/Core/WebSocket/Private/Add-ModuleWebSocketConfig.ps1)* + +--- + +### Add-ModuleWebSocketMessageToQueue + +*Private function* + +**Synopsis:** Enqueue a message for a WebSocket writer worker. + +#### Description + `Add-ModuleWebSocketMessageToQueue` places a message into the configured WebSocket writer queue. It validates the WebSocket name (allowing an override) and the message payload, logs the enqueue operation and returns a -structured module return on error conditions. - -#### Parameters - -**`$Message`** - -| Name | Type | Description | Default | -|---------|--------------|------------------------------------|---------| -| Message | System.String| Message payload to enqueue. | | - -**`$OverrideWebSocketName`** - -| Name | Type | Description | Default | -|-----------------------|--------------|-------------------------------------------|---------| -| OverrideWebSocketName | System.String| Optional runtime websocket name override.| | - -#### Outputs - -System.Object — Emits module structured return values on error; otherwise the +structured module return on error conditions. + +#### Parameters + +**`$Message`** + +| Name | Type | Description | Default | +|---------|---------------|-----------------------------|---------| +| Message | System.String | Message payload to enqueue. | | + +**`$OverrideWebSocketName`** + +| Name | Type | Description | Default | +|-----------------------|---------------|-------------------------------------------|---------| +| OverrideWebSocketName | System.String | Optional runtime websocket name override. | | + +#### Outputs + +System.Object -- Emits module structured return values on error; otherwise the message is placed in the BlockingCollection and the function returns without -an explicit value. - -#### Examples - -```powershell -PS> Add-ModuleWebSocketMessageToQueue -Message $payload -``` - -#### Notes - +an explicit value. + +#### Examples + +```powershell +PS> Add-ModuleWebSocketMessageToQueue -Message $payload +``` + +#### Notes + The message is written directly to the `WriterWorker` BlockingCollection stored in `$Global:ModuleName.Public.WebSocket..WriterWorker`. This collection is consumed by `Write-ModuleWebSocket` running in a separate worker thread. The function must be called from within a worker context where `Get-GlobalRuntimeVariable` provides a valid WebSocket name via -`Private.WebSocket.Name`. - -*Source: [src/Core/WebSocket/Private/Add-ModuleWebSocketMessageToQueue.ps1](../../src/Core/WebSocket/Private/Add-ModuleWebSocketMessageToQueue.ps1)* - ---- - -### Connect-ModuleWebSocket - -*Private function* - -**Synopsis:** Establish a new ClientWebSocket connection and register it in runtime state. - -#### Description - +`Private.WebSocket.Name`. + +*Source: [src/Core/WebSocket/Private/Add-ModuleWebSocketMessageToQueue.ps1](../src/Core/WebSocket/Private/Add-ModuleWebSocketMessageToQueue.ps1)* + +--- + +### Connect-ModuleWebSocket + +*Private function* + +**Synopsis:** Establish a new ClientWebSocket connection and register it in runtime state. + +#### Description + `Connect-ModuleWebSocket` connects to a remote WebSocket URI using `System.Net.WebSockets.ClientWebSocket`, initializes cancellation token sources and stores the resulting objects in the private runtime state for use by reader/writer workers. It validates parameters and returns structured -module return values. - -#### Parameters - -**`$Name`** - -| Name | Type | Description | Default | -|------|--------------|--------------------------------------|---------| -| Name | System.String| Logical name for the WebSocket entry.| | - -**`$Address`** - -| Name | Type | Description | Default | -|---------|--------------|-------------------------------------------|---------| -| Address | System.String| WebSocket URI to connect to. | | - -#### Outputs - -System.Object — Emits `Write-FunctionReturnValue` results describing success or failure. - -#### Examples - -```powershell -PS> Connect-ModuleWebSocket -Name 'MyWebSocket' -Address 'wss://example.com' -``` - -#### Notes - +module return values. + +#### Parameters + +**`$Name`** + +| Name | Type | Description | Default | +|------|---------------|---------------------------------------|---------| +| Name | System.String | Logical name for the WebSocket entry. | | + +**`$Address`** + +| Name | Type | Description | Default | +|---------|---------------|------------------------------|---------| +| Address | System.String | WebSocket URI to connect to. | | + +#### Outputs + +System.Object -- Emits `Write-FunctionReturnValue` results describing success or failure. + +#### Examples + +```powershell +PS> Connect-ModuleWebSocket -Name 'MyWebSocket' -Address 'wss://example.com' +``` + +#### Notes + Any existing connection is cleaned up via `Disconnect-ModuleWebSocket` before a new one is established. The resulting `ClientWebSocket` and `CancellationTokenSource` are stored in `$Global:ModuleName.Private.WebSocket` -and must be accessed via `Get-GlobalRuntimeVariable` from worker threads. - -*Source: [src/Core/WebSocket/Private/Connect-ModuleWebSocket.ps1](../../src/Core/WebSocket/Private/Connect-ModuleWebSocket.ps1)* - ---- - -### Disconnect-ModuleWebSocket - -*Private function* - -**Synopsis:** Close and dispose the active WebSocket connection. - -#### Description - +and must be accessed via `Get-GlobalRuntimeVariable` from worker threads. + +*Source: [src/Core/WebSocket/Private/Connect-ModuleWebSocket.ps1](../src/Core/WebSocket/Private/Connect-ModuleWebSocket.ps1)* + +--- + +### Disconnect-ModuleWebSocket + +*Private function* + +**Synopsis:** Close and dispose the active WebSocket connection. + +#### Description + `Disconnect-ModuleWebSocket` attempts a graceful close of the active `ClientWebSocket` then disposes runtime resources. It returns structured -module results for success, not-connected, and various error conditions. - -#### Outputs - -System.Object — Structured `Write-FunctionReturnValue` values describing the outcome. - -#### Examples - -```powershell -PS> Disconnect-ModuleWebSocket -``` - -#### Notes - +module results for success, not-connected, and various error conditions. + +#### Outputs + +System.Object -- Structured `Write-FunctionReturnValue` values describing the outcome. + +#### Examples + +```powershell +PS> Disconnect-ModuleWebSocket +``` + +#### Notes + This function is safe to call even when no connection exists. It ensures cleanup of any lingering `ClientWebSocket` and `CancellationTokenSource` objects to avoid memory leaks. The function accesses runtime state via -`Get-GlobalRuntimeVariable`. - -*Source: [src/Core/WebSocket/Private/Disconnect-ModuleWebSocket.ps1](../../src/Core/WebSocket/Private/Disconnect-ModuleWebSocket.ps1)* - ---- - -### Get-ModuleCurrentWebSocketConfig - -*Private function* - -**Synopsis:** Return the WebSocket configuration object for the current thread. - -#### Description - +`Get-GlobalRuntimeVariable`. + +*Source: [src/Core/WebSocket/Private/Disconnect-ModuleWebSocket.ps1](../src/Core/WebSocket/Private/Disconnect-ModuleWebSocket.ps1)* + +--- + +### Get-ModuleCurrentWebSocketConfig + +*Private function* + +**Synopsis:** Return the WebSocket configuration object for the current thread. + +#### Description + `Get-ModuleCurrentWebSocketConfig` determines which WebSocket instance is assigned to the calling thread (via `$Global:ModuleName.Private.WebSocket.Name`) and returns the corresponding configuration object stored in `$Global:ModuleName.Public.WebSocket.Config`. If no name or config is found the -function returns `$null`. - -#### Outputs - -System.Management.Automation.PSCustomObject — Returns the WebSocket configuration -object for the current thread, or `$null` when no configuration is available. - -#### Examples - -```powershell -PS> Get-ModuleCurrentWebSocketConfig -``` - -#### Notes - +function returns `$null`. + +#### Outputs + +System.Management.Automation.PSCustomObject -- Returns the WebSocket configuration +object for the current thread, or `$null` when no configuration is available. + +#### Examples + +```powershell +PS> Get-ModuleCurrentWebSocketConfig +``` + +#### Notes + Relies on global state populated by WebSocket management functions under `Core\WebSocket`. Typical consumers are reader and handler threads that need access to the current connection credentials and settings. The thread-local WebSocket name is read from `$Global:ModuleName.Private.WebSocket.Name` via -`Get-GlobalRuntimeVariable`. - -*Source: [src/Core/WebSocket/Private/Get-ModuleCurrentWebSocketConfig.ps1](../../src/Core/WebSocket/Private/Get-ModuleCurrentWebSocketConfig.ps1)* - ---- - -### New-ModuleWebSocketEnvironment - -*Private function* - -**Synopsis:** Initialize WebSocket runtime environments and start handler threads. - -#### Description - +`Get-GlobalRuntimeVariable`. + +*Source: [src/Core/WebSocket/Private/Get-ModuleCurrentWebSocketConfig.ps1](../src/Core/WebSocket/Private/Get-ModuleCurrentWebSocketConfig.ps1)* + +--- + +### New-ModuleWebSocketEnvironment + +*Private function* + +**Synopsis:** Initialize WebSocket runtime environments and start handler threads. + +#### Description + `New-ModuleWebSocketEnvironment` loads WebSocket configuration files, creates per-instance runtime containers (reader/writer queues) and starts handler threads for each configured WebSocket instance. The function ensures -that the public runtime structure is populated for subsequent operations. - -#### Outputs - -System.Object — Returns a structured `Write-FunctionReturnValue` indicating -success or the absence of any configurations to initialize. - -#### Examples - -```powershell -PS> New-ModuleWebSocketEnvironment -``` - -#### Notes - +that the public runtime structure is populated for subsequent operations. + +#### Outputs + +System.Object -- Returns a structured `Write-FunctionReturnValue` indicating +success or the absence of any configurations to initialize. + +#### Examples + +```powershell +PS> New-ModuleWebSocketEnvironment +``` + +#### Notes + Uses `Read-ModuleWebSocketConfig` to load persisted configurations and `New-Thread` to spawn a `Start-ModuleWebSocketHandler` thread per instance. Each instance receives its own `ReaderWorker` and `WriterWorker` -`BlockingCollection` stored in `$Global:ModuleName.Public.WebSocket`. - -*Source: [src/Core/WebSocket/Private/New-ModuleWebSocketEnvironment.ps1](../../src/Core/WebSocket/Private/New-ModuleWebSocketEnvironment.ps1)* - ---- - -### Read-ModuleWebSocket - -*Private function* - -**Synopsis:** Read messages from an open WebSocket and enqueue them for processing. - -#### Description - +`BlockingCollection` stored in `$Global:ModuleName.Public.WebSocket`. + +*Source: [src/Core/WebSocket/Private/New-ModuleWebSocketEnvironment.ps1](../src/Core/WebSocket/Private/New-ModuleWebSocketEnvironment.ps1)* + +--- + +### Read-ModuleWebSocket + +*Private function* + +**Synopsis:** Read messages from an open WebSocket and enqueue them for processing. + +#### Description + `Read-ModuleWebSocket` continuously reads messages from the active `ClientWebSocket`, converts the received bytes into UTF8 strings and pushes complete messages to the configured reader worker queue for the connection name. It updates thread processing state and handles -exceptions by emitting structured module return values. - -#### Parameters - -**`$Name`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Name | System.String | Logical name of the WebSocket connection | | - -**`$ClientWebSocket`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ClientWebSocket | System.Net.WebSockets.ClientWebSocket | The active client WebSocket instance | | - -**`$CancellationTokenSource`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CancellationTokenSource | System.Threading.CancellationTokenSource | Token source used to cancel read operations | | - -#### Outputs - -System.Object — Emits structured `Write-FunctionReturnValue` values on errors; +exceptions by emitting structured module return values. + +#### Parameters + +**`$Name`** + +| Name | Type | Description | Default | +|------|---------------|------------------------------------------|---------| +| Name | System.String | Logical name of the WebSocket connection | | + +**`$ClientWebSocket`** + +| Name | Type | Description | Default | +|-----------------|---------------------------------------|--------------------------------------|---------| +| ClientWebSocket | System.Net.WebSockets.ClientWebSocket | The active client WebSocket instance | | + +**`$CancellationTokenSource`** + +| Name | Type | Description | Default | +|-------------------------|------------------------------------------|---------------------------------------------|---------| +| CancellationTokenSource | System.Threading.CancellationTokenSource | Token source used to cancel read operations | | + +#### Outputs + +System.Object -- Emits structured `Write-FunctionReturnValue` values on errors; otherwise received messages are placed into the named reader worker queue for -downstream processing. - -#### Examples - -```powershell -PS> Read-ModuleWebSocket -Name 'MyWebSocket' -ClientWebSocket $ws -CancellationTokenSource $cts -``` - -#### Notes - +downstream processing. + +#### Examples + +```powershell +PS> Read-ModuleWebSocket -Name 'MyWebSocket' -ClientWebSocket $ws -CancellationTokenSource $cts +``` + +#### Notes + This function is designed to run inside a dedicated worker thread spawned by `Start-ModuleWebSocketHandler`. It stores connection references via `Update-ModuleWebSocketThread` into `$Global:ModuleName.Private.WebSocket` and reads from the `ClientWebSocket` in a blocking loop. Received messages are placed in the `ReaderWorker` BlockingCollection under `$Global:ModuleName.Public.WebSocket.`. The loop runs until -`Test-ThreadRunning -CheckWebSocket` returns `$false`. - -*Source: [src/Core/WebSocket/Private/Read-ModuleWebSocket.ps1](../../src/Core/WebSocket/Private/Read-ModuleWebSocket.ps1)* - ---- - -### Read-ModuleWebSocketConfig - -*Private function* - -**Synopsis:** Load WebSocket configuration files into the runtime config store. - -#### Description - +`Test-ThreadRunning -CheckWebSocket` returns `$false`. + +*Source: [src/Core/WebSocket/Private/Read-ModuleWebSocket.ps1](../src/Core/WebSocket/Private/Read-ModuleWebSocket.ps1)* + +--- + +### Read-ModuleWebSocketConfig + +*Private function* + +**Synopsis:** Load WebSocket configuration files into the runtime config store. + +#### Description + `Read-ModuleWebSocketConfig` scans the module configuration directory for WebSocket JSON files, validates and parses each file, then loads the referenced type-specific configuration using `Read-ModuleConfigFile`. -Parsed configurations are stored in `$Global:ModuleName.Public.WebSocket.Config`. - -#### Outputs - -System.Object — Emits structured `Write-FunctionReturnValue` values indicating -load results and returns the populated config object on success. - -#### Examples - -```powershell -PS> Read-ModuleWebSocketConfig -``` - -#### Notes - +Parsed configurations are stored in `$Global:ModuleName.Public.WebSocket.Config`. + +#### Outputs + +System.Object -- Emits structured `Write-FunctionReturnValue` values indicating +load results and returns the populated config object on success. + +#### Examples + +```powershell +PS> Read-ModuleWebSocketConfig +``` + +#### Notes + Each WebSocket configuration file must include a `Name` property and a `Config` pointer referencing the type-specific configuration file. Parsed configurations are stored in `$Global:ModuleName.Public.WebSocket.Config` and accessed via -`Get-GlobalRuntimeVariable`. - -*Source: [src/Core/WebSocket/Private/Read-ModuleWebSocketConfig.ps1](../../src/Core/WebSocket/Private/Read-ModuleWebSocketConfig.ps1)* - ---- - -### Remove-ModuleWebSocketConfig - -*Private function* - -**Synopsis:** Remove a persisted WebSocket configuration file. - -#### Description - +`Get-GlobalRuntimeVariable`. + +*Source: [src/Core/WebSocket/Private/Read-ModuleWebSocketConfig.ps1](../src/Core/WebSocket/Private/Read-ModuleWebSocketConfig.ps1)* + +--- + +### Remove-ModuleWebSocketConfig + +*Private function* + +**Synopsis:** Remove a persisted WebSocket configuration file. + +#### Description + `Remove-ModuleWebSocketConfig` removes the persisted pointer file for a named WebSocket configuration from the module config directory. It does -not modify in-memory runtime structures. - -#### Parameters - -**`$Name`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Name | System.String | Logical name of the WebSocket config to remove | | - -#### Outputs - -System.Object — Emits a structured return value when no name is provided; otherwise it removes the file and returns quietly. - -#### Examples - -```powershell -PS> Remove-ModuleWebSocketConfig -Name 'MyWebSocket' -``` - -*Source: [src/Core/WebSocket/Private/Remove-ModuleWebSocketConfig.ps1](../../src/Core/WebSocket/Private/Remove-ModuleWebSocketConfig.ps1)* - ---- - -### Show-ModuleWebSockets - -*Private function* - -**Synopsis:** Display the currently configured WebSocket endpoints. - -#### Description - +not modify in-memory runtime structures. + +#### Parameters + +**`$Name`** + +| Name | Type | Description | Default | +|------|---------------|------------------------------------------------|---------| +| Name | System.String | Logical name of the WebSocket config to remove | | + +#### Outputs + +System.Object -- Emits a structured return value when no name is provided; otherwise it removes the file and returns quietly. + +#### Examples + +```powershell +PS> Remove-ModuleWebSocketConfig -Name 'MyWebSocket' +``` + +#### Notes + +Removes the JSON configuration file from the `WebSocket` subfolder inside +`Get-ModuleConfigDirectory` via `Remove-SecureItem`. + +*Source: [src/Core/WebSocket/Private/Remove-ModuleWebSocketConfig.ps1](../src/Core/WebSocket/Private/Remove-ModuleWebSocketConfig.ps1)* + +--- + +### Show-ModuleWebSockets + +*Private function* + +**Synopsis:** Display the currently configured WebSocket endpoints. + +#### Description + `Show-ModuleWebSockets` reads all WebSocket configurations from -`$Global:ModuleName.Public.WebSocket.Config` via `Get-GlobalRuntimeVariable` and +`$Global:IcingaForWindows.Public.WebSocket.Config` via `Get-GlobalRuntimeVariable` and emits them as a formatted output message using `Write-LoggingEntry` at the `Output` level. The function is intended for interactive inspection during -runtime and produces no return value. - -#### Outputs - -None — Writes the WebSocket configurations as a formatted output entry via -`Write-LoggingEntry`. - -#### Examples - -```powershell -PS> Show-ModuleWebSockets -``` - -*Source: [src/Core/WebSocket/Private/Show-ModuleWebSockets.ps1](../../src/Core/WebSocket/Private/Show-ModuleWebSockets.ps1)* - ---- - -### Start-ModuleWebSocketDaemon - -*Private function* - -**Synopsis:** Start the WebSocket environment background thread. - -#### Description - +runtime and produces no return value. + +#### Outputs + +None -- Writes the WebSocket configurations as a formatted output entry via +`Write-LoggingEntry`. + +#### Examples + +```powershell +PS> Show-ModuleWebSockets +``` + +#### Notes + +Internal implementation behind the public `Show-IcingaWebSockets` cmdlet. + +*Source: [src/Core/WebSocket/Private/Show-ModuleWebSockets.ps1](../src/Core/WebSocket/Private/Show-ModuleWebSockets.ps1)* + +--- + +### Start-ModuleWebSocketDaemon + +*Private function* + +**Synopsis:** Start the WebSocket environment background thread. + +#### Description + `Start-ModuleWebSocketDaemon` starts the WebSocket environment by creating a background thread that initializes the WebSocket runtime (`New-ModuleWebSocketEnvironment`). -The function returns immediately after the management thread is started. - -#### Outputs - -None — Starts a background thread and returns immediately without a return value. - -#### Examples - -```powershell -PS> Start-ModuleWebSocketDaemon -``` - -#### Notes - +The function returns immediately after the management thread is started. + +#### Outputs + +None -- Starts a background thread and returns immediately without a return value. + +#### Examples + +```powershell +PS> Start-ModuleWebSocketDaemon +``` + +#### Notes + This helper wraps `New-Thread` to ensure the WebSocket environment is initialized on a separate thread. The background thread executes `New-ModuleWebSocketEnvironment`, which loads all persisted WebSocket -configurations and spawns per-instance handler threads. - -*Source: [src/Core/WebSocket/Private/Start-ModuleWebSocketDaemon.ps1](../../src/Core/WebSocket/Private/Start-ModuleWebSocketDaemon.ps1)* - ---- - -### Start-ModuleWebSocketHandler - -*Private function* - -**Synopsis:** Manage a persistent WebSocket connection and spawn worker threads. - -#### Description - +configurations and spawns per-instance handler threads. + +*Source: [src/Core/WebSocket/Private/Start-ModuleWebSocketDaemon.ps1](../src/Core/WebSocket/Private/Start-ModuleWebSocketDaemon.ps1)* + +--- + +### Start-ModuleWebSocketHandler + +*Private function* + +**Synopsis:** Manage a persistent WebSocket connection and spawn worker threads. + +#### Description + `Start-ModuleWebSocketHandler` drives the lifecycle for a named WebSocket connection. It attempts to establish the connection, performs any type- specific authentication steps (for example MyWebSocket), and spawns reader, writer and processing worker threads. The handler runs in a -loop and is responsible for reconnection and keep-alive handling. - -#### Parameters - -**`$Name`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Name | System.String | Name of the WebSocket configuration to manage | | - -#### Outputs - -System.Object — Emits structured return codes for validation failures; otherwise -the function runs until the thread manager requests termination. - -#### Examples - -```powershell -PS> Start-ModuleWebSocketHandler -Name 'MySocket' -``` - -#### Notes - +loop and is responsible for reconnection and keep-alive handling. + +#### Parameters + +**`$Name`** + +| Name | Type | Description | Default | +|------|---------------|-----------------------------------------------|---------| +| Name | System.String | Name of the WebSocket configuration to manage | | + +#### Outputs + +System.Object -- Emits structured return codes for validation failures; otherwise +the function runs until the thread manager requests termination. + +#### Examples + +```powershell +PS> Start-ModuleWebSocketHandler -Name 'MySocket' +``` + +#### Notes + The function expects a corresponding configuration entry in `$Global:ModuleName.Public.WebSocket.Config` for the provided `Name`. It runs inside a dedicated thread spawned by `New-ModuleWebSocketEnvironment` and drives connection, reconnection, keep-alive handling, as well as spawning of reader, -writer and processing worker threads. - -*Source: [src/Core/WebSocket/Private/Start-ModuleWebSocketHandler.ps1](../../src/Core/WebSocket/Private/Start-ModuleWebSocketHandler.ps1)* - ---- - -### Start-ModuleWebSocketReaderWorker - -*Private function* - -**Synopsis:** Worker loop: dequeue WebSocket messages and dispatch by type. - -#### Description - +writer and processing worker threads. + +*Source: [src/Core/WebSocket/Private/Start-ModuleWebSocketHandler.ps1](../src/Core/WebSocket/Private/Start-ModuleWebSocketHandler.ps1)* + +--- + +### Start-ModuleWebSocketReaderWorker + +*Private function* + +**Synopsis:** Worker loop: dequeue WebSocket messages and dispatch by type. + +#### Description + `Start-ModuleWebSocketReaderWorker` consumes messages from the named WebSocket reader queue, converts them into message objects depending on the WebSocket type (for example MyWebSocket), and augments them with `Origin` metadata for downstream processing. The worker runs until the thread -manager requests shutdown. - -#### Parameters - -**`$Name`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Name | System.String | Logical name of the WebSocket connection to read from | | - -**`$ClientWebSocket`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ClientWebSocket | System.Net.WebSockets.ClientWebSocket | Active client WebSocket instance | | - -**`$CancellationTokenSource`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CancellationTokenSource | System.Threading.CancellationTokenSource | Cancellation token source used to cancel operations | | - -#### Outputs - -System.Object — Emits structured module return values on errors; otherwise -messages are prepared and enqueued for further processing. - -#### Examples - -```powershell -PS> Start-ModuleWebSocketReaderWorker -Name 'MyWebSocket' -ClientWebSocket $ws -CancellationTokenSource $cts -``` - -*Source: [src/Core/WebSocket/Private/Start-ModuleWebSocketReaderWorker.ps1](../../src/Core/WebSocket/Private/Start-ModuleWebSocketReaderWorker.ps1)* - ---- - -### Test-ModuleWebSocket - -*Private function* - -**Synopsis:** Check whether the current WebSocket client is connected and open. - -#### Description - +manager requests shutdown. + +#### Parameters + +**`$Name`** + +| Name | Type | Description | Default | +|------|---------------|-------------------------------------------------------|---------| +| Name | System.String | Logical name of the WebSocket connection to read from | | + +**`$ClientWebSocket`** + +| Name | Type | Description | Default | +|-----------------|---------------------------------------|----------------------------------|---------| +| ClientWebSocket | System.Net.WebSockets.ClientWebSocket | Active client WebSocket instance | | + +**`$CancellationTokenSource`** + +| Name | Type | Description | Default | +|-------------------------|------------------------------------------|-----------------------------------------------------|---------| +| CancellationTokenSource | System.Threading.CancellationTokenSource | Cancellation token source used to cancel operations | | + +#### Outputs + +System.Object -- Emits structured module return values on errors; otherwise +messages are prepared and enqueued for further processing. + +#### Examples + +```powershell +PS> Start-ModuleWebSocketReaderWorker -Name 'MyWebSocket' -ClientWebSocket $ws -CancellationTokenSource $cts +``` + +#### Notes + +Runs on a dedicated background worker runspace managed by `New-Thread` and +exits cleanly when `Test-ThreadRunning -CheckWebSocket` returns `$false`. + +*Source: [src/Core/WebSocket/Private/Start-ModuleWebSocketReaderWorker.ps1](../src/Core/WebSocket/Private/Start-ModuleWebSocketReaderWorker.ps1)* + +--- + +### Test-ModuleWebSocket + +*Private function* + +**Synopsis:** Check whether the current WebSocket client is connected and open. + +#### Description + `Test-ModuleWebSocket` verifies that a `ClientWebSocket` exists in -`$Global:ModuleName.Private.WebSocket` and that its `State` equals `Open`. -Returns a boolean value indicating whether the WebSocket is connected. - -#### Outputs - -System.Boolean — $true when the WebSocket connection is active and open; $false otherwise. - -#### Examples - -```powershell -PS> if (Test-ModuleWebSocket) { Write-LoggingEntry -Message 'WebSocket connected' -Level 'Output' } -``` - -*Source: [src/Core/WebSocket/Private/Test-ModuleWebSocket.ps1](../../src/Core/WebSocket/Private/Test-ModuleWebSocket.ps1)* - ---- - -### Update-ModuleWebSocketThread - -*Private function* - -**Synopsis:** Update the global WebSocket thread state for the current runtime. - -#### Description - +`$Global:IcingaForWindows.Private.WebSocket` via `Get-GlobalRuntimeVariable` and +that its `State` equals `Open`. Returns a boolean value indicating whether the +WebSocket is connected. + +#### Outputs + +System.Boolean -- $true when the WebSocket connection is active and open; $false otherwise. + +#### Examples + +```powershell +PS> if (Test-ModuleWebSocket) { Write-LoggingEntry -Message 'WebSocket connected' -Level 'Output' } +``` + +#### Notes + +Reads thread-local `Private.WebSocket.ClientWebSocket` state for the active +WebSocket worker runspace. + +*Source: [src/Core/WebSocket/Private/Test-ModuleWebSocket.ps1](../src/Core/WebSocket/Private/Test-ModuleWebSocket.ps1)* + +--- + +### Update-ModuleWebSocketThread + +*Private function* + +**Synopsis:** Update the global WebSocket thread state for the current runtime. + +#### Description + `Update-ModuleWebSocketThread` stores the active WebSocket thread values (`Name`, `ClientWebSocket`, `CancellationTokenSource`) in -`$Global:ModuleName.Private.WebSocket` so other WebSocket helper threads can -access the current connection reference. - -#### Parameters - -**`$Name`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Name | System.String | Logical name of the WebSocket connection | | - -**`$ClientWebSocket`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ClientWebSocket | System.Net.WebSockets.ClientWebSocket | Active client WebSocket instance | | - -**`$CancellationTokenSource`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CancellationTokenSource | System.Threading.CancellationTokenSource | Cancellation token source used to cancel reads/writes | | - -#### Outputs - -System.Object — Returns structured `Write-FunctionReturnValue` status codes indicating success or validation failures. - -#### Examples - -```powershell -PS> Update-ModuleWebSocketThread -Name 'MyWebSocket' -ClientWebSocket $ws -CancellationTokenSource $cts -``` - -*Source: [src/Core/WebSocket/Private/Update-ModuleWebSocketThread.ps1](../../src/Core/WebSocket/Private/Update-ModuleWebSocketThread.ps1)* - ---- - -### Write-ModuleWebSocket - -*Private function* - -**Synopsis:** Dequeue messages and send them over the active WebSocket. - -#### Description - +`$Global:IcingaForWindows.Private.WebSocket` via `Get-GlobalRuntimeVariable` so +other WebSocket helper functions in the same worker runspace can access the +current connection reference. + +#### Parameters + +**`$Name`** + +| Name | Type | Description | Default | +|------|---------------|------------------------------------------|---------| +| Name | System.String | Logical name of the WebSocket connection | | + +**`$ClientWebSocket`** + +| Name | Type | Description | Default | +|-----------------|---------------------------------------|----------------------------------|---------| +| ClientWebSocket | System.Net.WebSockets.ClientWebSocket | Active client WebSocket instance | | + +**`$CancellationTokenSource`** + +| Name | Type | Description | Default | +|-------------------------|------------------------------------------|-------------------------------------------------------|---------| +| CancellationTokenSource | System.Threading.CancellationTokenSource | Cancellation token source used to cancel reads/writes | | + +#### Outputs + +System.Object -- Returns structured `Write-FunctionReturnValue` status codes indicating success or validation failures. + +#### Examples + +```powershell +PS> Update-ModuleWebSocketThread -Name 'MyWebSocket' -ClientWebSocket $ws -CancellationTokenSource $cts +``` + +#### Notes + +Populates thread-local `Private.WebSocket` state before reader or writer loops start. + +*Source: [src/Core/WebSocket/Private/Update-ModuleWebSocketThread.ps1](../src/Core/WebSocket/Private/Update-ModuleWebSocketThread.ps1)* + +--- + +### Write-ModuleWebSocket + +*Private function* + +**Synopsis:** Dequeue messages and send them over the active WebSocket. + +#### Description + `Write-ModuleWebSocket` continuously reads messages from the named WebSocket writer queue and sends them to the remote endpoint using the active `ClientWebSocket`. The function retries queueing when the socket -is not connected and emits structured return values on errors. - -#### Parameters - -**`$Name`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Name | System.String | Logical name of the WebSocket connection to write to | | - -**`$ClientWebSocket`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ClientWebSocket | System.Net.WebSockets.ClientWebSocket | Active client WebSocket instance | | - -**`$CancellationTokenSource`** - -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CancellationTokenSource | System.Threading.CancellationTokenSource | Token source used to cancel send operations | | - -#### Outputs - -System.Object — Emits structured `Write-FunctionReturnValue` values on send errors. - -#### Examples - -```powershell -PS> Write-ModuleWebSocket -Name 'MyWebSocket' -ClientWebSocket $ws -CancellationTokenSource $cts -``` - -*Source: [src/Core/WebSocket/Private/Write-ModuleWebSocket.ps1](../../src/Core/WebSocket/Private/Write-ModuleWebSocket.ps1)* - - +is not connected and emits structured return values on errors. + +#### Parameters + +**`$Name`** + +| Name | Type | Description | Default | +|------|---------------|------------------------------------------------------|---------| +| Name | System.String | Logical name of the WebSocket connection to write to | | + +**`$ClientWebSocket`** + +| Name | Type | Description | Default | +|-----------------|---------------------------------------|----------------------------------|---------| +| ClientWebSocket | System.Net.WebSockets.ClientWebSocket | Active client WebSocket instance | | + +**`$CancellationTokenSource`** + +| Name | Type | Description | Default | +|-------------------------|------------------------------------------|---------------------------------------------|---------| +| CancellationTokenSource | System.Threading.CancellationTokenSource | Token source used to cancel send operations | | + +#### Outputs + +System.Object -- Emits structured `Write-FunctionReturnValue` values on send errors. + +#### Examples + +```powershell +PS> Write-ModuleWebSocket -Name 'MyWebSocket' -ClientWebSocket $ws -CancellationTokenSource $cts +``` + +#### Notes + +Runs on a dedicated background writer runspace and disposes `SendAsync` task +handles after each frame to prevent memory leaks. + +*Source: [src/Core/WebSocket/Private/Write-ModuleWebSocket.ps1](../src/Core/WebSocket/Private/Write-ModuleWebSocket.ps1)* + diff --git a/docs/Icinga.IcingaProtocol.md b/docs/Icinga.IcingaProtocol.md index b83baca..7093c4b 100644 --- a/docs/Icinga.IcingaProtocol.md +++ b/docs/Icinga.IcingaProtocol.md @@ -60,19 +60,19 @@ directory as 'ca.crt' (on Linux/macOS). **`$Certificate`** -| Name | Type | Description | Default | -|-------------|---------------|--------------------------------------------|---------| -| Certificate | System.String | The PEM-formatted CA certificate payload. | | +| Name | Type | Description | Default | +|-------------|---------------|-------------------------------------------|---------| +| Certificate | System.String | The PEM-formatted CA certificate payload. | | **`$Path`** -| Name | Type | Description | Default | -|------|---------------|-----------------------------------------------------|---------| -| Path | System.String | Local file path or HTTP/HTTPS URL to the CA cert. | | +| Name | Type | Description | Default | +|------|---------------|---------------------------------------------------|---------| +| Path | System.String | Local file path or HTTP/HTTPS URL to the CA cert. | | #### Outputs -None — Performs the import or file write without returning a value. +None -- Performs the import or file write without returning a value. #### Examples @@ -93,7 +93,7 @@ Downloads and imports the CA certificate from a web server. Operates on the CurrentUser CertificateAuthority store to avoid Windows security prompts. Does not require administrative elevation. -*Source: [src/IcingaProtocol/Public/Import-IcingaCertAuthority.ps1](../../src/IcingaProtocol/Public/Import-IcingaCertAuthority.ps1)* +*Source: [src/IcingaProtocol/Public/Import-IcingaCertAuthority.ps1](../src/IcingaProtocol/Public/Import-IcingaCertAuthority.ps1)* --- @@ -117,19 +117,19 @@ certificate is removed from the store automatically. **`$CommonName`** -| Name | Type | Description | Default | -|------------|---------------|--------------------------------------------|---------| -| CommonName | System.String | The common name (CN) for the certificate. | $null | +| Name | Type | Description | Default | +|------------|---------------|-------------------------------------------|---------| +| CommonName | System.String | The common name (CN) for the certificate. | $null | **`$SignedCert`** -| Name | Type | Description | Default | -|------------|---------------|--------------------------------------------|---------| -| SignedCert | System.String | The PEM-formatted signed certificate. | $null | +| Name | Type | Description | Default | +|------------|---------------|---------------------------------------|---------| +| SignedCert | System.String | The PEM-formatted signed certificate. | $null | #### Outputs -System.Object — Returns a structured result via Write-FunctionReturnValue containing the storage path. +System.Object -- Returns a structured result via Write-FunctionReturnValue containing the storage path. #### Examples @@ -150,7 +150,7 @@ Merges the signed certificate with the existing private key for 'IcingaNode'. Requires administrative privileges on Windows to access the LocalMachine certificate store. Cross-platform compatible; relies on .NET cryptography classes. -*Source: [src/IcingaProtocol/Public/New-IcingaProtocolCertificate.ps1](../../src/IcingaProtocol/Public/New-IcingaProtocolCertificate.ps1)* +*Source: [src/IcingaProtocol/Public/New-IcingaProtocolCertificate.ps1](../src/IcingaProtocol/Public/New-IcingaProtocolCertificate.ps1)* --- @@ -169,25 +169,25 @@ This object is typically passed into New-IcingaProtocolEnvironment. **`$Name`** -| Name | Type | Description | Default | -|------|---------------|--------------------------------------------|---------| -| Name | System.String | The human-readable name of the endpoint. | | +| Name | Type | Description | Default | +|------|---------------|------------------------------------------|---------| +| Name | System.String | The human-readable name of the endpoint. | | **`$Address`** -| Name | Type | Description | Default | -|---------|---------------|--------------------------------------------|---------| -| Address | System.String | The IP address or FQDN of the endpoint. | | +| Name | Type | Description | Default | +|---------|---------------|-----------------------------------------|---------| +| Address | System.String | The IP address or FQDN of the endpoint. | | **`$Port`** -| Name | Type | Description | Default | -|------|--------------|--------------------------------------------|---------| -| Port | System.Int32 | The TCP port to connect to. | | +| Name | Type | Description | Default | +|------|--------------|-----------------------------|---------| +| Port | System.Int32 | The TCP port to connect to. | | #### Outputs -System.Collections.Hashtable — Returns a hashtable with the endpoint configuration. +System.Collections.Hashtable -- Returns a hashtable with the endpoint configuration. #### Examples @@ -201,7 +201,7 @@ Creates a new endpoint object for Master1. This object is required for configuring the Icinga environment structure. -*Source: [src/IcingaProtocol/Public/New-IcingaProtocolEndpoint.ps1](../../src/IcingaProtocol/Public/New-IcingaProtocolEndpoint.ps1)* +*Source: [src/IcingaProtocol/Public/New-IcingaProtocolEndpoint.ps1](../src/IcingaProtocol/Public/New-IcingaProtocolEndpoint.ps1)* --- @@ -221,37 +221,37 @@ or returns a diff against the current configuration if -DryRun is used. **`$Endpoints`** -| Name | Type | Description | Default | -|-----------|--------------|--------------------------------------------|---------| -| Endpoints | System.Array | An array of endpoint hashtables. | @() | +| Name | Type | Description | Default | +|-----------|--------------|----------------------------------|---------| +| Endpoints | System.Array | An array of endpoint hashtables. | @() | **`$Zone`** -| Name | Type | Description | Default | -|------|---------------|--------------------------------------------|----------| -| Zone | System.String | The name of the Icinga zone. | 'master' | +| Name | Type | Description | Default | +|------|---------------|------------------------------|----------| +| Zone | System.String | The name of the Icinga zone. | 'master' | **`$Hostname`** -| Name | Type | Description | Default | -|----------|---------------|--------------------------------------------|-------------| -| Hostname | System.String | The local hostname for this node. | '$hostname' | +| Name | Type | Description | Default | +|----------|---------------|-----------------------------------|-------------| +| Hostname | System.String | The local hostname for this node. | '$hostname' | **`$TlsCertConfig`** -| Name | Type | Description | Default | -|---------------|----------------|--------------------------------------------|---------| -| TlsCertConfig | PSCustomObject | The TLS certificate configuration object. | $null | +| Name | Type | Description | Default | +|---------------|----------------|-------------------------------------------|---------| +| TlsCertConfig | PSCustomObject | The TLS certificate configuration object. | $null | **`$DryRun`** -| Name | Type | Description | Default | -|--------|--------|--------------------------------------------|---------| -| DryRun | switch | Outputs a diff without saving the file. | $false | +| Name | Type | Description | Default | +|--------|--------|-----------------------------------------|---------| +| DryRun | switch | Outputs a diff without saving the file. | $false | #### Outputs -System.Object — Returns a status object from Write-FunctionReturnValue or a diff string. +System.Object -- Returns a status object from Write-FunctionReturnValue or a diff string. #### Examples @@ -266,7 +266,7 @@ Generates the protocol configuration and writes it to disk. Writes configuration data to the internal Icinga Protocol connection JSON file. -*Source: [src/IcingaProtocol/Public/New-IcingaProtocolEnvironment.ps1](../../src/IcingaProtocol/Public/New-IcingaProtocolEnvironment.ps1)* +*Source: [src/IcingaProtocol/Public/New-IcingaProtocolEnvironment.ps1](../src/IcingaProtocol/Public/New-IcingaProtocolEnvironment.ps1)* --- @@ -285,7 +285,7 @@ threads for Icinga JSON-RPC communication. #### Outputs -None — Starts a background thread; no pipeline output. +None -- Starts a background thread; no pipeline output. #### Examples @@ -299,7 +299,7 @@ This function requires New-IcingaAgentEnvironment and New-Thread to be available The agent environment is initialized asynchronously in the spawned thread. Call this once during module startup after global configuration is in place. -*Source: [src/IcingaProtocol/Public/Start-IcingaAgent.ps1](../../src/IcingaProtocol/Public/Start-IcingaAgent.ps1)* +*Source: [src/IcingaProtocol/Public/Start-IcingaAgent.ps1](../src/IcingaProtocol/Public/Start-IcingaAgent.ps1)* --- @@ -330,13 +330,13 @@ to emit a standardized operation result object indicating success or failure. **`$TcpClient`** -| Name | Type | Description | Default | -|-----------|----------------------------------|---------------------------------------------------------|---------| -| TcpClient | System.Net.Sockets.TcpClient | Active TcpClient instance to store in the connections table. | $null | +| Name | Type | Description | Default | +|-----------|------------------------------|--------------------------------------------------------------|---------| +| TcpClient | System.Net.Sockets.TcpClient | Active TcpClient instance to store in the connections table. | $null | #### Outputs -PSCustomObject — Return value produced by Write-FunctionReturnValue. +PSCustomObject -- Return value produced by Write-FunctionReturnValue. Possible tokens: IcingaClientAddingFailed (validation failed) or IcingaClientAdded (success). #### Examples @@ -359,7 +359,7 @@ This function modifies $Global:IcingaForWindows.Public.IcingaProtocol.Connection The caller is responsible for the lifetime and disposal of the TcpClient objects. No additional connectivity checks are performed; the function only stores the provided instance. -*Source: [src/IcingaProtocol/Private/Add-IcingaProtocolClient.ps1](../../src/IcingaProtocol/Private/Add-IcingaProtocolClient.ps1)* +*Source: [src/IcingaProtocol/Private/Add-IcingaProtocolClient.ps1](../src/IcingaProtocol/Private/Add-IcingaProtocolClient.ps1)* --- @@ -383,9 +383,9 @@ and are dropped without throwing. **`$Message`** -| Name | Type | Description | Default | -|---------|---------------|------------------------------------------------------------------------------|---------| -| Message | System.String | Serialized JSON-RPC message payload to enqueue. Ignored when null or empty. | $null | +| Name | Type | Description | Default | +|---------|---------------|-----------------------------------------------------------------------------|---------| +| Message | System.String | Serialized JSON-RPC message payload to enqueue. Ignored when null or empty. | $null | #### Outputs @@ -404,7 +404,7 @@ Parses the JSON-RPC message and dispatches it to the next protocol worker queue. Caller must ensure WorkerCount and WorkerQueue are initialized in Public.IcingaProtocol before invoking this helper. -*Source: [src/IcingaProtocol/Private/Add-IcingaRPCMessageToWorker.ps1](../../src/IcingaProtocol/Private/Add-IcingaRPCMessageToWorker.ps1)* +*Source: [src/IcingaProtocol/Private/Add-IcingaRPCMessageToWorker.ps1](../src/IcingaProtocol/Private/Add-IcingaRPCMessageToWorker.ps1)* --- @@ -430,13 +430,13 @@ that it works correctly inside worker thread runspaces. **`$MsgObj`** -| Name | Type | Description | Default | -|--------|---------------|-----------------------------------------------------------------------|---------| +| Name | Type | Description | Default | +|--------|---------------|-------------------------------------------------------------------------|---------| | MsgObj | System.Object | Message object as returned by New-IcingaRPCMessage (@{message;length}). | $null | #### Outputs -None — The function enqueues the message or sends it directly; no pipeline output is produced. +None -- The function enqueues the message or sends it directly; no pipeline output is produced. #### Examples @@ -450,7 +450,7 @@ This function uses Get-GlobalRuntimeVariable to access global state, making it s call from within thread runspaces. The writer queue is keyed by the string representation of the remote endpoint IP address. -*Source: [src/IcingaProtocol/Private/Add-IcingaRPCMessageToWriterQueue.ps1](../../src/IcingaProtocol/Private/Add-IcingaRPCMessageToWriterQueue.ps1)* +*Source: [src/IcingaProtocol/Private/Add-IcingaRPCMessageToWriterQueue.ps1](../src/IcingaProtocol/Private/Add-IcingaRPCMessageToWriterQueue.ps1)* --- @@ -486,15 +486,15 @@ Two Icinga 2 delivery modes are supported seamlessly across Windows PowerShell **`$ResolvedCommand`** -| Name | Type | Description | Default | -|-----------------|------------------------------|--------------------------------------------------------------|---------| -| ResolvedCommand | System.Collections.Hashtable | Command descriptor returned by Resolve-IcingaProtocolCommand.| @{} | +| Name | Type | Description | Default | +|-----------------|------------------------------|---------------------------------------------------------------|---------| +| ResolvedCommand | System.Collections.Hashtable | Command descriptor returned by Resolve-IcingaProtocolCommand. | @{} | **`$Macros`** -| Name | Type | Description | Default | -|--------|---------------|-----------------------------------------------------------------------|---------| -| Macros | System.Object | Deserialized macros dictionary or object from event::ExecuteCommand. | $null | +| Name | Type | Description | Default | +|--------|---------------|----------------------------------------------------------------------|---------| +| Macros | System.Object | Deserialized macros dictionary or object from event::ExecuteCommand. | $null | #### Outputs @@ -517,7 +517,7 @@ Callers must dispose every entry in AllocatedSecureStrings once plugin execution completes. On validation errors, any SecureString allocated earlier in the same call is disposed before returning. -*Source: [src/IcingaProtocol/Private/ConvertFrom-IcingaProtocolMacros.ps1](../../src/IcingaProtocol/Private/ConvertFrom-IcingaProtocolMacros.ps1)* +*Source: [src/IcingaProtocol/Private/ConvertFrom-IcingaProtocolMacros.ps1](../src/IcingaProtocol/Private/ConvertFrom-IcingaProtocolMacros.ps1)* --- @@ -546,21 +546,21 @@ table: **`$Expression`** -| Name | Type | Description | Default | -|------------|---------------|-----------------------------------------------------------|---------| -| Expression | System.Object | Raw 'value' or 'set_if' expression from ifw_api_arguments.| $null | +| Name | Type | Description | Default | +|------------|---------------|------------------------------------------------------------|---------| +| Expression | System.Object | Raw 'value' or 'set_if' expression from ifw_api_arguments. | $null | **`$MacroMap`** -| Name | Type | Description | Default | -|----------|---------------|----------------------------------------------------------|---------| -| MacroMap | System.Object | Case-sensitive OrderedDictionary of macro key/values. | $null | +| Name | Type | Description | Default | +|----------|---------------|-------------------------------------------------------|---------| +| MacroMap | System.Object | Case-sensitive OrderedDictionary of macro key/values. | $null | **`$MacroIgnoreCase`** -| Name | Type | Description | Default | -|-----------------|------------------------------|---------------------------------------------------|---------| -| MacroIgnoreCase | System.Collections.Hashtable | Case-insensitive fallback hashtable for macros. | @{} | +| Name | Type | Description | Default | +|-----------------|------------------------------|-------------------------------------------------|---------| +| MacroIgnoreCase | System.Collections.Hashtable | Case-insensitive fallback hashtable for macros. | @{} | #### Outputs @@ -579,7 +579,7 @@ Interpolates the '$address$' and '$port$' tokens in a single pass. Pure macro evaluator with no side effects or global state dependencies. -*Source: [src/IcingaProtocol/Private/Expand-IcingaProtocolMacroValue.ps1](../../src/IcingaProtocol/Private/Expand-IcingaProtocolMacroValue.ps1)* +*Source: [src/IcingaProtocol/Private/Expand-IcingaProtocolMacroValue.ps1](../src/IcingaProtocol/Private/Expand-IcingaProtocolMacroValue.ps1)* --- @@ -608,21 +608,21 @@ UseShellExecute = $false: **`$BinaryPath`** -| Name | Type | Description | Default | -|------------|---------------|-----------------------------------------------------------|---------| -| BinaryPath | System.String | Full canonical path to the approved binary executable. | '' | +| Name | Type | Description | Default | +|------------|---------------|--------------------------------------------------------|---------| +| BinaryPath | System.String | Full canonical path to the approved binary executable. | '' | **`$CommandName`** -| Name | Type | Description | Default | -|-------------|---------------|-----------------------------------------------------------|---------| -| CommandName | System.String | Display file name of the binary for status messages. | '' | +| Name | Type | Description | Default | +|-------------|---------------|------------------------------------------------------|---------| +| CommandName | System.String | Display file name of the binary for status messages. | '' | **`$BinaryArguments`** -| Name | Type | Description | Default | -|-----------------|-----------------|-------------------------------------------------------|---------| -| BinaryArguments | System.String[] | Ordered CLI argument tokens to pass to the process. | @() | +| Name | Type | Description | Default | +|-----------------|-----------------|-----------------------------------------------------|---------| +| BinaryArguments | System.String[] | Ordered CLI argument tokens to pass to the process. | @() | **`$TimeoutMs`** @@ -653,7 +653,7 @@ Executes check_load.exe with a 60s timeout and splits its Nagios output. Always disposes the root Process handle in finally. -*Source: [src/IcingaProtocol/Private/Invoke-IcingaProtocolBinaryProcess.ps1](../../src/IcingaProtocol/Private/Invoke-IcingaProtocolBinaryProcess.ps1)* +*Source: [src/IcingaProtocol/Private/Invoke-IcingaProtocolBinaryProcess.ps1](../src/IcingaProtocol/Private/Invoke-IcingaProtocolBinaryProcess.ps1)* --- @@ -687,9 +687,9 @@ instance ever crosses runspace boundaries. **`$Params`** -| Name | Type | Description | Default | -|--------|---------------|-----------------------------------------------------------------------|---------| -| Params | System.Object | Deserialized params dictionary or object from event::ExecuteCommand. | $null | +| Name | Type | Description | Default | +|--------|---------------|----------------------------------------------------------------------|---------| +| Params | System.Object | Deserialized params dictionary or object from event::ExecuteCommand. | $null | #### Outputs @@ -710,7 +710,7 @@ and rendered command line. Runs inside protocol worker threads; accesses runtime state exclusively via Get-GlobalRuntimeVariable. -*Source: [src/IcingaProtocol/Private/Invoke-IcingaProtocolCheckCommand.ps1](../../src/IcingaProtocol/Private/Invoke-IcingaProtocolCheckCommand.ps1)* +*Source: [src/IcingaProtocol/Private/Invoke-IcingaProtocolCheckCommand.ps1](../src/IcingaProtocol/Private/Invoke-IcingaProtocolCheckCommand.ps1)* --- @@ -734,27 +734,27 @@ in-process via Invoke-ModulePowerShellCommand -UseLastExitCode. **`$ScriptPath`** -| Name | Type | Description | Default | -|------------|---------------|---------------------------------------------------------|---------| -| ScriptPath | System.String | Full canonical path to the approved .ps1 check script. | '' | +| Name | Type | Description | Default | +|------------|---------------|--------------------------------------------------------|---------| +| ScriptPath | System.String | Full canonical path to the approved .ps1 check script. | '' | **`$CommandName`** -| Name | Type | Description | Default | -|-------------|---------------|---------------------------------------------------------|---------| -| CommandName | System.String | Display file name of the script for error messages. | '' | +| Name | Type | Description | Default | +|-------------|---------------|-----------------------------------------------------|---------| +| CommandName | System.String | Display file name of the script for error messages. | '' | **`$BinaryArguments`** -| Name | Type | Description | Default | -|-----------------|-----------------|-----------------------------------------------------|---------| -| BinaryArguments | System.String[] | Ordered CLI tokens produced by macro resolution. | @() | +| Name | Type | Description | Default | +|-----------------|-----------------|--------------------------------------------------|---------| +| BinaryArguments | System.String[] | Ordered CLI tokens produced by macro resolution. | @() | **`$DefaultCommandLine`** -| Name | Type | Description | Default | -|--------------------|---------------|---------------------------------------------------------|---------| -| DefaultCommandLine | System.String | Pre-rendered command line when no secret masking occurs.| '' | +| Name | Type | Description | Default | +|--------------------|---------------|----------------------------------------------------------|---------| +| DefaultCommandLine | System.String | Pre-rendered command line when no secret masking occurs. | '' | #### Outputs @@ -774,7 +774,7 @@ Binds the parameters of check_custom.ps1 and executes it in-process. Delegates execution and deterministic SecureString disposal to Invoke-ModulePowerShellCommand. -*Source: [src/IcingaProtocol/Private/Invoke-IcingaProtocolExternalScript.ps1](../../src/IcingaProtocol/Private/Invoke-IcingaProtocolExternalScript.ps1)* +*Source: [src/IcingaProtocol/Private/Invoke-IcingaProtocolExternalScript.ps1](../src/IcingaProtocol/Private/Invoke-IcingaProtocolExternalScript.ps1)* --- @@ -803,7 +803,7 @@ process initialization and must not be called again while threads are running. #### Outputs -None — Performs initialization and starts background threads. Returns early via +None -- Performs initialization and starts background threads. Returns early via Write-FunctionReturnValue when the certificate file is missing. #### Examples @@ -823,7 +823,7 @@ Global state modified: $Global:IcingaForWindows.Public.IcingaProtocol.Config, Certificate, Connections and WorkerQueue. Config.WorkerCount must be a positive integer before this function is called. -*Source: [src/IcingaProtocol/Private/New-IcingaAgentEnvironment.ps1](../../src/IcingaProtocol/Private/New-IcingaAgentEnvironment.ps1)* +*Source: [src/IcingaProtocol/Private/New-IcingaAgentEnvironment.ps1](../src/IcingaProtocol/Private/New-IcingaAgentEnvironment.ps1)* --- @@ -845,19 +845,19 @@ passed to Send-TCPMessage or Add-IcingaRPCMessageToWriterQueue. **`$Method`** -| Name | Type | Description | Default | -|--------|---------------|-----------------------------------------------------|---------| -| Method | System.String | JSON-RPC method name (for example icinga::Hello). | | +| Name | Type | Description | Default | +|--------|---------------|---------------------------------------------------|---------| +| Method | System.String | JSON-RPC method name (for example icinga::Hello). | | **`$Parameters`** -| Name | Type | Description | Default | -|------------|-------------------------------|------------------------------------------------|---------| -| Parameters | System.Collections.Hashtable | Parameters to include in the RPC params field. | @{} | +| Name | Type | Description | Default | +|------------|------------------------------|------------------------------------------------|---------| +| Parameters | System.Collections.Hashtable | Parameters to include in the RPC params field. | @{} | #### Outputs -System.Collections.Hashtable — Hashtable with keys message (System.Byte[]) and length (System.Int32). +System.Collections.Hashtable -- Hashtable with keys message (System.Byte[]) and length (System.Int32). #### Examples @@ -872,7 +872,7 @@ Returns a length-prefixed encoded message hashtable for the Hello handshake. The method call is logged at Debug level via Write-LoggingEntry before the byte encoding step. -*Source: [src/IcingaProtocol/Private/New-IcingaRPCMessage.ps1](../../src/IcingaProtocol/Private/New-IcingaRPCMessage.ps1)* +*Source: [src/IcingaProtocol/Private/New-IcingaRPCMessage.ps1](../src/IcingaProtocol/Private/New-IcingaRPCMessage.ps1)* --- @@ -892,7 +892,7 @@ Write-FunctionReturnValue with return value IcingaClientConfigNotFound. #### Outputs -PSCustomObject — Parsed JSON connection configuration. +PSCustomObject -- Parsed JSON connection configuration. Returns a Write-FunctionReturnValue result object when the file is missing. #### Examples @@ -906,7 +906,7 @@ PS> $cfg = Read-IcingaProtocolConnection Placeholder substitution uses [System.Net.Dns]::GetHostEntry and GetHostName. The configuration file is read through Read-SecureFile to enforce path approval. -*Source: [src/IcingaProtocol/Private/Read-IcingaProtocolConnections.ps1](../../src/IcingaProtocol/Private/Read-IcingaProtocolConnections.ps1)* +*Source: [src/IcingaProtocol/Private/Read-IcingaProtocolConnections.ps1](../src/IcingaProtocol/Private/Read-IcingaProtocolConnections.ps1)* --- @@ -930,13 +930,13 @@ for a complete frame. **`$Buffer`** -| Name | Type | Description | Default | -|--------|---------------------------|-----------------------------------------------------------------------------|---------| +| Name | Type | Description | Default | +|--------|---------------------------|-------------------------------------------------------------------------------------|---------| | Buffer | System.Text.StringBuilder | Accumulated StringBuilder buffer containing one or more length-prefixed RPC frames. | $null | #### Outputs -None — The buffer is modified in place. +None -- The buffer is modified in place. #### Examples @@ -950,7 +950,7 @@ Each call may process multiple complete frames in a single pass. Partial frames the end of the buffer are preserved for the next read cycle. Complete messages are dispatched via Add-IcingaRPCMessageToWorker. -*Source: [src/IcingaProtocol/Private/Read-IcingaRPCMessage.ps1](../../src/IcingaProtocol/Private/Read-IcingaRPCMessage.ps1)* +*Source: [src/IcingaProtocol/Private/Read-IcingaRPCMessage.ps1](../src/IcingaProtocol/Private/Read-IcingaRPCMessage.ps1)* --- @@ -984,15 +984,15 @@ are expanded to 'Invoke-IcingaCheck*' and resolved as PowerShell check commands. **`$Macros`** -| Name | Type | Description | Default | -|--------|---------------|-----------------------------------------------------------------------|---------| -| Macros | System.Object | Deserialized macros dictionary or object from event::ExecuteCommand. | $null | +| Name | Type | Description | Default | +|--------|---------------|----------------------------------------------------------------------|---------| +| Macros | System.Object | Deserialized macros dictionary or object from event::ExecuteCommand. | $null | **`$CheckCommand`** -| Name | Type | Description | Default | -|--------------|---------------|-------------------------------------------------------------------------------|---------| -| CheckCommand | System.String | Optional Icinga CheckCommand object name (params.command) for error context. | '' | +| Name | Type | Description | Default | +|--------------|---------------|------------------------------------------------------------------------------|---------| +| CheckCommand | System.String | Optional Icinga CheckCommand object name (params.command) for error context. | '' | #### Outputs @@ -1019,7 +1019,7 @@ in Get-ModuleBinaryDirectory. Never searches $env:PATH for binaries or scripts. External executables must reside inside Get-ModuleBinaryDirectory. -*Source: [src/IcingaProtocol/Private/Resolve-IcingaProtocolCommand.ps1](../../src/IcingaProtocol/Private/Resolve-IcingaProtocolCommand.ps1)* +*Source: [src/IcingaProtocol/Private/Resolve-IcingaProtocolCommand.ps1](../src/IcingaProtocol/Private/Resolve-IcingaProtocolCommand.ps1)* --- @@ -1040,13 +1040,13 @@ provided it is included in the RPC parameters for auto-signing. **`$Ticket`** -| Name | Type | Description | Default | -|--------|---------------|--------------------------------------------|---------| -| Ticket | System.String | The ticket to use for auto-signing. | $null | +| Name | Type | Description | Default | +|--------|---------------|-------------------------------------|---------| +| Ticket | System.String | The ticket to use for auto-signing. | $null | #### Outputs -None — Does not return any value. +None -- Does not return any value. #### Examples @@ -1060,7 +1060,7 @@ Sends a certificate request to the connected Icinga endpoint. Requires an active TCP connection to the Icinga endpoint. -*Source: [src/IcingaProtocol/Private/Send-IcingaProtocolCertificateRequest.ps1](../../src/IcingaProtocol/Private/Send-IcingaProtocolCertificateRequest.ps1)* +*Source: [src/IcingaProtocol/Private/Send-IcingaProtocolCertificateRequest.ps1](../src/IcingaProtocol/Private/Send-IcingaProtocolCertificateRequest.ps1)* --- @@ -1082,13 +1082,13 @@ or null. **`$CheckResult`** -| Name | Type | Description | Default | -|-------------|-------------------------------|---------------------------------------------------------|---------| -| CheckResult | System.Collections.Hashtable | Check result fields expected by Icinga (host, service, cr). | @{} | +| Name | Type | Description | Default | +|-------------|------------------------------|-------------------------------------------------------------|---------| +| CheckResult | System.Collections.Hashtable | Check result fields expected by Icinga (host, service, cr). | @{} | #### Outputs -None — Logs errors via Write-LoggingEntry and enqueues the message through the writer queue. +None -- Logs errors via Write-LoggingEntry and enqueues the message through the writer queue. #### Examples @@ -1101,7 +1101,7 @@ PS> Send-IcingaProtocolCheckResult -CheckResult @{ host = 'myhost'; service = 'p Requires New-IcingaRPCMessage and Add-IcingaRPCMessageToWriterQueue to be available. The check result is sent asynchronously via the per-endpoint writer queue. -*Source: [src/IcingaProtocol/Private/Send-IcingaProtocolCheckResult.ps1](../../src/IcingaProtocol/Private/Send-IcingaProtocolCheckResult.ps1)* +*Source: [src/IcingaProtocol/Private/Send-IcingaProtocolCheckResult.ps1](../src/IcingaProtocol/Private/Send-IcingaProtocolCheckResult.ps1)* --- @@ -1121,7 +1121,7 @@ updates the global heartbeat timestamp. #### Outputs -None — Performs side effects: sends a TCP heartbeat message, writes log entries and updates the global heartbeat timestamp. +None -- Performs side effects: sends a TCP heartbeat message, writes log entries and updates the global heartbeat timestamp. #### Examples @@ -1138,7 +1138,7 @@ being present and correctly configured. Requires Write-LoggingEntry, New-IcingaR and Send-TCPMessage. The heartbeat message includes a parameter timeout set to 120 seconds. Time comparisons use Get-Date and TotalSeconds to determine interval expiry. -*Source: [src/IcingaProtocol/Private/Send-IcingaProtocolHeartbeat.ps1](../../src/IcingaProtocol/Private/Send-IcingaProtocolHeartbeat.ps1)* +*Source: [src/IcingaProtocol/Private/Send-IcingaProtocolHeartbeat.ps1](../src/IcingaProtocol/Private/Send-IcingaProtocolHeartbeat.ps1)* --- @@ -1157,7 +1157,7 @@ by the remote endpoint, typically before the writer queue is active. #### Outputs -None — Sends the Hello frame directly via Send-TCPMessage; no pipeline output. +None -- Sends the Hello frame directly via Send-TCPMessage; no pipeline output. #### Examples @@ -1172,7 +1172,7 @@ Sends the Hello message over the current TCP/SSL stream. This function bypasses the writer queue and calls Send-TCPMessage directly, making it suitable for early handshake messages before the queue is initialized. -*Source: [src/IcingaProtocol/Private/Send-IcingaProtocolHello.ps1](../../src/IcingaProtocol/Private/Send-IcingaProtocolHello.ps1)* +*Source: [src/IcingaProtocol/Private/Send-IcingaProtocolHello.ps1](../src/IcingaProtocol/Private/Send-IcingaProtocolHello.ps1)* --- @@ -1191,7 +1191,7 @@ using Get-IcingaUnixTime. #### Outputs -None — Does not return any value. +None -- Does not return any value. #### Examples @@ -1205,7 +1205,7 @@ Sends the log position update to the connected Icinga endpoint. Requires an active TCP connection to the Icinga endpoint. -*Source: [src/IcingaProtocol/Private/Send-IcingaProtocolLogPosition.ps1](../../src/IcingaProtocol/Private/Send-IcingaProtocolLogPosition.ps1)* +*Source: [src/IcingaProtocol/Private/Send-IcingaProtocolLogPosition.ps1](../src/IcingaProtocol/Private/Send-IcingaProtocolLogPosition.ps1)* --- @@ -1229,9 +1229,9 @@ individual elements in the returned PerformanceData array. **`$RawOutput`** -| Name | Type | Description | Default | -|-----------|---------------|-----------------------------------------------------------|---------| -| RawOutput | System.String | Raw stdout captured from an external binary or script. | '' | +| Name | Type | Description | Default | +|-----------|---------------|--------------------------------------------------------|---------| +| RawOutput | System.String | Raw stdout captured from an external binary or script. | '' | #### Outputs @@ -1251,7 +1251,7 @@ individual performance-data metric strings. Pure string parser with no external dependencies or side effects. -*Source: [src/IcingaProtocol/Private/Split-IcingaBinaryPluginOutput.ps1](../../src/IcingaProtocol/Private/Split-IcingaBinaryPluginOutput.ps1)* +*Source: [src/IcingaProtocol/Private/Split-IcingaBinaryPluginOutput.ps1](../src/IcingaProtocol/Private/Split-IcingaBinaryPluginOutput.ps1)* --- @@ -1275,7 +1275,7 @@ scans. Because the function runs indefinitely, it must always be started in a ba #### Outputs -None — Manages connections, global state and log entries; no pipeline output. +None -- Manages connections, global state and log entries; no pipeline output. #### Examples @@ -1294,7 +1294,7 @@ thread. Exceptions during individual connection attempts are logged and do not s overall loop. The loop pauses for 5 seconds between full endpoint scans to avoid tight reconnect cycles. -*Source: [src/IcingaProtocol/Private/Start-IcingaProtocolConnector.ps1](../../src/IcingaProtocol/Private/Start-IcingaProtocolConnector.ps1)* +*Source: [src/IcingaProtocol/Private/Start-IcingaProtocolConnector.ps1](../src/IcingaProtocol/Private/Start-IcingaProtocolConnector.ps1)* --- @@ -1308,25 +1308,25 @@ reconnect cycles. Start-IcingaProtocolHeartbeat validates and registers a provided System.Net.Sockets.TcpClient and System.Net.Security.SslStream for use by the Icinga protocol heartbeat subsystem, then enters a loop that periodically sends heartbeat messages until the TCP connection is lost. The function logs connection loss and other exceptions, closes the TCP connection when the client disconnects, and stops the current Icinga thread. -This function relies on helper functions from the IcingaForWindows module (for example: Set-TCPClientAndStream, Test-TCPConnection, Send-IcingaProtocolHeartbeat, Close-TCPConnection, Stop-Thread, Get-ThreadId and Write-LoggingEntry) to perform its work. It is intended to be used after a successful connection handshake and when you have an active SslStream wrapped around a TcpClient. +This function relies on helper functions from the Icinga for Windows module (for example: Set-TCPClientAndStream, Test-TCPConnection, Send-IcingaProtocolHeartbeat, Close-TCPConnection, Stop-Thread, Get-ThreadId and Write-LoggingEntry) to perform its work. It is intended to be used after a successful connection handshake and when you have an active SslStream wrapped around a TcpClient. #### Parameters **`$TcpClient`** -| Name | Type | Description | Default | -|-----------|------------------------------|---------------------------------------------------------------------------|---------| -| TcpClient | System.Net.Sockets.TcpClient | Connected TCP client representing the remote endpoint. Required. | $null | +| Name | Type | Description | Default | +|-----------|------------------------------|------------------------------------------------------------------|---------| +| TcpClient | System.Net.Sockets.TcpClient | Connected TCP client representing the remote endpoint. Required. | $null | **`$SslStream`** -| Name | Type | Description | Default | -|-----------|---------------------------------|--------------------------------------------------------------------------|---------| -| SslStream | System.Net.Security.SslStream | SSL/TLS stream wrapping the network stream for secure communication. Required. | $null | +| Name | Type | Description | Default | +|-----------|-------------------------------|--------------------------------------------------------------------------------|---------| +| SslStream | System.Net.Security.SslStream | SSL/TLS stream wrapping the network stream for secure communication. Required. | $null | #### Outputs -None — Sends heartbeat messages, writes log entries, closes the connection and stops +None -- Sends heartbeat messages, writes log entries, closes the connection and stops the current thread when the connection terminates. #### Examples @@ -1351,7 +1351,7 @@ true. MethodInvocationException during send is logged at Info level as a connect event. After the loop exits, the TCP connection is closed and the current thread is stopped via Stop-Thread. -*Source: [src/IcingaProtocol/Private/Start-IcingaProtocolHeartbeat.ps1](../../src/IcingaProtocol/Private/Start-IcingaProtocolHeartbeat.ps1)* +*Source: [src/IcingaProtocol/Private/Start-IcingaProtocolHeartbeat.ps1](../src/IcingaProtocol/Private/Start-IcingaProtocolHeartbeat.ps1)* --- @@ -1374,7 +1374,7 @@ hosting process is stopped and must always be started in a background thread. #### Outputs -None — Side-effect driven: opens a network listener, updates global state, writes log entries and spawns threads. +None -- Side-effect driven: opens a network listener, updates global state, writes log entries and spawns threads. #### Examples @@ -1392,7 +1392,7 @@ background thread. Requires Open-TCPSocket, Close-TCPConnection, Test-IcingaProt Add-IcingaProtocolClient, New-Thread, Start-IcingaProtocolSocketReader and Write-LoggingEntry. Exceptions are caught per iteration to keep the listener loop alive. -*Source: [src/IcingaProtocol/Private/Start-IcingaProtocolListener.ps1](../../src/IcingaProtocol/Private/Start-IcingaProtocolListener.ps1)* +*Source: [src/IcingaProtocol/Private/Start-IcingaProtocolListener.ps1](../src/IcingaProtocol/Private/Start-IcingaProtocolListener.ps1)* --- @@ -1410,25 +1410,25 @@ Start-IcingaProtocolSocketReader initializes and manages reading from a provided **`$Client`** -| Name | Type | Description | Default | -|--------|------------------------------|---------------------------------------------------------------------------|---------| +| Name | Type | Description | Default | +|--------|------------------------------|----------------------------------------------------------------------------|---------| | Client | System.Net.Sockets.TcpClient | Established TCP connection to read from. Required; null causes early exit. | $null | **`$Endpoint`** -| Name | Type | Description | Default | -|----------|---------------|---------------------------------------------------------------------------------|---------| -| Endpoint | System.String | Endpoint name used for SSL authentication with the IcingaProtocol certificate. | $null | +| Name | Type | Description | Default | +|----------|---------------|--------------------------------------------------------------------------------|---------| +| Endpoint | System.String | Endpoint name used for SSL authentication with the IcingaProtocol certificate. | $null | **`$IsClient`** -| Name | Type | Description | Default | -|----------|--------------------------------------------------|----------------------------------------------------------------------|---------| -| IsClient | System.Management.Automation.SwitchParameter | When set, the reader sends an initial Hello after TLS handshake. | $false | +| Name | Type | Description | Default | +|----------|----------------------------------------------|------------------------------------------------------------------|---------| +| IsClient | System.Management.Automation.SwitchParameter | When set, the reader sends an initial Hello after TLS handshake. | $false | #### Outputs -None — Enqueues parsed JSON-RPC payloads for worker processing and updates global connection state. +None -- Enqueues parsed JSON-RPC payloads for worker processing and updates global connection state. #### Examples @@ -1451,7 +1451,7 @@ Uses a 4096-byte read buffer per iteration. Partial frames are accumulated and p to Read-IcingaRPCMessage on subsequent reads. Heartbeat and writer threads are started via New-Thread before the read loop begins. -*Source: [src/IcingaProtocol/Private/Start-IcingaProtocolSocketReader.ps1](../../src/IcingaProtocol/Private/Start-IcingaProtocolSocketReader.ps1)* +*Source: [src/IcingaProtocol/Private/Start-IcingaProtocolSocketReader.ps1](../src/IcingaProtocol/Private/Start-IcingaProtocolSocketReader.ps1)* --- @@ -1478,19 +1478,19 @@ by Start-IcingaProtocolSocketReader. **`$TcpClient`** -| Name | Type | Description | Default | -|-----------|------------------------------|--------------------------------------------------------------------------|---------| -| TcpClient | System.Net.Sockets.TcpClient | Connected TCP client whose remote endpoint identifies the writer queue. | $null | +| Name | Type | Description | Default | +|-----------|------------------------------|-------------------------------------------------------------------------|---------| +| TcpClient | System.Net.Sockets.TcpClient | Connected TCP client whose remote endpoint identifies the writer queue. | $null | **`$SslStream`** -| Name | Type | Description | Default | -|-----------|-------------------------------|-------------------------------------------------------------------------|---------| -| SslStream | System.Net.Security.SslStream | Authenticated SSL stream used by Send-TCPMessage to write bytes. | $null | +| Name | Type | Description | Default | +|-----------|-------------------------------|------------------------------------------------------------------|---------| +| SslStream | System.Net.Security.SslStream | Authenticated SSL stream used by Send-TCPMessage to write bytes. | $null | #### Outputs -None — Dequeues and sends messages; no pipeline output. +None -- Dequeues and sends messages; no pipeline output. #### Examples @@ -1506,7 +1506,7 @@ The writer queue entry for the endpoint is created inside this function using a ConcurrentQueue-backed BlockingCollection. The WaitForJobs flag on New-Thread ensures the queue slot exists before the first message is enqueued by other threads. -*Source: [src/IcingaProtocol/Private/Start-IcingaProtocolSocketWriter.ps1](../../src/IcingaProtocol/Private/Start-IcingaProtocolSocketWriter.ps1)* +*Source: [src/IcingaProtocol/Private/Start-IcingaProtocolSocketWriter.ps1](../src/IcingaProtocol/Private/Start-IcingaProtocolSocketWriter.ps1)* --- @@ -1553,7 +1553,7 @@ New-IcingaAgentEnvironment. Accesses shared state via Get-GlobalRuntimeVariable and nulls all per-iteration reference variables in finally to prevent daemon memory retention. -*Source: [src/IcingaProtocol/Private/Start-IcingaProtocolWorker.ps1](../../src/IcingaProtocol/Private/Start-IcingaProtocolWorker.ps1)* +*Source: [src/IcingaProtocol/Private/Start-IcingaProtocolWorker.ps1](../src/IcingaProtocol/Private/Start-IcingaProtocolWorker.ps1)* --- @@ -1581,9 +1581,9 @@ consuming host resources: **`$Process`** -| Name | Type | Description | Default | -|---------|----------------------------|-----------------------------------------------------|---------| -| Process | System.Diagnostics.Process | Live root Process object whose handle stays open. | $null | +| Name | Type | Description | Default | +|---------|----------------------------|---------------------------------------------------|---------| +| Process | System.Diagnostics.Process | Live root Process object whose handle stays open. | $null | **`$RootProcessId`** @@ -1608,7 +1608,7 @@ Kills the root process and all descendant processes spawned by it. Caller remains responsible for disposing the root Process instance after stream drain completes. -*Source: [src/IcingaProtocol/Private/Stop-IcingaProtocolProcessTree.ps1](../../src/IcingaProtocol/Private/Stop-IcingaProtocolProcessTree.ps1)* +*Source: [src/IcingaProtocol/Private/Stop-IcingaProtocolProcessTree.ps1](../src/IcingaProtocol/Private/Stop-IcingaProtocolProcessTree.ps1)* --- @@ -1620,19 +1620,19 @@ drain completes. #### Description -Test-IcingaProtocolClientStatus examines the global IcingaForWindows protocol connection table to determine whether a TCP client for the provided Address is present and connected. If Address is null or empty, the function returns an invalid-address result. If a connection entry exists, the function checks the client object and its Connected property and returns a corresponding status. If no entry exists, the function attempts to add a new entry to the global connection table using the $TcpClient variable from the current scope and returns a created status. +Test-IcingaProtocolClientStatus examines the global Icinga for Windows protocol connection table to determine whether a TCP client for the provided Address is present and connected. If Address is null or empty, the function returns an invalid-address result. If a connection entry exists, the function checks the client object and its Connected property and returns a corresponding status. If no entry exists, the function attempts to add a new entry to the global connection table using the $TcpClient variable from the current scope and returns a created status. #### Parameters **`$Address`** -| Name | Type | Description | Default | -|---------|---------------|------------------------------------------------------------------------------------------|---------| -| Address | System.String | IP address string used to look up the client in the global connections table. | $null | +| Name | Type | Description | Default | +|---------|---------------|-------------------------------------------------------------------------------|---------| +| Address | System.String | IP address string used to look up the client in the global connections table. | $null | #### Outputs -PSCustomObject — Standardized result object from Write-FunctionReturnValue. +PSCustomObject -- Standardized result object from Write-FunctionReturnValue. Possible tokens: IcingaAddressInvalid, IcingaClientReplaced, IcingaClientConnected, IcingaClientCreated. #### Examples @@ -1656,5 +1656,5 @@ Returns IcingaAddressInvalid when no Address is provided. - Precondition: $Global:IcingaForWindows.Public.IcingaProtocol.Connections must be an initialized hashtable or dictionary-like object that supports ContainsKey(), indexing, and Add(). - The function relies on client objects exposing a Connected property to determine connectivity. -*Source: [src/IcingaProtocol/Private/Test-IcingaProtocolClientStatus.ps1](../../src/IcingaProtocol/Private/Test-IcingaProtocolClientStatus.ps1)* +*Source: [src/IcingaProtocol/Private/Test-IcingaProtocolClientStatus.ps1](../src/IcingaProtocol/Private/Test-IcingaProtocolClientStatus.ps1)* diff --git a/docs/Icinga.PerformanceCounter.md b/docs/Icinga.PerformanceCounter.md index 1add266..6a52183 100644 --- a/docs/Icinga.PerformanceCounter.md +++ b/docs/Icinga.PerformanceCounter.md @@ -108,7 +108,7 @@ A counter without an instance is keyed category-first. The request/response transport lives under `(Get-GlobalRuntimeVariable).Public.PerformanceCounter`. Timeouts are logged through `Write-LoggingEntry` at Warning level. No external services are used. -*Source: [src/PerformanceCounter/Public/Get-IcingaPerformanceCounter.ps1](../../src/PerformanceCounter/Public/Get-IcingaPerformanceCounter.ps1)* +*Source: [src/PerformanceCounter/Public/Get-IcingaPerformanceCounter.ps1](../src/PerformanceCounter/Public/Get-IcingaPerformanceCounter.ps1)* --- @@ -181,7 +181,7 @@ Lists the concrete per-instance paths that currently exist for the wildcard coun Uses `System.Diagnostics.PerformanceCounterCategory` directly. No global state is read or written, and no external services are used. -*Source: [src/PerformanceCounter/Public/Show-IcingaPerformanceCounter.ps1](../../src/PerformanceCounter/Public/Show-IcingaPerformanceCounter.ps1)* +*Source: [src/PerformanceCounter/Public/Show-IcingaPerformanceCounter.ps1](../src/PerformanceCounter/Public/Show-IcingaPerformanceCounter.ps1)* --- @@ -238,7 +238,7 @@ Shows the live value for a single specified counter. This is a thin convenience layer over `Get-IcingaPerformanceCounter`; the same daemon/inline behavior and return shape apply. No external services are used. -*Source: [src/PerformanceCounter/Public/Show-IcingaPerformanceCounterDetails.ps1](../../src/PerformanceCounter/Public/Show-IcingaPerformanceCounterDetails.ps1)* +*Source: [src/PerformanceCounter/Public/Show-IcingaPerformanceCounterDetails.ps1](../src/PerformanceCounter/Public/Show-IcingaPerformanceCounterDetails.ps1)* --- @@ -288,7 +288,7 @@ Extracts the category name from the counter path and returns $true when the cate Delegates to `IcingaPerformanceCounter::CategoryExists`. Never throws and reads no global state. -*Source: [src/PerformanceCounter/Public/Test-IcingaPerformanceCounterCategory.ps1](../../src/PerformanceCounter/Public/Test-IcingaPerformanceCounterCategory.ps1)* +*Source: [src/PerformanceCounter/Public/Test-IcingaPerformanceCounterCategory.ps1](../src/PerformanceCounter/Public/Test-IcingaPerformanceCounterCategory.ps1)* --- @@ -344,7 +344,7 @@ PS> ConvertTo-IcingaPerformanceCounterInstanceStructure -Result $raw -Counter '\ Called by `Get-IcingaPerformanceCounter` when `-StructureByInstance` is set. Pure transform; touches no global state and reads no counters. -*Source: [src/PerformanceCounter/Private/ConvertTo-IcingaPerformanceCounterInstanceStructure.ps1](../../src/PerformanceCounter/Private/ConvertTo-IcingaPerformanceCounterInstanceStructure.ps1)* +*Source: [src/PerformanceCounter/Private/ConvertTo-IcingaPerformanceCounterInstanceStructure.ps1](../src/PerformanceCounter/Private/ConvertTo-IcingaPerformanceCounterInstanceStructure.ps1)* --- @@ -386,7 +386,7 @@ PS> Get-IcingaPerformanceCounterLiteral -Argument $argumentAst Called by `Register-IcingaPerformanceCounterFromComponents`. Returns an empty array when the argument is null or contains no string literals. -*Source: [src/PerformanceCounter/Private/Get-IcingaPerformanceCounterLiteral.ps1](../../src/PerformanceCounter/Private/Get-IcingaPerformanceCounterLiteral.ps1)* +*Source: [src/PerformanceCounter/Private/Get-IcingaPerformanceCounterLiteral.ps1](../src/PerformanceCounter/Private/Get-IcingaPerformanceCounterLiteral.ps1)* --- @@ -434,7 +434,7 @@ Returns the processor load of core 0, or the error text if that counter could no Pure helper; reads no global state and touches no counters. Intended for use by plugins after they have selected a single counter from a `Get-IcingaPerformanceCounter` result. -*Source: [src/PerformanceCounter/Private/Get-IcingaPerformanceCounterValue.ps1](../../src/PerformanceCounter/Private/Get-IcingaPerformanceCounterValue.ps1)* +*Source: [src/PerformanceCounter/Private/Get-IcingaPerformanceCounterValue.ps1](../src/PerformanceCounter/Private/Get-IcingaPerformanceCounterValue.ps1)* --- @@ -482,7 +482,7 @@ Declares two counters so the daemon keeps them warm and the discovery step can f The counters are stored under `(Get-GlobalRuntimeVariable).Public.PerformanceCounter.Registered`. This function does not return counter values -- use `Get-IcingaPerformanceCounter` to read them. -*Source: [src/PerformanceCounter/Private/New-IcingaPerformanceCounter.ps1](../../src/PerformanceCounter/Private/New-IcingaPerformanceCounter.ps1)* +*Source: [src/PerformanceCounter/Private/New-IcingaPerformanceCounter.ps1](../src/PerformanceCounter/Private/New-IcingaPerformanceCounter.ps1)* --- @@ -519,7 +519,7 @@ PS> New-IcingaPerformanceCounterEnvironment All shared state is read through `Get-GlobalRuntimeVariable`. The manager is stored on the `Manager` slot of the global store and is only ever touched by the daemon thread. -*Source: [src/PerformanceCounter/Private/New-IcingaPerformanceCounterEnvironment.ps1](../../src/PerformanceCounter/Private/New-IcingaPerformanceCounterEnvironment.ps1)* +*Source: [src/PerformanceCounter/Private/New-IcingaPerformanceCounterEnvironment.ps1](../src/PerformanceCounter/Private/New-IcingaPerformanceCounterEnvironment.ps1)* --- @@ -553,7 +553,7 @@ PS> Read-IcingaPerformanceCounterCache PowerShell 7 (the `-AsHashtable` switch is deliberately not used because it is PowerShell 6+ only). Entries are read through the object's properties for cross-version compatibility. -*Source: [src/PerformanceCounter/Private/Read-IcingaPerformanceCounterCache.ps1](../../src/PerformanceCounter/Private/Read-IcingaPerformanceCounterCache.ps1)* +*Source: [src/PerformanceCounter/Private/Read-IcingaPerformanceCounterCache.ps1](../src/PerformanceCounter/Private/Read-IcingaPerformanceCounterCache.ps1)* --- @@ -586,7 +586,7 @@ PS> Register-IcingaDefaultPerformanceCounter The literal counter list here is what the discovery step reads from the compiled kernel. The set is intentionally minimal and generic; it is an example, not a fixed contract. -*Source: [src/PerformanceCounter/Private/Register-IcingaDefaultPerformanceCounter.ps1](../../src/PerformanceCounter/Private/Register-IcingaDefaultPerformanceCounter.ps1)* +*Source: [src/PerformanceCounter/Private/Register-IcingaDefaultPerformanceCounter.ps1](../src/PerformanceCounter/Private/Register-IcingaDefaultPerformanceCounter.ps1)* --- @@ -622,7 +622,7 @@ PS> Register-IcingaPerformanceCounterFromComponents Only literal array/string arguments are discoverable. The kernel file is produced by `Build-ModuleProject`; if it is missing the discovery step is skipped. -*Source: [src/PerformanceCounter/Private/Register-IcingaPerformanceCounterFromComponents.ps1](../../src/PerformanceCounter/Private/Register-IcingaPerformanceCounterFromComponents.ps1)* +*Source: [src/PerformanceCounter/Private/Register-IcingaPerformanceCounterFromComponents.ps1](../src/PerformanceCounter/Private/Register-IcingaPerformanceCounterFromComponents.ps1)* --- @@ -662,7 +662,7 @@ Must run inside a dedicated background runspace created by `New-Thread`. All sha accessed through `Get-GlobalRuntimeVariable` because the runspace receives only a snapshot of the runtime at startup. The daemon exits cleanly when `Test-ThreadRunning` returns $false. -*Source: [src/PerformanceCounter/Private/Start-IcingaPerformanceCounterDaemon.ps1](../../src/PerformanceCounter/Private/Start-IcingaPerformanceCounterDaemon.ps1)* +*Source: [src/PerformanceCounter/Private/Start-IcingaPerformanceCounterDaemon.ps1](../src/PerformanceCounter/Private/Start-IcingaPerformanceCounterDaemon.ps1)* --- @@ -695,7 +695,7 @@ PS> if (Test-IcingaPerformanceCounterDaemon) { 'daemon is serving requests' } The heartbeat lives at `(Get-GlobalRuntimeVariable).Public.PerformanceCounter.Heartbeat`. A heartbeat older than five seconds is treated as not alive. -*Source: [src/PerformanceCounter/Private/Test-IcingaPerformanceCounterDaemon.ps1](../../src/PerformanceCounter/Private/Test-IcingaPerformanceCounterDaemon.ps1)* +*Source: [src/PerformanceCounter/Private/Test-IcingaPerformanceCounterDaemon.ps1](../src/PerformanceCounter/Private/Test-IcingaPerformanceCounterDaemon.ps1)* --- @@ -742,7 +742,7 @@ Reads configuration (`RefreshIntervalMs`, `EvictionMinutes`) from the store's Co Heartbeat is always refreshed so liveness detection stays responsive even under load. The daemon passes its cached store reference to avoid re-resolving it through Get-GlobalRuntimeVariable each cycle. -*Source: [src/PerformanceCounter/Private/Update-IcingaPerformanceCounterState.ps1](../../src/PerformanceCounter/Private/Update-IcingaPerformanceCounterState.ps1)* +*Source: [src/PerformanceCounter/Private/Update-IcingaPerformanceCounterState.ps1](../src/PerformanceCounter/Private/Update-IcingaPerformanceCounterState.ps1)* --- @@ -777,5 +777,5 @@ The cache file is `PerformanceCounter.json` under `Get-ModuleCacheDirectory`. Ti are stored in ISO 8601 round-trip format so they parse identically on Windows PowerShell 5.1 and PowerShell 7. -*Source: [src/PerformanceCounter/Private/Write-IcingaPerformanceCounterCache.ps1](../../src/PerformanceCounter/Private/Write-IcingaPerformanceCounterCache.ps1)* +*Source: [src/PerformanceCounter/Private/Write-IcingaPerformanceCounterCache.ps1](../src/PerformanceCounter/Private/Write-IcingaPerformanceCounterCache.ps1)* diff --git a/docs/Icinga.Plugins.Checks.md b/docs/Icinga.Plugins.Checks.md index d3e62d7..1847b8d 100644 --- a/docs/Icinga.Plugins.Checks.md +++ b/docs/Icinga.Plugins.Checks.md @@ -65,15 +65,15 @@ This plugin is Windows-only because it relies on the Windows performance counter **`$Warning`** -| Name | Type | Description | Default | -|---------|---------------|--------------------------------------------------------------------|---------| -| Warning | System.String | Warning threshold in percent, using the Icinga threshold grammar. | | +| Name | Type | Description | Default | +|---------|---------------|-------------------------------------------------------------------|---------| +| Warning | System.String | Warning threshold in percent, using the Icinga threshold grammar. | | **`$Critical`** -| Name | Type | Description | Default | -|----------|---------------|---------------------------------------------------------------------|---------| -| Critical | System.String | Critical threshold in percent, using the Icinga threshold grammar. | | +| Name | Type | Description | Default | +|----------|---------------|--------------------------------------------------------------------|---------| +| Critical | System.String | Critical threshold in percent, using the Icinga threshold grammar. | | **`$Core`** @@ -83,9 +83,9 @@ This plugin is Windows-only because it relies on the Windows performance counter **`$NodeFilter`** -| Name | Type | Description | Default | -|------------|--------------|---------------------------------------------------------------------------|---------| -| NodeFilter | System.Array | NUMA node IDs to include (wildcards allowed; aliased to SocketFilter). | @() | +| Name | Type | Description | Default | +|------------|--------------|------------------------------------------------------------------------|---------| +| NodeFilter | System.Array | NUMA node IDs to include (wildcards allowed; aliased to SocketFilter). | @() | **`$OverallOnly`** @@ -95,9 +95,9 @@ This plugin is Windows-only because it relies on the Windows performance counter **`$Verbosity`** -| Name | Type | Description | Default | -|-----------|--------------|------------------------------------------------------------------------------------|---------| -| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config.| 0 | +| Name | Type | Description | Default | +|-----------|--------------|-------------------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | **`$NoPerfData`** @@ -139,7 +139,7 @@ numbered across all nodes, '_total::ifw_cpu::load' and 'totalload::ifw_cpu::load'. The integer exit code is the return value; an Icinga command wrapper is expected to exit with it. -*Source: [src/Plugins/Checks/Public/Invoke-IcingaCheckCPU.ps1](../../src/Plugins/Checks/Public/Invoke-IcingaCheckCPU.ps1)* +*Source: [src/Plugins/Checks/Public/Invoke-IcingaCheckCPU.ps1](../src/Plugins/Checks/Public/Invoke-IcingaCheckCPU.ps1)* --- @@ -336,9 +336,9 @@ reported as UNKNOWN with its reason. **`$Verbosity`** -| Name | Type | Description | Default | -|-----------|--------------|------------------------------------------------------------------------------------|---------| -| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config.| 0 | +| Name | Type | Description | Default | +|-----------|--------------|-------------------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | **`$NoPerfData`** @@ -376,7 +376,7 @@ Windows-only. Reads the file system through Get-IcingaDirectoryInformation; the user needs list permission on every checked directory. The integer exit code is the return value; an Icinga command wrapper is expected to exit with it. -*Source: [src/Plugins/Checks/Public/Invoke-IcingaCheckDirectory.ps1](../../src/Plugins/Checks/Public/Invoke-IcingaCheckDirectory.ps1)* +*Source: [src/Plugins/Checks/Public/Invoke-IcingaCheckDirectory.ps1](../src/Plugins/Checks/Public/Invoke-IcingaCheckDirectory.ps1)* --- @@ -415,15 +415,15 @@ as UNKNOWN with its reason. **`$Warning`** -| Name | Type | Description | Default | -|---------|---------------|---------------------------------------------------------------------|---------| -| Warning | System.String | Warning threshold for the used memory, e.g. '80%' or '12GiB'. | | +| Name | Type | Description | Default | +|---------|---------------|---------------------------------------------------------------|---------| +| Warning | System.String | Warning threshold for the used memory, e.g. '80%' or '12GiB'. | | **`$Critical`** -| Name | Type | Description | Default | -|----------|---------------|---------------------------------------------------------------------|---------| -| Critical | System.String | Critical threshold for the used memory, e.g. '90%' or '14GiB'. | | +| Name | Type | Description | Default | +|----------|---------------|----------------------------------------------------------------|---------| +| Critical | System.String | Critical threshold for the used memory, e.g. '90%' or '14GiB'. | | **`$PageFileWarning`** @@ -439,33 +439,33 @@ as UNKNOWN with its reason. **`$MemoryPagesSecWarning`** -| Name | Type | Description | Default | -|-----------------------|---------------|-----------------------------------------------|---------| -| MemoryPagesSecWarning | System.String | Warning threshold for the memory pages/sec. | | +| Name | Type | Description | Default | +|-----------------------|---------------|---------------------------------------------|---------| +| MemoryPagesSecWarning | System.String | Warning threshold for the memory pages/sec. | | **`$MemoryPagesSecCritical`** -| Name | Type | Description | Default | -|------------------------|---------------|-----------------------------------------------|---------| -| MemoryPagesSecCritical | System.String | Critical threshold for the memory pages/sec. | | +| Name | Type | Description | Default | +|------------------------|---------------|----------------------------------------------|---------| +| MemoryPagesSecCritical | System.String | Critical threshold for the memory pages/sec. | | **`$IncludePageFile`** -| Name | Type | Description | Default | -|-----------------|--------------|----------------------------------------------------------|---------| -| IncludePageFile | System.Array | Only check page files matching these names (wildcards). | @() | +| Name | Type | Description | Default | +|-----------------|--------------|---------------------------------------------------------|---------| +| IncludePageFile | System.Array | Only check page files matching these names (wildcards). | @() | **`$ExcludePageFile`** -| Name | Type | Description | Default | -|-----------------|--------------|------------------------------------------------------|---------| -| ExcludePageFile | System.Array | Skip page files matching these names (wildcards). | @() | +| Name | Type | Description | Default | +|-----------------|--------------|---------------------------------------------------|---------| +| ExcludePageFile | System.Array | Skip page files matching these names (wildcards). | @() | **`$Verbosity`** -| Name | Type | Description | Default | -|-----------|--------------|------------------------------------------------------------------------------------|---------| -| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config.| 0 | +| Name | Type | Description | Default | +|-----------|--------------|-------------------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | **`$NoPerfData`** @@ -498,7 +498,7 @@ performance counters ('Performance Monitor Users') and the Win32_ComputerSystem, Win32_PageFileUsage and Win32_PageFileSetting CIM classes. The integer exit code is the return value; an Icinga command wrapper is expected to exit with it. -*Source: [src/Plugins/Checks/Public/Invoke-IcingaCheckMemory.ps1](../../src/Plugins/Checks/Public/Invoke-IcingaCheckMemory.ps1)* +*Source: [src/Plugins/Checks/Public/Invoke-IcingaCheckMemory.ps1](../src/Plugins/Checks/Public/Invoke-IcingaCheckMemory.ps1)* --- @@ -584,9 +584,9 @@ Windows-only because it relies on the Win32_Volume CIM class. **`$Verbosity`** -| Name | Type | Description | Default | -|-----------|--------------|------------------------------------------------------------------------------------|---------| -| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config.| 0 | +| Name | Type | Description | Default | +|-----------|--------------|-------------------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | **`$NoPerfData`** @@ -624,7 +624,7 @@ Windows-only. Reads Win32_Volume and MSFT_Partition through Get-IcingaDiskInformation. The integer exit code is the return value; an Icinga command wrapper is expected to exit with it. -*Source: [src/Plugins/Checks/Public/Invoke-IcingaCheckPartitionSpace.ps1](../../src/Plugins/Checks/Public/Invoke-IcingaCheckPartitionSpace.ps1)* +*Source: [src/Plugins/Checks/Public/Invoke-IcingaCheckPartitionSpace.ps1](../src/Plugins/Checks/Public/Invoke-IcingaCheckPartitionSpace.ps1)* --- @@ -672,9 +672,9 @@ with '%' spelled out as 'percent', for example **`$PerfCounter`** -| Name | Type | Description | Default | -|-------------|--------------|---------------------------------------------------------------|---------| -| PerfCounter | System.Array | Counter paths to check, e.g. '\Processor(*)\% Processor Time'.| @() | +| Name | Type | Description | Default | +|-------------|--------------|----------------------------------------------------------------|---------| +| PerfCounter | System.Array | Counter paths to check, e.g. '\Processor(*)\% Processor Time'. | @() | **`$Warning`** @@ -708,9 +708,9 @@ with '%' spelled out as 'percent', for example **`$Verbosity`** -| Name | Type | Description | Default | -|-----------|--------------|------------------------------------------------------------------------------------|---------| -| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config.| 0 | +| Name | Type | Description | Default | +|-----------|--------------|-------------------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | **`$NoPerfData`** @@ -742,7 +742,7 @@ Windows-only. Reads the Windows performance counters; the user needs read access to them ('Performance Monitor Users'). The integer exit code is the return value; an Icinga command wrapper is expected to exit with it. -*Source: [src/Plugins/Checks/Public/Invoke-IcingaCheckPerfCounter.ps1](../../src/Plugins/Checks/Public/Invoke-IcingaCheckPerfCounter.ps1)* +*Source: [src/Plugins/Checks/Public/Invoke-IcingaCheckPerfCounter.ps1](../src/Plugins/Checks/Public/Invoke-IcingaCheckPerfCounter.ps1)* --- @@ -783,51 +783,51 @@ Performance data is written for the summary only, with the labels **`$PageFileWarning`** -| Name | Type | Description | Default | -|-----------------|---------------|-----------------------------------------------------------------|---------| -| PageFileWarning | System.String | Warning threshold for the page file usage of each process. | | +| Name | Type | Description | Default | +|-----------------|---------------|------------------------------------------------------------|---------| +| PageFileWarning | System.String | Warning threshold for the page file usage of each process. | | **`$PageFileCritical`** -| Name | Type | Description | Default | -|------------------|---------------|-----------------------------------------------------------------|---------| -| PageFileCritical | System.String | Critical threshold for the page file usage of each process. | | +| Name | Type | Description | Default | +|------------------|---------------|-------------------------------------------------------------|---------| +| PageFileCritical | System.String | Critical threshold for the page file usage of each process. | | **`$MemoryWarning`** -| Name | Type | Description | Default | -|---------------|---------------|-------------------------------------------------------------|---------| -| MemoryWarning | System.String | Warning threshold for the memory usage of each process. | | +| Name | Type | Description | Default | +|---------------|---------------|---------------------------------------------------------|---------| +| MemoryWarning | System.String | Warning threshold for the memory usage of each process. | | **`$MemoryCritical`** -| Name | Type | Description | Default | -|----------------|---------------|-------------------------------------------------------------|---------| -| MemoryCritical | System.String | Critical threshold for the memory usage of each process. | | +| Name | Type | Description | Default | +|----------------|---------------|----------------------------------------------------------|---------| +| MemoryCritical | System.String | Critical threshold for the memory usage of each process. | | **`$CPUWarning`** -| Name | Type | Description | Default | -|------------|---------------|----------------------------------------------------------|---------| -| CPUWarning | System.String | Warning threshold for the CPU usage of each process. | | +| Name | Type | Description | Default | +|------------|---------------|------------------------------------------------------|---------| +| CPUWarning | System.String | Warning threshold for the CPU usage of each process. | | **`$CPUCritical`** -| Name | Type | Description | Default | -|-------------|---------------|----------------------------------------------------------|---------| -| CPUCritical | System.String | Critical threshold for the CPU usage of each process. | | +| Name | Type | Description | Default | +|-------------|---------------|-------------------------------------------------------|---------| +| CPUCritical | System.String | Critical threshold for the CPU usage of each process. | | **`$ThreadCountWarning`** -| Name | Type | Description | Default | -|--------------------|---------------|------------------------------------------------------------|---------| -| ThreadCountWarning | System.String | Warning threshold for the thread count of each process. | | +| Name | Type | Description | Default | +|--------------------|---------------|---------------------------------------------------------|---------| +| ThreadCountWarning | System.String | Warning threshold for the thread count of each process. | | **`$ThreadCountCritical`** -| Name | Type | Description | Default | -|---------------------|---------------|------------------------------------------------------------|---------| -| ThreadCountCritical | System.String | Critical threshold for the thread count of each process. | | +| Name | Type | Description | Default | +|---------------------|---------------|----------------------------------------------------------|---------| +| ThreadCountCritical | System.String | Critical threshold for the thread count of each process. | | **`$TotalPageFileWarning`** @@ -867,15 +867,15 @@ Performance data is written for the summary only, with the labels **`$TotalThreadCountWarning`** -| Name | Type | Description | Default | -|-------------------------|---------------|-------------------------------------------------------------------|---------| -| TotalThreadCountWarning | System.String | Warning threshold for the thread count of all processes of a name.| | +| Name | Type | Description | Default | +|-------------------------|---------------|--------------------------------------------------------------------|---------| +| TotalThreadCountWarning | System.String | Warning threshold for the thread count of all processes of a name. | | **`$TotalThreadCountCritical`** -| Name | Type | Description | Default | -|--------------------------|---------------|--------------------------------------------------------------------|---------| -| TotalThreadCountCritical | System.String | Critical threshold for the thread count of all processes of a name.| | +| Name | Type | Description | Default | +|--------------------------|---------------|---------------------------------------------------------------------|---------| +| TotalThreadCountCritical | System.String | Critical threshold for the thread count of all processes of a name. | | **`$TotalProcessCountWarning`** @@ -903,15 +903,15 @@ Performance data is written for the summary only, with the labels **`$OverrideNotFound`** -| Name | Type | Description | Default | -|------------------|---------------|-------------------------------------------------------------------------------|---------| -| OverrideNotFound | System.String | State for a Process entry without a match: Ok, Warning, Critical or Unknown. | Unknown | +| Name | Type | Description | Default | +|------------------|---------------|------------------------------------------------------------------------------|---------| +| OverrideNotFound | System.String | State for a Process entry without a match: Ok, Warning, Critical or Unknown. | Unknown | **`$Verbosity`** -| Name | Type | Description | Default | -|-----------|--------------|------------------------------------------------------------------------------------|---------| -| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config.| 0 | +| Name | Type | Description | Default | +|-----------|--------------|-------------------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | **`$NoPerfData`** @@ -945,7 +945,7 @@ Users'), '\Memory\Commit Limit' and the Win32_ComputerSystem CIM class through Get-IcingaProcessInformation. The integer exit code is the return value; an Icinga command wrapper is expected to exit with it. -*Source: [src/Plugins/Checks/Public/Invoke-IcingaCheckProcess.ps1](../../src/Plugins/Checks/Public/Invoke-IcingaCheckProcess.ps1)* +*Source: [src/Plugins/Checks/Public/Invoke-IcingaCheckProcess.ps1](../src/Plugins/Checks/Public/Invoke-IcingaCheckProcess.ps1)* --- @@ -988,27 +988,27 @@ Performance data uses the labels '::ifw_scheduledtask::state', **`$TaskName`** -| Name | Type | Description | Default | -|----------|--------------|-------------------------------------------------------------------------------|---------| -| TaskName | System.Array | Task names to check (wildcards allowed; plain names must exist). | @() | +| Name | Type | Description | Default | +|----------|--------------|------------------------------------------------------------------|---------| +| TaskName | System.Array | Task names to check (wildcards allowed; plain names must exist). | @() | **`$ExcludeTaskName`** -| Name | Type | Description | Default | -|-----------------|--------------|------------------------------------------------------------------------|---------| -| ExcludeTaskName | System.Array | Task names to exclude from the check (wildcards allowed). | @() | +| Name | Type | Description | Default | +|-----------------|--------------|-----------------------------------------------------------|---------| +| ExcludeTaskName | System.Array | Task names to exclude from the check (wildcards allowed). | @() | **`$TaskPath`** -| Name | Type | Description | Default | -|----------|--------------|-------------------------------------------------------------------------------|---------| -| TaskPath | System.Array | Task folder paths to include (wildcards allowed, e.g. '\Icinga\*'). | @() | +| Name | Type | Description | Default | +|----------|--------------|---------------------------------------------------------------------|---------| +| TaskPath | System.Array | Task folder paths to include (wildcards allowed, e.g. '\Icinga\*'). | @() | **`$ExcludeTaskPath`** -| Name | Type | Description | Default | -|-----------------|--------------|------------------------------------------------------------------------|---------| -| ExcludeTaskPath | System.Array | Task folder paths to exclude (wildcards allowed). | @() | +| Name | Type | Description | Default | +|-----------------|--------------|---------------------------------------------------|---------| +| ExcludeTaskPath | System.Array | Task folder paths to exclude (wildcards allowed). | @() | **`$State`** @@ -1024,57 +1024,57 @@ Performance data uses the labels '::ifw_scheduledtask::state', **`$WarningMissedRuns`** -| Name | Type | Description | Default | -|-------------------|---------------|---------------------------------------------------------------------|---------| -| WarningMissedRuns | System.String | Warning threshold for the number of missed runs. | | +| Name | Type | Description | Default | +|-------------------|---------------|--------------------------------------------------|---------| +| WarningMissedRuns | System.String | Warning threshold for the number of missed runs. | | **`$CriticalMissedRuns`** -| Name | Type | Description | Default | -|--------------------|---------------|--------------------------------------------------------------------|---------| -| CriticalMissedRuns | System.String | Critical threshold for the number of missed runs. | | +| Name | Type | Description | Default | +|--------------------|---------------|---------------------------------------------------|---------| +| CriticalMissedRuns | System.String | Critical threshold for the number of missed runs. | | **`$WarningLastRunTime`** -| Name | Type | Description | Default | -|--------------------|---------------|--------------------------------------------------------------------|---------| -| WarningLastRunTime | System.String | Warning threshold for the age of the last run (e.g. '1d', '12h'). | | +| Name | Type | Description | Default | +|--------------------|---------------|-------------------------------------------------------------------|---------| +| WarningLastRunTime | System.String | Warning threshold for the age of the last run (e.g. '1d', '12h'). | | **`$CriticalLastRunTime`** -| Name | Type | Description | Default | -|---------------------|---------------|-------------------------------------------------------------------|---------| -| CriticalLastRunTime | System.String | Critical threshold for the age of the last run (e.g. '2d', '24h').| | +| Name | Type | Description | Default | +|---------------------|---------------|--------------------------------------------------------------------|---------| +| CriticalLastRunTime | System.String | Critical threshold for the age of the last run (e.g. '2d', '24h'). | | **`$WarningNextRunTime`** -| Name | Type | Description | Default | -|--------------------|---------------|--------------------------------------------------------------------|---------| -| WarningNextRunTime | System.String | Warning threshold for the next run offset (e.g. '10m', '-1h:'). | | +| Name | Type | Description | Default | +|--------------------|---------------|-----------------------------------------------------------------|---------| +| WarningNextRunTime | System.String | Warning threshold for the next run offset (e.g. '10m', '-1h:'). | | **`$CriticalNextRunTime`** -| Name | Type | Description | Default | -|---------------------|---------------|-------------------------------------------------------------------|---------| -| CriticalNextRunTime | System.String | Critical threshold for the next run offset (e.g. '30m', '-2h:'). | | +| Name | Type | Description | Default | +|---------------------|---------------|------------------------------------------------------------------|---------| +| CriticalNextRunTime | System.String | Critical threshold for the next run offset (e.g. '30m', '-2h:'). | | **`$IgnoreLastRunTime`** -| Name | Type | Description | Default | -|-------------------|----------------------------------------------|----------------------------------------------------|---------| -| IgnoreLastRunTime | System.Management.Automation.SwitchParameter | Do not alert on non-zero Last Task Result codes. | False | +| Name | Type | Description | Default | +|-------------------|----------------------------------------------|--------------------------------------------------|---------| +| IgnoreLastRunTime | System.Management.Automation.SwitchParameter | Do not alert on non-zero Last Task Result codes. | False | **`$MitigateUnknown`** -| Name | Type | Description | Default | -|-----------------|----------------------------------------------|--------------------------------------------------------------|---------| -| MitigateUnknown | System.Management.Automation.SwitchParameter | Return OK instead of UNKNOWN when no task matches the filter.| False | +| Name | Type | Description | Default | +|-----------------|----------------------------------------------|---------------------------------------------------------------|---------| +| MitigateUnknown | System.Management.Automation.SwitchParameter | Return OK instead of UNKNOWN when no task matches the filter. | False | **`$OverrideNotFound`** -| Name | Type | Description | Default | -|------------------|---------------|---------------------------------------------------------------------------|---------| -| OverrideNotFound | System.String | State for missing required tasks ('Ok', 'Warning', 'Critical', 'Unknown').| Unknown | +| Name | Type | Description | Default | +|------------------|---------------|----------------------------------------------------------------------------|---------| +| OverrideNotFound | System.String | State for missing required tasks ('Ok', 'Warning', 'Critical', 'Unknown'). | Unknown | **`$Verbosity`** @@ -1111,7 +1111,7 @@ Checks all tasks under \Icinga\ for Ready or Running state and warns if a task h Windows-only. Queries tasks through Get-IcingaScheduledTask. The integer exit code is the return value; an Icinga command wrapper is expected to exit with it. -*Source: [src/Plugins/Checks/Public/Invoke-IcingaCheckScheduledTask.ps1](../../src/Plugins/Checks/Public/Invoke-IcingaCheckScheduledTask.ps1)* +*Source: [src/Plugins/Checks/Public/Invoke-IcingaCheckScheduledTask.ps1](../src/Plugins/Checks/Public/Invoke-IcingaCheckScheduledTask.ps1)* --- @@ -1161,9 +1161,9 @@ This plugin is Windows-only because it relies on the Win32_Service CIM class. **`$Status`** -| Name | Type | Description | Default | -|--------|-----------------------|----------------------------------------------------------------------------------------------------------------------------------------|------------| -| Status | IcingaServiceStatus[] | Expected status(es) of the given services: Stopped, StartPending, StopPending, Running, ContinuePending, PausePending, Paused, Unknown.| @(Running) | +| Name | Type | Description | Default | +|--------|-----------------------|-----------------------------------------------------------------------------------------------------------------------------------------|------------| +| Status | IcingaServiceStatus[] | Expected status(es) of the given services: Stopped, StartPending, StopPending, Running, ContinuePending, PausePending, Paused, Unknown. | @(Running) | **`$FilterStartupType`** @@ -1191,9 +1191,9 @@ This plugin is Windows-only because it relies on the Win32_Service CIM class. **`$Verbosity`** -| Name | Type | Description | Default | -|-----------|--------------|------------------------------------------------------------------------------------|---------| -| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config.| 0 | +| Name | Type | Description | Default | +|-----------|--------------|-------------------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | **`$NoPerfData`** @@ -1233,7 +1233,7 @@ Get-IcingaWindowsInformation; a failed query is reported as UNKNOWN with its reason. The integer exit code is the return value; an Icinga command wrapper is expected to exit with it. -*Source: [src/Plugins/Checks/Public/Invoke-IcingaCheckService.ps1](../../src/Plugins/Checks/Public/Invoke-IcingaCheckService.ps1)* +*Source: [src/Plugins/Checks/Public/Invoke-IcingaCheckService.ps1](../src/Plugins/Checks/Public/Invoke-IcingaCheckService.ps1)* --- @@ -1264,21 +1264,21 @@ Performance data uses the label 'windows::ifw_uptime::uptime' in seconds. **`$Warning`** -| Name | Type | Description | Default | -|---------|---------------|----------------------------------------------------------|---------| -| Warning | System.String | Warning threshold as duration or range, e.g. '1d:'. | | +| Name | Type | Description | Default | +|---------|---------------|-----------------------------------------------------|---------| +| Warning | System.String | Warning threshold as duration or range, e.g. '1d:'. | | **`$Critical`** -| Name | Type | Description | Default | -|----------|---------------|----------------------------------------------------------|---------| -| Critical | System.String | Critical threshold as duration or range, e.g. '30m:'. | | +| Name | Type | Description | Default | +|----------|---------------|-------------------------------------------------------|---------| +| Critical | System.String | Critical threshold as duration or range, e.g. '30m:'. | | **`$Verbosity`** -| Name | Type | Description | Default | -|-----------|--------------|------------------------------------------------------------------------------------|---------| -| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config.| 0 | +| Name | Type | Description | Default | +|-----------|--------------|-------------------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | **`$NoPerfData`** @@ -1311,5 +1311,5 @@ needs read access to the performance counters ('Performance Monitor Users'). The integer exit code is the return value; an Icinga command wrapper is expected to exit with it. -*Source: [src/Plugins/Checks/Public/Invoke-IcingaCheckUptime.ps1](../../src/Plugins/Checks/Public/Invoke-IcingaCheckUptime.ps1)* +*Source: [src/Plugins/Checks/Public/Invoke-IcingaCheckUptime.ps1](../src/Plugins/Checks/Public/Invoke-IcingaCheckUptime.ps1)* diff --git a/docs/Icinga.Plugins.Lib.md b/docs/Icinga.Plugins.Lib.md index d191d0f..2d6433d 100644 --- a/docs/Icinga.Plugins.Lib.md +++ b/docs/Icinga.Plugins.Lib.md @@ -32,9 +32,9 @@ positional in the order Name, Value, Unit. **`$Name`** -| Name | Type | Description | Default | -|------|---------------|--------------------------------------|---------| -| Name | System.String | Display name of the plugin node. | $null | +| Name | Type | Description | Default | +|------|---------------|----------------------------------|---------| +| Name | System.String | Display name of the plugin node. | $null | **`$Value`** @@ -78,5 +78,5 @@ 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. -*Source: [src/Plugins/Lib/Public/New-IcingaPlugin.ps1](../../src/Plugins/Lib/Public/New-IcingaPlugin.ps1)* +*Source: [src/Plugins/Lib/Public/New-IcingaPlugin.ps1](../src/Plugins/Lib/Public/New-IcingaPlugin.ps1)* diff --git a/docs/Icinga.Plugins.Provider.Disk.md b/docs/Icinga.Plugins.Provider.Disk.md index ddc409d..66a8793 100644 --- a/docs/Icinga.Plugins.Provider.Disk.md +++ b/docs/Icinga.Plugins.Provider.Disk.md @@ -49,9 +49,9 @@ DiskInformationDiskQueryFailed), so the log shows where the collection stopped. **`$SkipPartitionMapping`** -| Name | Type | Description | Default | -|----------------------|----------------------------------------------|-----------------------------------------------------------------------|---------| -| SkipPartitionMapping | System.Management.Automation.SwitchParameter | Skip querying MSFT_Partition when Entrypoint is set to 'Volume'. | $false | +| Name | Type | Description | Default | +|----------------------|----------------------------------------------|------------------------------------------------------------------|---------| +| SkipPartitionMapping | System.Management.Automation.SwitchParameter | Skip querying MSFT_Partition when Entrypoint is set to 'Volume'. | $false | #### Outputs @@ -96,5 +96,5 @@ Windows-only. Reads root/cimv2 (Win32_Volume), root/Microsoft/Windows/Storage Standard users can read all of them. Spanned volumes are linked to the first partition reporting them. -*Source: [src/Plugins/Provider/Disk/Private/Get-IcingaDiskInformation.ps1](../../src/Plugins/Provider/Disk/Private/Get-IcingaDiskInformation.ps1)* +*Source: [src/Plugins/Provider/Disk/Private/Get-IcingaDiskInformation.ps1](../src/Plugins/Provider/Disk/Private/Get-IcingaDiskInformation.ps1)* diff --git a/docs/Icinga.Plugins.Provider.FileSystem.md b/docs/Icinga.Plugins.Provider.FileSystem.md index 8042bec..175eb05 100644 --- a/docs/Icinga.Plugins.Provider.FileSystem.md +++ b/docs/Icinga.Plugins.Provider.FileSystem.md @@ -165,5 +165,5 @@ Reads the file system through System.IO.DirectoryInfo; the user needs list permission on every scanned directory. Relative paths are resolved against the current PowerShell file system location. No external services are used. -*Source: [src/Plugins/Provider/FileSystem/Private/Get-IcingaDirectoryInformation.ps1](../../src/Plugins/Provider/FileSystem/Private/Get-IcingaDirectoryInformation.ps1)* +*Source: [src/Plugins/Provider/FileSystem/Private/Get-IcingaDirectoryInformation.ps1](../src/Plugins/Provider/FileSystem/Private/Get-IcingaDirectoryInformation.ps1)* diff --git a/docs/Icinga.Plugins.Provider.Process.md b/docs/Icinga.Plugins.Provider.Process.md index 90aff78..5d6d76e 100644 --- a/docs/Icinga.Plugins.Provider.Process.md +++ b/docs/Icinga.Plugins.Provider.Process.md @@ -51,9 +51,9 @@ PowerShell 5.1. **`$Exclude`** -| Name | Type | Description | Default | -|---------|--------------|-----------------------------------------------------|---------| -| Exclude | System.Array | Skip processes matching these names (wildcards). | @() | +| Name | Type | Description | Default | +|---------|--------------|--------------------------------------------------|---------| +| Exclude | System.Array | Skip processes matching these names (wildcards). | @() | #### Outputs @@ -78,5 +78,5 @@ Windows-only. Reads the '\Process(*)' performance counters ('Performance Monitor Users'), '\Memory\Commit Limit' and the Win32_ComputerSystem CIM class. Without a running daemon the first call in a runspace waits for the counter warm-up. -*Source: [src/Plugins/Provider/Process/Private/Get-IcingaProcessInformation.ps1](../../src/Plugins/Provider/Process/Private/Get-IcingaProcessInformation.ps1)* +*Source: [src/Plugins/Provider/Process/Private/Get-IcingaProcessInformation.ps1](../src/Plugins/Provider/Process/Private/Get-IcingaProcessInformation.ps1)* diff --git a/docs/Icinga.Plugins.Provider.ScheduledTask.md b/docs/Icinga.Plugins.Provider.ScheduledTask.md index b7a9451..10a60e1 100644 --- a/docs/Icinga.Plugins.Provider.ScheduledTask.md +++ b/docs/Icinga.Plugins.Provider.ScheduledTask.md @@ -38,9 +38,9 @@ grouped by TaskPath and sorted by TaskName. **`$ExcludeTaskName`** -| Name | Type | Description | Default | -|-----------------|--------------|--------------------------------------------------------------|---------| -| ExcludeTaskName | System.Array | Skip tasks matching these names (wildcards allowed). | @() | +| Name | Type | Description | Default | +|-----------------|--------------|------------------------------------------------------|---------| +| ExcludeTaskName | System.Array | Skip tasks matching these names (wildcards allowed). | @() | **`$TaskPath`** @@ -50,9 +50,9 @@ grouped by TaskPath and sorted by TaskName. **`$ExcludeTaskPath`** -| Name | Type | Description | Default | -|-----------------|--------------|--------------------------------------------------------------|---------| -| ExcludeTaskPath | System.Array | Skip tasks matching these paths (wildcards allowed). | @() | +| Name | Type | Description | Default | +|-----------------|--------------|------------------------------------------------------|---------| +| ExcludeTaskPath | System.Array | Skip tasks matching these paths (wildcards allowed). | @() | #### Outputs @@ -73,5 +73,5 @@ Returns all scheduled tasks under the \Icinga\ task path hierarchy. Windows-only. Relies on Get-ScheduledTask and Get-ScheduledTaskInfo from the ScheduledTasks module. -*Source: [src/Plugins/Provider/ScheduledTask/Private/Get-IcingaScheduledTask.ps1](../../src/Plugins/Provider/ScheduledTask/Private/Get-IcingaScheduledTask.ps1)* +*Source: [src/Plugins/Provider/ScheduledTask/Private/Get-IcingaScheduledTask.ps1](../src/Plugins/Provider/ScheduledTask/Private/Get-IcingaScheduledTask.ps1)* diff --git a/docs/Icinga.Security.md b/docs/Icinga.Security.md index 27f37a5..62f4cf7 100644 --- a/docs/Icinga.Security.md +++ b/docs/Icinga.Security.md @@ -30,13 +30,13 @@ is present. Returns a short encoding identifier string. **`$Path`** -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Path | System.String | Path to the file to inspect | '' | +| Name | Type | Description | Default | +|------|---------------|-----------------------------|---------| +| Path | System.String | Path to the file to inspect | '' | #### Outputs -System.String — One of: UTF8-BOM, UTF8, Unicode, BigEndianUnicode, UTF7, UTF32, ASCII. +System.String -- One of: UTF8-BOM, UTF8, Unicode, BigEndianUnicode, UTF7, UTF32, ASCII. #### Examples @@ -48,7 +48,7 @@ Get-FileEncoding -Path (Join-Path (Get-ModuleConfigDirectory) 'settings.json') - Returns a cmdlet-style error via `Write-FunctionReturnValue` when the file is not found. -*Source: [src/Security/Private/Get-FileEncoding.ps1](../../src/Security/Private/Get-FileEncoding.ps1)* +*Source: [src/Security/Private/Get-FileEncoding.ps1](../src/Security/Private/Get-FileEncoding.ps1)* --- @@ -82,21 +82,21 @@ enumerated child items via -OverrideReturn on success or $null on error. **`$Include`** -| Name | Type | Description | Default | -|---------|--------------|-------------------------------------------------|---------| -| Include | System.Array | Additional include patterns for Get-ChildItem. | @() | +| Name | Type | Description | Default | +|---------|--------------|------------------------------------------------|---------| +| Include | System.Array | Additional include patterns for Get-ChildItem. | @() | **`$File`** -| Name | Type | Description | Default | -|------|----------------------------------------------|---------------------------|---------| -| File | System.Management.Automation.SwitchParameter | If set, only return files.| $false | +| Name | Type | Description | Default | +|------|----------------------------------------------|----------------------------|---------| +| File | System.Management.Automation.SwitchParameter | If set, only return files. | $false | **`$Directory`** -| Name | Type | Description | Default | -|-----------|----------------------------------------------|---------------------------------|---------| -| Directory | System.Management.Automation.SwitchParameter | If set, only return directories.| $false | +| Name | Type | Description | Default | +|-----------|----------------------------------------------|----------------------------------|---------| +| Directory | System.Management.Automation.SwitchParameter | If set, only return directories. | $false | **`$Recurse`** @@ -120,7 +120,7 @@ PS> Get-SecureChildItem -Path (Get-ModuleConfigDirectory) -File This helper logs attempted access to unapproved paths and returns AccessViolation. -*Source: [src/Security/Private/Get-SecureChildItem.ps1](../../src/Security/Private/Get-SecureChildItem.ps1)* +*Source: [src/Security/Private/Get-SecureChildItem.ps1](../src/Security/Private/Get-SecureChildItem.ps1)* --- @@ -141,25 +141,25 @@ unauthorized attempts. **`$Path`** -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Path | System.String | Path to create (file or directory). | $null | +| Name | Type | Description | Default | +|------|---------------|-------------------------------------|---------| +| Path | System.String | Path to create (file or directory). | $null | **`$ItemType`** -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ItemType | System.String | 'File' or 'Directory'. | 'File' | +| Name | Type | Description | Default | +|----------|---------------|------------------------|---------| +| ItemType | System.String | 'File' or 'Directory'. | 'File' | **`$Force`** -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Force | System.Management.Automation.SwitchParameter | Pass `-Force` to `New-Item` to overwrite existing items. | $false | +| Name | Type | Description | Default | +|-------|----------------------------------------------|----------------------------------------------------------|---------| +| Force | System.Management.Automation.SwitchParameter | Pass `-Force` to `New-Item` to overwrite existing items. | $false | #### Outputs -PSCustomObject — Function return value via Write-FunctionReturnValue. +PSCustomObject -- Function return value via Write-FunctionReturnValue. ObjectCreationSucceeded on success (Data contains Path, ItemType and Item). ObjectCreationFailed, AccessViolation or DirectoryArgumentEmpty on errors. @@ -174,7 +174,7 @@ PS> New-SecureItem -Path (Join-Path (Get-ModuleConfigDirectory) 'my.conf') -Item Intended for use when module code must create config files; restricts creation to module config directories only. -*Source: [src/Security/Private/New-SecureItem.ps1](../../src/Security/Private/New-SecureItem.ps1)* +*Source: [src/Security/Private/New-SecureItem.ps1](../src/Security/Private/New-SecureItem.ps1)* --- @@ -195,13 +195,13 @@ assembling the file content. Returns standardized return values via **`$File`** -| Name | Type | Description | Default | -|------|------|-------------|---------| -| File | System.String | Path to the file to read. | $null | +| Name | Type | Description | Default | +|------|---------------|---------------------------|---------| +| File | System.String | Path to the file to read. | $null | #### Outputs -System.String — File content on success (returned as raw override via Write-FunctionReturnValue). +System.String -- File content on success (returned as raw override via Write-FunctionReturnValue). ObjectReadSucceeded on success (Data contains Path and Content). FileNotFound, AccessViolation or FileLockException on errors. @@ -216,7 +216,7 @@ PS> Read-SecureFile -File (Join-Path (Get-ModuleConfigDirectory) 'settings.json' This helper attempts to open the file for up to ~5 seconds before failing with `FileLockException`. Use for reading module configuration files safely. -*Source: [src/Security/Private/Read-SecureFile.ps1](../../src/Security/Private/Read-SecureFile.ps1)* +*Source: [src/Security/Private/Read-SecureFile.ps1](../src/Security/Private/Read-SecureFile.ps1)* --- @@ -236,25 +236,25 @@ using `Write-FunctionReturnValue`. **`$Path`** -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Path | System.String | Path to remove. | '' | +| Name | Type | Description | Default | +|------|---------------|-----------------|---------| +| Path | System.String | Path to remove. | '' | **`$Recurse`** -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Recurse | System.Management.Automation.SwitchParameter | Remove child items recursively. | $false | +| Name | Type | Description | Default | +|---------|----------------------------------------------|---------------------------------|---------| +| Recurse | System.Management.Automation.SwitchParameter | Remove child items recursively. | $false | **`$Force`** -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Force | System.Management.Automation.SwitchParameter | Force deletion (pass `-Force` to `Remove-Item`). | $false | +| Name | Type | Description | Default | +|-------|----------------------------------------------|--------------------------------------------------|---------| +| Force | System.Management.Automation.SwitchParameter | Force deletion (pass `-Force` to `Remove-Item`). | $false | #### Outputs -PSCustomObject — Function return value via Write-FunctionReturnValue. +PSCustomObject -- Function return value via Write-FunctionReturnValue. RemoveItemSuccess on success (Data contains Path). RemoveItemFailed, AccessViolation, RemoveItemNoPathProvided or RemoveItemPathNotFound on errors. @@ -268,7 +268,7 @@ PS> Remove-SecureItem -Path (Join-Path (Get-ModuleCacheDirectory) 'temp.log') -F Intended to limit deletion operations to module-managed directories only. -*Source: [src/Security/Private/Remove-SecureItem.ps1](../../src/Security/Private/Remove-SecureItem.ps1)* +*Source: [src/Security/Private/Remove-SecureItem.ps1](../src/Security/Private/Remove-SecureItem.ps1)* --- @@ -288,19 +288,19 @@ entry for each check and returns standardized return values. **`$Path`** -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Path | System.String | Path to validate. | $null | +| Name | Type | Description | Default | +|------|---------------|-------------------|---------| +| Path | System.String | Path to validate. | $null | **`$ApprovedPath`** -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ApprovedPath | System.Array | Array of allowed directory paths (strings). | @() | +| Name | Type | Description | Default | +|--------------|--------------|---------------------------------------------|---------| +| ApprovedPath | System.Array | Array of allowed directory paths (strings). | @() | #### Outputs -PSCustomObject — Function return value via Write-FunctionReturnValue. +PSCustomObject -- Function return value via Write-FunctionReturnValue. AccessGranted when the path is within an approved directory. AccessViolation or DirectoryArgumentEmpty otherwise. @@ -314,7 +314,7 @@ PS> Test-SecureApprovedPath -Path (Join-Path (Get-ModuleConfigDirectory) 'x') -A Uses `Resolve-Path` to normalize paths; callers should ensure ApprovedPath entries exist. -*Source: [src/Security/Private/Test-SecureApprovedPath.ps1](../../src/Security/Private/Test-SecureApprovedPath.ps1)* +*Source: [src/Security/Private/Test-SecureApprovedPath.ps1](../src/Security/Private/Test-SecureApprovedPath.ps1)* --- @@ -336,19 +336,19 @@ and retries on lock for a short period. Returns structured return values via **`$File`** -| Name | Type | Description | Default | -|------|------|-------------|---------| -| File | System.String | Target file path to write. | $null | +| Name | Type | Description | Default | +|------|---------------|----------------------------|---------| +| File | System.String | Target file path to write. | $null | **`$Value`** -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Value | System.Object | Content to write. Can be hashtable, PSCustomObject, array or string. | (none) | +| Name | Type | Description | Default | +|-------|---------------|----------------------------------------------------------------------|---------| +| Value | System.Object | Content to write. Can be hashtable, PSCustomObject, array or string. | (none) | #### Outputs -PSCustomObject — Function return value via Write-FunctionReturnValue. +PSCustomObject -- Function return value via Write-FunctionReturnValue. WriteFileSuccess on success (Data contains Path and Content), WriteFileLockException when the file cannot be opened within the retry window. @@ -363,5 +363,5 @@ PS> Write-SecureFile -File (Join-Path (Get-ModuleConfigDirectory) 'settings.json Creates the file if it does not exist by delegating to `New-SecureItem`. Uses UTF8 without BOM when writing bytes. Caller receives the content in the return data. -*Source: [src/Security/Private/Write-SecureFile.ps1](../../src/Security/Private/Write-SecureFile.ps1)* +*Source: [src/Security/Private/Write-SecureFile.ps1](../src/Security/Private/Write-SecureFile.ps1)* diff --git a/docs/Icinga.Tools.md b/docs/Icinga.Tools.md index 9ab5ab5..05adc04 100644 --- a/docs/Icinga.Tools.md +++ b/docs/Icinga.Tools.md @@ -62,25 +62,25 @@ tools or modules are required. **`$OldConfig`** -| Name | Type | Description | Default | -|-----------|---------------|-------------------------------------------------------|---------| -| OldConfig | System.String | The baseline content as a JSON string or plain text. | $null | +| Name | Type | Description | Default | +|-----------|---------------|------------------------------------------------------|---------| +| OldConfig | System.String | The baseline content as a JSON string or plain text. | $null | **`$OldFile`** -| Name | Type | Description | Default | -|---------|---------------|-----------------------------------------------------------------------|---------| -| OldFile | System.String | File path to the baseline; read via Read-SecureFile when provided. | $null | +| Name | Type | Description | Default | +|---------|---------------|--------------------------------------------------------------------|---------| +| OldFile | System.String | File path to the baseline; read via Read-SecureFile when provided. | $null | **`$Colorized`** -| Name | Type | Description | Default | -|-----------|----------------------------------------------|----------------------------------------------------------------|---------| +| Name | Type | Description | Default | +|-----------|----------------------------------------------|---------------------------------------------------------------|---------| | Colorized | System.Management.Automation.SwitchParameter | When set, embeds ANSI color codes (green/red/cyan) in output. | $false | #### Outputs -System.Collections.Hashtable — Always returns @{ ExitCode = System.Int32; Output = System.String }. +System.Collections.Hashtable -- Always returns @{ ExitCode = System.Int32; Output = System.String }. ExitCode is 0 when both inputs are identical after normalization, 1 when they differ. Output is an empty string when identical; otherwise a unified diff with header lines (--- old / +++ new), @@ hunk headers and +/-/space-prefixed content lines. @@ -111,7 +111,7 @@ matrix; inputs beyond a few thousand lines will consume significant memory, whic is acceptable for config-file comparison. No external binaries, modules, or .NET packages beyond the PowerShell standard library are used. -*Source: [src/Tools/Public/Compare-IcingaTextContent.ps1](../../src/Tools/Public/Compare-IcingaTextContent.ps1)* +*Source: [src/Tools/Public/Compare-IcingaTextContent.ps1](../src/Tools/Public/Compare-IcingaTextContent.ps1)* --- @@ -141,9 +141,9 @@ member name. **`$InputObject`** -| Name | Type | Description | Default | -|-------------|--------------|------------------------|---------| -| InputObject | System.Array | The elements to sort. | @() | +| Name | Type | Description | Default | +|-------------|--------------|-----------------------|---------| +| InputObject | System.Array | The elements to sort. | @() | **`$Property`** @@ -180,7 +180,7 @@ Sorts Win32_Service instances by their name. No external dependencies. Replaces 'Sort-Object -Property { ... }' in plugin code. The verb follows the approved PowerShell verbs; 'Sort' is not one of them. -*Source: [src/Tools/Public/ConvertTo-IcingaSortedArray.ps1](../../src/Tools/Public/ConvertTo-IcingaSortedArray.ps1)* +*Source: [src/Tools/Public/ConvertTo-IcingaSortedArray.ps1](../src/Tools/Public/ConvertTo-IcingaSortedArray.ps1)* --- @@ -276,7 +276,7 @@ Write-FunctionReturnValue, which logs at the severity registered for each return code in Set-InternalExitCodes (Error for failures, Debug for the successful conversion). No external services, credentials or configuration files are used. -*Source: [src/Tools/Public/ConvertTo-IcingaUnit.ps1](../../src/Tools/Public/ConvertTo-IcingaUnit.ps1)* +*Source: [src/Tools/Public/ConvertTo-IcingaUnit.ps1](../src/Tools/Public/ConvertTo-IcingaUnit.ps1)* --- @@ -299,9 +299,9 @@ Icinga 2 check result payloads (execution_start and execution_end). **`$Milliseconds`** -| Name | Type | Description | Default | -|--------------|----------------------------------------------|-------------------------------------------------------------------------------|---------| -| Milliseconds | System.Management.Automation.SwitchParameter | When set, returns fractional Unix seconds with millisecond precision (Double).| $false | +| Name | Type | Description | Default | +|--------------|----------------------------------------------|--------------------------------------------------------------------------------|---------| +| Milliseconds | System.Management.Automation.SwitchParameter | When set, returns fractional Unix seconds with millisecond precision (Double). | $false | #### Outputs @@ -328,7 +328,7 @@ Returns the current UTC Unix time in seconds with millisecond precision. Uses System.DateTimeOffset.UtcNow across Windows PowerShell 5.1 and PowerShell 7+. -*Source: [src/Tools/Public/Get-IcingaUnixTime.ps1](../../src/Tools/Public/Get-IcingaUnixTime.ps1)* +*Source: [src/Tools/Public/Get-IcingaUnixTime.ps1](../src/Tools/Public/Get-IcingaUnixTime.ps1)* --- @@ -363,15 +363,15 @@ the ReturnCode of the IcingaError. **`$ClassName`** -| Name | Type | Description | Default | -|-----------|---------------|-----------------------------------------|---------| -| ClassName | System.String | Name of the CIM class to query. | | +| Name | Type | Description | Default | +|-----------|---------------|---------------------------------|---------| +| ClassName | System.String | Name of the CIM class to query. | | **`$Namespace`** -| Name | Type | Description | Default | -|-----------|---------------|--------------------------------|------------| -| Namespace | System.String | CIM namespace of the class. | root/cimv2 | +| Name | Type | Description | Default | +|-----------|---------------|-----------------------------|------------| +| Namespace | System.String | CIM namespace of the class. | root/cimv2 | **`$Filter`** @@ -412,7 +412,7 @@ the class; standard users can read most root/cimv2 classes. Unknown classes and namespaces are logged at Debug level only, because optional classes are probed on purpose. -*Source: [src/Tools/Public/Get-IcingaWindowsInformation.ps1](../../src/Tools/Public/Get-IcingaWindowsInformation.ps1)* +*Source: [src/Tools/Public/Get-IcingaWindowsInformation.ps1](../src/Tools/Public/Get-IcingaWindowsInformation.ps1)* --- @@ -431,19 +431,19 @@ URL query parameters and avoiding duplicate slashes. Preserves scheme endings li **`$Path`** -| Name | Type | Description | Default | -|------|---------------|------------------------------|---------| +| Name | Type | Description | Default | +|------|---------------|---------------------------------|---------| | Path | System.String | Base path or URL to start from. | $null | **`$ChildPath`** -| Name | Type | Description | Default | -|-----------|--------------|--------------------------------------------------------------------------------------|---------| +| Name | Type | Description | Default | +|-----------|--------------|-------------------------------------------------------------------------------------|---------| | ChildPath | System.Array | Child path segments to append. Segments may start with /, ? or & for query strings. | $null | #### Outputs -System.String — The assembled web path or URL. +System.String -- The assembled web path or URL. #### Examples @@ -463,7 +463,7 @@ Returns 'http://example.com/search?q=test&page=2'. No external dependencies. -*Source: [src/Tools/Public/Join-WebPath.ps1](../../src/Tools/Public/Join-WebPath.ps1)* +*Source: [src/Tools/Public/Join-WebPath.ps1](../src/Tools/Public/Join-WebPath.ps1)* --- @@ -486,13 +486,13 @@ mechanism to emit a standardized return value and typically returns $null. **`$Address`** -| Name | Type | Description | Default | -|---------|---------------|------------------------------------------------------------------------------|---------| +| Name | Type | Description | Default | +|---------|---------------|---------------------------------------------------------------------------------|---------| | Address | System.String | Hostname or IP address to resolve. Empty or null triggers IPAddressLookupEmpty. | $null | #### Outputs -System.String — IPv4 or IPv6 address string on success. +System.String -- IPv4 or IPv6 address string on success. Returns $null via Write-FunctionReturnValue on failure with tokens IPAddressLookupEmpty, IPAddressLookupFailure, IPAddressLookupFailedForV4AndV6 or IPAddressLookupException. @@ -519,7 +519,7 @@ are preferred; the function returns the first IPv4 found, otherwise the first IP Simple regex literal checks are performed before DNS resolution to avoid unnecessary lookups. Error conditions are surfaced via Write-FunctionReturnValue. -*Source: [src/Tools/Public/Resolve-IcingaIPAddress.ps1](../../src/Tools/Public/Resolve-IcingaIPAddress.ps1)* +*Source: [src/Tools/Public/Resolve-IcingaIPAddress.ps1](../src/Tools/Public/Resolve-IcingaIPAddress.ps1)* --- @@ -548,21 +548,21 @@ pattern. **`$InputObject`** -| Name | Type | Description | Default | -|-------------|---------------|----------------------------------------------|---------| -| InputObject | System.Object | Value, or array of values, to test. | $null | +| Name | Type | Description | Default | +|-------------|---------------|-------------------------------------|---------| +| InputObject | System.Object | Value, or array of values, to test. | $null | **`$Include`** -| Name | Type | Description | Default | -|---------|--------------|--------------------------------------------------------|---------| -| Include | System.Array | Wildcard patterns of which at least one has to match. | @() | +| Name | Type | Description | Default | +|---------|--------------|-------------------------------------------------------|---------| +| Include | System.Array | Wildcard patterns of which at least one has to match. | @() | **`$Exclude`** -| Name | Type | Description | Default | -|---------|--------------|-----------------------------------------------|---------| -| Exclude | System.Array | Wildcard patterns of which none may match. | @() | +| Name | Type | Description | Default | +|---------|--------------|--------------------------------------------|---------| +| Exclude | System.Array | Wildcard patterns of which none may match. | @() | #### Outputs @@ -589,7 +589,7 @@ No external dependencies. A $null value never passes. Used by the plugins for their -Include/-Exclude parameters, which must not rely on script blocks so the plugins stay usable in JEA sessions. -*Source: [src/Tools/Public/Test-IcingaArrayFilter.ps1](../../src/Tools/Public/Test-IcingaArrayFilter.ps1)* +*Source: [src/Tools/Public/Test-IcingaArrayFilter.ps1](../src/Tools/Public/Test-IcingaArrayFilter.ps1)* --- @@ -613,9 +613,9 @@ and evaluate to $false. **`$Value`** -| Name | Type | Description | Default | -|-------|---------------|-----------------------------------------------------------|---------| -| Value | System.Object | Input value from JSON or Icinga macros to convert. | $null | +| Name | Type | Description | Default | +|-------|---------------|----------------------------------------------------|---------| +| Value | System.Object | Input value from JSON or Icinga macros to convert. | $null | #### Outputs @@ -636,7 +636,7 @@ string truthiness. Uses Write-FunctionReturnValue with key StringToBoolConversionInvalidValue when an unrecognized value is supplied. -*Source: [src/Tools/Private/ConvertFrom-ModuleBoolean.ps1](../../src/Tools/Private/ConvertFrom-ModuleBoolean.ps1)* +*Source: [src/Tools/Private/ConvertFrom-ModuleBoolean.ps1](../src/Tools/Private/ConvertFrom-ModuleBoolean.ps1)* --- @@ -658,13 +658,13 @@ it uses the native ConvertFrom-Json cmdlet with the -AsHashtable switch. **`$InputObject`** -| Name | Type | Description | Default | -|-------------|---------------|--------------------------------------------|---------| -| InputObject | System.String | The JSON string to deserialize. | '' | +| Name | Type | Description | Default | +|-------------|---------------|---------------------------------|---------| +| InputObject | System.String | The JSON string to deserialize. | '' | #### Outputs -System.Collections.Hashtable — Returns a hashtable (or dictionary) representation of the JSON string. +System.Collections.Hashtable -- Returns a hashtable (or dictionary) representation of the JSON string. Returns `$null` if the input is empty or parsing fails. #### Examples @@ -678,7 +678,7 @@ PS> $hashtable = ConvertFrom-ModuleJson -InputObject '{"key": "value"}' In Windows PowerShell 5.1, this function dynamically loads the System.Web.Extensions assembly if it is not already loaded in the current runspace. -*Source: [src/Tools/Private/ConvertFrom-ModuleJson.ps1](../../src/Tools/Private/ConvertFrom-ModuleJson.ps1)* +*Source: [src/Tools/Private/ConvertFrom-ModuleJson.ps1](../src/Tools/Private/ConvertFrom-ModuleJson.ps1)* --- @@ -700,13 +700,13 @@ and higher, it uses the native ConvertTo-Json cmdlet. **`$InputObject`** -| Name | Type | Description | Default | -|-------------|---------------|--------------------------------------------|---------| -| InputObject | System.Object | The object to serialize. | $null | +| Name | Type | Description | Default | +|-------------|---------------|--------------------------|---------| +| InputObject | System.Object | The object to serialize. | $null | #### Outputs -System.String — Returns a JSON string representation of the object. +System.String -- Returns a JSON string representation of the object. Returns an empty string if the input is null or serialization fails. #### Examples @@ -720,7 +720,7 @@ PS> $json = ConvertTo-ModuleJson -InputObject @{ key = "value" } In Windows PowerShell 5.1, this function dynamically loads the System.Web.Extensions assembly if it is not already loaded. -*Source: [src/Tools/Private/ConvertTo-ModuleJson.ps1](../../src/Tools/Private/ConvertTo-ModuleJson.ps1)* +*Source: [src/Tools/Private/ConvertTo-ModuleJson.ps1](../src/Tools/Private/ConvertTo-ModuleJson.ps1)* --- @@ -744,15 +744,15 @@ placeholder macros) are omitted. **`$InputObject`** -| Name | Type | Description | Default | -|-------------|---------------|-------------------------------------------------|---------| -| InputObject | System.Object | Dictionary or object to copy entries from. | $null | +| Name | Type | Description | Default | +|-------------|---------------|--------------------------------------------|---------| +| InputObject | System.Object | Dictionary or object to copy entries from. | $null | **`$SkipEmptyKeys`** -| Name | Type | Description | Default | -|---------------|----------------------------------------------|-------------------------------------------------------|---------| -| SkipEmptyKeys | System.Management.Automation.SwitchParameter | Omit null, empty or whitespace-only keys when set. | $false | +| Name | Type | Description | Default | +|---------------|----------------------------------------------|----------------------------------------------------|---------| +| SkipEmptyKeys | System.Management.Automation.SwitchParameter | Omit null, empty or whitespace-only keys when set. | $false | #### Outputs @@ -771,7 +771,7 @@ Creates an ordinal OrderedDictionary preserving exact key casing. Compatible with Windows PowerShell 5.1 and PowerShell 7+. -*Source: [src/Tools/Private/ConvertTo-ModuleOrderedDictionary.ps1](../../src/Tools/Private/ConvertTo-ModuleOrderedDictionary.ps1)* +*Source: [src/Tools/Private/ConvertTo-ModuleOrderedDictionary.ps1](../src/Tools/Private/ConvertTo-ModuleOrderedDictionary.ps1)* --- @@ -830,7 +830,7 @@ Coerces the string '2' into Int32 2 with Status 'Bound'. Callers must call Dispose() on AllocatedSecret when non-null once command execution completes. -*Source: [src/Tools/Private/ConvertTo-ModuleParameterValue.ps1](../../src/Tools/Private/ConvertTo-ModuleParameterValue.ps1)* +*Source: [src/Tools/Private/ConvertTo-ModuleParameterValue.ps1](../src/Tools/Private/ConvertTo-ModuleParameterValue.ps1)* --- @@ -878,7 +878,7 @@ Compatible with Windows PowerShell 5.1 and PowerShell 7+. Callers that allocate temporary SecureString instances for check execution should call Dispose() once the check finishes. -*Source: [src/Tools/Private/ConvertTo-ModuleSecureString.ps1](../../src/Tools/Private/ConvertTo-ModuleSecureString.ps1)* +*Source: [src/Tools/Private/ConvertTo-ModuleSecureString.ps1](../src/Tools/Private/ConvertTo-ModuleSecureString.ps1)* --- @@ -900,15 +900,15 @@ consistent comparisons. **`$InputArray`** -| Name | Type | Description | Default | -|------|------|-------------|---------| -| InputArray | System.Object[] | Array of items to normalize; string items will be case-normalized | @() | +| Name | Type | Description | Default | +|------------|-----------------|-------------------------------------------------------------------|---------| +| InputArray | System.Object[] | Array of items to normalize; string items will be case-normalized | @() | **`$UpperCase`** -| Name | Type | Description | Default | -|------|------|-------------|---------| -| UpperCase | Switch | When set, convert string items to upper-case instead of lower-case | $false | +| Name | Type | Description | Default | +|-----------|--------|--------------------------------------------------------------------|---------| +| UpperCase | Switch | When set, convert string items to upper-case instead of lower-case | $false | #### Outputs @@ -928,7 +928,7 @@ $normUpper = ConvertTo-StringNormalizedArray -InputArray @('Alice','BOB') -Upper - Non-string items are returned unchanged. -*Source: [src/Tools/Private/ConvertTo-StringNormalizedArray.ps1](../../src/Tools/Private/ConvertTo-StringNormalizedArray.ps1)* +*Source: [src/Tools/Private/ConvertTo-StringNormalizedArray.ps1](../src/Tools/Private/ConvertTo-StringNormalizedArray.ps1)* --- @@ -951,9 +951,9 @@ before the closing quote. **`$Arguments`** -| Name | Type | Description | Default | -|-----------|--------------|-------------------------------------------------|---------| -| Arguments | System.Array | Ordered CLI argument tokens to quote and join. | @() | +| Name | Type | Description | Default | +|-----------|--------------|------------------------------------------------|---------| +| Arguments | System.Array | Ordered CLI argument tokens to quote and join. | @() | #### Outputs @@ -972,7 +972,7 @@ Quotes tokens containing spaces or quotes while leaving simple tokens intact. Pure string formatter with no external dependencies or global state access. -*Source: [src/Tools/Private/Format-ModuleCommandLineArguments.ps1](../../src/Tools/Private/Format-ModuleCommandLineArguments.ps1)* +*Source: [src/Tools/Private/Format-ModuleCommandLineArguments.ps1](../src/Tools/Private/Format-ModuleCommandLineArguments.ps1)* --- @@ -1018,7 +1018,7 @@ Builds the canonical/alias lookup map and positional list for the command. Pure metadata helper with no external dependencies or side effects. -*Source: [src/Tools/Private/Get-ModuleCommandParameterMap.ps1](../../src/Tools/Private/Get-ModuleCommandParameterMap.ps1)* +*Source: [src/Tools/Private/Get-ModuleCommandParameterMap.ps1](../src/Tools/Private/Get-ModuleCommandParameterMap.ps1)* --- @@ -1078,7 +1078,7 @@ Reads the value of 'Check_Timeout' case-insensitively from the dictionary. Compatible with Windows PowerShell 5.1 and PowerShell 7+. Does not mutate global state. -*Source: [src/Tools/Private/Get-ModuleObjectValue.ps1](../../src/Tools/Private/Get-ModuleObjectValue.ps1)* +*Source: [src/Tools/Private/Get-ModuleObjectValue.ps1](../src/Tools/Private/Get-ModuleObjectValue.ps1)* --- @@ -1107,7 +1107,7 @@ empty input returns an empty string without attempting any conversion. #### Outputs -System.String — Re-serialized JSON string when the input is valid JSON, the +System.String -- Re-serialized JSON string when the input is valid JSON, the original input string when it is not, or an empty string for null or empty input. #### Examples @@ -1124,7 +1124,7 @@ Used by Compare-IcingaTextContent to ensure both sides of a diff use identical formatting before line-level comparison. Relies only on ConvertFrom-Json and ConvertTo-Json from the PowerShell standard library; no external dependencies. -*Source: [src/Tools/Private/Get-NormalizedTextContent.ps1](../../src/Tools/Private/Get-NormalizedTextContent.ps1)* +*Source: [src/Tools/Private/Get-NormalizedTextContent.ps1](../src/Tools/Private/Get-NormalizedTextContent.ps1)* --- @@ -1161,33 +1161,33 @@ Get-ModuleBinaryDirectory: **`$NamedArguments`** -| Name | Type | Description | Default | -|----------------|------------------------------|----------------------------------------------|---------| -| NamedArguments | System.Collections.Hashtable | Named parameter splatting hashtable. | @{} | +| Name | Type | Description | Default | +|----------------|------------------------------|--------------------------------------|---------| +| NamedArguments | System.Collections.Hashtable | Named parameter splatting hashtable. | @{} | **`$PositionalArguments`** -| Name | Type | Description | Default | -|---------------------|--------------|-------------------------------------------------|---------| -| PositionalArguments | System.Array | Optional positional arguments to pass after @. | @() | +| Name | Type | Description | Default | +|---------------------|--------------|------------------------------------------------|---------| +| PositionalArguments | System.Array | Optional positional arguments to pass after @. | @() | **`$AllocatedSecrets`** -| Name | Type | Description | Default | -|------------------|--------------|----------------------------------------------------------|---------| -| AllocatedSecrets | System.Array | Temporary SecureString instances to dispose in finally. | @() | +| Name | Type | Description | Default | +|------------------|--------------|---------------------------------------------------------|---------| +| AllocatedSecrets | System.Array | Temporary SecureString instances to dispose in finally. | @() | **`$UseLastExitCode`** -| Name | Type | Description | Default | -|-----------------|----------------------------------------------|-------------------------------------------------------------|---------| -| UseLastExitCode | System.Management.Automation.SwitchParameter | Fall back to $global:LASTEXITCODE for external .ps1 scripts.| $false | +| Name | Type | Description | Default | +|-----------------|----------------------------------------------|--------------------------------------------------------------|---------| +| UseLastExitCode | System.Management.Automation.SwitchParameter | Fall back to $global:LASTEXITCODE for external .ps1 scripts. | $false | **`$ErrorContext`** -| Name | Type | Description | Default | -|--------------|---------------|-----------------------------------------------------------------|---------| -| ErrorContext | System.String | Optional custom prefix for [UNKNOWN] unhandled error messages. | '' | +| Name | Type | Description | Default | +|--------------|---------------|----------------------------------------------------------------|---------| +| ErrorContext | System.String | Optional custom prefix for [UNKNOWN] unhandled error messages. | '' | #### Outputs @@ -1208,7 +1208,7 @@ result hashtable. Accesses runtime state exclusively via Get-GlobalRuntimeVariable. Never returns PowerShell class instances across thread boundaries. -*Source: [src/Tools/Private/Invoke-ModulePowerShellCommand.ps1](../../src/Tools/Private/Invoke-ModulePowerShellCommand.ps1)* +*Source: [src/Tools/Private/Invoke-ModulePowerShellCommand.ps1](../src/Tools/Private/Invoke-ModulePowerShellCommand.ps1)* --- @@ -1228,19 +1228,19 @@ deriving filenames from user-supplied role names or identifiers. **`$InputString`** -| Name | Type | Description | Default | -|------|------|-------------|---------| -| InputString | System.String | Input string to sanitize. | $null | +| Name | Type | Description | Default | +|-------------|---------------|---------------------------|---------| +| InputString | System.String | Input string to sanitize. | $null | **`$RemoveSpaces`** -| Name | Type | Description | Default | -|------|------|-------------|---------| -| RemoveSpaces | System.Management.Automation.SwitchParameter | Remove all whitespace characters when set. | $false | +| Name | Type | Description | Default | +|--------------|----------------------------------------------|--------------------------------------------|---------| +| RemoveSpaces | System.Management.Automation.SwitchParameter | Remove all whitespace characters when set. | $false | #### Outputs -System.String — The sanitized string suitable for use as a filename. +System.String -- The sanitized string suitable for use as a filename. #### Examples @@ -1253,7 +1253,7 @@ PS> Remove-ModuleAmbitiousCharacters -InputString 'Admin Role #1' -RemoveSpaces Only removes a restricted set of characters; callers may perform additional normalization (lowercasing, trimming) if needed. -*Source: [src/Tools/Private/Remove-ModuleAmbitiousCharacters.ps1](../../src/Tools/Private/Remove-ModuleAmbitiousCharacters.ps1)* +*Source: [src/Tools/Private/Remove-ModuleAmbitiousCharacters.ps1](../src/Tools/Private/Remove-ModuleAmbitiousCharacters.ps1)* --- @@ -1274,9 +1274,9 @@ a broken filter argument never aborts a plugin. **`$Value`** -| Name | Type | Description | Default | -|-------|---------------|----------------------|---------| -| Value | System.String | The value to test. | | +| Name | Type | Description | Default | +|-------|---------------|--------------------|---------| +| Value | System.String | The value to test. | | **`$Pattern`** @@ -1300,5 +1300,5 @@ Returns $true. Internal helper of Test-IcingaArrayFilter. -*Source: [src/Tools/Private/Test-ModuleWildcardMatch.ps1](../../src/Tools/Private/Test-ModuleWildcardMatch.ps1)* +*Source: [src/Tools/Private/Test-ModuleWildcardMatch.ps1](../src/Tools/Private/Test-ModuleWildcardMatch.ps1)* diff --git a/docs/index.md b/docs/index.md index bcfb4db..f7d1a01 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,6 +1,6 @@ -# Icinga API Reference +# Icinga for Windows API Reference -*Auto-generated on 2026-11-16 23:35:50.* +*Auto-generated on 2026-11-17 09:32:42.* | Component | Public functions | Private helpers | |-----------|------------------|-----------------| diff --git a/src/Classes/DataTypes/IcingaScheduledTaskStatus.ps1 b/src/Classes/DataTypes/IcingaScheduledTaskStatus.ps1 index 703e256..fcbf797 100644 --- a/src/Classes/DataTypes/IcingaScheduledTaskStatus.ps1 +++ b/src/Classes/DataTypes/IcingaScheduledTaskStatus.ps1 @@ -25,6 +25,9 @@ Returns 3, the code used for the scheduled task state performance data. Defined in the kernel ahead of every function, so functions may use it as a parameter type. Not visible outside the module scope; callers pass the name or code as a string. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> enum IcingaScheduledTaskStatus { @@ -55,6 +58,9 @@ Returns IcingaScheduledTaskStatus::Ready. .NOTES Pure conversion helper without state or external dependencies. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> class IcingaScheduledTaskStatusMap { @@ -68,9 +74,9 @@ class IcingaScheduledTaskStatusMap Returns Unknown for $null, empty strings, unknown names and undefined codes. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|-----------------------------------------------------------|---------| - | Value | System.Object | Status name, ScheduledTask StateEnum or numeric code. | | + | Name | Type | Description | Default | + |-------|---------------|-------------------------------------------------------|---------| + | Value | System.Object | Status name, ScheduledTask StateEnum or numeric code. | | .OUTPUTS IcingaScheduledTaskStatus -- The resolved status, Unknown when it cannot be mapped. diff --git a/src/Classes/DataTypes/IcingaServiceStartupType.ps1 b/src/Classes/DataTypes/IcingaServiceStartupType.ps1 index 3fc7832..f6c9ced 100644 --- a/src/Classes/DataTypes/IcingaServiceStartupType.ps1 +++ b/src/Classes/DataTypes/IcingaServiceStartupType.ps1 @@ -24,6 +24,9 @@ Converts the name into IcingaServiceStartupType::Manual. Defined in the kernel ahead of every function, so functions may use it as a parameter type. Not visible outside the module scope; callers pass the name or code as a string. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> enum IcingaServiceStartupType { @@ -57,6 +60,9 @@ Returns IcingaServiceStartupType::Automatic. .NOTES Pure conversion helper without state or external dependencies. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> class IcingaServiceStartupTypeMap { diff --git a/src/Classes/DataTypes/IcingaServiceStatus.ps1 b/src/Classes/DataTypes/IcingaServiceStatus.ps1 index b1855b9..757e610 100644 --- a/src/Classes/DataTypes/IcingaServiceStatus.ps1 +++ b/src/Classes/DataTypes/IcingaServiceStatus.ps1 @@ -26,6 +26,9 @@ Returns 4, the code used for the service state performance data. Defined in the kernel ahead of every function, so functions may use it as a parameter type. Not visible outside the module scope; callers pass the name or code as a string. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> enum IcingaServiceStatus { @@ -61,6 +64,9 @@ Returns IcingaServiceStatus::StartPending. .NOTES Pure conversion helper without state or external dependencies. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> class IcingaServiceStatusMap { @@ -74,9 +80,9 @@ class IcingaServiceStatusMap unknown names and undefined codes. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|---------------------------------------------------------------------|---------| - | Value | System.Object | Status name, Win32_Service state, ServiceControllerStatus or code. | | + | Name | Type | Description | Default | + |-------|---------------|--------------------------------------------------------------------|---------| + | Value | System.Object | Status name, Win32_Service state, ServiceControllerStatus or code. | | .OUTPUTS IcingaServiceStatus -- The resolved status, Unknown when it cannot be mapped. diff --git a/src/Classes/Icinga/IcingaCheckResult.ps1 b/src/Classes/Icinga/IcingaCheckResult.ps1 index 99454f4..2f1229b 100644 --- a/src/Classes/Icinga/IcingaCheckResult.ps1 +++ b/src/Classes/Icinga/IcingaCheckResult.ps1 @@ -22,6 +22,9 @@ 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. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> class IcingaCheckResult { @@ -64,14 +67,14 @@ class IcingaCheckResult | 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. | | + | 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. | | + | Name | Type | Description | Default | + |-----------------|--------------|--------------------------------------------------|---------| + | PerformanceData | System.Array | Performance-data metrics, one string per metric. | | .OUTPUTS IcingaCheckResult -- Configured result instance. diff --git a/src/Classes/Icinga/IcingaError.ps1 b/src/Classes/Icinga/IcingaError.ps1 index bb15fd1..ac785ee 100644 --- a/src/Classes/Icinga/IcingaError.ps1 +++ b/src/Classes/Icinga/IcingaError.ps1 @@ -33,6 +33,9 @@ Functions create and test errors through the type of the current runspace 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. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> class IcingaError { @@ -109,9 +112,9 @@ class IcingaError failure. .PARAMETER ReturnCode - | Name | Type | Description | Default | - |------------|---------------|-----------------------------------------------|---------| - | ReturnCode | System.String | Semantic key of the return-code table entry. | | + | Name | Type | Description | Default | + |------------|---------------|----------------------------------------------|---------| + | ReturnCode | System.String | Semantic key of the return-code table entry. | | .PARAMETER Message | Name | Type | Description | Default | @@ -119,9 +122,9 @@ class IcingaError | Message | System.String | Human-readable error message. | | .PARAMETER Data - | Name | Type | Description | Default | - |------|------------------------------|---------------------------------|---------| - | Data | System.Collections.Hashtable | Context values of the failure. | | + | Name | Type | Description | Default | + |------|------------------------------|--------------------------------|---------| + | Data | System.Collections.Hashtable | Context values of the failure. | | .OUTPUTS IcingaError -- The error object. diff --git a/src/Classes/Icinga/IcingaPerformanceCounter.ps1 b/src/Classes/Icinga/IcingaPerformanceCounter.ps1 index e7e5af9..6b6547d 100644 --- a/src/Classes/Icinga/IcingaPerformanceCounter.ps1 +++ b/src/Classes/Icinga/IcingaPerformanceCounter.ps1 @@ -24,6 +24,9 @@ PS> [IcingaPerformanceCounterEntry]::new('\Processor(_Total)\% Processor Time', .NOTES `System.Diagnostics.PerformanceCounter` is IDisposable; the handle is created on the `Handle` field and released in `Dispose`. Never share a single instance across threads. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> class IcingaPerformanceCounterEntry { @@ -232,6 +235,9 @@ PS> $Snapshot.Read('svchost', '% Processor Time') Holds no native counter handles. The counter help texts are read once through `GetCounters` and those handles are disposed right away. Like the counter entries an instance is used on one thread only. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> class IcingaPerformanceCounterCategory { @@ -603,6 +609,9 @@ PS> $manager.Resolve(@('\Processor(_Total)\% Processor Time')) Every handle is created, sampled and disposed on one thread. All class methods are self-contained and perform no logging or global-state access so they remain safe under the module's runspace model. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> class IcingaPerformanceCounter { diff --git a/src/Classes/Icinga/IcingaPlugin.ps1 b/src/Classes/Icinga/IcingaPlugin.ps1 index d8d3f67..3693a4d 100644 --- a/src/Classes/Icinga/IcingaPlugin.ps1 +++ b/src/Classes/Icinga/IcingaPlugin.ps1 @@ -62,6 +62,9 @@ Functions create instances only through New-IcingaPlugin, never with 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. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> class IcingaPlugin { @@ -134,9 +137,9 @@ class IcingaPlugin aggregates child checks added with AddCheck. .PARAMETER Name - | Name | Type | Description | Default | - |------|---------------|--------------------------------------|---------| - | Name | System.String | Display name of the plugin node. | | + | Name | Type | Description | Default | + |------|---------------|----------------------------------|---------| + | Name | System.String | Display name of the plugin node. | | .OUTPUTS IcingaPlugin -- Configured plugin node. @@ -162,14 +165,14 @@ class IcingaPlugin afterwards through the fluent setters and comparison methods. .PARAMETER Name - | Name | Type | Description | Default | - |------|---------------|-----------------------------------|---------| - | Name | System.String | Display name of the check. | | + | 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 ''. | | + | Name | Type | Description | Default | + |-------|---------------|---------------------------------------------|---------| + | Value | System.Object | Measured value; number or ''. | | .OUTPUTS IcingaPlugin -- Configured plugin node. @@ -196,19 +199,19 @@ class IcingaPlugin threshold comparison. .PARAMETER Name - | Name | Type | Description | Default | - |------|---------------|-----------------------------------|---------| - | Name | System.String | Display name of the check. | | + | 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 ''. | | + | 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. | | + | Name | Type | Description | Default | + |------|---------------|-----------------------------------|---------| + | Unit | System.String | Icinga unit appended to perfdata. | | .OUTPUTS IcingaPlugin -- Configured plugin node. @@ -234,19 +237,19 @@ class IcingaPlugin a single helper so every constructor overload behaves identically. .PARAMETER Name - | Name | Type | Description | Default | - |------|---------------|--------------------------------|---------| - | Name | System.String | Display name of the node. | | + | 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. | | + | Name | Type | Description | Default | + |-------|---------------|--------------------------|---------| + | Value | System.Object | Measured value or $null. | | .PARAMETER Unit - | Name | Type | Description | Default | - |------|---------------|--------------------|---------| - | Unit | System.String | Icinga unit. | | + | Name | Type | Description | Default | + |------|---------------|--------------|---------| + | Unit | System.String | Icinga unit. | | .OUTPUTS None -- Updates instance state. @@ -286,9 +289,9 @@ class IcingaPlugin CheckGreater, ...) is called. .PARAMETER Warning - | Name | Type | Description | Default | - |---------|---------------|------------------------------------------|---------| - | Warning | System.String | Warning threshold string ('' = unset). | | + | Name | Type | Description | Default | + |---------|---------------|----------------------------------------|---------| + | Warning | System.String | Warning threshold string ('' = unset). | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -319,9 +322,9 @@ class IcingaPlugin comma-separated display string in WarningThreshold. .PARAMETER Warning - | Name | Type | Description | Default | - |---------|--------------|-------------------------------------------------|---------| - | Warning | System.Array | Array of warning threshold values or patterns. | | + | Name | Type | Description | Default | + |---------|--------------|------------------------------------------------|---------| + | Warning | System.Array | Array of warning threshold values or patterns. | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -361,9 +364,9 @@ class IcingaPlugin through an untyped variable. .PARAMETER Warning - | Name | Type | Description | Default | - |---------|---------------|--------------------------------------------------|---------| - | Warning | System.Object | Warning threshold value (number, enum, TimeSpan).| | + | Name | Type | Description | Default | + |---------|---------------|---------------------------------------------------|---------| + | Warning | System.Object | Warning threshold value (number, enum, TimeSpan). | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -427,9 +430,9 @@ class IcingaPlugin comma-separated display string in CriticalThreshold. .PARAMETER Critical - | Name | Type | Description | Default | - |----------|--------------|--------------------------------------------------|---------| - | Critical | System.Array | Array of critical threshold values or patterns. | | + | Name | Type | Description | Default | + |----------|--------------|-------------------------------------------------|---------| + | Critical | System.Array | Array of critical threshold values or patterns. | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -469,9 +472,9 @@ class IcingaPlugin through an untyped variable. .PARAMETER Critical - | Name | Type | Description | Default | - |----------|---------------|---------------------------------------------------|---------| - | Critical | System.Object | Critical threshold value (number, enum, TimeSpan).| | + | Name | Type | Description | Default | + |----------|---------------|----------------------------------------------------|---------| + | Critical | System.Object | Critical threshold value (number, enum, TimeSpan). | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -504,9 +507,9 @@ class IcingaPlugin other non-null values use their string representation. .PARAMETER Entry - | Name | Type | Description | Default | - |-------|---------------|------------------------------------|---------| - | Entry | System.Object | Threshold list item to normalize. | | + | Name | Type | Description | Default | + |-------|---------------|-----------------------------------|---------| + | Entry | System.Object | Threshold list item to normalize. | | .OUTPUTS System.String -- Normalized threshold string, or '' when null. @@ -583,9 +586,9 @@ class IcingaPlugin data. Accepts a number or string; does not influence the threshold evaluation. .PARAMETER Minimum - | Name | Type | Description | Default | - |---------|---------------|-------------------------------------|---------| - | Minimum | System.Object | Perfdata minimum ('' = unset). | | + | Name | Type | Description | Default | + |---------|---------------|--------------------------------|---------| + | Minimum | System.Object | Perfdata minimum ('' = unset). | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -620,9 +623,9 @@ class IcingaPlugin data. Accepts a number or string; does not influence the threshold evaluation. .PARAMETER Maximum - | Name | Type | Description | Default | - |---------|---------------|-------------------------------------|---------| - | Maximum | System.Object | Perfdata maximum ('' = unset). | | + | Name | Type | Description | Default | + |---------|---------------|--------------------------------|---------| + | Maximum | System.Object | Perfdata maximum ('' = unset). | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -658,9 +661,9 @@ class IcingaPlugin IcingaThresholds when a comparison method is called. .PARAMETER BaseValue - | Name | Type | Description | Default | - |-----------|---------------|------------------------------------------------|---------| - | BaseValue | System.Object | Base/maximum value; number or unit string. | | + | Name | Type | Description | Default | + |-----------|---------------|--------------------------------------------|---------| + | BaseValue | System.Object | Base/maximum value; number or unit string. | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -692,9 +695,9 @@ class IcingaPlugin 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. | | + | Name | Type | Description | Default | + |-------|---------------|-------------------------------------|---------| + | Index | System.String | Metric index / instance identifier. | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -810,9 +813,9 @@ class IcingaPlugin numeric value in the performance data. .PARAMETER Translation - | Name | Type | Description | Default | - |-------------|------------------------------|------------------------------------------------|---------| - | Translation | System.Collections.Hashtable | Mapping of raw values to display strings. | | + | Name | Type | Description | Default | + |-------------|------------------------------|-------------------------------------------|---------| + | Translation | System.Collections.Hashtable | Mapping of raw values to display strings. | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -844,9 +847,9 @@ class IcingaPlugin performance data. .PARAMETER Text - | Name | Type | Description | Default | - |------|---------------|--------------------------------------------------|---------| - | Text | System.String | Human-readable display representation of Value. | | + | Name | Type | Description | Default | + |------|---------------|-------------------------------------------------|---------| + | Text | System.String | Human-readable display representation of Value. | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -872,9 +875,9 @@ class IcingaPlugin 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). | | + | Name | Type | Description | Default | + |---------|--------------|-------------------------|---------| + | Verbose | System.Int32 | Verbosity level (0..3). | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -921,9 +924,9 @@ class IcingaPlugin 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. | | + | Name | Type | Description | Default | + |------------|----------------|---------------------------------------|---------| + | NoPerfData | System.Boolean | When true, suppress performance data. | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -970,9 +973,9 @@ class IcingaPlugin 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. | | + | Name | Type | Description | Default | + |--------|----------------|---------------------------------------|---------| + | Hidden | System.Boolean | When true, hide the node from output. | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -1020,9 +1023,9 @@ class IcingaPlugin 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. | | + | Name | Type | Description | Default | + |--------|----------------|---------------------------------------------|---------| + | Ignore | System.Boolean | When true, an empty package resolves to OK. | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -1069,9 +1072,9 @@ class IcingaPlugin 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. | | + | Name | Type | Description | Default | + |-----------|----------------|----------------------------------------|---------| + | AddHeader | System.Boolean | When true, include the summary header. | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -1119,9 +1122,9 @@ class IcingaPlugin 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. | | + | Name | Type | Description | Default | + |------|----------------|----------------------------------------------------|---------| + | Skip | System.Boolean | When true, omit from the container summary header. | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -1510,9 +1513,9 @@ class IcingaPlugin ResolveTranslation when a translation applies. .PARAMETER List - | Name | Type | Description | Default | - |------|--------------|-------------------------------------------|---------| - | List | System.Array | Multi-value threshold list on the node. | | + | Name | Type | Description | Default | + |------|--------------|-----------------------------------------|---------| + | List | System.Array | Multi-value threshold list on the node. | | .PARAMETER Fallback | Name | Type | Description | Default | @@ -1563,9 +1566,9 @@ class IcingaPlugin pattern string, or $null when no entry matches. .PARAMETER InputValue - | Name | Type | Description | Default | - |------------|---------------|------------------------------|---------| - | InputValue | System.String | String value to test. | | + | Name | Type | Description | Default | + |------------|---------------|-----------------------|---------| + | InputValue | System.String | String value to test. | | .PARAMETER Patterns | Name | Type | Description | Default | @@ -1831,9 +1834,9 @@ class IcingaPlugin translation applies. .PARAMETER Item - | Name | Type | Description | Default | - |------|---------------|------------------------------------|---------| - | Item | System.Object | Value or threshold token to map. | | + | Name | Type | Description | Default | + |------|---------------|----------------------------------|---------| + | Item | System.Object | Value or threshold token to map. | | .OUTPUTS System.String -- Translated display string, or $null when none applies. @@ -1926,9 +1929,9 @@ class IcingaPlugin unchanged. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|------------------------------------------|---------| - | Value | System.Object | Measured value or base value to adjust. | | + | 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. @@ -2041,9 +2044,9 @@ class IcingaPlugin 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. | | + | Name | Type | Description | Default | + |---------|---------------|---------------------------------------|---------| + | Message | System.String | Output message after unit formatting. | | .OUTPUTS System.String -- Message with the translated value applied when configured. @@ -2093,9 +2096,9 @@ class IcingaPlugin percentages are left untouched. .PARAMETER Message - | Name | Type | Description | Default | - |---------|---------------|--------------------------------|---------| - | Message | System.String | The threshold output 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. @@ -2139,9 +2142,9 @@ class IcingaPlugin percentages are left untouched. .PARAMETER Message - | Name | Type | Description | Default | - |---------|---------------|--------------------------------|---------| - | Message | System.String | The threshold output message. | | + | Name | Type | Description | Default | + |---------|---------------|-------------------------------|---------| + | Message | System.String | The threshold output message. | | .OUTPUTS System.String -- The message with second figures converted to durations. @@ -2187,9 +2190,9 @@ class IcingaPlugin counter perfdata unit 'c' is not appended to display text. .PARAMETER Message - | Name | Type | Description | Default | - |---------|---------------|--------------------------------|---------| - | Message | System.String | The threshold output message. | | + | Name | Type | Description | Default | + |---------|---------------|-------------------------------|---------| + | Message | System.String | The threshold output message. | | .OUTPUTS System.String -- The message with the unit appended to each bare number. @@ -2292,9 +2295,9 @@ class IcingaPlugin 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). | | + | Name | Type | Description | Default | + |-------|--------------|----------------------------------------------|---------| + | State | System.Int32 | Forced state (0 OK, 1 WARN, 2 CRIT, 3 UNKN). | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -2319,14 +2322,14 @@ class IcingaPlugin 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). | | + | 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. | | + | Name | Type | Description | Default | + |---------|---------------|------------------------------------------------|---------| + | Message | System.String | Output message; '' keeps the existing message. | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -2354,14 +2357,14 @@ class IcingaPlugin 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). | | + | 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. | | + | Name | Type | Description | Default | + |---------|---------------|------------------------------------------------|---------| + | Message | System.String | Output message; '' keeps the existing message. | | .PARAMETER Lock | Name | Type | Description | Default | @@ -2436,9 +2439,9 @@ class IcingaPlugin | State | System.String | Forced state ('Ok', 'Warning', 'Critical', 'Unknown'). | | .PARAMETER Message - | Name | Type | Description | Default | - |---------|---------------|--------------------------------------------------|---------| - | Message | System.String | Output message; '' keeps the existing message. | | + | Name | Type | Description | Default | + |---------|---------------|------------------------------------------------|---------| + | Message | System.String | Output message; '' keeps the existing message. | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -2469,9 +2472,9 @@ class IcingaPlugin | State | System.String | Forced state ('Ok', 'Warning', 'Critical', 'Unknown'). | | .PARAMETER Message - | Name | Type | Description | Default | - |---------|---------------|--------------------------------------------------|---------| - | Message | System.String | Output message; '' keeps the existing message. | | + | Name | Type | Description | Default | + |---------|---------------|------------------------------------------------|---------| + | Message | System.String | Output message; '' keeps the existing message. | | .PARAMETER Lock | Name | Type | Description | Default | @@ -2522,9 +2525,9 @@ class IcingaPlugin 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. | | + | Name | Type | Description | Default | + |---------|---------------|----------------------------------|---------| + | Message | System.String | Output message for the OK state. | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -2549,14 +2552,14 @@ class IcingaPlugin freezes the state against later changes. .PARAMETER Message - | Name | Type | Description | Default | - |---------|---------------|------------------------------------|---------| - | Message | System.String | Output message for the OK state. | | + | 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. | | + | Name | Type | Description | Default | + |------|----------------|------------------------------|---------| + | Lock | System.Boolean | When true, freeze the state. | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -2602,9 +2605,9 @@ class IcingaPlugin 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. | | + | Name | Type | Description | Default | + |---------|---------------|---------------------------------------|---------| + | Message | System.String | Output message for the WARNING state. | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -2629,14 +2632,14 @@ class IcingaPlugin true, freezes the state against later changes. .PARAMETER Message - | Name | Type | Description | Default | - |---------|---------------|----------------------------------------|---------| - | Message | System.String | Output message for the WARNING state. | | + | 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. | | + | Name | Type | Description | Default | + |------|----------------|------------------------------|---------| + | Lock | System.Boolean | When true, freeze the state. | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -2682,9 +2685,9 @@ class IcingaPlugin 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. | | + | Name | Type | Description | Default | + |---------|---------------|----------------------------------------|---------| + | Message | System.String | Output message for the CRITICAL state. | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -2709,14 +2712,14 @@ class IcingaPlugin true, freezes the state against later changes. .PARAMETER Message - | Name | Type | Description | Default | - |---------|---------------|-----------------------------------------|---------| - | Message | System.String | Output message for the CRITICAL state. | | + | 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. | | + | Name | Type | Description | Default | + |------|----------------|------------------------------|---------| + | Lock | System.Boolean | When true, freeze the state. | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -2762,9 +2765,9 @@ class IcingaPlugin 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. | | + | Name | Type | Description | Default | + |---------|---------------|---------------------------------------|---------| + | Message | System.String | Output message for the UNKNOWN state. | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -2789,14 +2792,14 @@ class IcingaPlugin true, freezes the state against later changes. .PARAMETER Message - | Name | Type | Description | Default | - |---------|---------------|----------------------------------------|---------| - | Message | System.String | Output message for the UNKNOWN state. | | + | 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. | | + | Name | Type | Description | Default | + |------|----------------|------------------------------|---------| + | Lock | System.Boolean | When true, freeze the state. | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -2823,9 +2826,9 @@ class IcingaPlugin 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. | | + | Name | Type | Description | Default | + |---------|---------------|------------------------|---------| + | Message | System.String | Error message to show. | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -2855,9 +2858,9 @@ class IcingaPlugin | Message | System.String | Format string with a '{0}' placeholder. | | .PARAMETER Argument - | Name | Type | Description | Default | - |----------|---------------|--------------------------------|---------| - | Argument | System.Object | Value inserted for '{0}'. | | + | Name | Type | Description | Default | + |----------|---------------|---------------------------|---------| + | Argument | System.Object | Value inserted for '{0}'. | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -2882,9 +2885,9 @@ class IcingaPlugin 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}'. | | + | Name | Type | Description | Default | + |---------|---------------|-------------------------------------|---------| + | Message | System.String | Format string with '{0}' and '{1}'. | | .PARAMETER Argument1 | Name | Type | Description | Default | @@ -2919,9 +2922,9 @@ class IcingaPlugin 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}'. | | + | Name | Type | Description | Default | + |---------|---------------|-----------------------------------------|---------| + | Message | System.String | Format string with '{0}', '{1}', '{2}'. | | .PARAMETER Argument1 | Name | Type | Description | Default | @@ -2993,9 +2996,9 @@ class IcingaPlugin 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. | | + | Name | Type | Description | Default | + |-------------|-------------|--------------------------------------|---------| + | IcingaError | IcingaError | Error returned by a data collection. | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -3025,9 +3028,9 @@ class IcingaPlugin locked keeps its state and message. .PARAMETER Message - | Name | Type | Description | Default | - |---------|---------------|-------------------------|---------| - | Message | System.String | Final error message. | | + | Name | Type | Description | Default | + |---------|---------------|----------------------|---------| + | Message | System.String | Final error message. | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -3116,9 +3119,9 @@ class IcingaPlugin | Message | System.String | Informational message to display. | | .PARAMETER Lock - | Name | Type | Description | Default | - |------|----------------|--------------------------------|---------| - | Lock | System.Boolean | When true, freeze the node. | | + | Name | Type | Description | Default | + |------|----------------|-----------------------------|---------| + | Lock | System.Boolean | When true, freeze the node. | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -3273,9 +3276,9 @@ class IcingaPlugin 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. | | + | Name | Type | Description | Default | + |-------|--------------|--------------------------------------------|---------| + | Count | System.Int32 | Maximum number of children that may be OK. | | .OUTPUTS IcingaPlugin -- The same node, for chaining. @@ -3302,9 +3305,9 @@ class IcingaPlugin Returns this container so multiple AddCheck calls chain. .PARAMETER Check - | Name | Type | Description | Default | - |-------|--------------|--------------------------------|---------| - | Check | IcingaPlugin | Child plugin to add. | | + | Name | Type | Description | Default | + |-------|--------------|----------------------|---------| + | Check | IcingaPlugin | Child plugin to add. | | .OUTPUTS IcingaPlugin -- This container, for chaining. @@ -3339,9 +3342,9 @@ class IcingaPlugin container so the call chains. .PARAMETER Checks - | Name | Type | Description | Default | - |--------|--------------|-------------------------------|---------| - | Checks | System.Array | Child plugins to add. | | + | Name | Type | Description | Default | + |--------|--------------|-----------------------|---------| + | Checks | System.Array | Child plugins to add. | | .OUTPUTS IcingaPlugin -- This container, for chaining. @@ -3454,9 +3457,9 @@ class IcingaPlugin | 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. | | + | Name | Type | Description | Default | + |------------------|---------------|---------------------------------------------------|---------| + | NormalizePattern | System.String | Regex removed from each entry; '' keeps it as is. | | .OUTPUTS IcingaPlugin -- This container, for chaining. @@ -3526,9 +3529,9 @@ class IcingaPlugin | Message | System.String | Output message of every missing check. | | .PARAMETER State - | Name | Type | Description | Default | - |-------|---------------|-----------------------------------------------------------|---------| - | State | System.String | State name ('Ok', 'Warning', 'Critical', 'Unknown'). | | + | Name | Type | Description | Default | + |-------|---------------|------------------------------------------------------|---------| + | State | System.String | State name ('Ok', 'Warning', 'Critical', 'Unknown'). | | .OUTPUTS IcingaPlugin -- This container, for chaining. @@ -3573,14 +3576,14 @@ class IcingaPlugin | Message | System.String | Output message of every missing check. | | .PARAMETER State - | Name | Type | Description | Default | - |-------|---------------|-----------------------------------------------------------|---------| - | State | System.String | State name ('Ok', 'Warning', 'Critical', 'Unknown'). | | + | 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. | | + | Name | Type | Description | Default | + |------------------|---------------|---------------------------------------------------|---------| + | NormalizePattern | System.String | Regex removed from each entry; '' keeps it as is. | | .OUTPUTS IcingaPlugin -- This container, for chaining. @@ -3605,9 +3608,9 @@ class IcingaPlugin wildcard pattern. An invalid pattern matches nothing instead of throwing. .PARAMETER Entries - | Name | Type | Description | Default | - |---------|--------------|-----------------------|---------| - | Entries | System.Array | Entries to compare. | | + | Name | Type | Description | Default | + |---------|--------------|---------------------|---------| + | Entries | System.Array | Entries to compare. | | .PARAMETER Pattern | Name | Type | Description | Default | @@ -4055,9 +4058,9 @@ class IcingaPlugin 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. | | + | Name | Type | Description | Default | + |-----------|--------------|------------------------|---------| + | Indention | System.Int32 | Zero-based tree depth. | | .OUTPUTS System.String -- The indentation prefix. @@ -4378,9 +4381,9 @@ class IcingaPlugin 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.| | + | Name | Type | Description | Default | + |------|---------------|-------------------------------|---------| + | Item | System.Object | Value to resolve numerically. | | .OUTPUTS System.Object -- The numeric representation, or the original value. @@ -4429,14 +4432,14 @@ class IcingaPlugin data by returning an empty string. .PARAMETER Threshold - | Name | Type | Description | Default | - |-----------|---------------|------------------------------------|---------| - | Threshold | System.String | Configured threshold string. | | + | Name | Type | Description | Default | + |-----------|---------------|------------------------------|---------| + | Threshold | System.String | Configured threshold string. | | .PARAMETER Resolved - | Name | Type | Description | Default | - |----------|---------------|------------------------------------|---------| - | Resolved | System.String | Threshold resolved by comparison. | | + | Name | Type | Description | Default | + |----------|---------------|-----------------------------------|---------| + | Resolved | System.String | Threshold resolved by comparison. | | .OUTPUTS System.String -- Numeric Icinga threshold string, or '' when non-numeric. @@ -4588,9 +4591,9 @@ class IcingaPlugin 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. | | + | Name | Type | Description | Default | + |-------|---------------|-------------------------|---------| + | Value | System.String | The raw metric segment. | | .OUTPUTS System.String -- The sanitized, lower-cased segment. @@ -4730,9 +4733,9 @@ class IcingaPlugin performance data. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|---------------------------|---------| - | Value | System.Object | Value to test. | | + | Name | Type | Description | Default | + |-------|---------------|----------------|---------| + | Value | System.Object | Value to test. | | .OUTPUTS System.Boolean -- True when the value is numeric. @@ -4764,9 +4767,9 @@ class IcingaPlugin value is not numeric. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|---------------------------|---------| - | Value | System.Object | Value to format. | | + | Name | Type | Description | Default | + |-------|---------------|------------------|---------| + | Value | System.Object | Value to format. | | .OUTPUTS System.String -- The formatted value. @@ -4803,14 +4806,14 @@ class IcingaPlugin this and leaves the result in the thread-local runtime state. .PARAMETER Output - | Name | Type | Description | Default | - |--------|---------------|------------------------------|---------| - | Output | System.String | Rendered plugin output. | | + | Name | Type | Description | Default | + |--------|---------------|-------------------------|---------| + | Output | System.String | Rendered plugin output. | | .PARAMETER Perf - | Name | Type | Description | Default | - |------|--------------|--------------------------------------|---------| - | Perf | System.Array | Performance-data metric strings. | | + | Name | Type | Description | Default | + |------|--------------|----------------------------------|---------| + | Perf | System.Array | Performance-data metric strings. | | .OUTPUTS None -- Writes to the console. diff --git a/src/Classes/Icinga/IcingaThresholds.ps1 b/src/Classes/Icinga/IcingaThresholds.ps1 index 5593539..932ddd9 100644 --- a/src/Classes/Icinga/IcingaThresholds.ps1 +++ b/src/Classes/Icinga/IcingaThresholds.ps1 @@ -23,7 +23,7 @@ failure through Success and a semantic ReturnCode instead. All bound arithmetic uses [decimal] for precision and open ends are stored as [double] infinities. .OUTPUTS -IcingaThresholdRange — Value object describing the parsed range. +IcingaThresholdRange -- Value object describing the parsed range. .EXAMPLE PS> [IcingaThresholdRange]::new('10:20', 0, $false) @@ -39,23 +39,26 @@ Resolves 90% of the base value 1000 into the upper bound 900. Self-contained value object. Does not modify global state or access external services. Reuses the IcingaUnit class for unit-carrying bounds. Safe to construct in multi-threaded runspaces. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> class IcingaThresholdRange { - hidden [string]$Threshold = ''; - hidden [bool]$IsSet = $false; - hidden [bool]$Inverted = $false; - hidden [double]$Start = 0; - hidden [double]$End = 0; - hidden [string]$StartUnit = ''; - hidden [string]$EndUnit = ''; - hidden [string]$StartPercent = ''; - hidden [string]$EndPercent = ''; - hidden [string]$Family = ''; - hidden [bool]$Success = $false; - hidden [string]$ReturnCode = ''; - hidden [double]$BaseValue = 0; - hidden [bool]$HasBaseValue = $false; + hidden [string]$Threshold = ''; + hidden [bool]$IsSet = $false; + hidden [bool]$Inverted = $false; + hidden [double]$Start = 0; + hidden [double]$End = 0; + hidden [string]$StartUnit = ''; + hidden [string]$EndUnit = ''; + hidden [string]$StartPercent = ''; + hidden [string]$EndPercent = ''; + hidden [string]$Family = ''; + hidden [bool]$Success = $false; + hidden [string]$ReturnCode = ''; + hidden [double]$BaseValue = 0; + hidden [bool]$HasBaseValue = $false; static hidden [regex]$PercentRegex = [regex]::new('^\s*(-?\d+(?:[.,]\d+)?)\s*%\s*$', [System.Text.RegularExpressions.RegexOptions]::Compiled); static hidden [regex]$NumberRegex = [regex]::new('^\s*(-?\d+(?:[.,]\d+)?)\s*$', [System.Text.RegularExpressions.RegexOptions]::Compiled); @@ -71,22 +74,22 @@ class IcingaThresholdRange records a failure via Success and ReturnCode instead of throwing. .PARAMETER Threshold - | Name | Type | Description | Default | - |-----------|---------------|------------------------------------------------------------|---------| - | Threshold | System.String | Threshold range string, e.g. '10', '10:', '~:10', '@10:20'.| | + | Name | Type | Description | Default | + |-----------|---------------|-------------------------------------------------------------|---------| + | Threshold | System.String | Threshold range string, e.g. '10', '10:', '~:10', '@10:20'. | | .PARAMETER BaseValue - | Name | Type | Description | Default | - |-----------|----------------|---------------------------------------------------------|---------| - | BaseValue | System.Double | Base value that percent bounds are resolved against. | | + | Name | Type | Description | Default | + |-----------|---------------|------------------------------------------------------|---------| + | BaseValue | System.Double | Base value that percent bounds are resolved against. | | .PARAMETER HasBaseValue - | Name | Type | Description | Default | - |--------------|----------------|----------------------------------------------------|---------| - | HasBaseValue | System.Boolean | Whether a base value was supplied for percent math.| | + | Name | Type | Description | Default | + |--------------|----------------|-----------------------------------------------------|---------| + | HasBaseValue | System.Boolean | Whether a base value was supplied for percent math. | | .OUTPUTS - IcingaThresholdRange — Configured range instance with Success and ReturnCode. + IcingaThresholdRange -- Configured range instance with Success and ReturnCode. .EXAMPLE PS> [IcingaThresholdRange]::new('~:10', 0, $false) @@ -110,7 +113,7 @@ class IcingaThresholdRange $this.Threshold = $Threshold; $this.IsSet = $true; - [string]$Body = $Threshold.Trim(); + [string]$Body = $Threshold.Trim(); # A leading '@' inverts the range: alert when the value is inside the # bounds instead of outside them. @@ -190,24 +193,24 @@ class IcingaThresholdRange number is taken as-is in the smallest/base unit. Any other token is rejected. .PARAMETER Token - | Name | Type | Description | Default | - |-------|---------------|--------------------------------------|---------| - | Token | System.String | Single bound token to resolve. | | + | Name | Type | Description | Default | + |-------|---------------|--------------------------------|---------| + | Token | System.String | Single bound token to resolve. | | .PARAMETER Result - | Name | Type | Description | Default | - |--------|----------------------------------|----------------------------------------------|---------| - | Result | System.Management.Automation.PSReference | Receives the resolved numeric bound value. | | + | Name | Type | Description | Default | + |--------|------------------------------------------|--------------------------------------------|---------| + | Result | System.Management.Automation.PSReference | Receives the resolved numeric bound value. | | .PARAMETER Family - | Name | Type | Description | Default | - |--------|------------------------------------------|--------------------------------------------------------|---------| - | Family | System.Management.Automation.PSReference | Receives the unit family ('Data'/'Time'), '' when none.| | + | Name | Type | Description | Default | + |--------|------------------------------------------|---------------------------------------------------------|---------| + | Family | System.Management.Automation.PSReference | Receives the unit family ('Data'/'Time'), '' when none. | | .PARAMETER Unit - | Name | Type | Description | Default | - |------|------------------------------------------|---------------------------------------------------|---------| - | Unit | System.Management.Automation.PSReference | Receives the original unit token, '' when none. | | + | Name | Type | Description | Default | + |------|------------------------------------------|-------------------------------------------------|---------| + | Unit | System.Management.Automation.PSReference | Receives the original unit token, '' when none. | | .PARAMETER PercentToken | Name | Type | Description | Default | @@ -215,7 +218,7 @@ class IcingaThresholdRange | PercentToken | System.Management.Automation.PSReference | Receives the original percent token, '' when none. | | .OUTPUTS - System.Boolean — $true on success, $false when the bound could not be resolved. + System.Boolean -- $true on success, $false when the bound could not be resolved. .EXAMPLE PS> $this.ParseBound('100MB', [ref]$value, [ref]$family, [ref]$unit, [ref]$percent) @@ -231,7 +234,7 @@ class IcingaThresholdRange $Unit.Value = ''; $PercentToken.Value = ''; - [string]$Trimmed = $Token.Trim(); + [string]$Trimmed = $Token.Trim(); if ([string]::IsNullOrEmpty($Trimmed)) { $this.Fail('IcingaThresholdInvalidBound'); @@ -294,12 +297,12 @@ class IcingaThresholdRange raises an alert. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|----------------------------------------------|---------| - | Value | System.Double | Measured value in base units to evaluate. | | + | Name | Type | Description | Default | + |-------|---------------|-------------------------------------------|---------| + | Value | System.Double | Measured value in base units to evaluate. | | .OUTPUTS - System.Boolean — $true when the value is in the alert region, otherwise $false. + System.Boolean -- $true when the value is in the alert region, otherwise $false. .EXAMPLE PS> $range.InAlertRange(15) @@ -331,7 +334,7 @@ class IcingaThresholdRange parsed range renders back into exactly the same notation it was given. .OUTPUTS - System.String — The original threshold string ('' for an unset range). + System.String -- The original threshold string ('' for an unset range). .EXAMPLE PS> $range.ToString() @@ -355,7 +358,7 @@ class IcingaThresholdRange invariant culture and open ends are omitted. An unset range returns ''. .OUTPUTS - System.String — The alert condition, or '' when the range is unset. + System.String -- The alert condition, or '' when the range is unset. .EXAMPLE PS> $range.ToAlertString() @@ -385,7 +388,7 @@ class IcingaThresholdRange | EffectiveFamily | System.String | Family of the compared quantity ('Data'/'Time'), '' when none. | | .OUTPUTS - System.String — The alert condition, or '' when the range is unset. + System.String -- The alert condition, or '' when the range is unset. .EXAMPLE PS> $range.ToAlertString('Data') @@ -449,7 +452,7 @@ class IcingaThresholdRange warning/critical fields of a plugin result. An unset range returns ''. .OUTPUTS - System.String — The resolved range string, or '' when the range is unset. + System.String -- The resolved range string, or '' when the range is unset. .EXAMPLE PS> $range.ToBaseThresholdString() @@ -475,12 +478,12 @@ class IcingaThresholdRange such as '15GiB:' is covered too. .PARAMETER EffectiveFamily - | Name | Type | Description | Default | - |-----------------|---------------|-----------------------------------------------------------------|---------| - | EffectiveFamily | System.String | Family of the compared quantity ('Data'/'Time'), '' when none. | | + | Name | Type | Description | Default | + |-----------------|---------------|----------------------------------------------------------------|---------| + | EffectiveFamily | System.String | Family of the compared quantity ('Data'/'Time'), '' when none. | | .OUTPUTS - System.String — The resolved range string, or '' when the range is unset. + System.String -- The resolved range string, or '' when the range is unset. .EXAMPLE PS> $range.ToBaseThresholdString('Data') @@ -535,12 +538,12 @@ class IcingaThresholdRange error code in ReturnCode for downstream error propagation. .PARAMETER Code - | Name | Type | Description | Default | - |------|---------------|----------------------------------------------|---------| - | Code | System.String | Semantic return code identifying the failure.| | + | Name | Type | Description | Default | + |------|---------------|-----------------------------------------------|---------| + | Code | System.String | Semantic return code identifying the failure. | | .OUTPUTS - None — Updates instance state. + None -- Updates instance state. .EXAMPLE PS> $this.Fail('IcingaThresholdInvalidBound') @@ -561,7 +564,7 @@ class IcingaThresholdRange .DESCRIPTION Returns the single-character base-unit symbol for a resolved unit family: 'B' for the Data family (bytes) and 's' for the Time family (seconds). Any other - family — including the empty family of a plain number — yields an empty string + family -- including the empty family of a plain number -- yields an empty string so that unit-less values render without a suffix. .PARAMETER Family @@ -570,7 +573,7 @@ class IcingaThresholdRange | Family | System.String | Resolved unit family ('Data' or 'Time'). | | .OUTPUTS - System.String — The base-unit symbol, or '' when the family is unknown/unset. + System.String -- The base-unit symbol, or '' when the family is unknown/unset. .EXAMPLE PS> [IcingaThresholdRange]::UnitSymbol('Data') @@ -598,8 +601,8 @@ class IcingaThresholdRange Bytes are indivisible, so a Data-family value must never carry a fractional part in a rendered result field even when it was derived from a fractional unit (for example '254.55GiB') or from percentage arithmetic. This rounds a Data-family value to the - nearest whole base unit and returns every other family — including sub-second Time - values and unit-less numbers — unchanged, preserving their precision. + nearest whole base unit and returns every other family -- including sub-second Time + values and unit-less numbers -- unchanged, preserving their precision. .PARAMETER Value | Name | Type | Description | Default | @@ -612,7 +615,7 @@ class IcingaThresholdRange | Family | System.String | Resolved unit family ('Data' or 'Time'). | | .OUTPUTS - System.Double — The value rounded to a whole number for 'Data', otherwise unchanged. + System.Double -- The value rounded to a whole number for 'Data', otherwise unchanged. .EXAMPLE PS> [IcingaThresholdRange]::RoundBaseValue(273320981299.2, 'Data') @@ -641,9 +644,9 @@ class IcingaThresholdRange numbers and percent-resolved values. Used for the InputValue result field. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|--------------------------------------|---------| - | Value | System.Double | Value already scaled to base units. | | + | Name | Type | Description | Default | + |-------|---------------|-------------------------------------|---------| + | Value | System.Double | Value already scaled to base units. | | .PARAMETER Family | Name | Type | Description | Default | @@ -651,7 +654,7 @@ class IcingaThresholdRange | Family | System.String | Resolved unit family ('Data' or 'Time'). | | .OUTPUTS - System.String — The base value with its base-unit symbol, e.g. '19000000B'. + System.String -- The base value with its base-unit symbol, e.g. '19000000B'. .EXAMPLE PS> [IcingaThresholdRange]::FormatBase(19000000, 'Data') @@ -679,9 +682,9 @@ class IcingaThresholdRange bare number if the conversion fails. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|--------------------------------------|---------| - | Value | System.Double | Value already scaled to base units. | | + | Name | Type | Description | Default | + |-------|---------------|-------------------------------------|---------| + | Value | System.Double | Value already scaled to base units. | | .PARAMETER Family | Name | Type | Description | Default | @@ -694,7 +697,7 @@ class IcingaThresholdRange | Unit | System.String | Original unit token to render the value in. | | .OUTPUTS - System.String — The value rendered in its original unit, e.g. '10MB' or '6h'. + System.String -- The value rendered in its original unit, e.g. '10MB' or '6h'. .EXAMPLE PS> [IcingaThresholdRange]::FormatBest(10000000, 'Data', 'MB') @@ -729,15 +732,15 @@ Result of evaluating a measured value against an IcingaThresholds definition .DESCRIPTION IcingaThresholdResult is the value object every IcingaThresholds comparison method returns. It carries the measured value together with the warning and critical -thresholds it was compared against — for numeric comparisons these are expressed -in the smallest (base) unit, for pattern comparisons they hold the raw strings — +thresholds it was compared against -- for numeric comparisons these are expressed +in the smallest (base) unit, for pattern comparisons they hold the raw strings -- plus the resulting Icinga plugin state code and a short, user-friendly output message describing why that state was chosen. When the threshold was created with a base value, BaseValue additionally carries that resolved base (its maximum) in the smallest unit; otherwise it is $null. .OUTPUTS -IcingaThresholdResult — Value object describing a single evaluation. +IcingaThresholdResult -- Value object describing a single evaluation. .EXAMPLE PS> [IcingaThresholdResult]::new(950, 800, 900, 2, 'value 950 is greater than critical threshold 900') @@ -747,6 +750,9 @@ Creates a critical result for a value that exceeded the critical threshold. .NOTES Self-contained value object. Does not modify global state or access external services. Safe to construct in multi-threaded runspaces. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> class IcingaThresholdResult { @@ -772,19 +778,19 @@ class IcingaThresholdResult | InputValue | System.Object | Measured value in the smallest unit, or the raw input. | | .PARAMETER WarningValue - | Name | Type | Description | Default | - |--------------|---------------|------------------------------------------------------|---------| - | WarningValue | System.Object | Warning threshold (smallest unit or pattern), or $null.| | + | Name | Type | Description | Default | + |--------------|---------------|---------------------------------------------------------|---------| + | WarningValue | System.Object | Warning threshold (smallest unit or pattern), or $null. | | .PARAMETER CriticalValue - | Name | Type | Description | Default | - |---------------|---------------|--------------------------------------------------------|---------| - | CriticalValue | System.Object | Critical threshold (smallest unit or pattern), or $null.| | + | Name | Type | Description | Default | + |---------------|---------------|----------------------------------------------------------|---------| + | CriticalValue | System.Object | Critical threshold (smallest unit or pattern), or $null. | | .PARAMETER StatusCode - | Name | Type | Description | Default | - |------------|--------------|---------------------------------------------------|---------| - | StatusCode | System.Int32 | Icinga plugin state: 0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN. | | + | Name | Type | Description | Default | + |------------|--------------|--------------------------------------------------------------|---------| + | StatusCode | System.Int32 | Icinga plugin state: 0 OK, 1 WARNING, 2 CRITICAL, 3 UNKNOWN. | | .PARAMETER Output | Name | Type | Description | Default | @@ -792,7 +798,7 @@ class IcingaThresholdResult | Output | System.String | Human-readable description of the result state. | | .OUTPUTS - IcingaThresholdResult — Configured result instance. + IcingaThresholdResult -- Configured result instance. .EXAMPLE PS> [IcingaThresholdResult]::new(5, $null, 10, 2, 'value 5 is lower than critical threshold 10') @@ -818,7 +824,7 @@ class IcingaThresholdResult string context. .OUTPUTS - System.String — The Output message. + System.String -- The Output message. .EXAMPLE PS> $result.ToString() @@ -854,14 +860,14 @@ may be plain numbers (smallest/base unit), unit strings such as '10GB' or '500ms base value itself may be a number or a unit string such as '1TB'. The warning and critical strings are stored verbatim so they round-trip 1:1. -The class never throws. Any problem — an invalid threshold or base value, an +The class never throws. Any problem -- an invalid threshold or base value, an unresolvable measured value, a percentage without a base value, or an invalid -pattern — yields a result with StatusCode 3 (UNKNOWN) and a clean explanatory +pattern -- yields a result with StatusCode 3 (UNKNOWN) and a clean explanatory Output message. A null or empty warning or critical is a valid "unset" threshold that never raises that state. .OUTPUTS -IcingaThresholds — Threshold object exposing the comparison methods. +IcingaThresholds -- Threshold object exposing the comparison methods. .EXAMPLE PS> [IcingaThresholds]::new('10:20', '5:30').CheckRange(3) @@ -877,20 +883,23 @@ Resolves the percent thresholds against the 1 TB maximum and evaluates 950 GB. Self-contained value object. Reuses IcingaUnit for unit normalization and IcingaThresholdRange for range parsing. Does not modify global state or access external services. Safe to construct in multi-threaded runspaces. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> class IcingaThresholds { - [string]$Warning = ''; - [string]$Critical = ''; - [double]$Maximum = 0; + [string]$Warning = ''; + [string]$Critical = ''; + [double]$Maximum = 0; - hidden [bool]$HasBaseValue = $false; - hidden [bool]$BaseValid = $true; - hidden [string]$BaseError = ''; - hidden [string]$BaseFamily = ''; - hidden [string]$BaseUnit = ''; + hidden [bool]$HasBaseValue = $false; + hidden [bool]$BaseValid = $true; + hidden [string]$BaseError = ''; + hidden [string]$BaseFamily = ''; + hidden [string]$BaseUnit = ''; - static hidden [regex]$PercentRegex = [regex]::new('^\s*(-?\d+(?:[.,]\d+)?)\s*%\s*$', [System.Text.RegularExpressions.RegexOptions]::Compiled); + static hidden [regex]$PercentRegex = [regex]::new('^\s*(-?\d+(?:[.,]\d+)?)\s*%\s*$', [System.Text.RegularExpressions.RegexOptions]::Compiled); # Regex metacharacters that make a pattern more than a plain literal. Whitespace and # '#' are literal under the operators' default options and so are not listed. @@ -905,17 +914,17 @@ class IcingaThresholds supported without a base value and produce an UNKNOWN result at comparison time. .PARAMETER Warning - | Name | Type | Description | Default | - |---------|---------------|----------------------------------------------|---------| - | Warning | System.String | Warning threshold string ('' = unset). | | + | Name | Type | Description | Default | + |---------|---------------|----------------------------------------|---------| + | Warning | System.String | Warning threshold string ('' = unset). | | .PARAMETER Critical - | Name | Type | Description | Default | - |----------|---------------|---------------------------------------------|---------| - | Critical | System.String | Critical threshold string ('' = unset). | | + | Name | Type | Description | Default | + |----------|---------------|-----------------------------------------|---------| + | Critical | System.String | Critical threshold string ('' = unset). | | .OUTPUTS - IcingaThresholds — Configured threshold object. + IcingaThresholds -- Configured threshold object. .EXAMPLE PS> [IcingaThresholds]::new('10:20', '5:30') @@ -938,22 +947,22 @@ class IcingaThresholds Percentages in thresholds are resolved against this base value. .PARAMETER Warning - | Name | Type | Description | Default | - |---------|---------------|----------------------------------------------|---------| - | Warning | System.String | Warning threshold string ('' = unset). | | + | Name | Type | Description | Default | + |---------|---------------|----------------------------------------|---------| + | Warning | System.String | Warning threshold string ('' = unset). | | .PARAMETER Critical - | Name | Type | Description | Default | - |----------|---------------|---------------------------------------------|---------| - | Critical | System.String | Critical threshold string ('' = unset). | | + | Name | Type | Description | Default | + |----------|---------------|-----------------------------------------|---------| + | Critical | System.String | Critical threshold string ('' = unset). | | .PARAMETER BaseValue - | Name | Type | Description | Default | - |-----------|---------------|-----------------------------------------------------------------|---------| - | BaseValue | System.String | Base/maximum value; a number or unit string such as '1TB'. | | + | Name | Type | Description | Default | + |-----------|---------------|------------------------------------------------------------|---------| + | BaseValue | System.String | Base/maximum value; a number or unit string such as '1TB'. | | .OUTPUTS - IcingaThresholds — Configured threshold object. + IcingaThresholds -- Configured threshold object. .EXAMPLE PS> [IcingaThresholds]::new('20%:', '10%:', '1TB') @@ -977,19 +986,19 @@ class IcingaThresholds every comparison into an UNKNOWN result; nothing is thrown. .PARAMETER Warning - | Name | Type | Description | Default | - |---------|---------------|----------------------------------|---------| - | Warning | System.String | Warning threshold string. | | + | Name | Type | Description | Default | + |---------|---------------|---------------------------|---------| + | Warning | System.String | Warning threshold string. | | .PARAMETER Critical - | Name | Type | Description | Default | - |----------|---------------|---------------------------------|---------| - | Critical | System.String | Critical threshold string. | | + | Name | Type | Description | Default | + |----------|---------------|----------------------------|---------| + | Critical | System.String | Critical threshold string. | | .PARAMETER BaseValue - | Name | Type | Description | Default | - |-----------|---------------|----------------------------------------------------|---------| - | BaseValue | System.String | Base value as a number or unit string. | | + | Name | Type | Description | Default | + |-----------|---------------|----------------------------------------|---------| + | BaseValue | System.String | Base value as a number or unit string. | | .PARAMETER HasBaseValue | Name | Type | Description | Default | @@ -997,7 +1006,7 @@ class IcingaThresholds | HasBaseValue | System.Boolean | Whether a base value was supplied. | | .OUTPUTS - None — Updates instance state. + None -- Updates instance state. .EXAMPLE PS> $this.Initialize('20%:', '10%:', '1TB', $true) @@ -1039,12 +1048,12 @@ class IcingaThresholds message. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|----------------------------------------------------------|---------| - | Value | System.Object | Measured value; a number, a '' string, or $null. | | + | Name | Type | Description | Default | + |-------|---------------|----------------------------------------------------------------|---------| + | Value | System.Object | Measured value; a number, a '' string, or $null. | | .OUTPUTS - IcingaThresholdResult — The evaluation result. + IcingaThresholdResult -- The evaluation result. .EXAMPLE PS> $thresholds.CheckRange(15) @@ -1132,12 +1141,12 @@ class IcingaThresholds thresholds yield UNKNOWN. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|----------------------------------------------------------|---------| - | Value | System.Object | Measured value; number, '' string, or $null.| | + | Name | Type | Description | Default | + |-------|---------------|------------------------------------------------------------|---------| + | Value | System.Object | Measured value; number, '' string, or $null. | | .OUTPUTS - IcingaThresholdResult — The evaluation result. + IcingaThresholdResult -- The evaluation result. .EXAMPLE PS> $thresholds.CheckGreater(950) @@ -1160,12 +1169,12 @@ class IcingaThresholds otherwise OK. Unresolvable input or thresholds yield UNKNOWN. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|----------------------------------------------------------|---------| - | Value | System.Object | Measured value; number, '' string, or $null.| | + | Name | Type | Description | Default | + |-------|---------------|------------------------------------------------------------|---------| + | Value | System.Object | Measured value; number, '' string, or $null. | | .OUTPUTS - IcingaThresholdResult — The evaluation result. + IcingaThresholdResult -- The evaluation result. .EXAMPLE PS> $thresholds.CheckGreaterEqual(90) @@ -1188,12 +1197,12 @@ class IcingaThresholds thresholds yield UNKNOWN. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|----------------------------------------------------------|---------| - | Value | System.Object | Measured value; number, '' string, or $null.| | + | Name | Type | Description | Default | + |-------|---------------|------------------------------------------------------------|---------| + | Value | System.Object | Measured value; number, '' string, or $null. | | .OUTPUTS - IcingaThresholdResult — The evaluation result. + IcingaThresholdResult -- The evaluation result. .EXAMPLE PS> $thresholds.CheckLower(5) @@ -1216,12 +1225,12 @@ class IcingaThresholds OK. Unresolvable input or thresholds yield UNKNOWN. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|----------------------------------------------------------|---------| - | Value | System.Object | Measured value; number, '' string, or $null.| | + | Name | Type | Description | Default | + |-------|---------------|------------------------------------------------------------|---------| + | Value | System.Object | Measured value; number, '' string, or $null. | | .OUTPUTS - IcingaThresholdResult — The evaluation result. + IcingaThresholdResult -- The evaluation result. .EXAMPLE PS> $thresholds.CheckLowerEqual(10) @@ -1245,12 +1254,12 @@ class IcingaThresholds resolved against the Maximum. Without a base value the result is UNKNOWN. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|----------------------------------------------------------|---------| - | Value | System.Object | Measured value; number, '' string, or $null.| | + | Name | Type | Description | Default | + |-------|---------------|------------------------------------------------------------|---------| + | Value | System.Object | Measured value; number, '' string, or $null. | | .OUTPUTS - IcingaThresholdResult — The evaluation result. + IcingaThresholdResult -- The evaluation result. .EXAMPLE PS> [IcingaThresholds]::new('80%', '90%', '1TB').CheckMax('950GB') @@ -1277,12 +1286,12 @@ class IcingaThresholds yields UNKNOWN. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|------------------------------------------|---------| - | Value | System.Object | Value to test as a string, or $null. | | + | Name | Type | Description | Default | + |-------|---------------|--------------------------------------|---------| + | Value | System.Object | Value to test as a string, or $null. | | .OUTPUTS - IcingaThresholdResult — The evaluation result. + IcingaThresholdResult -- The evaluation result. .EXAMPLE PS> [IcingaThresholds]::new('^warn', '^err').CheckMatch('error state') @@ -1305,12 +1314,12 @@ class IcingaThresholds invalid pattern yields UNKNOWN. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|------------------------------------------|---------| - | Value | System.Object | Value to test as a string, or $null. | | + | Name | Type | Description | Default | + |-------|---------------|--------------------------------------|---------| + | Value | System.Object | Value to test as a string, or $null. | | .OUTPUTS - IcingaThresholdResult — The evaluation result. + IcingaThresholdResult -- The evaluation result. .EXAMPLE PS> [IcingaThresholds]::new('^ok', '^healthy').CheckNotMatch('degraded') @@ -1332,12 +1341,12 @@ class IcingaThresholds when it is like the warning wildcard pattern, otherwise OK. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|------------------------------------------|---------| - | Value | System.Object | Value to test as a string, or $null. | | + | Name | Type | Description | Default | + |-------|---------------|--------------------------------------|---------| + | Value | System.Object | Value to test as a string, or $null. | | .OUTPUTS - IcingaThresholdResult — The evaluation result. + IcingaThresholdResult -- The evaluation result. .EXAMPLE PS> [IcingaThresholds]::new('*warn*', '*error*').CheckLike('fatal error occurred') @@ -1359,12 +1368,12 @@ class IcingaThresholds WARNING when it is not like the warning wildcard pattern, otherwise OK. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|------------------------------------------|---------| - | Value | System.Object | Value to test as a string, or $null. | | + | Name | Type | Description | Default | + |-------|---------------|--------------------------------------|---------| + | Value | System.Object | Value to test as a string, or $null. | | .OUTPUTS - IcingaThresholdResult — The evaluation result. + IcingaThresholdResult -- The evaluation result. .EXAMPLE PS> [IcingaThresholds]::new('*ok*', '*healthy*').CheckNotLike('service down') @@ -1387,12 +1396,12 @@ class IcingaThresholds string equality test, not a pattern match. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|------------------------------------------|---------| - | Value | System.Object | Value to test as a string, or $null. | | + | Name | Type | Description | Default | + |-------|---------------|--------------------------------------|---------| + | Value | System.Object | Value to test as a string, or $null. | | .OUTPUTS - IcingaThresholdResult — The evaluation result. + IcingaThresholdResult -- The evaluation result. .EXAMPLE PS> [IcingaThresholds]::new('degraded', 'offline').CheckEqual('offline') @@ -1415,12 +1424,12 @@ class IcingaThresholds case-insensitive string equality test, not a pattern match. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|------------------------------------------|---------| - | Value | System.Object | Value to test as a string, or $null. | | + | Name | Type | Description | Default | + |-------|---------------|--------------------------------------|---------| + | Value | System.Object | Value to test as a string, or $null. | | .OUTPUTS - IcingaThresholdResult — The evaluation result. + IcingaThresholdResult -- The evaluation result. .EXAMPLE PS> [IcingaThresholds]::new('online', 'online').CheckNotEqual('offline') @@ -1446,14 +1455,14 @@ class IcingaThresholds resolution failure returns an UNKNOWN result with an explanatory message. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|---------------------------------------|---------| - | Value | System.Object | Measured value to evaluate. | | + | Name | Type | Description | Default | + |-------|---------------|-----------------------------|---------| + | Value | System.Object | Measured value to evaluate. | | .PARAMETER Operator - | Name | Type | Description | Default | - |----------|---------------|---------------------------------------------------|---------| - | Operator | System.String | Comparison operator: 'gt', 'ge', 'lt' or 'le'. | | + | Name | Type | Description | Default | + |----------|---------------|------------------------------------------------|---------| + | Operator | System.String | Comparison operator: 'gt', 'ge', 'lt' or 'le'. | | .PARAMETER OperatorText | Name | Type | Description | Default | @@ -1461,7 +1470,7 @@ class IcingaThresholds | OperatorText | System.String | Human-readable operator for the message. | | .OUTPUTS - IcingaThresholdResult — The evaluation result. + IcingaThresholdResult -- The evaluation result. .EXAMPLE PS> $this.CompareNumeric(950, 'gt', 'greater than') @@ -1557,13 +1566,13 @@ class IcingaThresholds pattern or a null value returns an UNKNOWN result with an explanatory message. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|---------------------------------|---------| - | Value | System.Object | Value to test as a string. | | + | Name | Type | Description | Default | + |-------|---------------|----------------------------|---------| + | Value | System.Object | Value to test as a string. | | .PARAMETER Operator - | Name | Type | Description | Default | - |----------|---------------|--------------------------------------------------------|---------| + | Name | Type | Description | Default | + |----------|---------------|--------------------------------------------------------------|---------| | Operator | System.String | One of 'match', 'notmatch', 'like', 'notlike', 'eq' or 'ne'. | | .PARAMETER OperatorText @@ -1572,7 +1581,7 @@ class IcingaThresholds | OperatorText | System.String | Human-readable operator for the message. | | .OUTPUTS - IcingaThresholdResult — The evaluation result. + IcingaThresholdResult -- The evaluation result. .EXAMPLE PS> $this.CompareString('error', 'match', 'matches') @@ -1631,14 +1640,14 @@ class IcingaThresholds whether the comparison is true. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|-------------------------------|---------| - | Value | System.Double | Resolved measured value. | | + | Name | Type | Description | Default | + |-------|---------------|--------------------------|---------| + | Value | System.Double | Resolved measured value. | | .PARAMETER Threshold - | Name | Type | Description | Default | - |-----------|---------------|-------------------------------|---------| - | Threshold | System.Double | Resolved threshold value. | | + | Name | Type | Description | Default | + |-----------|---------------|---------------------------|---------| + | Threshold | System.Double | Resolved threshold value. | | .PARAMETER Operator | Name | Type | Description | Default | @@ -1646,7 +1655,7 @@ class IcingaThresholds | Operator | System.String | Comparison operator: 'gt', 'ge', 'lt' or 'le'. | | .OUTPUTS - System.Boolean — Result of the comparison. + System.Boolean -- Result of the comparison. .EXAMPLE PS> $this.CompareOp(950, 900, 'gt') @@ -1681,9 +1690,9 @@ class IcingaThresholds wildcard (like/notlike) semantics and returns whether the comparison is true. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|----------------------------|---------| - | Value | System.String | Value to test. | | + | Name | Type | Description | Default | + |-------|---------------|----------------|---------| + | Value | System.String | Value to test. | | .PARAMETER Pattern | Name | Type | Description | Default | @@ -1691,12 +1700,12 @@ class IcingaThresholds | Pattern | System.String | Regex or wildcard pattern. | | .PARAMETER Operator - | Name | Type | Description | Default | - |----------|---------------|----------------------------------------------------|---------| + | Name | Type | Description | Default | + |----------|---------------|--------------------------------------------------------------|---------| | Operator | System.String | One of 'match', 'notmatch', 'like', 'notlike', 'eq' or 'ne'. | | .OUTPUTS - System.Boolean — Result of the comparison. + System.Boolean -- Result of the comparison. .EXAMPLE PS> $this.MatchOp('error', '^err', 'match') @@ -1741,12 +1750,12 @@ class IcingaThresholds nothing to quantify; such patterns belong to the '-like' comparisons instead. .PARAMETER Pattern - | Name | Type | Description | Default | - |---------|---------------|----------------------------------|---------| - | Pattern | System.String | Pattern to validate as a regex. | | + | Name | Type | Description | Default | + |---------|---------------|---------------------------------|---------| + | Pattern | System.String | Pattern to validate as a regex. | | .OUTPUTS - System.Boolean — $true when the pattern compiles as a regex, otherwise $false. + System.Boolean -- $true when the pattern compiles as a regex, otherwise $false. .EXAMPLE PS> $this.IsValidRegex('^err') @@ -1771,29 +1780,29 @@ class IcingaThresholds .DESCRIPTION Central factory for every IcingaThresholdResult this class returns. It creates the result from the measured value, the warning and critical thresholds, the - plugin state and the output message, and — when the threshold was created with a - valid base value — additionally records that resolved base (its maximum) in + plugin state and the output message, and -- when the threshold was created with a + valid base value -- additionally records that resolved base (its maximum) in BaseValue so callers see it alongside WarningValue and CriticalValue. .PARAMETER InputValue - | Name | Type | Description | Default | - |------------|---------------|-----------------------------------------|---------| - | InputValue | System.Object | Measured value for the result field. | | + | Name | Type | Description | Default | + |------------|---------------|--------------------------------------|---------| + | InputValue | System.Object | Measured value for the result field. | | .PARAMETER WarningValue - | Name | Type | Description | Default | - |--------------|---------------|---------------------------------------|---------| - | WarningValue | System.Object | Warning threshold field, or $null. | | + | Name | Type | Description | Default | + |--------------|---------------|------------------------------------|---------| + | WarningValue | System.Object | Warning threshold field, or $null. | | .PARAMETER CriticalValue - | Name | Type | Description | Default | - |---------------|---------------|--------------------------------------|---------| - | CriticalValue | System.Object | Critical threshold field, or $null. | | + | Name | Type | Description | Default | + |---------------|---------------|-------------------------------------|---------| + | CriticalValue | System.Object | Critical threshold field, or $null. | | .PARAMETER StatusCode - | Name | Type | Description | Default | - |------------|--------------|----------------------------------------------------|---------| - | StatusCode | System.Int32 | Icinga plugin state: 0 OK, 1 WARN, 2 CRIT, 3 UNKNOWN.| | + | Name | Type | Description | Default | + |------------|--------------|-------------------------------------------------------|---------| + | StatusCode | System.Int32 | Icinga plugin state: 0 OK, 1 WARN, 2 CRIT, 3 UNKNOWN. | | .PARAMETER Output | Name | Type | Description | Default | @@ -1801,7 +1810,7 @@ class IcingaThresholds | Output | System.String | Human-readable result description. | | .OUTPUTS - IcingaThresholdResult — The configured result, with BaseValue set when a base + IcingaThresholdResult -- The configured result, with BaseValue set when a base value is available. .EXAMPLE @@ -1830,26 +1839,26 @@ class IcingaThresholds base value. The value and the base value are both rendered in their own unit and followed by their resolved base-unit form in parentheses (for example '1000MB (1000000000B)'). The parenthetical is omitted whenever it would merely - repeat the rendered form — a plain number, or a value already given in the base - unit — so no redundant '(…)' is shown. + repeat the rendered form -- a plain number, or a value already given in the base + unit -- so no redundant '(...)' is shown. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|------------------------------------------|---------| - | Value | System.Object | Original measured value as supplied. | | + | Name | Type | Description | Default | + |-------|---------------|--------------------------------------|---------| + | Value | System.Object | Original measured value as supplied. | | .PARAMETER InputOut - | Name | Type | Description | Default | - |----------|---------------|-------------------------------------------------|---------| - | InputOut | System.String | Value resolved to its base-unit form (with B/s).| | + | Name | Type | Description | Default | + |----------|---------------|--------------------------------------------------|---------| + | InputOut | System.String | Value resolved to its base-unit form (with B/s). | | .PARAMETER ValueFamily - | Name | Type | Description | Default | - |-------------|---------------|----------------------------------------------|---------| - | ValueFamily | System.String | The value's unit family, '' for a plain number.| | + | Name | Type | Description | Default | + |-------------|---------------|-------------------------------------------------|---------| + | ValueFamily | System.String | The value's unit family, '' for a plain number. | | .OUTPUTS - System.String — The formatted "cannot be greater than the BaseValue" message. + System.String -- The formatted "cannot be greater than the BaseValue" message. .EXAMPLE PS> $this.DescribeBaseValueExceeded('10GB', '10000000000B', 'Data') @@ -1883,12 +1892,12 @@ class IcingaThresholds percentage instead of dividing by zero. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|-----------------------------------------------|---------| - | Value | System.Double | Measured value in base units. | | + | Name | Type | Description | Default | + |-------|---------------|-------------------------------|---------| + | Value | System.Double | Measured value in base units. | | .OUTPUTS - System.String — The percentage number without a sign, e.g. '50', or '' when unset. + System.String -- The percentage number without a sign, e.g. '50', or '' when unset. .EXAMPLE PS> $this.PercentOf(100) @@ -1917,9 +1926,9 @@ class IcingaThresholds numeric comparison message so a percent-driven check reads '100 (50%)'. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|--------------------------------------|---------| - | Value | System.Double | Measured value in base units. | | + | Name | Type | Description | Default | + |-------|---------------|-------------------------------|---------| + | Value | System.Double | Measured value in base units. | | .PARAMETER Family | Name | Type | Description | Default | @@ -1927,17 +1936,17 @@ class IcingaThresholds | Family | System.String | The value's resolved unit family, '' none. | | .PARAMETER Unit - | Name | Type | Description | Default | - |------|---------------|------------------------------------------|---------| - | Unit | System.String | The value's original unit token, '' none.| | + | Name | Type | Description | Default | + |------|---------------|-------------------------------------------|---------| + | Unit | System.String | The value's original unit token, '' none. | | .PARAMETER ShowPercent - | Name | Type | Description | Default | - |-------------|----------------|----------------------------------------------------|---------| - | ShowPercent | System.Boolean | Whether to append the value's percentage of base. | | + | Name | Type | Description | Default | + |-------------|----------------|---------------------------------------------------|---------| + | ShowPercent | System.Boolean | Whether to append the value's percentage of base. | | .OUTPUTS - System.String — The value display, e.g. '100 (50%)' or '100'. + System.String -- The value display, e.g. '100 (50%)' or '100'. .EXAMPLE PS> $this.FormatValueDisplay(100, '', '', $true) @@ -1972,9 +1981,9 @@ class IcingaThresholds own unit through FormatBest, exactly as before. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|----------------------------------------|---------| - | Value | System.Double | Resolved threshold value in base units.| | + | Name | Type | Description | Default | + |-------|---------------|-----------------------------------------|---------| + | Value | System.Double | Resolved threshold value in base units. | | .PARAMETER Family | Name | Type | Description | Default | @@ -1982,9 +1991,9 @@ class IcingaThresholds | Family | System.String | The threshold's resolved unit family, '' none. | | .PARAMETER Unit - | Name | Type | Description | Default | - |------|---------------|----------------------------------------------|---------| - | Unit | System.String | The threshold's original unit token, '' none.| | + | Name | Type | Description | Default | + |------|---------------|-----------------------------------------------|---------| + | Unit | System.String | The threshold's original unit token, '' none. | | .PARAMETER Percent | Name | Type | Description | Default | @@ -1992,7 +2001,7 @@ class IcingaThresholds | Percent | System.String | Original percent token when the threshold is a percent. | | .OUTPUTS - System.String — The threshold display, e.g. '40 (20%)' or '10MB'. + System.String -- The threshold display, e.g. '40 (20%)' or '10MB'. .EXAMPLE PS> $this.FormatThresholdDisplay(40, '', '', '20%') @@ -2020,24 +2029,24 @@ class IcingaThresholds user-friendly reason is written to the ErrorMessage reference. .PARAMETER Token - | Name | Type | Description | Default | - |-------|---------------|---------------------------------|---------| - | Token | System.String | Threshold token to resolve. | | + | Name | Type | Description | Default | + |-------|---------------|-----------------------------|---------| + | Token | System.String | Threshold token to resolve. | | .PARAMETER Result - | Name | Type | Description | Default | - |--------|------------------------------------------|--------------------------------------|---------| - | Result | System.Management.Automation.PSReference | Receives the resolved base value. | | + | Name | Type | Description | Default | + |--------|------------------------------------------|-----------------------------------|---------| + | Result | System.Management.Automation.PSReference | Receives the resolved base value. | | .PARAMETER ErrorMessage - | Name | Type | Description | Default | - |--------------|------------------------------------------|-----------------------------------|---------| - | ErrorMessage | System.Management.Automation.PSReference | Receives a reason on failure. | | + | Name | Type | Description | Default | + |--------------|------------------------------------------|-------------------------------|---------| + | ErrorMessage | System.Management.Automation.PSReference | Receives a reason on failure. | | .PARAMETER Family - | Name | Type | Description | Default | - |--------|------------------------------------------|--------------------------------------------------------|---------| - | Family | System.Management.Automation.PSReference | Receives the unit family ('Data'/'Time'), '' when none.| | + | Name | Type | Description | Default | + |--------|------------------------------------------|---------------------------------------------------------|---------| + | Family | System.Management.Automation.PSReference | Receives the unit family ('Data'/'Time'), '' when none. | | .PARAMETER Unit | Name | Type | Description | Default | @@ -2050,7 +2059,7 @@ class IcingaThresholds | PercentToken | System.Management.Automation.PSReference | Receives the original percent token, '' when none. | | .OUTPUTS - System.Boolean — $true on success, $false when the token could not be resolved. + System.Boolean -- $true on success, $false when the token could not be resolved. .EXAMPLE PS> $this.TryResolveThreshold('90%', [ref]$value, [ref]$reason, [ref]$family, [ref]$unit, [ref]$percent) @@ -2064,9 +2073,9 @@ class IcingaThresholds $Unit.Value = ''; $PercentToken.Value = ''; - [string]$Trimmed = $Token.Trim(); + [string]$Trimmed = $Token.Trim(); - $PercentMatch = [IcingaThresholds]::PercentRegex.Match($Trimmed); + $PercentMatch = [IcingaThresholds]::PercentRegex.Match($Trimmed); if ($PercentMatch.Success) { if (-not ($this.HasBaseValue -and $this.BaseValid)) { $ErrorMessage.Value = ("the percent threshold '{0}' requires a base value" -f $Token); @@ -2107,9 +2116,9 @@ class IcingaThresholds uninterpretable input fails. Delegates to the four-argument overload. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|-----------------------------|---------| - | Value | System.Object | Value to resolve. | | + | Name | Type | Description | Default | + |-------|---------------|-------------------|---------| + | Value | System.Object | Value to resolve. | | .PARAMETER Result | Name | Type | Description | Default | @@ -2117,7 +2126,7 @@ class IcingaThresholds | Result | System.Management.Automation.PSReference | Receives the resolved base-unit value. | | .OUTPUTS - System.Boolean — $true on success, $false when the value cannot be resolved. + System.Boolean -- $true on success, $false when the value cannot be resolved. .EXAMPLE PS> $this.TryResolveValue('10GB', [ref]$value) @@ -2144,9 +2153,9 @@ class IcingaThresholds an empty family and token so they render without a unit. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|-----------------------------|---------| - | Value | System.Object | Value to resolve. | | + | Name | Type | Description | Default | + |-------|---------------|-------------------|---------| + | Value | System.Object | Value to resolve. | | .PARAMETER Result | Name | Type | Description | Default | @@ -2154,9 +2163,9 @@ class IcingaThresholds | Result | System.Management.Automation.PSReference | Receives the resolved base-unit value. | | .PARAMETER Family - | Name | Type | Description | Default | - |--------|------------------------------------------|--------------------------------------------------------|---------| - | Family | System.Management.Automation.PSReference | Receives the unit family ('Data'/'Time'), '' when none.| | + | Name | Type | Description | Default | + |--------|------------------------------------------|---------------------------------------------------------|---------| + | Family | System.Management.Automation.PSReference | Receives the unit family ('Data'/'Time'), '' when none. | | .PARAMETER Unit | Name | Type | Description | Default | @@ -2164,7 +2173,7 @@ class IcingaThresholds | Unit | System.Management.Automation.PSReference | Receives the original unit token, '' when none. | | .OUTPUTS - System.Boolean — $true on success, $false when the value cannot be resolved. + System.Boolean -- $true on success, $false when the value cannot be resolved. .EXAMPLE PS> $this.TryResolveValue('10GB', [ref]$value, [ref]$family, [ref]$unit) @@ -2225,17 +2234,17 @@ class IcingaThresholds short, human-readable explanation for the result Output. .PARAMETER Code - | Name | Type | Description | Default | - |------|---------------|--------------------------------------|---------| - | Code | System.String | ReturnCode from IcingaThresholdRange.| | + | Name | Type | Description | Default | + |------|---------------|---------------------------------------|---------| + | Code | System.String | ReturnCode from IcingaThresholdRange. | | .PARAMETER Threshold - | Name | Type | Description | Default | - |-----------|---------------|------------------------------------|---------| - | Threshold | System.String | The offending threshold string. | | + | Name | Type | Description | Default | + |-----------|---------------|---------------------------------|---------| + | Threshold | System.String | The offending threshold string. | | .OUTPUTS - System.String — A user-friendly explanation. + System.String -- A user-friendly explanation. .EXAMPLE PS> $this.RangeError('IcingaThresholdStartGreaterEnd', '20:10') @@ -2267,9 +2276,9 @@ class IcingaThresholds lies within the bounds. A percent bound additionally shows its percent token. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|------------------------------------------|---------| - | Value | System.Double | Measured value that raised the alert. | | + | Name | Type | Description | Default | + |-------|---------------|---------------------------------------|---------| + | Value | System.Double | Measured value that raised the alert. | | .PARAMETER ValueDisplay | Name | Type | Description | Default | @@ -2277,12 +2286,12 @@ class IcingaThresholds | ValueDisplay | System.String | Measured value pre-rendered for display (unit and percentage). | | .PARAMETER Range - | Name | Type | Description | Default | - |-------|----------------------|--------------------------------------|---------| - | Range | IcingaThresholdRange | The range that is in its alert region.| | + | Name | Type | Description | Default | + |-------|----------------------|----------------------------------------|---------| + | Range | IcingaThresholdRange | The range that is in its alert region. | | .OUTPUTS - System.String — The short, human-readable alert description. + System.String -- The short, human-readable alert description. .EXAMPLE PS> $this.DescribeRangeAlert(100, '100 (50%)', $range) @@ -2318,14 +2327,14 @@ class IcingaThresholds when warning is lower than or equal to critical. .PARAMETER WarningValue - | Name | Type | Description | Default | - |--------------|---------------|----------------------------------|---------| - | WarningValue | System.Double | Resolved warning threshold. | | + | Name | Type | Description | Default | + |--------------|---------------|-----------------------------|---------| + | WarningValue | System.Double | Resolved warning threshold. | | .PARAMETER CriticalValue - | Name | Type | Description | Default | - |---------------|---------------|---------------------------------|---------| - | CriticalValue | System.Double | Resolved critical threshold. | | + | Name | Type | Description | Default | + |---------------|---------------|------------------------------|---------| + | CriticalValue | System.Double | Resolved critical threshold. | | .PARAMETER Operator | Name | Type | Description | Default | @@ -2333,7 +2342,7 @@ class IcingaThresholds | Operator | System.String | Comparison operator: 'gt', 'ge', 'lt' or 'le'. | | .OUTPUTS - System.Boolean — $true when the warning state is unreachable. + System.Boolean -- $true when the warning state is unreachable. .EXAMPLE PS> $this.NumericWarningMasked(90, 80, 'gt') @@ -2365,9 +2374,9 @@ class IcingaThresholds invariant culture. .PARAMETER Value - | Name | Type | Description | Default | - |-------|---------------|------------------------------|---------| - | Value | System.Double | Resolved threshold value. | | + | Name | Type | Description | Default | + |-------|---------------|---------------------------|---------| + | Value | System.Double | Resolved threshold value. | | .PARAMETER Operator | Name | Type | Description | Default | @@ -2375,17 +2384,17 @@ class IcingaThresholds | Operator | System.String | Comparison operator: 'gt', 'ge', 'lt' or 'le'. | | .PARAMETER Family - | Name | Type | Description | Default | - |--------|---------------|-------------------------------------------------|---------| - | Family | System.String | Resolved unit family ('Data'/'Time'), '' none. | | + | Name | Type | Description | Default | + |--------|---------------|------------------------------------------------|---------| + | Family | System.String | Resolved unit family ('Data'/'Time'), '' none. | | .PARAMETER Unit - | Name | Type | Description | Default | - |------|---------------|---------------------------------------------|---------| - | Unit | System.String | Original unit token to render, '' when none.| | + | Name | Type | Description | Default | + |------|---------------|----------------------------------------------|---------| + | Unit | System.String | Original unit token to render, '' when none. | | .OUTPUTS - System.String — The alert condition, e.g. '> 90'. + System.String -- The alert condition, e.g. '> 90'. .EXAMPLE PS> $this.NumericAlertString(90, 'gt', '', '') @@ -2428,17 +2437,17 @@ class IcingaThresholds open-ended ranges. .PARAMETER WarningRange - | Name | Type | Description | Default | - |--------------|----------------------|-----------------------------|---------| - | WarningRange | IcingaThresholdRange | Parsed warning range. | | + | Name | Type | Description | Default | + |--------------|----------------------|-----------------------|---------| + | WarningRange | IcingaThresholdRange | Parsed warning range. | | .PARAMETER CriticalRange - | Name | Type | Description | Default | - |---------------|----------------------|----------------------------|---------| - | CriticalRange | IcingaThresholdRange | Parsed critical range. | | + | Name | Type | Description | Default | + |---------------|----------------------|------------------------|---------| + | CriticalRange | IcingaThresholdRange | Parsed critical range. | | .OUTPUTS - System.String — 'WARNING', 'OK', or '' when the pair is sound. + System.String -- 'WARNING', 'OK', or '' when the pair is sound. .EXAMPLE PS> $this.RangeUnreachableState($warnRange, $critRange) @@ -2525,7 +2534,7 @@ class IcingaThresholds | Operator | System.String | One of 'match', 'notmatch', 'like', 'notlike', 'eq' or 'ne'. | | .OUTPUTS - System.Boolean — $true when the warning state is unreachable, otherwise $false. + System.Boolean -- $true when the warning state is unreachable, otherwise $false. .EXAMPLE PS> $this.PatternWarningMasked('like') @@ -2575,21 +2584,21 @@ class IcingaThresholds contains that literal; the Inner language is therefore contained in the Outer language exactly when the Outer literal occurs somewhere inside the Inner literal. Any pattern that carries a regex metacharacter is not a plain literal and is - declined with $false so a sound configuration is never falsely rejected — general + declined with $false so a sound configuration is never falsely rejected -- general regex-language containment is not decided here. .PARAMETER Inner - | Name | Type | Description | Default | - |-------|---------------|------------------------------------------------------|---------| - | Inner | System.String | Pattern whose match language must be contained. | | + | Name | Type | Description | Default | + |-------|---------------|-------------------------------------------------|---------| + | Inner | System.String | Pattern whose match language must be contained. | | .PARAMETER Outer - | Name | Type | Description | Default | - |-------|---------------|------------------------------------------------------|---------| - | Outer | System.String | Pattern that must contain the Inner match language. | | + | Name | Type | Description | Default | + |-------|---------------|-----------------------------------------------------|---------| + | Outer | System.String | Pattern that must contain the Inner match language. | | .OUTPUTS - System.Boolean — $true when both patterns are plain literals and L(Inner) is a + System.Boolean -- $true when both patterns are plain literals and L(Inner) is a subset of L(Outer), otherwise $false. .EXAMPLE @@ -2627,9 +2636,9 @@ class IcingaThresholds contains one yields $false so a sound configuration is never falsely rejected. .PARAMETER Inner - | Name | Type | Description | Default | - |-------|---------------|--------------------------------------------------------|---------| - | Inner | System.String | Wildcard pattern whose language must be contained. | | + | Name | Type | Description | Default | + |-------|---------------|----------------------------------------------------|---------| + | Inner | System.String | Wildcard pattern whose language must be contained. | | .PARAMETER Outer | Name | Type | Description | Default | @@ -2637,7 +2646,7 @@ class IcingaThresholds | Outer | System.String | Wildcard pattern that must contain the Inner language. | | .OUTPUTS - System.Boolean — $true when L(Inner) is a subset of L(Outer), otherwise $false. + System.Boolean -- $true when L(Inner) is a subset of L(Outer), otherwise $false. .EXAMPLE PS> $this.WildcardSubset('*fo*', '*f*') @@ -2663,7 +2672,7 @@ class IcingaThresholds return $false; } - [int]$Accept = $OuterKinds.Length; + [int]$Accept = $OuterKinds.Length; # Minterm alphabet: every distinct character the outer pattern discriminates on, # plus one sentinel ('') that stands for any other character. All non-literal @@ -2684,8 +2693,8 @@ class IcingaThresholds # Reach: every outer state set reachable by some concrete string the inner # pattern can produce, keyed canonically so duplicates collapse. [System.Collections.Generic.Dictionary[string, int[]]]$Reach = [System.Collections.Generic.Dictionary[string, int[]]]::new(); - [int[]]$Start = $this.WildcardClosure(@(0), $OuterKinds); - $Reach[$this.PosKey($Start)] = $Start; + [int[]]$Start = $this.WildcardClosure(@(0), $OuterKinds); + $Reach[$this.PosKey($Start)] = $Start; for ($t = 0; $t -lt $InnerKinds.Length; $t++) { [System.Collections.Generic.Dictionary[string, int[]]]$Next = [System.Collections.Generic.Dictionary[string, int[]]]::new(); @@ -2699,13 +2708,13 @@ class IcingaThresholds } foreach ($State in $Reach.Values) { - [int[]]$Moved = $this.WildcardStep($State, $Symbol, $OuterKinds, $OuterChars); + [int[]]$Moved = $this.WildcardStep($State, $Symbol, $OuterKinds, $OuterChars); $Next[$this.PosKey($Moved)] = $Moved; } } elseif ($InnerKinds[$t] -eq 'any') { foreach ($State in $Reach.Values) { foreach ($Symbol in $Alphabet) { - [int[]]$Moved = $this.WildcardStep($State, $Symbol, $OuterKinds, $OuterChars); + [int[]]$Moved = $this.WildcardStep($State, $Symbol, $OuterKinds, $OuterChars); $Next[$this.PosKey($Moved)] = $Moved; } } @@ -2725,7 +2734,7 @@ class IcingaThresholds [int[]]$State = $Work.Dequeue(); foreach ($Symbol in $Alphabet) { [int[]]$Moved = $this.WildcardStep($State, $Symbol, $OuterKinds, $OuterChars); - [string]$Key = $this.PosKey($Moved); + [string]$Key = $this.PosKey($Moved); if (-not $Next.ContainsKey($Key)) { $Next[$Key] = $Moved; $Work.Enqueue($Moved); @@ -2761,22 +2770,22 @@ class IcingaThresholds method return $false so the caller treats the containment as undecidable. .PARAMETER Pattern - | Name | Type | Description | Default | - |---------|---------------|------------------------------------|---------| - | Pattern | System.String | Wildcard pattern to tokenize. | | + | Name | Type | Description | Default | + |---------|---------------|-------------------------------|---------| + | Pattern | System.String | Wildcard pattern to tokenize. | | .PARAMETER Kinds - | Name | Type | Description | Default | - |-------|------------------------------------------|---------------------------------------------------|---------| - | Kinds | System.Management.Automation.PSReference | Receives the per-token kinds ('star'/'any'/'lit').| | + | Name | Type | Description | Default | + |-------|------------------------------------------|----------------------------------------------------|---------| + | Kinds | System.Management.Automation.PSReference | Receives the per-token kinds ('star'/'any'/'lit'). | | .PARAMETER Chars - | Name | Type | Description | Default | - |-------|------------------------------------------|------------------------------------------------------|---------| - | Chars | System.Management.Automation.PSReference | Receives the per-token literal character, '' if none.| | + | Name | Type | Description | Default | + |-------|------------------------------------------|-------------------------------------------------------|---------| + | Chars | System.Management.Automation.PSReference | Receives the per-token literal character, '' if none. | | .OUTPUTS - System.Boolean — $true when the pattern was fully tokenized, $false when it contains + System.Boolean -- $true when the pattern was fully tokenized, $false when it contains an unsupported character class. .EXAMPLE @@ -2791,7 +2800,7 @@ class IcingaThresholds [System.Collections.Generic.List[string]]$K = [System.Collections.Generic.List[string]]::new(); [System.Collections.Generic.List[string]]$C = [System.Collections.Generic.List[string]]::new(); - [int]$i = 0; + [int]$i = 0; while ($i -lt $Pattern.Length) { [char]$Ch = $Pattern[$i]; @@ -2850,17 +2859,17 @@ class IcingaThresholds token count is the accepting position. .PARAMETER Positions - | Name | Type | Description | Default | - |-----------|---------------|----------------------------------------------|---------| - | Positions | System.Int32[]| Positions to expand. | | + | Name | Type | Description | Default | + |-----------|----------------|----------------------|---------| + | Positions | System.Int32[] | Positions to expand. | | .PARAMETER Kinds - | Name | Type | Description | Default | - |-------|----------------|--------------------------------------------|---------| - | Kinds | System.String[]| Token kinds of the outer pattern. | | + | Name | Type | Description | Default | + |-------|-----------------|-----------------------------------|---------| + | Kinds | System.String[] | Token kinds of the outer pattern. | | .OUTPUTS - System.Int32[] — The epsilon-closed set of positions. + System.Int32[] -- The epsilon-closed set of positions. .EXAMPLE PS> $this.WildcardClosure(@(0), $outerKinds) @@ -2906,27 +2915,27 @@ class IcingaThresholds epsilon-closed before it is returned. .PARAMETER Positions - | Name | Type | Description | Default | - |-----------|---------------|----------------------------------------------------|---------| - | Positions | System.Int32[]| Epsilon-closed positions to advance. | | + | Name | Type | Description | Default | + |-----------|----------------|--------------------------------------|---------| + | Positions | System.Int32[] | Epsilon-closed positions to advance. | | .PARAMETER Symbol - | Name | Type | Description | Default | - |--------|---------------|---------------------------------------------------------|---------| - | Symbol | System.String | Input symbol; '' is the sentinel for any other character.| | + | Name | Type | Description | Default | + |--------|---------------|-----------------------------------------------------------|---------| + | Symbol | System.String | Input symbol; '' is the sentinel for any other character. | | .PARAMETER Kinds - | Name | Type | Description | Default | - |-------|----------------|------------------------------------|---------| - | Kinds | System.String[]| Token kinds of the outer pattern. | | + | Name | Type | Description | Default | + |-------|-----------------|-----------------------------------|---------| + | Kinds | System.String[] | Token kinds of the outer pattern. | | .PARAMETER Chars - | Name | Type | Description | Default | - |-------|----------------|----------------------------------------------|---------| - | Chars | System.String[]| Literal characters of the outer pattern. | | + | Name | Type | Description | Default | + |-------|-----------------|------------------------------------------|---------| + | Chars | System.String[] | Literal characters of the outer pattern. | | .OUTPUTS - System.Int32[] — The epsilon-closed set of positions after the transition. + System.Int32[] -- The epsilon-closed set of positions after the transition. .EXAMPLE PS> $this.WildcardStep(@(0, 1), 'f', $outerKinds, $outerChars) @@ -2965,21 +2974,21 @@ class IcingaThresholds Determine whether a set of wildcard-automaton positions is accepting .DESCRIPTION - Returns whether the accepting position — the index equal to the outer pattern's token - count, reached when every token has been consumed — is present in the given set. + Returns whether the accepting position -- the index equal to the outer pattern's token + count, reached when every token has been consumed -- is present in the given set. .PARAMETER Positions - | Name | Type | Description | Default | - |-----------|---------------|--------------------------------------|---------| - | Positions | System.Int32[]| Positions to test. | | + | Name | Type | Description | Default | + |-----------|----------------|--------------------|---------| + | Positions | System.Int32[] | Positions to test. | | .PARAMETER Accept - | Name | Type | Description | Default | - |--------|--------------|---------------------------------------|---------| - | Accept | System.Int32 | The accepting position index. | | + | Name | Type | Description | Default | + |--------|--------------|-------------------------------|---------| + | Accept | System.Int32 | The accepting position index. | | .OUTPUTS - System.Boolean — $true when the accepting position is present, otherwise $false. + System.Boolean -- $true when the accepting position is present, otherwise $false. .EXAMPLE PS> $this.WildcardAccepts(@(0, 1, 3), 3) @@ -3008,12 +3017,12 @@ class IcingaThresholds ascending and joined with commas. .PARAMETER Positions - | Name | Type | Description | Default | - |-----------|---------------|--------------------------------------|---------| - | Positions | System.Int32[]| Positions to render. | | + | Name | Type | Description | Default | + |-----------|----------------|----------------------|---------| + | Positions | System.Int32[] | Positions to render. | | .OUTPUTS - System.String — The canonical comma-joined key, '' for an empty set. + System.String -- The canonical comma-joined key, '' for an empty set. .EXAMPLE PS> $this.PosKey(@(2, 0, 1)) diff --git a/src/Classes/Icinga/IcingaUnit.ps1 b/src/Classes/Icinga/IcingaUnit.ps1 index 9ddff15..9997a40 100644 --- a/src/Classes/Icinga/IcingaUnit.ps1 +++ b/src/Classes/Icinga/IcingaUnit.ps1 @@ -9,7 +9,7 @@ ladders to resolve unit tokens, map them to unit families, and scale values to and from base units (bytes for data, seconds for time). .OUTPUTS -IcingaUnitEntry — Instantiated unit definition entry. +IcingaUnitEntry -- Instantiated unit definition entry. .EXAMPLE PS> [IcingaUnitEntry]::new('KiB', [decimal]1024, 'Kibibyte', 'byte', 'Data') @@ -19,6 +19,9 @@ Creates a unit entry representing Kibibytes with a base factor of 1024 bytes. .NOTES Internal data structure used exclusively by the IcingaUnit conversion system. No external dependencies or global state. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> class IcingaUnitEntry { @@ -37,9 +40,9 @@ class IcingaUnitEntry long name, kind category, and parent family. .PARAMETER Short - | Name | Type | Description | Default | - |-------|---------------|------------------------------------------|---------| - | Short | System.String | Short unit symbol (e.g. 'KiB', 's', 'B').| | + | Name | Type | Description | Default | + |-------|---------------|-------------------------------------------|---------| + | Short | System.String | Short unit symbol (e.g. 'KiB', 's', 'B'). | | .PARAMETER Factor | Name | Type | Description | Default | @@ -47,9 +50,9 @@ class IcingaUnitEntry | Factor | System.Decimal | Conversion factor relative to family base unit. | | .PARAMETER Long - | Name | Type | Description | Default | - |------|---------------|------------------------------------------------|---------| - | Long | System.String | Full singular name (e.g. 'Kibibyte', 'Second').| | + | Name | Type | Description | Default | + |------|---------------|-------------------------------------------------|---------| + | Long | System.String | Full singular name (e.g. 'Kibibyte', 'Second'). | | .PARAMETER Kind | Name | Type | Description | Default | @@ -62,7 +65,7 @@ class IcingaUnitEntry | Family | System.String | Major unit family ('Data' or 'Time'). | | .OUTPUTS - IcingaUnitEntry — Configured unit definition instance. + IcingaUnitEntry -- Configured unit definition instance. .EXAMPLE PS> [IcingaUnitEntry]::new('MiB', [decimal]1048576, 'Mebibyte', 'byte', 'Data') @@ -111,7 +114,7 @@ fully self-contained, thread-safe, and compatible with Windows PowerShell 5.1 and PowerShell 7+. .OUTPUTS -IcingaUnit — Value object describing the conversion result. +IcingaUnit -- Value object describing the conversion result. .EXAMPLE PS> [IcingaUnit]::new('1024B', $null, $null, $false) @@ -131,19 +134,22 @@ Converts 1000 bytes explicitly to GiB. .NOTES Self-contained value object. Does not modify global state or access external services. Safe to construct in multi-threaded runspaces. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> class IcingaUnit { - [double]$InputValue = 0; - [string]$InputUnit = ''; - [double]$OutputValue = 0; - [string]$OutputUnit = ''; - [string]$OutputString = ''; - [double]$BaseValue = 0; - [string]$Family = ''; + [double]$InputValue = 0; + [string]$InputUnit = ''; + [double]$OutputValue = 0; + [string]$OutputUnit = ''; + [string]$OutputString = ''; + [double]$BaseValue = 0; + [string]$Family = ''; - hidden [bool]$Success = $false; - hidden [string]$ReturnCode = ''; + hidden [bool]$Success = $false; + hidden [string]$ReturnCode = ''; static hidden [regex]$ValueRegex = [regex]::new('^\s*(-?\d+(?:[.,]\d+)?)\s*([A-Za-z]+)?\s*$', [System.Text.RegularExpressions.RegexOptions]::Compiled); static hidden [System.Collections.Generic.Dictionary[string, IcingaUnitEntry]]$TimeLookup = $null; @@ -164,7 +170,7 @@ class IcingaUnit expression. Safe to call multiple times (idempotent). .OUTPUTS - None — Populates static class fields. + None -- Populates static class fields. .EXAMPLE PS> [IcingaUnit]::InitializeUnitTables() @@ -194,11 +200,11 @@ class IcingaUnit ); [IcingaUnit]::SecondsEntry = [IcingaUnit]::TimeLadder[6]; - $LocalTimeLookup = [System.Collections.Generic.Dictionary[string, IcingaUnitEntry]]::new([System.StringComparer]::Ordinal); + $LocalTimeLookup = [System.Collections.Generic.Dictionary[string, IcingaUnitEntry]]::new([System.StringComparer]::Ordinal); foreach ($Entry in [IcingaUnit]::TimeLadder) { $LocalTimeLookup[$Entry.Short] = $Entry; } - [IcingaUnit]::TimeLookup = $LocalTimeLookup; + [IcingaUnit]::TimeLookup = $LocalTimeLookup; # Factors are expressed in bytes. 'Kind' selects the auto ladder: byte # input auto-formats against the binary ladder, bit input against bits. @@ -221,11 +227,11 @@ class IcingaUnit [IcingaUnitEntry]::new('Tbit', [decimal]125000000000, 'Terabit', 'bit', 'Data') ); - $LocalDataLookup = [System.Collections.Generic.Dictionary[string, IcingaUnitEntry]]::new([System.StringComparer]::OrdinalIgnoreCase); + $LocalDataLookup = [System.Collections.Generic.Dictionary[string, IcingaUnitEntry]]::new([System.StringComparer]::OrdinalIgnoreCase); foreach ($Entry in $DataUnits) { $LocalDataLookup[$Entry.Short] = $Entry; } - [IcingaUnit]::DataLookup = $LocalDataLookup; + [IcingaUnit]::DataLookup = $LocalDataLookup; [IcingaUnit]::DataBinaryLadder = @( $LocalDataLookup['PiB'], @@ -236,7 +242,7 @@ class IcingaUnit $LocalDataLookup['B'] ); - [IcingaUnit]::DataBitLadder = @( + [IcingaUnit]::DataBitLadder = @( $LocalDataLookup['Tbit'], $LocalDataLookup['Gbit'], $LocalDataLookup['Mbit'], @@ -269,8 +275,8 @@ class IcingaUnit | InputUnit | System.String | Fallback unit when InputValue does not contain a unit suffix. | | .PARAMETER TargetUnit - | Name | Type | Description | Default | - |------------|---------------|--------------------------------------------------------------|---------| + | Name | Type | Description | Default | + |------------|---------------|---------------------------------------------------------------|---------| | TargetUnit | System.String | Target unit for conversion. When omitted, best-fit is chosen. | | .PARAMETER AsHumanReadable @@ -279,7 +285,7 @@ class IcingaUnit | AsHumanReadable | System.Boolean | When $true, formats OutputString with full pluralized names. | | .OUTPUTS - IcingaUnit — Configured instance containing conversion status and results. + IcingaUnit -- Configured instance containing conversion status and results. .EXAMPLE PS> [IcingaUnit]::new('1024B', '', '', $false) @@ -338,11 +344,11 @@ class IcingaUnit return; } - [string]$InputFamily = $InputEntry.Family; + [string]$InputFamily = $InputEntry.Family; - $this.InputValue = [double]$Number; - $this.InputUnit = $InputEntry.Short; - $this.Family = $InputFamily; + $this.InputValue = [double]$Number; + $this.InputUnit = $InputEntry.Short; + $this.Family = $InputFamily; # Convert the input into the family base unit (bytes for data, seconds for # time) so every following calculation shares a common scale. @@ -369,11 +375,11 @@ class IcingaUnit [decimal]$Converted = $BaseUnitValue / $TargetEntry.Factor; - $this.OutputValue = $Sign * [double][System.Math]::Round($Converted, 2); - $this.OutputUnit = $TargetEntry.Short; - $this.OutputString = $this.ApplySign($Sign, $this.FormatSingle($Converted, $TargetEntry, $AsHumanReadable)); - $this.Success = $true; - $this.ReturnCode = 'IcingaUnitConverted'; + $this.OutputValue = $Sign * [double][System.Math]::Round($Converted, 2); + $this.OutputUnit = $TargetEntry.Short; + $this.OutputString = $this.ApplySign($Sign, $this.FormatSingle($Converted, $TargetEntry, $AsHumanReadable)); + $this.Success = $true; + $this.ReturnCode = 'IcingaUnitConverted'; return; } @@ -398,12 +404,12 @@ class IcingaUnit error code in ReturnCode for downstream error propagation. .PARAMETER Code - | Name | Type | Description | Default | - |------|---------------|----------------------------------------------|---------| - | Code | System.String | Semantic return code identifying the failure.| | + | Name | Type | Description | Default | + |------|---------------|-----------------------------------------------|---------| + | Code | System.String | Semantic return code identifying the failure. | | .OUTPUTS - None — Updates instance state. + None -- Updates instance state. .EXAMPLE PS> $this.Fail('IcingaUnitInvalidInputValue') @@ -432,7 +438,7 @@ class IcingaUnit | Token | System.String | Unit symbol or identifier to resolve. | | .OUTPUTS - IcingaUnitEntry — Matching unit definition entry, or $null if unknown. + IcingaUnitEntry -- Matching unit definition entry, or $null if unknown. .EXAMPLE PS> [IcingaUnit]::ResolveUnit('GiB') @@ -469,14 +475,14 @@ class IcingaUnit greater than or equal to 1. Sets OutputValue, OutputUnit, and OutputString. .PARAMETER BaseValue - | Name | Type | Description | Default | - |-----------|----------------|---------------------------------------|---------| - | BaseValue | System.Decimal | Value scaled to the base unit (bytes).| | + | Name | Type | Description | Default | + |-----------|----------------|----------------------------------------|---------| + | BaseValue | System.Decimal | Value scaled to the base unit (bytes). | | .PARAMETER Sign - | Name | Type | Description | Default | - |------|--------------|----------------------------------------------------|---------| - | Sign | System.Int32 | Numeric sign multiplier (1 for positive, -1 for -).| | + | Name | Type | Description | Default | + |------|--------------|-----------------------------------------------------|---------| + | Sign | System.Int32 | Numeric sign multiplier (1 for positive, -1 for -). | | .PARAMETER InputEntry | Name | Type | Description | Default | @@ -489,7 +495,7 @@ class IcingaUnit | AsHumanReadable | System.Boolean | When $true, formats OutputString with full pluralized names. | | .OUTPUTS - None — Updates instance output properties. + None -- Updates instance output properties. .EXAMPLE PS> $this.BuildDataBestFit([decimal]1048576, 1, $inputEntry, $false) @@ -521,9 +527,9 @@ class IcingaUnit [decimal]$Converted = $BaseValue / $Chosen.Factor; - $this.OutputValue = $Sign * [double][System.Math]::Round($Converted, 2); - $this.OutputUnit = $Chosen.Short; - $this.OutputString = $this.ApplySign($Sign, $this.FormatSingle($Converted, $Chosen, $AsHumanReadable)); + $this.OutputValue = $Sign * [double][System.Math]::Round($Converted, 2); + $this.OutputUnit = $Chosen.Short; + $this.OutputString = $this.ApplySign($Sign, $this.FormatSingle($Converted, $Chosen, $AsHumanReadable)); } <# @@ -541,9 +547,9 @@ class IcingaUnit | BaseValue | System.Decimal | Time duration scaled to base seconds. | | .PARAMETER Sign - | Name | Type | Description | Default | - |------|--------------|----------------------------------------------------|---------| - | Sign | System.Int32 | Numeric sign multiplier (1 for positive, -1 for -).| | + | Name | Type | Description | Default | + |------|--------------|-----------------------------------------------------|---------| + | Sign | System.Int32 | Numeric sign multiplier (1 for positive, -1 for -). | | .PARAMETER AsHumanReadable | Name | Type | Description | Default | @@ -551,7 +557,7 @@ class IcingaUnit | AsHumanReadable | System.Boolean | When $true, formats OutputString with full pluralized names. | | .OUTPUTS - None — Updates instance output properties. + None -- Updates instance output properties. .EXAMPLE PS> $this.BuildTimeDecomposition([decimal]8600, 1, $true) @@ -608,14 +614,14 @@ class IcingaUnit either the short symbol or the long pluralized name of the unit entry. .PARAMETER Value - | Name | Type | Description | Default | - |-------|----------------|-----------------------------|---------| - | Value | System.Decimal | Numeric value to format. | | + | Name | Type | Description | Default | + |-------|----------------|--------------------------|---------| + | Value | System.Decimal | Numeric value to format. | | .PARAMETER Entry - | Name | Type | Description | Default | - |-------|-----------------|-----------------------------|---------| - | Entry | IcingaUnitEntry | Target unit definition entry| | + | Name | Type | Description | Default | + |-------|-----------------|------------------------------|---------| + | Entry | IcingaUnitEntry | Target unit definition entry | | .PARAMETER AsHumanReadable | Name | Type | Description | Default | @@ -623,7 +629,7 @@ class IcingaUnit | AsHumanReadable | System.Boolean | When $true, uses full unit name with pluralization. | | .OUTPUTS - System.String — Formatted display string representing the value and unit. + System.String -- Formatted display string representing the value and unit. .EXAMPLE PS> $this.FormatSingle([decimal]1.5, $entry, $false) @@ -652,9 +658,9 @@ class IcingaUnit appends an 's' suffix to produce the regular English plural form. .PARAMETER Long - | Name | Type | Description | Default | - |------|---------------|-------------------------------|---------| - | Long | System.String | Singular unit name in English.| | + | Name | Type | Description | Default | + |------|---------------|--------------------------------|---------| + | Long | System.String | Singular unit name in English. | | .PARAMETER Value | Name | Type | Description | Default | @@ -662,7 +668,7 @@ class IcingaUnit | Value | System.Decimal | Numeric value evaluated for pluralization. | | .OUTPUTS - System.String — Appropriately inflected unit name string. + System.String -- Appropriately inflected unit name string. .EXAMPLE PS> $this.Pluralize('Hour', [decimal]2) @@ -688,9 +694,9 @@ class IcingaUnit unmodified when positive. .PARAMETER Sign - | Name | Type | Description | Default | - |------|--------------|----------------------------------------------------|---------| - | Sign | System.Int32 | Numeric sign multiplier (1 for positive, -1 for -).| | + | Name | Type | Description | Default | + |------|--------------|-----------------------------------------------------|---------| + | Sign | System.Int32 | Numeric sign multiplier (1 for positive, -1 for -). | | .PARAMETER Text | Name | Type | Description | Default | @@ -698,7 +704,7 @@ class IcingaUnit | Text | System.String | Formatted text string to prefix. | | .OUTPUTS - System.String — Sign-adjusted text string. + System.String -- Sign-adjusted text string. .EXAMPLE PS> $this.ApplySign(-1, '500MB') diff --git a/src/Classes/Tools/IcingaSortKey.ps1 b/src/Classes/Tools/IcingaSortKey.ps1 index 4141989..4d3c801 100644 --- a/src/Classes/Tools/IcingaSortKey.ps1 +++ b/src/Classes/Tools/IcingaSortKey.ps1 @@ -28,6 +28,9 @@ Returns the sort key of the volume's Name property. .NOTES Pure helper without state or external dependencies. Numbers are supported within +/- 1E20. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> class IcingaSortKey { @@ -48,9 +51,9 @@ class IcingaSortKey | InputObject | System.Object | The object to build for. | | .PARAMETER Property - | Name | Type | Description | Default | - |----------|-----------------|----------------------------------------------------------|---------| - | Property | System.String[] | Properties in order of precedence; empty uses the object.| | + | Name | Type | Description | Default | + |----------|-----------------|-----------------------------------------------------------|---------| + | Property | System.String[] | Properties in order of precedence; empty uses the object. | | .OUTPUTS System.String -- The sort key. diff --git a/src/Config/Private/New-ModuleConfigEnvironment.ps1 b/src/Config/Private/New-ModuleConfigEnvironment.ps1 index e9df088..d0197fa 100644 --- a/src/Config/Private/New-ModuleConfigEnvironment.ps1 +++ b/src/Config/Private/New-ModuleConfigEnvironment.ps1 @@ -24,6 +24,9 @@ creating them if necessary, and returns the mapped numeric return code. .NOTES Uses Get-ModuleConfigDirectory and Get-ModuleBinaryDirectory to resolve target paths. Missing directories are created with -Force. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function New-ModuleConfigEnvironment() { diff --git a/src/Config/Private/Read-ModuleConfigFile.ps1 b/src/Config/Private/Read-ModuleConfigFile.ps1 index 387623f..1447f18 100644 --- a/src/Config/Private/Read-ModuleConfigFile.ps1 +++ b/src/Config/Private/Read-ModuleConfigFile.ps1 @@ -12,17 +12,17 @@ error object via Write-FunctionReturnValue with -OverrideReturn $null so that callers receive $null on failure. .PARAMETER Config -| Name | Type | Description | Default | -|--------|---------------|-----------------------------------|---------| -| Config | System.String | Filename of the config to read. | $null | +| Name | Type | Description | Default | +|--------|---------------|---------------------------------|---------| +| Config | System.String | Filename of the config to read. | $null | .PARAMETER IncludeSubConfig -| Name | Type | Description | Default | -|------------------|---------------------------------------------|-----------------------------------------------------------|---------| +| Name | Type | Description | Default | +|------------------|----------------------------------------------|---------------------------------------------------------------|---------| | IncludeSubConfig | System.Management.Automation.SwitchParameter | When set, recursively reads sub-configs referenced by Config. | $false | .OUTPUTS -System.Object — Parsed JSON object on success, or $null on error. +System.Object -- Parsed JSON object on success, or $null on error. .EXAMPLE PS> Read-ModuleConfigFile -Config 'module.json' -IncludeSubConfig @@ -34,6 +34,9 @@ any referenced sub-config. Relies on Get-ModuleConfigDirectory and Read-SecureFile for file I/O. Returns $null via -OverrideReturn $null on error to match calling conventions elsewhere in the module. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Read-ModuleConfigFile() { diff --git a/src/Core/AccessControl/Private/New-ModuleAccessRole.ps1 b/src/Core/AccessControl/Private/New-ModuleAccessRole.ps1 index edf2b4b..7487991 100644 --- a/src/Core/AccessControl/Private/New-ModuleAccessRole.ps1 +++ b/src/Core/AccessControl/Private/New-ModuleAccessRole.ps1 @@ -9,32 +9,32 @@ file under the module config `AccessRoles` directory using secure file helpers and reloads the module access control definitions. .PARAMETER RoleName -| Name | Type | Description | Default | -|------|------|-------------|---------| -| RoleName | System.String | Friendly name for the access role. | '' | +| Name | Type | Description | Default | +|----------|---------------|------------------------------------|---------| +| RoleName | System.String | Friendly name for the access role. | '' | .PARAMETER Users -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Users | System.String[] | List of usernames (or identifiers) assigned to the role. | @() | +| Name | Type | Description | Default | +|-------|-----------------|----------------------------------------------------------|---------| +| Users | System.String[] | List of usernames (or identifiers) assigned to the role. | @() | .PARAMETER AccessControlObject -| Name | Type | Description | Default | -|------|------|-------------|---------| -| AccessControlObject | System.PSCustomObject[] | Array of access control objects (ACLs) to attach to the role. | @() | +| Name | Type | Description | Default | +|---------------------|-------------------------|---------------------------------------------------------------|---------| +| AccessControlObject | System.PSCustomObject[] | Array of access control objects (ACLs) to attach to the role. | @() | .PARAMETER InheritedRoles -| Name | Type | Description | Default | -|------|------|-------------|---------| -| InheritedRoles | System.String[] | Roles whose permissions are inherited by this role. | @() | +| Name | Type | Description | Default | +|----------------|-----------------|-----------------------------------------------------|---------| +| InheritedRoles | System.String[] | Roles whose permissions are inherited by this role. | @() | .PARAMETER Force -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Force | System.Management.Automation.SwitchParameter | Overwrite existing role file if present. | $false | +| Name | Type | Description | Default | +|-------|----------------------------------------------|------------------------------------------|---------| +| Force | System.Management.Automation.SwitchParameter | Overwrite existing role file if present. | $false | .OUTPUTS -System.Object — Structured return object from Write-FunctionReturnValue. Returns +System.Object -- Structured return object from Write-FunctionReturnValue. Returns AccessRoleCreated on success (Data contains RoleName and AccessRole) or one of several error return codes for validation or file errors. @@ -49,6 +49,9 @@ Role files are saved under the AccessRoles subfolder of Get-ModuleConfigDirector Write-SecureFile and New-SecureItem are used to persist files securely. Read-ModuleAccessControl is called after writing to reload the in-memory access control definitions for the current session. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function New-ModuleAccessRole() { @@ -84,8 +87,8 @@ function New-ModuleAccessRole() }; # Remove invalid filename characters from the role name for file saving - [string]$SafeRoleName = Remove-ModuleAmbitiousCharacters -InputString $RoleName -RemoveSpaces; - [string]$AccessRoleFile = Join-Path -Path (Get-ModuleConfigDirectory) -ChildPath ([string]::Format('AccessRoles\{0}.json', $SafeRoleName.ToLower())); + [string]$SafeRoleName = Remove-ModuleAmbitiousCharacters -InputString $RoleName -RemoveSpaces; + [string]$AccessRoleFile = Join-Path -Path (Get-ModuleConfigDirectory) -ChildPath ([string]::Format('AccessRoles\{0}.json', $SafeRoleName.ToLower())); # Test if the access role file already exists; return error if it does and Force is not specified if ((Test-Path $AccessRoleFile) -and -not $Force) { diff --git a/src/Core/AccessControl/Private/Read-ModuleAccessControl.ps1 b/src/Core/AccessControl/Private/Read-ModuleAccessControl.ps1 index 9839df2..8340820 100644 --- a/src/Core/AccessControl/Private/Read-ModuleAccessControl.ps1 +++ b/src/Core/AccessControl/Private/Read-ModuleAccessControl.ps1 @@ -9,7 +9,7 @@ stored in the global runtime variable `Protected.AccessControl` for runtime use. Parsing and IO errors are logged and reported via `Write-FunctionReturnValue`. .OUTPUTS -System.Object — Structured return object from Write-FunctionReturnValue when the +System.Object -- Structured return object from Write-FunctionReturnValue when the AccessRoles folder is not found; otherwise None (populates (Get-GlobalRuntimeVariable).Protected.AccessControl as a side effect). @@ -23,6 +23,9 @@ resulting objects in the global runtime variable. Role files are expected to be valid JSON and are read with Read-SecureFile. Parsing errors for individual files do not abort the overall loading process; they are logged and the loader continues with the remaining files. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Read-ModuleAccessControl() { diff --git a/src/Core/AccessControl/Private/Remove-ModuleAccessRole.ps1 b/src/Core/AccessControl/Private/Remove-ModuleAccessRole.ps1 index cb5b185..2bea695 100644 --- a/src/Core/AccessControl/Private/Remove-ModuleAccessRole.ps1 +++ b/src/Core/AccessControl/Private/Remove-ModuleAccessRole.ps1 @@ -8,12 +8,12 @@ sanitizing the role name into a safe filename. Reloads module access control definitions to reflect the deletion in the current runtime. .PARAMETER RoleName -| Name | Type | Description | Default | -|------|------|-------------|---------| -| RoleName | System.String | Name of the role to remove. | '' | +| Name | Type | Description | Default | +|----------|---------------|-----------------------------|---------| +| RoleName | System.String | Name of the role to remove. | '' | .OUTPUTS -System.Object — Structured return object from Write-FunctionReturnValue when the +System.Object -- Structured return object from Write-FunctionReturnValue when the role name is empty; otherwise None. .EXAMPLE @@ -26,6 +26,9 @@ access control definitions. Uses Remove-SecureItem to safely delete the role file and then calls Read-ModuleAccessControl to refresh the in-memory role list for the current session. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Remove-ModuleAccessRole() { diff --git a/src/Core/AccessControl/Private/Show-ModuleAccessRoles.ps1 b/src/Core/AccessControl/Private/Show-ModuleAccessRoles.ps1 index 6a59764..188504e 100644 --- a/src/Core/AccessControl/Private/Show-ModuleAccessRoles.ps1 +++ b/src/Core/AccessControl/Private/Show-ModuleAccessRoles.ps1 @@ -8,7 +8,7 @@ Writes a formatted access role summary to the module logging system at the the global runtime variable and emits them as structured log data. .OUTPUTS -None — Emits structured log output at the Output level as a side effect. +None -- Emits structured log output at the Output level as a side effect. .EXAMPLE PS> Show-ModuleAccessRoles @@ -19,6 +19,9 @@ Writes the currently loaded access roles to the logging system at Output level. This helper does not modify state; it only emits the current (Get-GlobalRuntimeVariable).Protected.AccessControl via Write-LoggingEntry. Read-ModuleAccessControl must have been called previously to populate the list. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Show-ModuleAccessRoles() { diff --git a/src/Core/AccessControl/Public/New-IcingaAccessRole.ps1 b/src/Core/AccessControl/Public/New-IcingaAccessRole.ps1 index 5d7de58..c093ecd 100644 --- a/src/Core/AccessControl/Public/New-IcingaAccessRole.ps1 +++ b/src/Core/AccessControl/Public/New-IcingaAccessRole.ps1 @@ -9,32 +9,32 @@ implementation; this wrapper simply forwards arguments and returns the same standardized return values. .PARAMETER RoleName -| Name | Type | Description | Default | -|------|------|-------------|---------| -| RoleName | System.String | Friendly name for the access role. | '' | +| Name | Type | Description | Default | +|----------|---------------|------------------------------------|---------| +| RoleName | System.String | Friendly name for the access role. | '' | .PARAMETER Users -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Users | System.String[] | List of usernames (or identifiers) assigned to the role. | @() | +| Name | Type | Description | Default | +|-------|-----------------|----------------------------------------------------------|---------| +| Users | System.String[] | List of usernames (or identifiers) assigned to the role. | @() | .PARAMETER AccessControlObject -| Name | Type | Description | Default | -|------|------|-------------|---------| -| AccessControlObject | System.PSCustomObject[] | Array of access control objects (ACLs) to attach to the role. | @() | +| Name | Type | Description | Default | +|---------------------|-------------------------|---------------------------------------------------------------|---------| +| AccessControlObject | System.PSCustomObject[] | Array of access control objects (ACLs) to attach to the role. | @() | .PARAMETER InheritedRoles -| Name | Type | Description | Default | -|------|------|-------------|---------| -| InheritedRoles | System.String[] | Roles whose permissions are inherited by this role. | @() | +| Name | Type | Description | Default | +|----------------|-----------------|-----------------------------------------------------|---------| +| InheritedRoles | System.String[] | Roles whose permissions are inherited by this role. | @() | .PARAMETER Force -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Force | System.Management.Automation.SwitchParameter | Overwrite existing role file if present. | $false | +| Name | Type | Description | Default | +|-------|----------------------------------------------|------------------------------------------|---------| +| Force | System.Management.Automation.SwitchParameter | Overwrite existing role file if present. | $false | .OUTPUTS -PSCustomObject — Forwarded return value from `New-ModuleAccessRole`. +PSCustomObject -- Forwarded return value from `New-ModuleAccessRole`. .EXAMPLE PS> New-IcingaAccessRole -RoleName 'admin' -Users @('alice') -AccessControlObject $acl @@ -46,6 +46,9 @@ control object and persists it via the private implementation. This function is intentionally thin and exists to expose a public command surface while the implementation and persistence logic remain in the module private helper. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function New-IcingaAccessRole() { diff --git a/src/Core/AccessControl/Public/Remove-IcingaAccessRole.ps1 b/src/Core/AccessControl/Public/Remove-IcingaAccessRole.ps1 index d5fba40..50b20f9 100644 --- a/src/Core/AccessControl/Public/Remove-IcingaAccessRole.ps1 +++ b/src/Core/AccessControl/Public/Remove-IcingaAccessRole.ps1 @@ -8,12 +8,12 @@ Deletes a persisted access role by delegating to the private return value or status codes in case of error. .PARAMETER RoleName -| Name | Type | Description | Default | -|------|------|-------------|---------| -| RoleName | System.String | Name of the role to remove. | '' | +| Name | Type | Description | Default | +|----------|---------------|-----------------------------|---------| +| RoleName | System.String | Name of the role to remove. | '' | .OUTPUTS -PSCustomObject — Forwarded return value from `Remove-ModuleAccessRole`. +PSCustomObject -- Forwarded return value from `Remove-ModuleAccessRole`. .EXAMPLE PS> Remove-IcingaAccessRole -RoleName 'admin' @@ -24,6 +24,9 @@ access control definitions via the private implementation. .NOTES This wrapper keeps the public module API distinct from the private implementation which performs the file deletion and reloads access control data. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Remove-IcingaAccessRole() { diff --git a/src/Core/AccessControl/Public/Show-IcingaAccessRoles.ps1 b/src/Core/AccessControl/Public/Show-IcingaAccessRoles.ps1 index ad80a93..bfb0dff 100644 --- a/src/Core/AccessControl/Public/Show-IcingaAccessRoles.ps1 +++ b/src/Core/AccessControl/Public/Show-IcingaAccessRoles.ps1 @@ -7,7 +7,7 @@ Public wrapper that emits the current in-memory access role definitions via the module logging system by delegating to `Show-ModuleAccessRoles`. .OUTPUTS -None — Emits the current access role list to the logging system at Output level. +None -- Emits the current access role list to the logging system at Output level. .EXAMPLE PS> Show-IcingaAccessRoles @@ -17,6 +17,9 @@ Writes all currently loaded Icinga access roles to the logging output channel. .NOTES This command does not modify state; it is purely informational and relies on Read-ModuleAccessControl having been run previously to populate the in-memory list. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Show-IcingaAccessRoles() { diff --git a/src/Core/ErrorHandling/Private/Set-InternalExitCodes.ps1 b/src/Core/ErrorHandling/Private/Set-InternalExitCodes.ps1 index a384da9..e433f08 100644 --- a/src/Core/ErrorHandling/Private/Set-InternalExitCodes.ps1 +++ b/src/Core/ErrorHandling/Private/Set-InternalExitCodes.ps1 @@ -21,6 +21,9 @@ is already populated. .NOTES Private helper used by error-handling and logging routines; safe to call multiple times because it will not overwrite an existing table. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Set-InternalExitCodes() { diff --git a/src/Core/ErrorHandling/Private/Write-FunctionReturnValue.ps1 b/src/Core/ErrorHandling/Private/Write-FunctionReturnValue.ps1 index 915aa46..3ce5065 100644 --- a/src/Core/ErrorHandling/Private/Write-FunctionReturnValue.ps1 +++ b/src/Core/ErrorHandling/Private/Write-FunctionReturnValue.ps1 @@ -9,29 +9,29 @@ the current logging configuration, a structured log entry is enqueued. Supports returning an override value instead of the mapped code. .PARAMETER ReturnValue -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ReturnValue | System.String | Semantic key of the return-code entry to emit (for example: 'TlsHandshakeSuccessful'). | | +| Name | Type | Description | Default | +|-------------|---------------|----------------------------------------------------------------------------------------|---------| +| ReturnValue | System.String | Semantic key of the return-code entry to emit (for example: 'TlsHandshakeSuccessful'). | | .PARAMETER Data -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Data | System.Collections.Hashtable | Additional contextual data to attach to the log entry. | @{} | +| Name | Type | Description | Default | +|------|------------------------------|--------------------------------------------------------|---------| +| Data | System.Collections.Hashtable | Additional contextual data to attach to the log entry. | @{} | .PARAMETER OverrideReturn -| Name | Type | Description | Default | -|------|------|-------------|---------| +| Name | Type | Description | Default | +|----------------|---------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------| | OverrideReturn | System.Object | If provided (not 'Core::IgnoreOverride'), this value is returned instead of the mapped numeric code. Booleans are returned via explicit cast to preserve type. | Core::IgnoreOverride | .PARAMETER AutomationRun -| Name | Type | Description | Default | -|------|------|-------------|---------| -| AutomationRun | System.Management.Automation.SwitchParameter | When set, returns @{ ExitCode; Output } instead of the numeric code. ExitCode is 0 for Info/Audit/Debug severities, 2 for all others. | $false | +| Name | Type | Description | Default | +|---------------|----------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------|---------| +| AutomationRun | System.Management.Automation.SwitchParameter | When set, returns @{ ExitCode; Output } instead of the numeric code. ExitCode is 0 for Info/Audit/Debug severities, 2 for all others. | $false | .OUTPUTS -System.Int32 — Numeric code from the return-code table when neither -OverrideReturn nor -AutomationRun is active. -System.Collections.Hashtable — @{ ExitCode = System.Int32; Output = System.String } when -AutomationRun is set. -System.Object — The -OverrideReturn value as-is when provided, taking precedence over both the numeric code and -AutomationRun. +System.Int32 -- Numeric code from the return-code table when neither -OverrideReturn nor -AutomationRun is active. +System.Collections.Hashtable -- @{ ExitCode = System.Int32; Output = System.String } when -AutomationRun is set. +System.Object -- The -OverrideReturn value as-is when provided, taking precedence over both the numeric code and -AutomationRun. .EXAMPLE PS> Write-FunctionReturnValue -ReturnValue 'TlsHandshakeSuccessful' @@ -41,6 +41,9 @@ Calls Set-InternalExitCodes to ensure the return-code table is populated before Enqueues a log entry via Write-LoggingEntry only when the entry's severity is enabled in the current logging configuration and is not 'Audit'. Must be called from the main thread or via Get-GlobalRuntimeVariable in daemon context. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Write-FunctionReturnValue() { @@ -58,7 +61,7 @@ function Write-FunctionReturnValue() # Lookup return code entry if ($GlobalVariable.Public.ReturnCodes.ContainsKey($ReturnValue)) { - $codeEntry = $GlobalVariable.Public.ReturnCodes[$ReturnValue]; + $codeEntry = $GlobalVariable.Public.ReturnCodes[$ReturnValue]; # Assign a unique message ID for tracking $Data['LoggingMessageId'] = $GlobalVariable.Private.Logging.CurrentLoggingId.ToString(); diff --git a/src/Core/ErrorHandling/Public/Test-IcingaError.ps1 b/src/Core/ErrorHandling/Public/Test-IcingaError.ps1 index 6fceb61..a2cfb41 100644 --- a/src/Core/ErrorHandling/Public/Test-IcingaError.ps1 +++ b/src/Core/ErrorHandling/Public/Test-IcingaError.ps1 @@ -10,9 +10,9 @@ 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 | +| 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. @@ -27,6 +27,9 @@ Stops the plugin with the error message when the query failed. 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. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Test-IcingaError() { diff --git a/src/Core/Logging/Private/Format-LoggingConsoleException.ps1 b/src/Core/Logging/Private/Format-LoggingConsoleException.ps1 index d875cf4..250e84e 100644 --- a/src/Core/Logging/Private/Format-LoggingConsoleException.ps1 +++ b/src/Core/Logging/Private/Format-LoggingConsoleException.ps1 @@ -7,23 +7,26 @@ Format an exception object for console output. using `Format-LoggingConsoleObjectProperties` and a predefined set of properties. .PARAMETER Exception -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Exception | System.Exception | The exception to format | | +| Name | Type | Description | Default | +|-----------|------------------|-------------------------|---------| +| Exception | System.Exception | The exception to format | | .PARAMETER Indent -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Indent | System.String | Optional indentation string for nested formatting | '' | +| Name | Type | Description | Default | +|--------|---------------|---------------------------------------------------|---------| +| Indent | System.String | Optional indentation string for nested formatting | '' | .OUTPUTS -System.String — A formatted multiline string describing the exception. +System.String -- A formatted multiline string describing the exception. .EXAMPLE PS> Format-LoggingConsoleException -Exception $ex -Indent ' ' .NOTES Uses `Format-LoggingConsoleObjectProperties` to extract common exception details. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Format-LoggingConsoleException() { diff --git a/src/Core/Logging/Private/Format-LoggingConsoleMessage.ps1 b/src/Core/Logging/Private/Format-LoggingConsoleMessage.ps1 index 0880ea3..0776da5 100644 --- a/src/Core/Logging/Private/Format-LoggingConsoleMessage.ps1 +++ b/src/Core/Logging/Private/Format-LoggingConsoleMessage.ps1 @@ -7,23 +7,26 @@ Format a markup-colored logging message for console output. and returns either a formatted string or writes the colored message to the host. .PARAMETER Message -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Message | System.String | Message containing optional color tags | | +| Name | Type | Description | Default | +|---------|---------------|----------------------------------------|---------| +| Message | System.String | Message containing optional color tags | | .PARAMETER GetMsgObj -| Name | Type | Description | Default | -|------|------|-------------|---------| +| Name | Type | Description | Default | +|-----------|------------------------|-------------------------------------------------------------------------------|----------| | GetMsgObj | System.SwitchParameter | When set the function returns the formatted string instead of writing to host | `$false` | .OUTPUTS -System.String — The formatted message string when `-GetMsgObj` is set; otherwise None, the message is written directly to the host. +System.String -- The formatted message string when `-GetMsgObj` is set; otherwise None, the message is written directly to the host. .EXAMPLE PS> Format-LoggingConsoleMessage -Message '[Green]OK[/Green] Completed' -GetMsgObj .NOTES Supports escaping and validates color names against `System.ConsoleColor`. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Format-LoggingConsoleMessage() { @@ -44,8 +47,8 @@ function Format-LoggingConsoleMessage() $StringBuilder = New-Object System.Text.StringBuilder; # Allowed colors (optional restriction) - $validColors = [enum]::GetNames([System.ConsoleColor]); - $currentIndex = 0 + $validColors = [enum]::GetNames([System.ConsoleColor]); + $currentIndex = 0 while ($currentIndex -lt $Message.Length) { # Find next opening tag: [color] diff --git a/src/Core/Logging/Private/Format-LoggingConsoleNullValue.ps1 b/src/Core/Logging/Private/Format-LoggingConsoleNullValue.ps1 index 326b6f5..453b286 100644 --- a/src/Core/Logging/Private/Format-LoggingConsoleNullValue.ps1 +++ b/src/Core/Logging/Private/Format-LoggingConsoleNullValue.ps1 @@ -7,18 +7,21 @@ Return a formatted representation for null values in console output. for null values used throughout logging output formatting helpers. .PARAMETER Indent -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Indent | System.String | Optional prefix indentation for the returned string | '' | +| Name | Type | Description | Default | +|--------|---------------|-----------------------------------------------------|---------| +| Indent | System.String | Optional prefix indentation for the returned string | '' | .OUTPUTS -System.String — A one-line formatted representation of a null value. +System.String -- A one-line formatted representation of a null value. .EXAMPLE PS> Format-LoggingConsoleNullValue -Indent ' ' .NOTES Used by multiple formatting helpers to ensure consistent null rendering. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Format-LoggingConsoleNullValue() { diff --git a/src/Core/Logging/Private/Format-LoggingConsoleObjectProperties.ps1 b/src/Core/Logging/Private/Format-LoggingConsoleObjectProperties.ps1 index 74d14e4..853dbdd 100644 --- a/src/Core/Logging/Private/Format-LoggingConsoleObjectProperties.ps1 +++ b/src/Core/Logging/Private/Format-LoggingConsoleObjectProperties.ps1 @@ -7,22 +7,22 @@ Format selected properties of an object for console logging. from an object and returns a colorized string suitable for console logging. .PARAMETER Object -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Object | System.Object | The input object to inspect | | +| Name | Type | Description | Default | +|--------|---------------|-----------------------------|---------| +| Object | System.Object | The input object to inspect | | .PARAMETER Properties -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Properties | System.Array | List of property paths to extract (e.g. 'Client.Address') | @() | +| Name | Type | Description | Default | +|------------|--------------|-----------------------------------------------------------|---------| +| Properties | System.Array | List of property paths to extract (e.g. 'Client.Address') | @() | .PARAMETER Indent -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Indent | System.String | Indentation prefix for each formatted line | '' | +| Name | Type | Description | Default | +|--------|---------------|--------------------------------------------|---------| +| Indent | System.String | Indentation prefix for each formatted line | '' | .OUTPUTS -System.String — A multi-line formatted string with property:value pairs. +System.String -- A multi-line formatted string with property:value pairs. .EXAMPLE PS> Format-LoggingConsoleObjectProperties -Object $resp -Properties @('Status','Body') @@ -30,6 +30,9 @@ PS> Format-LoggingConsoleObjectProperties -Object $resp -Properties @('Status',' .NOTES Relies on `Get-LoggingConsoleNestedProperty`, `Get-LoggingConsoleColorForObjectType`, and `Get-LoggingConsoleColorForValue` for nested access and color selection. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Format-LoggingConsoleObjectProperties() { diff --git a/src/Core/Logging/Private/Format-LoggingConsoleObjects.ps1 b/src/Core/Logging/Private/Format-LoggingConsoleObjects.ps1 index 11e6aac..0fdd926 100644 --- a/src/Core/Logging/Private/Format-LoggingConsoleObjects.ps1 +++ b/src/Core/Logging/Private/Format-LoggingConsoleObjects.ps1 @@ -8,17 +8,17 @@ several special CLR types (TcpClient, SslStream, X509Certificate2, TcpListener) and returns a string with structured, colorized output for logging. .PARAMETER Object -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Object | System.Object | The object to format for console output | | +| Name | Type | Description | Default | +|--------|---------------|-----------------------------------------|---------| +| Object | System.Object | The object to format for console output | | .PARAMETER Level -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Level | System.Int32 | Indentation/nesting level for pretty printing | 0 | +| Name | Type | Description | Default | +|-------|--------------|-----------------------------------------------|---------| +| Level | System.Int32 | Indentation/nesting level for pretty printing | 0 | .OUTPUTS -System.String — A formatted multi-line representation of the object. +System.String -- A formatted multi-line representation of the object. .EXAMPLE PS> Format-LoggingConsoleObjects -Object $response -Level 1 @@ -26,6 +26,9 @@ PS> Format-LoggingConsoleObjects -Object $response -Level 1 .NOTES This function delegates to other helpers (scalar, properties, nested access) and is the central place for human-friendly logging formatting. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Format-LoggingConsoleObjects() { @@ -41,8 +44,8 @@ function Format-LoggingConsoleObjects() if ($Level -eq 0) { $Prefix = ''; } else { - $Prefix = '└── ' - }; + $Prefix = [string]::Concat([char]0x2514, [char]0x2500, [char]0x2500, ' '); + } # Compute current indentation $Indent = [string]::Format('{0}{1}', $Indent, $Prefix); diff --git a/src/Core/Logging/Private/Format-LoggingConsoleScalar.ps1 b/src/Core/Logging/Private/Format-LoggingConsoleScalar.ps1 index 34fb3cd..1ddeafd 100644 --- a/src/Core/Logging/Private/Format-LoggingConsoleScalar.ps1 +++ b/src/Core/Logging/Private/Format-LoggingConsoleScalar.ps1 @@ -7,23 +7,26 @@ Format a scalar value with color for console logging. using `Get-LoggingConsoleColorForValue` to determine an appropriate color. .PARAMETER Object -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Object | System.Object | The value to format | | +| Name | Type | Description | Default | +|--------|---------------|---------------------|---------| +| Object | System.Object | The value to format | | .PARAMETER Indent -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Indent | System.String | Optional indentation prefix | '' | +| Name | Type | Description | Default | +|--------|---------------|-----------------------------|---------| +| Indent | System.String | Optional indentation prefix | '' | .OUTPUTS -System.String — A formatted single-line representation of the scalar value. +System.String -- A formatted single-line representation of the scalar value. .EXAMPLE PS> Format-LoggingConsoleScalar -Object 123 -Indent ' ' .NOTES Used internally by `Format-LoggingConsoleObjects` for fallback scalar formatting. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Format-LoggingConsoleScalar() { diff --git a/src/Core/Logging/Private/Format-LoggingConsoleSslStream.ps1 b/src/Core/Logging/Private/Format-LoggingConsoleSslStream.ps1 index b54c98a..abf7dda 100644 --- a/src/Core/Logging/Private/Format-LoggingConsoleSslStream.ps1 +++ b/src/Core/Logging/Private/Format-LoggingConsoleSslStream.ps1 @@ -7,23 +7,26 @@ Format `SslStream` properties for console output. from a `System.Net.Security.SslStream` and returns a colorized string. .PARAMETER Stream -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Stream | System.Net.Security.SslStream | The SSL stream to inspect | | +| Name | Type | Description | Default | +|--------|-------------------------------|---------------------------|---------| +| Stream | System.Net.Security.SslStream | The SSL stream to inspect | | .PARAMETER Indent -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Indent | System.String | Optional indentation prefix | $null | +| Name | Type | Description | Default | +|--------|---------------|-----------------------------|---------| +| Indent | System.String | Optional indentation prefix | $null | .OUTPUTS -System.String — A multi-line formatted representation of the stream properties. +System.String -- A multi-line formatted representation of the stream properties. .EXAMPLE PS> Format-LoggingConsoleSslStream -Stream $sslStream -Indent ' ' .NOTES Delegates property extraction to `Format-LoggingConsoleObjectProperties`. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Format-LoggingConsoleSslStream() { diff --git a/src/Core/Logging/Private/Format-LoggingConsoleTcpClient.ps1 b/src/Core/Logging/Private/Format-LoggingConsoleTcpClient.ps1 index e82a276..a7b4704 100644 --- a/src/Core/Logging/Private/Format-LoggingConsoleTcpClient.ps1 +++ b/src/Core/Logging/Private/Format-LoggingConsoleTcpClient.ps1 @@ -7,23 +7,26 @@ Format a `TcpClient` for console logging. `System.Net.Sockets.TcpClient`, including connection status and endpoints. .PARAMETER Client -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Client | System.Net.Sockets.TcpClient | The TCP client instance to format | | +| Name | Type | Description | Default | +|--------|------------------------------|-----------------------------------|---------| +| Client | System.Net.Sockets.TcpClient | The TCP client instance to format | | .PARAMETER Indent -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Indent | System.String | Optional indentation prefix | '' | +| Name | Type | Description | Default | +|--------|---------------|-----------------------------|---------| +| Indent | System.String | Optional indentation prefix | '' | .OUTPUTS -System.String — A formatted multi-line description of the `TcpClient`. +System.String -- A formatted multi-line description of the `TcpClient`. .EXAMPLE PS> Format-LoggingConsoleTcpClient -Client $client .NOTES This helper uses `Format-LoggingConsoleObjectProperties` for property extraction. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Format-LoggingConsoleTcpClient() { diff --git a/src/Core/Logging/Private/Format-LoggingConsoleTcpListener.ps1 b/src/Core/Logging/Private/Format-LoggingConsoleTcpListener.ps1 index 4a7e676..35d0174 100644 --- a/src/Core/Logging/Private/Format-LoggingConsoleTcpListener.ps1 +++ b/src/Core/Logging/Private/Format-LoggingConsoleTcpListener.ps1 @@ -7,23 +7,26 @@ Format a `TcpListener` object for console logging. `System.Net.Sockets.TcpListener` and returns a colorized string for logging. .PARAMETER TcpListener -| Name | Type | Description | Default | -|------|------|-------------|---------| -| TcpListener | System.Net.Sockets.TcpListener | The listener to format | | +| Name | Type | Description | Default | +|-------------|--------------------------------|------------------------|---------| +| TcpListener | System.Net.Sockets.TcpListener | The listener to format | | .PARAMETER Indent -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Indent | System.String | Optional indentation prefix | '' | +| Name | Type | Description | Default | +|--------|---------------|-----------------------------|---------| +| Indent | System.String | Optional indentation prefix | '' | .OUTPUTS -System.String — A formatted string describing listener properties. +System.String -- A formatted string describing listener properties. .EXAMPLE PS> Format-LoggingConsoleTcpListener -TcpListener $listener .NOTES Used to present network listener details consistently in logs. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Format-LoggingConsoleTcpListener() { diff --git a/src/Core/Logging/Private/Format-LoggingConsoleTlsCertificate.ps1 b/src/Core/Logging/Private/Format-LoggingConsoleTlsCertificate.ps1 index 55cfa0d..bd2408a 100644 --- a/src/Core/Logging/Private/Format-LoggingConsoleTlsCertificate.ps1 +++ b/src/Core/Logging/Private/Format-LoggingConsoleTlsCertificate.ps1 @@ -8,23 +8,26 @@ Format an X509 certificate for console logging. them as a colorized multi-line string for inclusion in logs. .PARAMETER Certificate -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Certificate | System.Security.Cryptography.X509Certificates.X509Certificate2 | Certificate to format | | +| Name | Type | Description | Default | +|-------------|----------------------------------------------------------------|-----------------------|---------| +| Certificate | System.Security.Cryptography.X509Certificates.X509Certificate2 | Certificate to format | | .PARAMETER Indent -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Indent | System.String | Optional indentation prefix | '' | +| Name | Type | Description | Default | +|--------|---------------|-----------------------------|---------| +| Indent | System.String | Optional indentation prefix | '' | .OUTPUTS -System.String — A formatted representation of the certificate. +System.String -- A formatted representation of the certificate. .EXAMPLE PS> Format-LoggingConsoleTlsCertificate -Certificate $cert .NOTES Useful when logging TLS connection metadata. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Format-LoggingConsoleTlsCertificate() { diff --git a/src/Core/Logging/Private/Get-LoggingConsoleColorForObjectType.ps1 b/src/Core/Logging/Private/Get-LoggingConsoleColorForObjectType.ps1 index 698f2a7..c4780a5 100644 --- a/src/Core/Logging/Private/Get-LoggingConsoleColorForObjectType.ps1 +++ b/src/Core/Logging/Private/Get-LoggingConsoleColorForObjectType.ps1 @@ -8,28 +8,31 @@ Select a console color name for a given object type or parameter. for special cases like parameters and null values. .PARAMETER ObjectName -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ObjectName | System.String | The CLR type name or friendly name to evaluate | | +| Name | Type | Description | Default | +|------------|---------------|------------------------------------------------|---------| +| ObjectName | System.String | The CLR type name or friendly name to evaluate | | .PARAMETER IsParameter -| Name | Type | Description | Default | -|------|------|-------------|---------| -| IsParameter | System.SwitchParameter | When set returns the color used for parameter names | $false | +| Name | Type | Description | Default | +|-------------|------------------------|-----------------------------------------------------|---------| +| IsParameter | System.SwitchParameter | When set returns the color used for parameter names | $false | .PARAMETER IsNullValue -| Name | Type | Description | Default | -|------|------|-------------|---------| -| IsNullValue | System.SwitchParameter | When set returns the color used for null values | $false | +| Name | Type | Description | Default | +|-------------|------------------------|-------------------------------------------------|---------| +| IsNullValue | System.SwitchParameter | When set returns the color used for null values | $false | .OUTPUTS -System.String — The name of a `System.ConsoleColor` value. +System.String -- The name of a `System.ConsoleColor` value. .EXAMPLE PS> Get-LoggingConsoleColorForObjectType -ObjectName 'String' .NOTES Color choices are mapped to common CLR type names and special flags. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Get-LoggingConsoleColorForObjectType() { diff --git a/src/Core/Logging/Private/Get-LoggingConsoleColorForValue.ps1 b/src/Core/Logging/Private/Get-LoggingConsoleColorForValue.ps1 index 66a8c5c..243f217 100644 --- a/src/Core/Logging/Private/Get-LoggingConsoleColorForValue.ps1 +++ b/src/Core/Logging/Private/Get-LoggingConsoleColorForValue.ps1 @@ -8,18 +8,21 @@ appropriate `System.ConsoleColor` name by delegating to `Get-LoggingConsoleColorForObjectType` with the value's CLR type name. .PARAMETER Value -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Value | System.Object | The value to choose a color for | | +| Name | Type | Description | Default | +|-------|---------------|---------------------------------|---------| +| Value | System.Object | The value to choose a color for | | .OUTPUTS -System.String — The chosen console color name. +System.String -- The chosen console color name. .EXAMPLE PS> Get-LoggingConsoleColorForValue -Value 42 .NOTES Returns a special color for `$null` values. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Get-LoggingConsoleColorForValue() { diff --git a/src/Core/Logging/Private/Get-LoggingConsoleNestedProperty.ps1 b/src/Core/Logging/Private/Get-LoggingConsoleNestedProperty.ps1 index 31adfc9..85b91b2 100644 --- a/src/Core/Logging/Private/Get-LoggingConsoleNestedProperty.ps1 +++ b/src/Core/Logging/Private/Get-LoggingConsoleNestedProperty.ps1 @@ -8,23 +8,26 @@ Resolve a nested property path on an object safely. any segment cannot be resolved. .PARAMETER InputObject -| Name | Type | Description | Default | -|------|------|-------------|---------| -| InputObject | System.Object | The object to query | | +| Name | Type | Description | Default | +|-------------|---------------|---------------------|---------| +| InputObject | System.Object | The object to query | | .PARAMETER PropertyPath -| Name | Type | Description | Default | -|------|------|-------------|---------| -| PropertyPath | System.String | Dot-separated property path to resolve | | +| Name | Type | Description | Default | +|--------------|---------------|----------------------------------------|---------| +| PropertyPath | System.String | Dot-separated property path to resolve | | .OUTPUTS -System.Object — The resolved property value or `$null` when not found. +System.Object -- The resolved property value or `$null` when not found. .EXAMPLE PS> Get-LoggingConsoleNestedProperty -InputObject $resp -PropertyPath 'Client.Address' .NOTES This helper intentionally swallows property access errors and returns `$null` on failure. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Get-LoggingConsoleNestedProperty() { diff --git a/src/Core/Logging/Private/Get-LoggingEventLogSeverity.ps1 b/src/Core/Logging/Private/Get-LoggingEventLogSeverity.ps1 index 8f1fc8e..c2c7fa3 100644 --- a/src/Core/Logging/Private/Get-LoggingEventLogSeverity.ps1 +++ b/src/Core/Logging/Private/Get-LoggingEventLogSeverity.ps1 @@ -7,18 +7,21 @@ Map internal log severity to Windows EventLog entry types. Windows EventLog entry types such as 'Information' or 'Error'. .PARAMETER Severity -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Severity | System.String | Internal severity string (e.g. 'Debug', 'Info') | | +| Name | Type | Description | Default | +|----------|---------------|-------------------------------------------------|---------| +| Severity | System.String | Internal severity string (e.g. 'Debug', 'Info') | | .OUTPUTS -System.String — The Windows EventLog entry type name. +System.String -- The Windows EventLog entry type name. .EXAMPLE PS> Get-LoggingEventLogSeverity -Severity 'Error' .NOTES Unknown severities default to 'Information'. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Get-LoggingEventLogSeverity() { diff --git a/src/Core/Logging/Private/Register-LoggingWindowsEventLog.ps1 b/src/Core/Logging/Private/Register-LoggingWindowsEventLog.ps1 index a38a49d..8eec0a8 100644 --- a/src/Core/Logging/Private/Register-LoggingWindowsEventLog.ps1 +++ b/src/Core/Logging/Private/Register-LoggingWindowsEventLog.ps1 @@ -7,7 +7,7 @@ Create and configure Windows Event Log sources for this module. namespace and ensures the log maximum size is configured. .OUTPUTS -None — Registers event sources under the module name and configures the maximum log size. +None -- Registers event sources under the module name and configures the maximum log size. .EXAMPLE PS> Register-LoggingWindowsEventLog @@ -16,6 +16,9 @@ PS> Register-LoggingWindowsEventLog Requires administrative privileges to create Windows EventLog sources and modify log settings. The module name is resolved via `Get-ModuleProjectName`. Return codes are read from `(Get-GlobalRuntimeVariable).Public.ReturnCodes` to derive the full list of source names. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Register-LoggingWindowsEventLog() { diff --git a/src/Core/Logging/Private/Set-LoggingLogLevel.ps1 b/src/Core/Logging/Private/Set-LoggingLogLevel.ps1 index 0474d5b..b6d8a49 100644 --- a/src/Core/Logging/Private/Set-LoggingLogLevel.ps1 +++ b/src/Core/Logging/Private/Set-LoggingLogLevel.ps1 @@ -7,18 +7,21 @@ Set the global logging level for this module. runtime variable so subsequent log writes follow the desired verbosity. .PARAMETER Level -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Level | System.String | One of 'Debug','Audit','Info','Success','Warning','Error','Fatal' | 'Info' | +| Name | Type | Description | Default | +|-------|---------------|-------------------------------------------------------------------|---------| +| Level | System.String | One of 'Debug','Audit','Info','Success','Warning','Error','Fatal' | 'Info' | .OUTPUTS -None — Updates `(Get-GlobalRuntimeVariable).Public.Logging.Level`. +None -- Updates `(Get-GlobalRuntimeVariable).Public.Logging.Level`. .EXAMPLE PS> Set-LoggingLogLevel -Level 'Debug' .NOTES Use `Test-LoggingWriteLog` to determine whether a message at a given level will be emitted. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Set-LoggingLogLevel() { diff --git a/src/Core/Logging/Private/Start-LoggingDaemon.ps1 b/src/Core/Logging/Private/Start-LoggingDaemon.ps1 index 1cf7c5f..95f0dd5 100644 --- a/src/Core/Logging/Private/Start-LoggingDaemon.ps1 +++ b/src/Core/Logging/Private/Start-LoggingDaemon.ps1 @@ -8,7 +8,7 @@ and processes objects from the global logging queue. It formats messages, writes Windows EventLog entries and prints colorized output to the console. .OUTPUTS -None — Operates for side effects (writes logs and event entries). +None -- Operates for side effects (writes logs and event entries). .EXAMPLE PS> Start-LoggingDaemon @@ -20,6 +20,9 @@ must never run on the main thread. All access to shared state goes through `Get-GlobalRuntimeVariable` because the runspace receives only a snapshot of `$Global:Icinga` at startup. The daemon exits cleanly when `Test-ThreadRunning` returns `$false`. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Start-LoggingDaemon() { @@ -79,10 +82,10 @@ function Start-LoggingDaemon() $EntryType = Get-LoggingEventLogSeverity -Severity $LogObject.Level; [string]$EventLogMessage = Format-LoggingConsoleMessage -Message $LogMessage -GetMsgObj; - $EventLogMessage += "`r`n" + '============================' + "`r`n" + $LogMessage; + $EventLogMessage += "`r`n" + '============================' + "`r`n" + $LogMessage; - $EventLogSource = [string]::Format('{0}::{1}', $ModuleName, $LogArea); - $EventLog = New-Object System.Diagnostics.EventLog; + $EventLogSource = [string]::Format('{0}::{1}', $ModuleName, $LogArea); + $EventLog = New-Object System.Diagnostics.EventLog; try { $EventLog.Log = $ModuleName; $EventLog.Source = $EventLogSource; diff --git a/src/Core/Logging/Private/Test-LoggingConsoleNextObjectIterable.ps1 b/src/Core/Logging/Private/Test-LoggingConsoleNextObjectIterable.ps1 index 9d1691d..49c21b2 100644 --- a/src/Core/Logging/Private/Test-LoggingConsoleNextObjectIterable.ps1 +++ b/src/Core/Logging/Private/Test-LoggingConsoleNextObjectIterable.ps1 @@ -8,18 +8,21 @@ Determine whether an object should be treated as iterable for logging. for scalar values such as strings. .PARAMETER Value -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Value | System.Object | The value to test for iterable printing | | +| Name | Type | Description | Default | +|-------|---------------|-----------------------------------------|---------| +| Value | System.Object | The value to test for iterable printing | | .OUTPUTS -System.Boolean — `$true` when the value is considered iterable for logging. +System.Boolean -- `$true` when the value is considered iterable for logging. .EXAMPLE PS> Test-LoggingConsoleNextObjectIterable -Value $arr .NOTES Strings and certain CLR types are intentionally excluded from iteration. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Test-LoggingConsoleNextObjectIterable() { diff --git a/src/Core/Logging/Private/Test-LoggingWriteLog.ps1 b/src/Core/Logging/Private/Test-LoggingWriteLog.ps1 index 8907a7e..3b14eb7 100644 --- a/src/Core/Logging/Private/Test-LoggingWriteLog.ps1 +++ b/src/Core/Logging/Private/Test-LoggingWriteLog.ps1 @@ -8,18 +8,21 @@ currently configured global logging level and returns `$true` when the message should be written. .PARAMETER Level -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Level | System.String | The severity of the message to evaluate | 'Info' | +| Name | Type | Description | Default | +|-------|---------------|-----------------------------------------|---------| +| Level | System.String | The severity of the message to evaluate | 'Info' | .OUTPUTS -System.Boolean — `$true` if the message should be written given the current logging level. +System.Boolean -- `$true` if the message should be written given the current logging level. .EXAMPLE PS> Test-LoggingWriteLog -Level 'Debug' .NOTES Logging level hierarchy is implemented by explicit membership checks per level. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Test-LoggingWriteLog() { @@ -76,4 +79,4 @@ function Test-LoggingWriteLog() } return $true; -} \ No newline at end of file +} diff --git a/src/Core/Logging/Private/Update-LoggingThreadLoggingId.ps1 b/src/Core/Logging/Private/Update-LoggingThreadLoggingId.ps1 index 6589549..721e191 100644 --- a/src/Core/Logging/Private/Update-LoggingThreadLoggingId.ps1 +++ b/src/Core/Logging/Private/Update-LoggingThreadLoggingId.ps1 @@ -7,18 +7,21 @@ Set or renew the current per-thread logging identifier. generated by a thread. If a `ThreadId` is provided it is used; otherwise a new GUID is created. .PARAMETER ThreadId -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ThreadId | System.String | Optional GUID to use as the current logging id | $null | +| Name | Type | Description | Default | +|----------|---------------|------------------------------------------------|---------| +| ThreadId | System.String | Optional GUID to use as the current logging id | $null | .OUTPUTS -None — Updates `(Get-GlobalRuntimeVariable).Private.Logging.CurrentLoggingId`. +None -- Updates `(Get-GlobalRuntimeVariable).Private.Logging.CurrentLoggingId`. .EXAMPLE PS> Update-LoggingThreadLoggingId -ThreadId (New-Guid).ToString() .NOTES This id helps correlate logs produced during the lifetime of a thread. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Update-LoggingThreadLoggingId() { diff --git a/src/Core/Logging/Private/Write-LoggingEntry.ps1 b/src/Core/Logging/Private/Write-LoggingEntry.ps1 index 939b965..22bc137 100644 --- a/src/Core/Logging/Private/Write-LoggingEntry.ps1 +++ b/src/Core/Logging/Private/Write-LoggingEntry.ps1 @@ -8,27 +8,27 @@ and additional data) and enqueues it into the global logging queue for processin by the logging daemon. It also assigns a per-message logging id for correlation. .PARAMETER Message -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Message | System.String | The log message text | | +| Name | Type | Description | Default | +|---------|---------------|----------------------|---------| +| Message | System.String | The log message text | | .PARAMETER Level -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Level | System.String | Severity (Debug,Output,Audit,Info,Success,Warning,Error,Fatal) | 'Info' | +| Name | Type | Description | Default | +|-------|---------------|----------------------------------------------------------------|---------| +| Level | System.String | Severity (Debug,Output,Audit,Info,Success,Warning,Error,Fatal) | 'Info' | .PARAMETER EventId -| Name | Type | Description | Default | -|------|------|-------------|---------| -| EventId | System.Int32 | Numeric event identifier for the log entry | 15 | +| Name | Type | Description | Default | +|---------|--------------|--------------------------------------------|---------| +| EventId | System.Int32 | Numeric event identifier for the log entry | 15 | .PARAMETER Data -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Data | System.Hashtable | Additional structured data to include with the log entry | @{} | +| Name | Type | Description | Default | +|------|------------------|----------------------------------------------------------|---------| +| Data | System.Hashtable | Additional structured data to include with the log entry | @{} | .OUTPUTS -System.Management.Automation.PSCustomObject — The enqueued log object when called from a background daemon with Level 'Output'; None otherwise. +System.Management.Automation.PSCustomObject -- The enqueued log object when called from a background daemon with Level 'Output'; None otherwise. .EXAMPLE PS> Write-LoggingEntry -Message 'Started processing' -Level 'Info' -EventId 100 @@ -36,6 +36,9 @@ PS> Write-LoggingEntry -Message 'Started processing' -Level 'Info' -EventId 100 .NOTES This function is intentionally non-blocking: it enqueues messages for a background consumer. It uses `(Get-GlobalRuntimeVariable).Private.Logging.CurrentLoggingId` to tag messages. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Write-LoggingEntry() { @@ -65,7 +68,7 @@ function Write-LoggingEntry() } # Assign a unique message ID for tracking - $Data['LoggingMessageId'] = (Get-GlobalRuntimeVariable).Private.Logging.CurrentLoggingId.ToString(); + $Data['LoggingMessageId'] = (Get-GlobalRuntimeVariable).Private.Logging.CurrentLoggingId.ToString(); # If we reached this point, we should log the message # Move everything to the logging queue for processing, to not block the current thread diff --git a/src/Core/Logging/Public/Set-IcingaLogLevel.ps1 b/src/Core/Logging/Public/Set-IcingaLogLevel.ps1 index 555f86e..e47ad03 100644 --- a/src/Core/Logging/Public/Set-IcingaLogLevel.ps1 +++ b/src/Core/Logging/Public/Set-IcingaLogLevel.ps1 @@ -9,12 +9,12 @@ to decide which messages should be enqueued and processed. Use one of the predefined levels to control verbosity. .PARAMETER Level -| Name | Type | Description | Default | -|-------|---------------|-------------------------------|----------| -| Level | System.String | Desired minimum logging level | 'Info' | +| Name | Type | Description | Default | +|-------|---------------|-------------------------------|---------| +| Level | System.String | Desired minimum logging level | 'Info' | .OUTPUTS -None — This function sets a global variable and does not emit pipeline output. +None -- This function sets a global variable and does not emit pipeline output. .EXAMPLE PS> Set-IcingaLogLevel -Level 'Warning' @@ -23,6 +23,9 @@ PS> Set-IcingaLogLevel -Level 'Warning' Valid levels are `Debug`, `Audit`, `Info`, `Success`, `Warning`, `Error` and `Fatal`. `Test-LoggingWriteLog` consults the global level to decide whether a message at a given severity should be emitted. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Set-IcingaLogLevel() { diff --git a/src/Core/RestApi/Private/Add-RestApiClientToWorker.ps1 b/src/Core/RestApi/Private/Add-RestApiClientToWorker.ps1 index 768c2a3..e212913 100644 --- a/src/Core/RestApi/Private/Add-RestApiClientToWorker.ps1 +++ b/src/Core/RestApi/Private/Add-RestApiClientToWorker.ps1 @@ -8,9 +8,9 @@ of the RestApi worker queues managed in the global runtime state. Logs the assignment and validates the input client. .PARAMETER TcpClient -| Name | Type | Description | Default | -|------|------|-------------|---------| -| TcpClient | System.Net.Sockets.TcpClient | Accepted TCP client to assign to a worker queue. | | +| Name | Type | Description | Default | +|-----------|------------------------------|--------------------------------------------------|---------| +| TcpClient | System.Net.Sockets.TcpClient | Accepted TCP client to assign to a worker queue. | | .OUTPUTS None @@ -22,6 +22,9 @@ PS> Add-RestApiClientToWorker -TcpClient $acceptedClient This helper expects RestApi worker queues to be initialized under `(Get-GlobalRuntimeVariable).Public.RestApi.WorkerQueue` and a `WorkerCount` value in the RestApi configuration. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Add-RestApiClientToWorker() { diff --git a/src/Core/RestApi/Private/Expand-RestApiHeader.ps1 b/src/Core/RestApi/Private/Expand-RestApiHeader.ps1 index d7a13e1..8ea7cac 100644 --- a/src/Core/RestApi/Private/Expand-RestApiHeader.ps1 +++ b/src/Core/RestApi/Private/Expand-RestApiHeader.ps1 @@ -8,18 +8,21 @@ request method, path, HTTP version and a dictionary of headers. Returns the parsed structure or logs an error and returns `$null` on parse failure. .PARAMETER HeaderString -| Name | Type | Description | Default | -|------|------|-------------|---------| -| HeaderString | System.String | Raw HTTP header string including request line and headers. | | +| Name | Type | Description | Default | +|--------------|---------------|------------------------------------------------------------|---------| +| HeaderString | System.String | Raw HTTP header string including request line and headers. | | .OUTPUTS -System.Collections.Hashtable — parsed header hashtable with `Method`, `Path`, `HttpVersion` and `Headers`. +System.Collections.Hashtable -- parsed header hashtable with `Method`, `Path`, `HttpVersion` and `Headers`. .EXAMPLE PS> Expand-RestApiHeader -HeaderString $rawHeader .NOTES Used by RestApi worker processing to interpret incoming HTTP requests. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Expand-RestApiHeader() { @@ -70,8 +73,8 @@ function Expand-RestApiHeader() # Split header by colon if ($HeaderLine -match '^([^:]+):\s*(.*)$') { - $HeaderName = $matches[1].Trim(); - $HeaderValue = $matches[2].Trim(); + $HeaderName = $matches[1].Trim(); + $HeaderValue = $matches[2].Trim(); # Store header (case-insensitive key, but preserve original case for reference) $ParsedHeader['Headers'][$HeaderName.ToLower()] = @{ diff --git a/src/Core/RestApi/Private/Expand-RestApiQueryString.ps1 b/src/Core/RestApi/Private/Expand-RestApiQueryString.ps1 index 0c225fd..5398a11 100644 --- a/src/Core/RestApi/Private/Expand-RestApiQueryString.ps1 +++ b/src/Core/RestApi/Private/Expand-RestApiQueryString.ps1 @@ -8,17 +8,17 @@ values and percent-encoding. Multiple occurrences of the same key are converted into arrays. .PARAMETER QueryString -| Name | Type | Description | Default | -|------|------|-------------|---------| -| QueryString | System.String | Raw query string (may include leading '?'). | | +| Name | Type | Description | Default | +|-------------|---------------|---------------------------------------------|---------| +| QueryString | System.String | Raw query string (may include leading '?'). | | .PARAMETER QueryParams -| Name | Type | Description | Default | -|------|------|-------------|---------| -| QueryParams | System.Collections.Hashtable | Hashtable to populate with parsed parameters. | @{} | +| Name | Type | Description | Default | +|-------------|------------------------------|-----------------------------------------------|---------| +| QueryParams | System.Collections.Hashtable | Hashtable to populate with parsed parameters. | @{} | .OUTPUTS -None — modifies the provided `QueryParams` hashtable in place. +None -- modifies the provided `QueryParams` hashtable in place. .EXAMPLE PS> Expand-RestApiQueryString -QueryString '?q=hello%20world&tags=one&tags=two' -QueryParams $params @@ -26,6 +26,9 @@ PS> Expand-RestApiQueryString -QueryString '?q=hello%20world&tags=one&tags=two' .NOTES This function is tolerant to quoted parameter values and retains array semantics for repeated keys. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Expand-RestApiQueryString() { @@ -94,7 +97,7 @@ function Expand-RestApiQueryString() $QueryParams[$Key] += $Value; } else { # Convert to array - $NewArray = @($CurrentValue, $Value); + $NewArray = @($CurrentValue, $Value); $QueryParams[$Key] = $NewArray; }; } else { diff --git a/src/Core/RestApi/Private/Expand-RestApiWebPath.ps1 b/src/Core/RestApi/Private/Expand-RestApiWebPath.ps1 index de1c165..e4ca115 100644 --- a/src/Core/RestApi/Private/Expand-RestApiWebPath.ps1 +++ b/src/Core/RestApi/Private/Expand-RestApiWebPath.ps1 @@ -8,12 +8,12 @@ slashes (except for root) and returning an object with the normalized path and an array of path segments. .PARAMETER WebPath -| Name | Type | Description | Default | -|------|------|-------------|---------| -| WebPath | System.String | The HTTP path to normalize (e.g. '/api/v1/resource/'). | | +| Name | Type | Description | Default | +|---------|---------------|--------------------------------------------------------|---------| +| WebPath | System.String | The HTTP path to normalize (e.g. '/api/v1/resource/'). | | .OUTPUTS -System.Collections.Hashtable — parsed path object with keys `Segments`, `QueryParams`, `WebPath`, +System.Collections.Hashtable -- parsed path object with keys `Segments`, `QueryParams`, `WebPath`, `HasQuery`, `SegmentCount` and optional `Version`, `Space`, `Action`, `Resource`. .EXAMPLE @@ -22,6 +22,9 @@ PS> Expand-RestApiWebPath -Path '/api//v1/resource/' .NOTES This helper is used when routing incoming requests to configured RestApi spaces and handlers. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Expand-RestApiWebPath() { diff --git a/src/Core/RestApi/Private/Invoke-RestApiCall.ps1 b/src/Core/RestApi/Private/Invoke-RestApiCall.ps1 index 4ca427f..4412587 100644 --- a/src/Core/RestApi/Private/Invoke-RestApiCall.ps1 +++ b/src/Core/RestApi/Private/Invoke-RestApiCall.ps1 @@ -5,16 +5,16 @@ Resolve the REST API path to a configured handler and execute it. .DESCRIPTION Core dispatcher of the Icinga for Windows REST API. Reads the parsed web-path and headers from `$Global.Private.RestApi.*`, walks the configured -spaces hashtable (Space → Action → Resource) to locate an +spaces hashtable (Space -> Action -> Resource) to locate an `ApiCommandExecution` field and invokes the bound PowerShell function via `Invoke-RestApiCommandExecutionField`. Emits the appropriate JSON response on success and well-formed error responses on failure -(missing space → 404, invalid path depth → 400, command error → 500, -no spaces configured → 500, no command at all → HTML endpoint listing +(missing space -> 404, invalid path depth -> 400, command error -> 500, +no spaces configured -> 500, no command at all -> HTML endpoint listing or 200 / 404 for JSON callers). .OUTPUTS -System.Int32 — A semantic return code resolved through +System.Int32 -- A semantic return code resolved through `Write-FunctionReturnValue` for downstream diagnostics. The HTTP response is sent directly over the worker's TCP stream. @@ -28,6 +28,9 @@ been parsed; arguments are taken from worker-private state. Path schema is `/v1///`. The actual `ApiCommandExecution` lookup supports 2, 3 or 4 segments (segment count is checked before the handler runs). + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Invoke-RestApiCall() { diff --git a/src/Core/RestApi/Private/Invoke-RestApiCommandExecutionField.ps1 b/src/Core/RestApi/Private/Invoke-RestApiCommandExecutionField.ps1 index df48556..612ab6c 100644 --- a/src/Core/RestApi/Private/Invoke-RestApiCommandExecutionField.ps1 +++ b/src/Core/RestApi/Private/Invoke-RestApiCommandExecutionField.ps1 @@ -11,12 +11,12 @@ are read from `(Get-GlobalRuntimeVariable).Private.RestApi`. Returns the function result or a structured error object on failure. .PARAMETER Space -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Space | PSCustomObject | ApiCommandExecution configuration object with `Function`, `Method` and `Parameters` properties. | $null | +| Name | Type | Description | Default | +|-------|----------------|-------------------------------------------------------------------------------------------------|---------| +| Space | PSCustomObject | ApiCommandExecution configuration object with `Function`, `Method` and `Parameters` properties. | $null | .OUTPUTS -System.Object — the return value of the invoked function, or a hashtable +System.Object -- the return value of the invoked function, or a hashtable with an `error` key when the invocation fails or is not permitted. .EXAMPLE @@ -27,6 +27,9 @@ Parameter type mapping supports `int`, `string`, `bool` and `array`. Array values in GET query strings are split on commas while respecting quoted strings. Must only be called from within a RestApi worker thread after `Private.RestApi.WebPath` and `Private.RestApi.Header` are set. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Invoke-RestApiCommandExecutionField() { diff --git a/src/Core/RestApi/Private/New-RestApiAccessControlObject.ps1 b/src/Core/RestApi/Private/New-RestApiAccessControlObject.ps1 index 7b2acd5..16ae40a 100644 --- a/src/Core/RestApi/Private/New-RestApiAccessControlObject.ps1 +++ b/src/Core/RestApi/Private/New-RestApiAccessControlObject.ps1 @@ -10,45 +10,48 @@ It is intended to be embedded in system access roles or used directly by the RestApi access control evaluation routines. .PARAMETER AllowedMethods -| Name | Type | Description | Default | -|------|------|-------------|---------| +| Name | Type | Description | Default | +|----------------|-----------------|------------------------------------------------------------------------|----------| | AllowedMethods | System.String[] | List of allowed HTTP methods (case-insensitive). Use `*` to allow all. | @('GET') | .PARAMETER AllowedResources -| Name | Type | Description | Default | -|------|------|-------------|---------| -| AllowedResources | System.String[] | Glob-style patterns of resources that are explicitly allowed. Use `*` to allow all. | @() | +| Name | Type | Description | Default | +|------------------|-----------------|-------------------------------------------------------------------------------------|---------| +| AllowedResources | System.String[] | Glob-style patterns of resources that are explicitly allowed. Use `*` to allow all. | @() | .PARAMETER BlockedResources -| Name | Type | Description | Default | -|------|------|-------------|---------| -| BlockedResources | System.String[] | Glob-style patterns of resources that are explicitly blocked. Use `*` to block all. | @('*') | +| Name | Type | Description | Default | +|------------------|-----------------|-------------------------------------------------------------------------------------|---------| +| BlockedResources | System.String[] | Glob-style patterns of resources that are explicitly blocked. Use `*` to block all. | @('*') | .PARAMETER AllowedOrigins -| Name | Type | Description | Default | -|------|------|-------------|---------| -| AllowedOrigins | System.String[] | Client IP/hostname patterns that are allowed to access the API. Use `*` to allow all origins. | @('*') | +| Name | Type | Description | Default | +|----------------|-----------------|-----------------------------------------------------------------------------------------------|---------| +| AllowedOrigins | System.String[] | Client IP/hostname patterns that are allowed to access the API. Use `*` to allow all origins. | @('*') | .PARAMETER RequireCredentials -| Name | Type | Description | Default | -|------|------|-------------|---------| -| RequireCredentials | System.Boolean | When true, the ACL requires credentials (not implemented in this helper). | $false | +| Name | Type | Description | Default | +|--------------------|----------------|---------------------------------------------------------------------------|---------| +| RequireCredentials | System.Boolean | When true, the ACL requires credentials (not implemented in this helper). | $false | .PARAMETER RequestBodySizeLimitKB -| Name | Type | Description | Default | -|------|------|-------------|---------| -| RequestBodySizeLimitKB | System.Int32 | Maximum allowed request body size in kilobytes. Negative values are normalized to 0. | 1024 | +| Name | Type | Description | Default | +|------------------------|--------------|--------------------------------------------------------------------------------------|---------| +| RequestBodySizeLimitKB | System.Int32 | Maximum allowed request body size in kilobytes. Negative values are normalized to 0. | 1024 | .OUTPUTS -PSCustomObject — access control object ready for inclusion in role definitions. +PSCustomObject -- access control object ready for inclusion in role definitions. .EXAMPLE PS> New-RestApiAccessControlObject -AllowedMethods @('GET','POST') -AllowedResources @('/v1/*') -RequestBodySizeLimitKB 512 .NOTES The returned object converts KB limit to bytes and normalizes string -arrays. The `RequireCredentials` flag is informational — credential +arrays. The `RequireCredentials` flag is informational -- credential enforcement must be implemented in the request handling logic. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function New-RestApiAccessControlObject() { diff --git a/src/Core/RestApi/Private/New-RestApiEnvironment.ps1 b/src/Core/RestApi/Private/New-RestApiEnvironment.ps1 index 29a041a..37da6ce 100644 --- a/src/Core/RestApi/Private/New-RestApiEnvironment.ps1 +++ b/src/Core/RestApi/Private/New-RestApiEnvironment.ps1 @@ -12,7 +12,7 @@ certificate and then creates the blocking worker queues and spawns one be populated before this function runs. .OUTPUTS -None — populates `(Get-GlobalRuntimeVariable).Public.RestApi.WorkerQueue` +None -- populates `(Get-GlobalRuntimeVariable).Public.RestApi.WorkerQueue` and starts all worker and listener threads. .EXAMPLE @@ -23,6 +23,9 @@ Must be called after `Set-RestApiConfig` has been executed so that a valid `restapi.json` configuration file exists. All threads started here rely on the global runtime variable rather than parameters, so thread-safety depends on the blocking collections used for the worker queues. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function New-RestApiEnvironment() { diff --git a/src/Core/RestApi/Private/New-RestApiFaviconResponse.ps1 b/src/Core/RestApi/Private/New-RestApiFaviconResponse.ps1 index c0e7bac..bc3b75f 100644 --- a/src/Core/RestApi/Private/New-RestApiFaviconResponse.ps1 +++ b/src/Core/RestApi/Private/New-RestApiFaviconResponse.ps1 @@ -8,7 +8,7 @@ and correct `Content-Type` header for `image/x-icon`. Returns the response structure or logs an error when no data is supplied. .OUTPUTS -System.Collections.Hashtable — response object with `Message` (byte[]) and +System.Collections.Hashtable -- response object with `Message` (byte[]) and `Length` (int), ready to pass to `Send-TCPMessage`. .EXAMPLE @@ -18,6 +18,9 @@ PS> New-RestApiFaviconResponse The favicon is read from `assets\restapi\favicon.png` under the module root directory. The function selects the correct MIME type (`image/x-icon` or `image/png`) based on the file extension found at that path. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function New-RestApiFaviconResponse() { @@ -39,7 +42,7 @@ function New-RestApiFaviconResponse() $ContentLength = $FaviconBytes.Count; # Build HTTP response with image/png MIME type (or image/x-icon for .ico) - [string]$ContentType = $null; + [string]$ContentType = $null; if ($FaviconPath -match '\.ico$') { $ContentType = 'image/x-icon'; @@ -47,18 +50,18 @@ function New-RestApiFaviconResponse() $ContentType = 'image/png'; }; - $ResponseString = "HTTP/1.1 200 OK`r`n"; - $ResponseString += "Date: $CurrentDateTime`r`n"; - $ResponseString += "Server: $(Get-ModuleProjectName)/2.0`r`n"; - $ResponseString += "Content-Type: $ContentType`r`n"; - $ResponseString += "Content-Length: $ContentLength`r`n"; - $ResponseString += "Cache-Control: public, max-age=86400`r`n"; # Cache for 1 day - $ResponseString += "Connection: close`r`n"; - $ResponseString += "`r`n"; + $ResponseString = "HTTP/1.1 200 OK`r`n"; + $ResponseString += "Date: $CurrentDateTime`r`n"; + $ResponseString += "Server: $(Get-ModuleProjectName)/2.0`r`n"; + $ResponseString += "Content-Type: $ContentType`r`n"; + $ResponseString += "Content-Length: $ContentLength`r`n"; + $ResponseString += "Cache-Control: public, max-age=86400`r`n"; # Cache for 1 day + $ResponseString += "Connection: close`r`n"; + $ResponseString += "`r`n"; # Convert headers to bytes and append favicon bytes - [byte[]]$HeaderBytes = [System.Text.Encoding]::UTF8.GetBytes($ResponseString); - [byte[]]$ResponseBytes = New-Object byte[]($HeaderBytes.Count + $ContentLength); + [byte[]]$HeaderBytes = [System.Text.Encoding]::UTF8.GetBytes($ResponseString); + [byte[]]$ResponseBytes = New-Object byte[]($HeaderBytes.Count + $ContentLength); # Copy header bytes [Array]::Copy($HeaderBytes, 0, $ResponseBytes, 0, $HeaderBytes.Count); diff --git a/src/Core/RestApi/Private/New-RestApiResponse.ps1 b/src/Core/RestApi/Private/New-RestApiResponse.ps1 index ab64ebd..01c54d6 100644 --- a/src/Core/RestApi/Private/New-RestApiResponse.ps1 +++ b/src/Core/RestApi/Private/New-RestApiResponse.ps1 @@ -8,24 +8,24 @@ into a single byte array suitable for sending over a TCP socket. When the `Content-Type` is JSON the body is serialized with `ConvertTo-Json`. .PARAMETER StatusCode -| Name | Type | Description | Default | -|------|------|-------------|---------| -| StatusCode | System.Int32 | HTTP status code to send (e.g. 200). | 200 | +| Name | Type | Description | Default | +|------------|--------------|--------------------------------------|---------| +| StatusCode | System.Int32 | HTTP status code to send (e.g. 200). | 200 | .PARAMETER StatusMessage -| Name | Type | Description | Default | -|------|------|-------------|---------| -| StatusMessage | System.String | Short HTTP status message (e.g. 'OK'). | 'OK' | +| Name | Type | Description | Default | +|---------------|---------------|----------------------------------------|---------| +| StatusMessage | System.String | Short HTTP status message (e.g. 'OK'). | 'OK' | .PARAMETER ContentType -| Name | Type | Description | Default | -|------|------|-------------|---------| +| Name | Type | Description | Default | +|-------------|---------------|----------------------------------|-----------------------------------| | ContentType | System.String | MIME type for the response body. | 'application/json; charset=utf-8' | .PARAMETER ResponseBody -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ResponseBody | Object | Body payload; may be byte[], string or object (serialized to JSON). | | +| Name | Type | Description | Default | +|--------------|--------|---------------------------------------------------------------------|---------| +| ResponseBody | Object | Body payload; may be byte[], string or object (serialized to JSON). | | .OUTPUTS Hashtable with `Message` (byte[]) and `Length` (int) keys. @@ -35,6 +35,9 @@ PS> New-RestApiResponse -StatusCode 200 -ResponseBody @{ success = $true } .NOTES The returned `Message` is ready to be written to a TCP stream. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function New-RestApiResponse() { @@ -56,18 +59,18 @@ function New-RestApiResponse() if ($null -eq $ResponseBody) { $BodyBytes = @(); } elseif ($ContentType -like 'application/json*') { - $json = ConvertTo-Json -InputObject $ResponseBody -Depth 10 -Compress; + $json = ConvertTo-Json -InputObject $ResponseBody -Depth 10 -Compress; $BodyBytes = $Encoding.GetBytes($json); } elseif ($ResponseBody -is [string]) { $BodyBytes = $Encoding.GetBytes($ResponseBody); } elseif ($ResponseBody -is [System.Array]) { - $json = ConvertTo-Json -InputObject $ResponseBody -Depth 10 -Compress; + $json = ConvertTo-Json -InputObject $ResponseBody -Depth 10 -Compress; $BodyBytes = $Encoding.GetBytes($json); } elseif ($ResponseBody -is [System.Collections.ArrayList]) { - $json = ConvertTo-Json -InputObject $ResponseBody -Depth 10 -Compress; + $json = ConvertTo-Json -InputObject $ResponseBody -Depth 10 -Compress; $BodyBytes = $Encoding.GetBytes($json); } elseif ($ResponseBody -is [System.Object[]] -or $ResponseBody -is [System.Collections.IDictionary]) { - $json = ConvertTo-Json -InputObject $ResponseBody -Depth 10 -Compress; + $json = ConvertTo-Json -InputObject $ResponseBody -Depth 10 -Compress; $BodyBytes = $Encoding.GetBytes($json); } elseif ($ResponseBody -is [byte[]]) { $BodyBytes = $ResponseBody; @@ -75,18 +78,18 @@ function New-RestApiResponse() $BodyBytes = $Encoding.GetBytes(([string]$ResponseBody)); } - $ContentLength = $BodyBytes.Length; + $ContentLength = $BodyBytes.Length; # Build response string - $HeaderString = "HTTP/1.1 $StatusCode $StatusMessage`r`n"; - $HeaderString += "Date: $CurrentDateTime`r`n"; - $HeaderString += "Server: $(Get-ModuleProjectName)/2.0`r`n"; - $HeaderString += "Content-Type: $ContentType`r`n"; - $HeaderString += "Content-Length: $ContentLength`r`n"; - $HeaderString += "Connection: close`r`n"; - $HeaderString += "`r`n"; - - $HeaderBytes = $Encoding.GetBytes($HeaderString); + $HeaderString = "HTTP/1.1 $StatusCode $StatusMessage`r`n"; + $HeaderString += "Date: $CurrentDateTime`r`n"; + $HeaderString += "Server: $(Get-ModuleProjectName)/2.0`r`n"; + $HeaderString += "Content-Type: $ContentType`r`n"; + $HeaderString += "Content-Length: $ContentLength`r`n"; + $HeaderString += "Connection: close`r`n"; + $HeaderString += "`r`n"; + + $HeaderBytes = $Encoding.GetBytes($HeaderString); [byte[]]$FullResponse = New-Object byte[] ($HeaderBytes.Length + $BodyBytes.Length); [System.Buffer]::BlockCopy($HeaderBytes, 0, $FullResponse, 0, $HeaderBytes.Length); diff --git a/src/Core/RestApi/Private/Read-RestApiBody.ps1 b/src/Core/RestApi/Private/Read-RestApiBody.ps1 index cc9cb11..5fb9236 100644 --- a/src/Core/RestApi/Private/Read-RestApiBody.ps1 +++ b/src/Core/RestApi/Private/Read-RestApiBody.ps1 @@ -9,14 +9,14 @@ Honors `Content-Length`, enforces access control via bytes, string and parsed JSON (if applicable). .PARAMETER ParsedHeaders -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ParsedHeaders | System.Collections.Hashtable | Parsed header object produced by `Expand-RestApiHeader`. | @{ } | +| Name | Type | Description | Default | +|---------------|------------------------------|----------------------------------------------------------|---------| +| ParsedHeaders | System.Collections.Hashtable | Parsed header object produced by `Expand-RestApiHeader`. | @{ } | .PARAMETER PreReadBodyBytes -| Name | Type | Description | Default | -|------|------|-------------|---------| -| PreReadBodyBytes | byte[] | Any body bytes that were read along with the headers. | @() | +| Name | Type | Description | Default | +|------------------|--------|-------------------------------------------------------|---------| +| PreReadBodyBytes | byte[] | Any body bytes that were read along with the headers. | @() | .OUTPUTS Hashtable with keys `RawBytes`, `RawString`, `JsonObj`, `ContentLength`. @@ -27,6 +27,9 @@ PS> Read-RestApiBody -ParsedHeaders $parsed -PreReadBodyBytes $extraBytes .NOTES Closes the TCP connection and returns `$null` if access control denies the request or a timeout occurs while reading. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Read-RestApiBody() { @@ -101,7 +104,7 @@ function Read-RestApiBody() if ($BytesRead -gt 0) { # Append read bytes to body buffer $BodyBufferStream.Write($ReadBuffer, 0, $BytesRead); - $TotalBytesRead += $BytesRead; + $TotalBytesRead += $BytesRead; } else { Start-Sleep -Milliseconds 10; }; diff --git a/src/Core/RestApi/Private/Read-RestApiConfig.ps1 b/src/Core/RestApi/Private/Read-RestApiConfig.ps1 index bee3df4..55a8140 100644 --- a/src/Core/RestApi/Private/Read-RestApiConfig.ps1 +++ b/src/Core/RestApi/Private/Read-RestApiConfig.ps1 @@ -8,7 +8,7 @@ directory and stores the parsed object into the global runtime variable under `(Get-GlobalRuntimeVariable).Public.RestApi.Config`. .OUTPUTS -PSCustomObject — the loaded RestApi configuration on success, or a +PSCustomObject -- the loaded RestApi configuration on success, or a structured return code object when the file is missing or corrupt. .EXAMPLE @@ -17,6 +17,9 @@ PS> Read-RestApiConfig .NOTES Logs structured return codes using `Write-FunctionReturnValue` when the file is missing or cannot be parsed. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Read-RestApiConfig() { diff --git a/src/Core/RestApi/Private/Read-RestApiHeader.ps1 b/src/Core/RestApi/Private/Read-RestApiHeader.ps1 index 50a0331..3b76d91 100644 --- a/src/Core/RestApi/Private/Read-RestApiHeader.ps1 +++ b/src/Core/RestApi/Private/Read-RestApiHeader.ps1 @@ -15,6 +15,9 @@ PS> Read-RestApiHeader .NOTES This function reads directly from `(Get-GlobalRuntimeVariable).Private.TCP.Stream`. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Read-RestApiHeader() { @@ -39,9 +42,9 @@ function Read-RestApiHeader() # Check for double newline (HTTP header terminator) if ($HeaderString -match "`r`n`r`n") { # Find the position of double newline in bytes - [string]$DoubleNewline = "`r`n`r`n"; + [string]$DoubleNewline = "`r`n`r`n"; # Search for header terminator pattern - $HeaderEndIndex = $HeaderString.IndexOf($DoubleNewline); + $HeaderEndIndex = $HeaderString.IndexOf($DoubleNewline); if ($HeaderEndIndex -ge 0) { # Calculate actual byte position accounting for potential multi-byte UTF8 characters diff --git a/src/Core/RestApi/Private/Read-RestApiSpacesConfig.ps1 b/src/Core/RestApi/Private/Read-RestApiSpacesConfig.ps1 index 18da7be..056ad88 100644 --- a/src/Core/RestApi/Private/Read-RestApiSpacesConfig.ps1 +++ b/src/Core/RestApi/Private/Read-RestApiSpacesConfig.ps1 @@ -8,7 +8,7 @@ private RestApi `Spaces` hashtable with parsed space configurations keyed by filename (lowercase). Logs per-file parse results using `Write-FunctionReturnValue`. .OUTPUTS -None — populates `(Get-GlobalRuntimeVariable).Private.RestApi.Spaces`. +None -- populates `(Get-GlobalRuntimeVariable).Private.RestApi.Spaces`. .EXAMPLE PS> Read-RestApiSpacesConfig @@ -16,12 +16,15 @@ PS> Read-RestApiSpacesConfig .NOTES Each space file must contain a valid JSON object describing routes, handlers and optional access control for that API space. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Read-RestApiSpacesConfig() { - $RestApiDirectory = Join-Path -Path (Get-ModuleRootDirectory) -ChildPath 'data\restapi\'; - $ApiSpaceFiles = Get-SecureChildItem -Path $RestApiDirectory -Filter '*.json' -Recurse -File; - $GlobalVariable = Get-GlobalRuntimeVariable; + $RestApiDirectory = Join-Path -Path (Get-ModuleRootDirectory) -ChildPath 'data\restapi\'; + $ApiSpaceFiles = Get-SecureChildItem -Path $RestApiDirectory -Filter '*.json' -Recurse -File; + $GlobalVariable = Get-GlobalRuntimeVariable; $GlobalVariable.Private.RestApi.Spaces = @{ }; diff --git a/src/Core/RestApi/Private/Send-RestApiHtmlEndpointResponse.ps1 b/src/Core/RestApi/Private/Send-RestApiHtmlEndpointResponse.ps1 index 7cd2013..b325244 100644 --- a/src/Core/RestApi/Private/Send-RestApiHtmlEndpointResponse.ps1 +++ b/src/Core/RestApi/Private/Send-RestApiHtmlEndpointResponse.ps1 @@ -8,18 +8,21 @@ provided space object or, if no space is given, lists all configured spaces. The HTML is returned to the client as an HTTP response. .PARAMETER SpaceObj -| Name | Type | Description | Default | -|------|------|-------------|---------| -| SpaceObj | PSCustomObject | Optional space configuration object to enumerate endpoints for. | | +| Name | Type | Description | Default | +|----------|----------------|-----------------------------------------------------------------|---------| +| SpaceObj | PSCustomObject | Optional space configuration object to enumerate endpoints for. | | .OUTPUTS -None — sends an HTTP response with `Content-Type: text/html` via `Send-TCPMessage`. +None -- sends an HTTP response with `Content-Type: text/html` via `Send-TCPMessage`. .EXAMPLE PS> Send-RestApiHtmlEndpointResponse -SpaceObj $space .NOTES Intended to be used by browser-based exploration of the RestApi. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Send-RestApiHtmlEndpointResponse() { @@ -27,9 +30,9 @@ function Send-RestApiHtmlEndpointResponse() [PSCustomObject]$SpaceObj = $null ); - $GlobalVariable = Get-GlobalRuntimeVariable; - [hashtable]$Spaces = $GlobalVariable.Private.RestApi.Spaces; - [hashtable]$WebPath = $GlobalVariable.Private.RestApi.WebPath; + $GlobalVariable = Get-GlobalRuntimeVariable; + [hashtable]$Spaces = $GlobalVariable.Private.RestApi.Spaces; + [hashtable]$WebPath = $GlobalVariable.Private.RestApi.WebPath; # Since we found a SpaceObj but no return value, there was nothing to be executed from # this path. However, we have sub-entries. We should help the user and provide an output diff --git a/src/Core/RestApi/Private/Send-RestApiRequest.ps1 b/src/Core/RestApi/Private/Send-RestApiRequest.ps1 index 2bd479b..654d23d 100644 --- a/src/Core/RestApi/Private/Send-RestApiRequest.ps1 +++ b/src/Core/RestApi/Private/Send-RestApiRequest.ps1 @@ -10,27 +10,27 @@ methods. The function returns standardized return values using `Write-FunctionReturnValue`. .PARAMETER WebPath -| Name | Type | Description | Default | -|------|------|-------------|---------| -| WebPath | System.String | Relative web path or endpoint (for example '/v1/status'). Leading slash optional. | '' | +| Name | Type | Description | Default | +|---------|---------------|-----------------------------------------------------------------------------------|---------| +| WebPath | System.String | Relative web path or endpoint (for example '/v1/status'). Leading slash optional. | '' | .PARAMETER Method -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Method | System.String | HTTP method to use (GET, POST, PUT, DELETE, etc.). | 'GET' | +| Name | Type | Description | Default | +|--------|---------------|----------------------------------------------------|---------| +| Method | System.String | HTTP method to use (GET, POST, PUT, DELETE, etc.). | 'GET' | .PARAMETER Headers -| Name | Type | Description | Default | -|------|------|-------------|---------| +| Name | Type | Description | Default | +|---------|------------------------------|-------------------------------------|-------------------------------------------| | Headers | System.Collections.Hashtable | Additional HTTP headers to include. | @{ 'Content-Type' = 'application/json'; } | .PARAMETER Body -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Body | System.Hashtable | Request body to be serialized as JSON for non-GET methods. | @{ } | +| Name | Type | Description | Default | +|------|------------------|------------------------------------------------------------|---------| +| Body | System.Hashtable | Request body to be serialized as JSON for non-GET methods. | @{ } | .OUTPUTS -PSCustomObject — Function return value produced by `Write-FunctionReturnValue`. +PSCustomObject -- Function return value produced by `Write-FunctionReturnValue`. - `RestApiRequestSuccessful`: Data contains `Response`. - `RestApiRequestFailed`: Data contains `Exception`, `Uri`, `Method`, `Headers`, `Body` or `StatusCode` and `Response`. @@ -42,6 +42,9 @@ PS> Send-RestApiRequest -WebPath '/v1/items' -Method 'POST' -Body @{ name = 'tes Uses `Read-RestApiConfig` to ensure RestApi is configured and `Invoke-RestMethod` with `-SkipCertificateCheck` for local/self-signed certificates. Non-200 status codes are treated as failures and returned via `Write-FunctionReturnValue`. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Send-RestApiRequest() { diff --git a/src/Core/RestApi/Private/Set-RestApiConfig.ps1 b/src/Core/RestApi/Private/Set-RestApiConfig.ps1 index 1e053b4..8687797 100644 --- a/src/Core/RestApi/Private/Set-RestApiConfig.ps1 +++ b/src/Core/RestApi/Private/Set-RestApiConfig.ps1 @@ -9,32 +9,32 @@ configuration and writes the configuration to the module config directory as `Write-FunctionReturnValue`. .PARAMETER ListenAddress -| Name | Type | Description | Default | -|------|------|-------------|---------| +| Name | Type | Description | Default | +|---------------|---------------|--------------------------------------------------------------------------------------------|-----------| | ListenAddress | System.String | IP address or hostname to bind the RestApi listener. Use '0.0.0.0' to bind all interfaces. | '0.0.0.0' | .PARAMETER ListenPort -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ListenPort | System.Int32 | TCP port to listen on (1-65535). | 10000 | +| Name | Type | Description | Default | +|------------|--------------|----------------------------------|---------| +| ListenPort | System.Int32 | TCP port to listen on (1-65535). | 10000 | .PARAMETER TlsCertConfig -| Name | Type | Description | Default | -|------|------|-------------|---------| -| TlsCertConfig | System.PSCustomObject | TLS certificate configuration created by `New-TlsCertConfig`. | $null | +| Name | Type | Description | Default | +|---------------|-----------------------|---------------------------------------------------------------|---------| +| TlsCertConfig | System.PSCustomObject | TLS certificate configuration created by `New-TlsCertConfig`. | $null | .PARAMETER WorkerCount -| Name | Type | Description | Default | -|------|------|-------------|---------| -| WorkerCount | System.Int32 | Number of worker threads to spawn for handling connections. | 5 | +| Name | Type | Description | Default | +|-------------|--------------|-------------------------------------------------------------|---------| +| WorkerCount | System.Int32 | Number of worker threads to spawn for handling connections. | 5 | .PARAMETER DryRun -| Name | Type | Description | Default | -|--------|----------------------------------------------|---------------------------------------------------------------------------------------------------|---------| -| DryRun | System.Management.Automation.SwitchParameter | When set, returns a unified diff of the pending configuration versus the persisted restapi.json instead of writing the change. | $false | +| Name | Type | Description | Default | +|--------|----------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------|---------| +| DryRun | System.Management.Automation.SwitchParameter | When set, returns a unified diff of the pending configuration versus the persisted restapi.json instead of writing the change. | $false | .OUTPUTS -PSCustomObject — Function return value via `Write-FunctionReturnValue`. +PSCustomObject -- Function return value via `Write-FunctionReturnValue`. - `RestApiConfigConfigured`: Data contains `Config`. - `NoRestApiListenAddressProvided`: invalid listen address. - `NoRestApiListenPortProvided`: invalid port. @@ -47,6 +47,9 @@ PS> Set-RestApiConfig -ListenAddress '127.0.0.1' -ListenPort 10443 -WorkerCount Persists the configuration to `restapi.json` under the module config directory using `Write-SecureFile` and `Get-ModuleConfigDirectory`. `WorkerCount` is bounded by the global `Threading.MaxThreads` setting. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Set-RestApiConfig() { diff --git a/src/Core/RestApi/Private/Start-RestApiDaemon.ps1 b/src/Core/RestApi/Private/Start-RestApiDaemon.ps1 index 438b669..5cbe786 100644 --- a/src/Core/RestApi/Private/Start-RestApiDaemon.ps1 +++ b/src/Core/RestApi/Private/Start-RestApiDaemon.ps1 @@ -8,7 +8,7 @@ environment. This is a lightweight helper that delegates to `New-RestApiEnvironment` on a new thread. .OUTPUTS -None — starts a background thread and returns immediately. +None -- starts a background thread and returns immediately. .EXAMPLE PS> Start-RestApiDaemon @@ -17,6 +17,9 @@ PS> Start-RestApiDaemon This function starts a thread but does not wait for the environment to be fully initialized. Use `New-RestApiEnvironment` directly when synchronous initialization is required. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Start-RestApiDaemon() { diff --git a/src/Core/RestApi/Private/Start-RestApiListener.ps1 b/src/Core/RestApi/Private/Start-RestApiListener.ps1 index 73f2cd3..21540b2 100644 --- a/src/Core/RestApi/Private/Start-RestApiListener.ps1 +++ b/src/Core/RestApi/Private/Start-RestApiListener.ps1 @@ -16,6 +16,9 @@ PS> Start-RestApiListener .NOTES This function runs on a dedicated thread and uses global runtime state for configuration and worker management. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Start-RestApiListener() { diff --git a/src/Core/RestApi/Private/Start-RestApiWorker.ps1 b/src/Core/RestApi/Private/Start-RestApiWorker.ps1 index 92c2e0a..d66816f 100644 --- a/src/Core/RestApi/Private/Start-RestApiWorker.ps1 +++ b/src/Core/RestApi/Private/Start-RestApiWorker.ps1 @@ -9,17 +9,17 @@ handshake, access control checks, reads the request and dispatches it to the appropriate handler. .PARAMETER WorkerId -| Name | Type | Description | Default | -|------|------|-------------|---------| -| WorkerId | System.Int32 | Numeric identifier for this worker. | -1 | +| Name | Type | Description | Default | +|----------|--------------|-------------------------------------|---------| +| WorkerId | System.Int32 | Numeric identifier for this worker. | -1 | .PARAMETER Spaces -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Spaces | System.Collections.Hashtable | Hashtable of RestApi space configurations. | @{ } | +| Name | Type | Description | Default | +|--------|------------------------------|--------------------------------------------|---------| +| Spaces | System.Collections.Hashtable | Hashtable of RestApi space configurations. | @{ } | .OUTPUTS -None — sends responses over the TCP connection and logs results. +None -- sends responses over the TCP connection and logs results. .EXAMPLE PS> Start-RestApiWorker -WorkerId 0 -Spaces $spaces @@ -27,6 +27,9 @@ PS> Start-RestApiWorker -WorkerId 0 -Spaces $spaces .NOTES This function is designed to run as a long-lived thread and relies on global runtime variables for TCP streams and timeouts. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Start-RestApiWorker() { @@ -140,10 +143,10 @@ function Start-RestApiWorker() $GlobalVariable.Private.RestApi.Header = $null; $GlobalVariable.Private.RestApi.ContentLength = 0; - $RawHttpHeader = $null; - $ParsedHttpHeader = $null; - $AclTest = $null; - $TcpClient = $null; + $RawHttpHeader = $null; + $ParsedHttpHeader = $null; + $AclTest = $null; + $TcpClient = $null; # Close the connection once we are done Close-TCPConnection; diff --git a/src/Core/RestApi/Private/Test-RestApiAccessControl.ps1 b/src/Core/RestApi/Private/Test-RestApiAccessControl.ps1 index 3c3d0c3..bb08728 100644 --- a/src/Core/RestApi/Private/Test-RestApiAccessControl.ps1 +++ b/src/Core/RestApi/Private/Test-RestApiAccessControl.ps1 @@ -8,17 +8,17 @@ determines whether the current request is permitted. Supports checking origins (client IP) and request body size limits. .PARAMETER TestOrigins -| Name | Type | Description | Default | -|------|------|-------------|---------| -| TestOrigins | SwitchParameter | If set, evaluates allowed client origins for the request. | $false | +| Name | Type | Description | Default | +|-------------|-----------------|-----------------------------------------------------------|---------| +| TestOrigins | SwitchParameter | If set, evaluates allowed client origins for the request. | $false | .PARAMETER TestContentLength -| Name | Type | Description | Default | -|------|------|-------------|---------| -| TestContentLength | SwitchParameter | If set, enforces configured request body size limits. | $false | +| Name | Type | Description | Default | +|-------------------|-----------------|-------------------------------------------------------|---------| +| TestContentLength | SwitchParameter | If set, enforces configured request body size limits. | $false | .OUTPUTS -System.Int32 — structured return code from `Write-FunctionReturnValue` indicating +System.Int32 -- structured return code from `Write-FunctionReturnValue` indicating permission granted, denied, origin blocked or content length exceeded. .EXAMPLE @@ -27,6 +27,9 @@ PS> Test-RestApiAccessControl -TestOrigins .NOTES This function uses the protected `AccessControl` configuration stored in the global runtime variable and the current RestApi context. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Test-RestApiAccessControl() { diff --git a/src/Core/RestApi/Private/Test-RestApiCommandExecutionField.ps1 b/src/Core/RestApi/Private/Test-RestApiCommandExecutionField.ps1 index 15aa012..b906969 100644 --- a/src/Core/RestApi/Private/Test-RestApiCommandExecutionField.ps1 +++ b/src/Core/RestApi/Private/Test-RestApiCommandExecutionField.ps1 @@ -9,12 +9,12 @@ space. Returns boolean-like structured return codes via `Write-FunctionReturnValue`. .PARAMETER Space -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Space | PSCustomObject | Space configuration object to inspect. | | +| Name | Type | Description | Default | +|-------|----------------|----------------------------------------|---------| +| Space | PSCustomObject | Space configuration object to inspect. | | .OUTPUTS -System.Boolean — `$true` when `ApiCommandExecution` is present, `$false` otherwise, +System.Boolean -- `$true` when `ApiCommandExecution` is present, `$false` otherwise, wrapped via `Write-FunctionReturnValue`. .EXAMPLE @@ -23,6 +23,9 @@ PS> Test-RestApiCommandExecutionField -Space $space .NOTES Used by routing logic to decide whether to invoke a command or render sub-endpoints for a space. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Test-RestApiCommandExecutionField() { diff --git a/src/Core/RestApi/Public/New-IcingaRestApiAccessControlObject.ps1 b/src/Core/RestApi/Public/New-IcingaRestApiAccessControlObject.ps1 index 77d04e3..22ac9d9 100644 --- a/src/Core/RestApi/Public/New-IcingaRestApiAccessControlObject.ps1 +++ b/src/Core/RestApi/Public/New-IcingaRestApiAccessControlObject.ps1 @@ -11,37 +11,37 @@ allowed request body size. Pass the returned object to `New-AccessRole` to attach it to a user or group. .PARAMETER AllowedMethods -| Name | Type | Description | Default | -|------|------|-------------|---------| +| Name | Type | Description | Default | +|----------------|-----------------|------------------------------------------------------------------------|----------| | AllowedMethods | System.String[] | List of allowed HTTP methods (case-insensitive). Use `*` to allow all. | @('GET') | .PARAMETER AllowedResources -| Name | Type | Description | Default | -|------|------|-------------|---------| -| AllowedResources | System.String[] | Glob-style patterns of resources that are explicitly allowed. Use `*` to allow all. | @() | +| Name | Type | Description | Default | +|------------------|-----------------|-------------------------------------------------------------------------------------|---------| +| AllowedResources | System.String[] | Glob-style patterns of resources that are explicitly allowed. Use `*` to allow all. | @() | .PARAMETER BlockedResources -| Name | Type | Description | Default | -|------|------|-------------|---------| -| BlockedResources | System.String[] | Glob-style patterns of resources that are explicitly blocked. Use `*` to block all. | @('*') | +| Name | Type | Description | Default | +|------------------|-----------------|-------------------------------------------------------------------------------------|---------| +| BlockedResources | System.String[] | Glob-style patterns of resources that are explicitly blocked. Use `*` to block all. | @('*') | .PARAMETER AllowedOrigins -| Name | Type | Description | Default | -|------|------|-------------|---------| -| AllowedOrigins | System.String[] | Client IP or hostname patterns that may access the API. Use `*` to allow all origins. | @('*') | +| Name | Type | Description | Default | +|----------------|-----------------|---------------------------------------------------------------------------------------|---------| +| AllowedOrigins | System.String[] | Client IP or hostname patterns that may access the API. Use `*` to allow all origins. | @('*') | .PARAMETER RequireCredentials -| Name | Type | Description | Default | -|------|------|-------------|---------| -| RequireCredentials | System.Boolean | When true, the access control entry requires credentials. | $false | +| Name | Type | Description | Default | +|--------------------|----------------|-----------------------------------------------------------|---------| +| RequireCredentials | System.Boolean | When true, the access control entry requires credentials. | $false | .PARAMETER RequestBodySizeLimitKB -| Name | Type | Description | Default | -|------|------|-------------|---------| -| RequestBodySizeLimitKB | System.Int32 | Maximum allowed request body size in kilobytes. Negative values are normalized to 0. | 1024 | +| Name | Type | Description | Default | +|------------------------|--------------|--------------------------------------------------------------------------------------|---------| +| RequestBodySizeLimitKB | System.Int32 | Maximum allowed request body size in kilobytes. Negative values are normalized to 0. | 1024 | .OUTPUTS -PSCustomObject — access control object with `AllowedMethods`, `AllowedResources`, +PSCustomObject -- access control object with `AllowedMethods`, `AllowedResources`, `BlockedResources`, `AllowedOrigins`, `RequireCredentials`, `RequestBodySizeLimit` (bytes) and `Scope` set to `RestApi`. @@ -53,6 +53,9 @@ The `RequireCredentials` flag is informational in the current implementation; credential enforcement must be added in the request handling logic. The KB limit is converted to bytes internally. At least one allowed method must be specified; passing an empty array causes the function to return `$null`. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function New-IcingaRestApiAccessControlObject() { diff --git a/src/Core/RestApi/Public/Send-IcingaRestApiRequest.ps1 b/src/Core/RestApi/Public/Send-IcingaRestApiRequest.ps1 index 790f839..00ca4c3 100644 --- a/src/Core/RestApi/Public/Send-IcingaRestApiRequest.ps1 +++ b/src/Core/RestApi/Public/Send-IcingaRestApiRequest.ps1 @@ -11,27 +11,27 @@ checking disabled for self-signed certificates. Non-GET methods serialize the `Body` hashtable as JSON. Non-200 responses are returned as failures. .PARAMETER WebPath -| Name | Type | Description | Default | -|------|------|-------------|---------| -| WebPath | System.String | Relative web path or endpoint (e.g. '/v1/status'). Leading slash is optional. | '' | +| Name | Type | Description | Default | +|---------|---------------|-------------------------------------------------------------------------------|---------| +| WebPath | System.String | Relative web path or endpoint (e.g. '/v1/status'). Leading slash is optional. | '' | .PARAMETER Method -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Method | System.String | HTTP method to use (GET, POST, PUT, DELETE, etc.). | 'GET' | +| Name | Type | Description | Default | +|--------|---------------|----------------------------------------------------|---------| +| Method | System.String | HTTP method to use (GET, POST, PUT, DELETE, etc.). | 'GET' | .PARAMETER Headers -| Name | Type | Description | Default | -|------|------|-------------|---------| +| Name | Type | Description | Default | +|---------|------------------------------|----------------------------------------------------|-------------------------------------------| | Headers | System.Collections.Hashtable | Additional HTTP headers to include in the request. | @{ 'Content-Type' = 'application/json'; } | .PARAMETER Body -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Body | System.Collections.Hashtable | Request body serialized as JSON for non-GET methods. | @{ } | +| Name | Type | Description | Default | +|------|------------------------------|------------------------------------------------------|---------| +| Body | System.Collections.Hashtable | Request body serialized as JSON for non-GET methods. | @{ } | .OUTPUTS -PSCustomObject — structured return value from `Write-FunctionReturnValue`. +PSCustomObject -- structured return value from `Write-FunctionReturnValue`. `RestApiRequestSuccessful` with `Response` in Data on success; `RestApiRequestFailed` with `StatusCode` and `Response` or `Exception` on failure. @@ -44,6 +44,9 @@ Requires a valid `restapi.json` configuration file to be present in the module config directory. The request always targets `https://localhost:`. Certificate validation is skipped via `-SkipCertificateCheck` to support self-signed TLS certificates. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Send-IcingaRestApiRequest() { diff --git a/src/Core/RestApi/Public/Set-IcingaRestApiConfig.ps1 b/src/Core/RestApi/Public/Set-IcingaRestApiConfig.ps1 index ac425df..ca88e36 100644 --- a/src/Core/RestApi/Public/Set-IcingaRestApiConfig.ps1 +++ b/src/Core/RestApi/Public/Set-IcingaRestApiConfig.ps1 @@ -10,32 +10,32 @@ configuration and worker count. The function returns the same standardized return objects as the underlying private implementation. .PARAMETER ListenAddress -| Name | Type | Description | Default | -|------|------|-------------|---------| +| Name | Type | Description | Default | +|---------------|---------------|--------------------------------------------------------------------------------------------|-----------| | ListenAddress | System.String | IP address or hostname to bind the RestApi listener. Use '0.0.0.0' to bind all interfaces. | '0.0.0.0' | .PARAMETER ListenPort -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ListenPort | System.Int32 | TCP port to listen on (1-65535). | 5668 | +| Name | Type | Description | Default | +|------------|--------------|----------------------------------|---------| +| ListenPort | System.Int32 | TCP port to listen on (1-65535). | 5668 | .PARAMETER TlsCertConfig -| Name | Type | Description | Default | -|------|------|-------------|---------| -| TlsCertConfig | System.PSCustomObject | TLS certificate configuration created by `New-IcingaTlsCertConfig`. | $null | +| Name | Type | Description | Default | +|---------------|-----------------------|---------------------------------------------------------------------|---------| +| TlsCertConfig | System.PSCustomObject | TLS certificate configuration created by `New-IcingaTlsCertConfig`. | $null | .PARAMETER WorkerCount -| Name | Type | Description | Default | -|------|------|-------------|---------| -| WorkerCount | System.Int32 | Number of worker threads to spawn for handling connections. | 5 | +| Name | Type | Description | Default | +|-------------|--------------|-------------------------------------------------------------|---------| +| WorkerCount | System.Int32 | Number of worker threads to spawn for handling connections. | 5 | .PARAMETER DryRun -| Name | Type | Description | Default | -|--------|----------------------------------------------|---------------------------------------------------------------------------------------------------|---------| -| DryRun | System.Management.Automation.SwitchParameter | When set, returns a unified diff of the pending configuration versus the persisted restapi.json instead of writing the change. | $false | +| Name | Type | Description | Default | +|--------|----------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------|---------| +| DryRun | System.Management.Automation.SwitchParameter | When set, returns a unified diff of the pending configuration versus the persisted restapi.json instead of writing the change. | $false | .OUTPUTS -PSCustomObject — Function return value forwarded from `Set-RestApiConfig`. +PSCustomObject -- Function return value forwarded from `Set-RestApiConfig`. .EXAMPLE PS> Set-IcingaRestApiConfig -ListenAddress '127.0.0.1' -ListenPort 10443 -WorkerCount 8 @@ -44,6 +44,9 @@ PS> Set-IcingaRestApiConfig -ListenAddress '127.0.0.1' -ListenPort 10443 -Worker This public wrapper exists to expose a stable module API while keeping the implementation in `Set-RestApiConfig` (private) where validation and persistence logic is implemented. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Set-IcingaRestApiConfig() { diff --git a/src/Core/Runtime/Private/Start-ModuleGarbageCollector.ps1 b/src/Core/Runtime/Private/Start-ModuleGarbageCollector.ps1 index 8d00653..ad2c706 100644 --- a/src/Core/Runtime/Private/Start-ModuleGarbageCollector.ps1 +++ b/src/Core/Runtime/Private/Start-ModuleGarbageCollector.ps1 @@ -10,10 +10,13 @@ while the runtime thread is running. Intended to run as a background helper thre PS> Start-ModuleGarbageCollector .OUTPUTS -None — Periodically runs garbage collection and clears the error buffer in the background. +None -- Periodically runs garbage collection and clears the error buffer in the background. .NOTES This helper should be run in a dedicated thread and relies on `Test-ThreadRunning`. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Start-ModuleGarbageCollector() { diff --git a/src/Core/Runtime/Public/Exit-Icinga.ps1 b/src/Core/Runtime/Public/Exit-Icinga.ps1 index 9ab0027..a7fa84b 100644 --- a/src/Core/Runtime/Public/Exit-Icinga.ps1 +++ b/src/Core/Runtime/Public/Exit-Icinga.ps1 @@ -8,18 +8,21 @@ shell freezing due to background threads that do not terminate on a normal exit. .PARAMETER ExitCode -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ExitCode | System.Int32 | Process exit code to return | 0 | +| Name | Type | Description | Default | +|----------|--------------|-----------------------------|---------| +| ExitCode | System.Int32 | Process exit code to return | 0 | .OUTPUTS -None — The process is terminated immediately; no value is returned. +None -- The process is terminated immediately; no value is returned. .EXAMPLE PS> Exit-Icinga .NOTES Uses `[System.Environment]::Exit($ExitCode)` to ensure the process exits cleanly with the desired exit code. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Exit-Icinga() { diff --git a/src/Core/TCPStack/Private/Close-TCPConnection.ps1 b/src/Core/TCPStack/Private/Close-TCPConnection.ps1 index 58ca63e..969428b 100644 --- a/src/Core/TCPStack/Private/Close-TCPConnection.ps1 +++ b/src/Core/TCPStack/Private/Close-TCPConnection.ps1 @@ -7,13 +7,16 @@ Close and dispose the active TCP client and SSL stream associated SSL stream stored in the global runtime variable, if present. .OUTPUTS -None — Clears the SSL stream, TCP client and their references in the global state. +None -- Clears the SSL stream, TCP client and their references in the global state. .EXAMPLE PS> Close-TCPConnection .NOTES This is idempotent and swallows disposal exceptions. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Close-TCPConnection() { diff --git a/src/Core/TCPStack/Private/Close-TCPSocket.ps1 b/src/Core/TCPStack/Private/Close-TCPSocket.ps1 index cba3a86..a9447b1 100644 --- a/src/Core/TCPStack/Private/Close-TCPSocket.ps1 +++ b/src/Core/TCPStack/Private/Close-TCPSocket.ps1 @@ -7,13 +7,16 @@ Stop and release the TCP listener socket and clears the listener reference in the global runtime variable. .OUTPUTS -None — Stops the listener and clears its reference in the global state. +None -- Stops the listener and clears its reference in the global state. .EXAMPLE PS> Close-TCPSocket .NOTES Requires privileges sufficient to stop the listener; exceptions are logged. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Close-TCPSocket() { diff --git a/src/Core/TCPStack/Private/Get-TlsCertificate.ps1 b/src/Core/TCPStack/Private/Get-TlsCertificate.ps1 index 24d77d2..dd65d2c 100644 --- a/src/Core/TCPStack/Private/Get-TlsCertificate.ps1 +++ b/src/Core/TCPStack/Private/Get-TlsCertificate.ps1 @@ -8,18 +8,21 @@ TLS configuration object. It supports loading from a file path or by searching the specified certificate store using thumbprint, common name or issuer filters. .PARAMETER TlsCertConfig -| Name | Type | Description | Default | -|------|------|-------------|---------| -| TlsCertConfig | System.PSCustomObject | Configuration describing how to locate the certificate | | +| Name | Type | Description | Default | +|---------------|-----------------------|--------------------------------------------------------|---------| +| TlsCertConfig | System.PSCustomObject | Configuration describing how to locate the certificate | | .OUTPUTS -System.Security.Cryptography.X509Certificates.X509Certificate2 — The loaded certificate, or $null on failure. +System.Security.Cryptography.X509Certificates.X509Certificate2 -- The loaded certificate, or $null on failure. .EXAMPLE PS> Get-TlsCertificate -TlsCertConfig $cfg .NOTES Uses `Write-FunctionReturnValue` to report detailed result codes for callers. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Get-TlsCertificate() { diff --git a/src/Core/TCPStack/Private/New-TlsCertConfig.ps1 b/src/Core/TCPStack/Private/New-TlsCertConfig.ps1 index 505275b..fb2c89f 100644 --- a/src/Core/TCPStack/Private/New-TlsCertConfig.ps1 +++ b/src/Core/TCPStack/Private/New-TlsCertConfig.ps1 @@ -8,43 +8,46 @@ TLS certificate, either by file path, thumbprint or search filters (CN/Issuer). It validates that at least one selector is provided. .PARAMETER CertPath -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CertPath | System.String | Optional filesystem path to a certificate file | $null | +| Name | Type | Description | Default | +|----------|---------------|------------------------------------------------|---------| +| CertPath | System.String | Optional filesystem path to a certificate file | $null | .PARAMETER CertThumbprint -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CertThumbprint | System.String | Thumbprint to locate certificate in store | $null | +| Name | Type | Description | Default | +|----------------|---------------|-------------------------------------------|---------| +| CertThumbprint | System.String | Thumbprint to locate certificate in store | $null | .PARAMETER CertCN -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CertCN | System.String | Common Name filter for certificate store search | $null | +| Name | Type | Description | Default | +|--------|---------------|-------------------------------------------------|---------| +| CertCN | System.String | Common Name filter for certificate store search | $null | .PARAMETER CertStore -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CertStore | System.String | Certificate store name (e.g. 'My') | 'My' | +| Name | Type | Description | Default | +|-----------|---------------|------------------------------------|---------| +| CertStore | System.String | Certificate store name (e.g. 'My') | 'My' | .PARAMETER CertStoreLocation -| Name | Type | Description | Default | -|------|------|-------------|---------| +| Name | Type | Description | Default | +|-------------------|---------------|--------------------------------------|----------------| | CertStoreLocation | System.String | Store location (e.g. 'LocalMachine') | 'LocalMachine' | .PARAMETER CertIssuer -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CertIssuer | System.Array | Array of issuer names to match when searching certificate stores | $null | +| Name | Type | Description | Default | +|------------|--------------|------------------------------------------------------------------|---------| +| CertIssuer | System.Array | Array of issuer names to match when searching certificate stores | $null | .OUTPUTS -System.Management.Automation.PSCustomObject — Constructed TLS configuration object, returned via `Write-FunctionReturnValue`. +System.Management.Automation.PSCustomObject -- Constructed TLS configuration object, returned via `Write-FunctionReturnValue`. .EXAMPLE PS> New-TlsCertConfig -CertThumbprint 'ABCDEF...' .NOTES At least one of `CertPath`, `CertThumbprint`, `CertCN` or `CertIssuer` must be provided. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function New-TlsCertConfig() { diff --git a/src/Core/TCPStack/Private/Open-SSLStream.ps1 b/src/Core/TCPStack/Private/Open-SSLStream.ps1 index 77dae11..43211f3 100644 --- a/src/Core/TCPStack/Private/Open-SSLStream.ps1 +++ b/src/Core/TCPStack/Private/Open-SSLStream.ps1 @@ -8,23 +8,26 @@ Create and authenticate an SSL stream for the active TCP client. using the thread-local TLS certificate. On failure it closes the TCP connection. .PARAMETER Endpoint -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Endpoint | System.String | Expected remote endpoint name (required for client auth) | $null | +| Name | Type | Description | Default | +|----------|---------------|----------------------------------------------------------|---------| +| Endpoint | System.String | Expected remote endpoint name (required for client auth) | $null | .PARAMETER IsClient -| Name | Type | Description | Default | -|------|------|-------------|---------| -| IsClient | System.SwitchParameter | When set perform client-side authentication | $false | +| Name | Type | Description | Default | +|----------|------------------------|---------------------------------------------|---------| +| IsClient | System.SwitchParameter | When set perform client-side authentication | $false | .OUTPUTS -None — Stores the opened SslStream in the global state; result codes are reported via `Write-FunctionReturnValue`. +None -- Stores the opened SslStream in the global state; result codes are reported via `Write-FunctionReturnValue`. .EXAMPLE PS> Open-SSLStream -Endpoint 'example.com' -IsClient .NOTES Requires a valid certificate in `(Get-GlobalRuntimeVariable).Private.TCP.Certificate`. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Open-SSLStream() { @@ -47,7 +50,7 @@ function Open-SSLStream() # otherwise silently drop our certificate when the remote side's CertificateRequest lists # a CA that doesn't match our cert's issuer chain (common with self-signed Icinga PKI). # [IcingaIgnoreDisposeCheck] - $sslStream = New-Object System.Net.Security.SslStream( + $sslStream = New-Object System.Net.Security.SslStream( $GlobalVariable.Private.TCP.Client.GetStream(), $false, $null, diff --git a/src/Core/TCPStack/Private/Open-TCPSocket.ps1 b/src/Core/TCPStack/Private/Open-TCPSocket.ps1 index ea949e1..7c01c6a 100644 --- a/src/Core/TCPStack/Private/Open-TCPSocket.ps1 +++ b/src/Core/TCPStack/Private/Open-TCPSocket.ps1 @@ -8,24 +8,24 @@ port, stores it in the global runtime variable and optionally starts listening. An optional TLS certificate can be associated for incoming connections. .PARAMETER Address -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Address | System.String | IP address to bind or empty for loopback | '' | +| Name | Type | Description | Default | +|---------|---------------|------------------------------------------|---------| +| Address | System.String | IP address to bind or empty for loopback | '' | .PARAMETER Port -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Port | System.Int32 | TCP port to bind | 0 | +| Name | Type | Description | Default | +|------|--------------|------------------|---------| +| Port | System.Int32 | TCP port to bind | 0 | .PARAMETER Start -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Start | System.SwitchParameter | When set, immediately start the listener | $false | +| Name | Type | Description | Default | +|-------|------------------------|------------------------------------------|---------| +| Start | System.SwitchParameter | When set, immediately start the listener | $false | .PARAMETER TlsCertificate -| Name | Type | Description | Default | -|------|------|-------------|---------| -| TlsCertificate | System.Security.Cryptography.X509Certificates.X509Certificate2 | Optional server certificate to attach | $null | +| Name | Type | Description | Default | +|----------------|----------------------------------------------------------------|---------------------------------------|---------| +| TlsCertificate | System.Security.Cryptography.X509Certificates.X509Certificate2 | Optional server certificate to attach | $null | .OUTPUTS None. Stores listener and certificate in global runtime state. @@ -35,6 +35,9 @@ PS> Open-TCPSocket -Port 8080 -Start .NOTES Use `Close-TCPSocket` to stop and clear the listener. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Open-TCPSocket() { diff --git a/src/Core/TCPStack/Private/Send-TCPMessage.ps1 b/src/Core/TCPStack/Private/Send-TCPMessage.ps1 index 6359f24..23f75e4 100644 --- a/src/Core/TCPStack/Private/Send-TCPMessage.ps1 +++ b/src/Core/TCPStack/Private/Send-TCPMessage.ps1 @@ -8,18 +8,21 @@ and writes it to the active SSL stream of the current TCP client. It logs an error if no valid stream is available. .PARAMETER MsgObj -| Name | Type | Description | Default | -|------|------|-------------|---------| -| MsgObj | System.Object | Object with `message` (buffer) and `length` properties | $null | +| Name | Type | Description | Default | +|--------|---------------|--------------------------------------------------------|---------| +| MsgObj | System.Object | Object with `message` (buffer) and `length` properties | $null | .OUTPUTS -None — Writes the message buffer to the SSL stream and flushes it; logs an error if no valid stream is available. +None -- Writes the message buffer to the SSL stream and flushes it; logs an error if no valid stream is available. .EXAMPLE PS> Send-TCPMessage -MsgObj $msg .NOTES This helper assumes the active stream is an `SslStream` exposing `Write` and `Flush`. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Send-TCPMessage() { diff --git a/src/Core/TCPStack/Private/Set-TCPClientAndStream.ps1 b/src/Core/TCPStack/Private/Set-TCPClientAndStream.ps1 index f70bae9..8d3bf26 100644 --- a/src/Core/TCPStack/Private/Set-TCPClientAndStream.ps1 +++ b/src/Core/TCPStack/Private/Set-TCPClientAndStream.ps1 @@ -7,23 +7,26 @@ Set the global TCP client and SSL stream references instances into the runtime private TCP container so other helpers can access them. .PARAMETER TcpClient -| Name | Type | Description | Default | -|------|------|-------------|---------| -| TcpClient | System.Net.Sockets.TcpClient | The connected TCP client instance | $null | +| Name | Type | Description | Default | +|-----------|------------------------------|-----------------------------------|---------| +| TcpClient | System.Net.Sockets.TcpClient | The connected TCP client instance | $null | .PARAMETER SslStream -| Name | Type | Description | Default | -|------|------|-------------|---------| -| SslStream | System.Net.Security.SslStream | The SSL stream wrapping the client's network stream | $null | +| Name | Type | Description | Default | +|-----------|-------------------------------|-----------------------------------------------------|---------| +| SslStream | System.Net.Security.SslStream | The SSL stream wrapping the client's network stream | $null | .OUTPUTS -None — Updates the `TcpClient` and `SslStream` references in `(Get-GlobalRuntimeVariable).Private.TCP`. +None -- Updates the `TcpClient` and `SslStream` references in `(Get-GlobalRuntimeVariable).Private.TCP`. .EXAMPLE PS> Set-TCPClientAndStream -TcpClient $c -SslStream $s .NOTES This is a trivial assignment helper used after connection establishment. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Set-TCPClientAndStream() { @@ -32,7 +35,7 @@ function Set-TCPClientAndStream() [System.Net.Security.SslStream]$SslStream = $null ); - $GlobalVariable = Get-GlobalRuntimeVariable; + $GlobalVariable = Get-GlobalRuntimeVariable; $GlobalVariable.Private.TCP.Client = $TcpClient; $GlobalVariable.Private.TCP.Stream = $SslStream; diff --git a/src/Core/TCPStack/Private/Test-TCPConnection.ps1 b/src/Core/TCPStack/Private/Test-TCPConnection.ps1 index da15d94..a66ea2f 100644 --- a/src/Core/TCPStack/Private/Test-TCPConnection.ps1 +++ b/src/Core/TCPStack/Private/Test-TCPConnection.ps1 @@ -7,20 +7,23 @@ Check whether the current TCP client and stream are connected. stream are present and returns the client's `Connected` state. .OUTPUTS -System.Boolean — $true when connected and a valid client and stream are present; $false otherwise. +System.Boolean -- $true when connected and a valid client and stream are present; $false otherwise. .EXAMPLE PS> Test-TCPConnection .NOTES Used by thread health checks and higher-level network monitors. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Test-TCPConnection() { $GlobalVariable = Get-GlobalRuntimeVariable; - $Client = $GlobalVariable.Private.TCP.Client; - $Stream = $GlobalVariable.Private.TCP.Stream; + $Client = $GlobalVariable.Private.TCP.Client; + $Stream = $GlobalVariable.Private.TCP.Stream; if ($null -eq $Stream -or $null -eq $Client -or $null -eq $Client.Client) { return $false; diff --git a/src/Core/TCPStack/Private/Update-TCPConnection.ps1 b/src/Core/TCPStack/Private/Update-TCPConnection.ps1 index ff0fb14..768515d 100644 --- a/src/Core/TCPStack/Private/Update-TCPConnection.ps1 +++ b/src/Core/TCPStack/Private/Update-TCPConnection.ps1 @@ -8,28 +8,31 @@ TCP container and calls `Open-SSLStream` to wrap and authenticate the connection as client or server depending on the `IsClient` flag. .PARAMETER Client -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Client | System.Net.Sockets.TcpClient | Connected TCP client instance to register | $null | +| Name | Type | Description | Default | +|--------|------------------------------|-------------------------------------------|---------| +| Client | System.Net.Sockets.TcpClient | Connected TCP client instance to register | $null | .PARAMETER Endpoint -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Endpoint | System.String | Remote endpoint name (used for client SSL auth) | $null | +| Name | Type | Description | Default | +|----------|---------------|-------------------------------------------------|---------| +| Endpoint | System.String | Remote endpoint name (used for client SSL auth) | $null | .PARAMETER IsClient -| Name | Type | Description | Default | -|------|------|-------------|---------| -| IsClient | System.SwitchParameter | When set perform client-side SSL authentication | $false | +| Name | Type | Description | Default | +|----------|------------------------|-------------------------------------------------|---------| +| IsClient | System.SwitchParameter | When set perform client-side SSL authentication | $false | .OUTPUTS -None — Result codes from `Open-SSLStream` are forwarded via `Write-FunctionReturnValue`. +None -- Result codes from `Open-SSLStream` are forwarded via `Write-FunctionReturnValue`. .EXAMPLE PS> Update-TCPConnection -Client $c -Endpoint 'example.com' -IsClient .NOTES Validates `$Client` and returns `UpdateTcpClientInvalid` when missing. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Update-TCPConnection() { diff --git a/src/Core/TCPStack/Public/New-IcingaTlsCertConfig.ps1 b/src/Core/TCPStack/Public/New-IcingaTlsCertConfig.ps1 index 197f232..994fddb 100644 --- a/src/Core/TCPStack/Public/New-IcingaTlsCertConfig.ps1 +++ b/src/Core/TCPStack/Public/New-IcingaTlsCertConfig.ps1 @@ -9,37 +9,37 @@ certificate store and store location while allowing callers to specify a certificate file, thumbprint, CN, issuer, or alternative store settings. .PARAMETER CertPath -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CertPath | System.String | Path to a PKCS#12/PFX certificate file to load. | | +| Name | Type | Description | Default | +|----------|---------------|-------------------------------------------------|---------| +| CertPath | System.String | Path to a PKCS#12/PFX certificate file to load. | | .PARAMETER CertThumbprint -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CertThumbprint | System.String | Thumbprint of a certificate to locate in a certificate store. | | +| Name | Type | Description | Default | +|----------------|---------------|---------------------------------------------------------------|---------| +| CertThumbprint | System.String | Thumbprint of a certificate to locate in a certificate store. | | .PARAMETER CertCN -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CertCN | System.String | Common Name (CN) to match when searching certificate stores. | | +| Name | Type | Description | Default | +|--------|---------------|--------------------------------------------------------------|---------| +| CertCN | System.String | Common Name (CN) to match when searching certificate stores. | | .PARAMETER CertStore -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CertStore | System.String | Certificate store name (for example: My, Root). | My | +| Name | Type | Description | Default | +|-----------|---------------|-------------------------------------------------|---------| +| CertStore | System.String | Certificate store name (for example: My, Root). | My | .PARAMETER CertStoreLocation -| Name | Type | Description | Default | -|------|------|-------------|---------| +| Name | Type | Description | Default | +|-------------------|---------------|----------------------------------------------------------------------|--------------| | CertStoreLocation | System.String | Certificate store location (for example: LocalMachine, CurrentUser). | LocalMachine | .PARAMETER CertIssuer -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CertIssuer | System.Array | Array of issuer names to match when searching certificate stores. | | +| Name | Type | Description | Default | +|------------|--------------|-------------------------------------------------------------------|---------| +| CertIssuer | System.Array | Array of issuer names to match when searching certificate stores. | | .OUTPUTS -System.Object — TLS certificate configuration object for the TCP stack, returned from `New-TlsCertConfig`. +System.Object -- TLS certificate configuration object for the TCP stack, returned from `New-TlsCertConfig`. .EXAMPLE PS> New-IcingaTlsCertConfig -CertPath 'C:\certs\icinga.pfx' @@ -48,6 +48,9 @@ PS> New-IcingaTlsCertConfig -CertPath 'C:\certs\icinga.pfx' This function is a thin Icinga-specific wrapper around `New-TlsCertConfig`. Refer to `New-TlsCertConfig` for full validation rules and additional options. At least one of CertPath, CertThumbprint, CertCN or CertIssuer must be supplied. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function New-IcingaTlsCertConfig() { diff --git a/src/Core/Threading/Private/Get-ThreadCallStack.ps1 b/src/Core/Threading/Private/Get-ThreadCallStack.ps1 index e2514a5..f75f4ff 100644 --- a/src/Core/Threading/Private/Get-ThreadCallStack.ps1 +++ b/src/Core/Threading/Private/Get-ThreadCallStack.ps1 @@ -8,13 +8,16 @@ human-readable thread name by joining function names with '`::`'. It normalizes scriptblock entries and removes internal `Set-ThreadData` frames. .OUTPUTS -System.String — A single-line thread name derived from the call stack. +System.String -- A single-line thread name derived from the call stack. .EXAMPLE PS> Get-ThreadCallStack .NOTES Used for naming threads created with `New-Thread` to aid diagnostics and tracing. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Get-ThreadCallStack() { diff --git a/src/Core/Threading/Private/Get-ThreadId.ps1 b/src/Core/Threading/Private/Get-ThreadId.ps1 index 0bad72c..0f95f70 100644 --- a/src/Core/Threading/Private/Get-ThreadId.ps1 +++ b/src/Core/Threading/Private/Get-ThreadId.ps1 @@ -7,13 +7,16 @@ Return the current thread identifier used by our runtime. container. It is a convenience helper to avoid repeating the global variable path. .OUTPUTS -System.String — The current thread GUID string, or $null if not set. +System.String -- The current thread GUID string, or $null if not set. .EXAMPLE PS> Get-ThreadId .NOTES The value is read from `(Get-GlobalRuntimeVariable).Private.Threading.ThreadId`. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Get-ThreadId() { diff --git a/src/Core/Threading/Private/Get-ThreadLastSeen.ps1 b/src/Core/Threading/Private/Get-ThreadLastSeen.ps1 index 25fc1f1..71fdc85 100644 --- a/src/Core/Threading/Private/Get-ThreadLastSeen.ps1 +++ b/src/Core/Threading/Private/Get-ThreadLastSeen.ps1 @@ -8,18 +8,21 @@ thread registry and returns the elapsed seconds (rounded) since that timestamp. If the thread or timestamp is missing, `$null` is returned. .PARAMETER ThreadId -| Name | Type | Description | Default | -|------|------|-------------|---------| +| Name | Type | Description | Default | +|----------|---------------|-----------------------------------------------------|----------------| | ThreadId | System.String | The thread id to query. Defaults to current thread. | (Get-ThreadId) | .OUTPUTS -System.Double — Seconds since the last heartbeat, or $null if the thread is unknown. +System.Double -- Seconds since the last heartbeat, or $null if the thread is unknown. .EXAMPLE PS> Get-ThreadLastSeen -ThreadId $tid .NOTES Used by health checks and thread state transitions in the housekeeper. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Get-ThreadLastSeen() { diff --git a/src/Core/Threading/Private/Get-ThreadState.ps1 b/src/Core/Threading/Private/Get-ThreadState.ps1 index 0e5c7c3..e6cdac8 100644 --- a/src/Core/Threading/Private/Get-ThreadState.ps1 +++ b/src/Core/Threading/Private/Get-ThreadState.ps1 @@ -9,18 +9,21 @@ unmodified. It uses the thread's `LastSeen` timestamp and `KeepAlive` flag to differentiate between active and idle conditions. .PARAMETER ThreadId -| Name | Type | Description | Default | -|------|------|-------------|---------| +| Name | Type | Description | Default | +|----------|---------------|--------------------------------------------------------|----------------| | ThreadId | System.String | The thread id to evaluate. Defaults to current thread. | (Get-ThreadId) | .OUTPUTS -System.String — Normalisierter Thread-State (z.B. RUNNING, IDLE, BLOCKED). +System.String -- Normalisierter Thread-State (z.B. RUNNING, IDLE, BLOCKED). .EXAMPLE PS> Get-ThreadState -ThreadId $tid .NOTES Relies on configuration values such as `(Get-GlobalRuntimeVariable).Public.Threading.IdleTime`. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Get-ThreadState() { diff --git a/src/Core/Threading/Private/Get-ThreadTree.ps1 b/src/Core/Threading/Private/Get-ThreadTree.ps1 index f80def5..e50e04e 100644 --- a/src/Core/Threading/Private/Get-ThreadTree.ps1 +++ b/src/Core/Threading/Private/Get-ThreadTree.ps1 @@ -6,7 +6,7 @@ Build a hierarchical tree of all registered threads as PSObjects. `Get-ThreadTree` collects every thread from the global thread registry and assembles it into a list of root-level tree nodes. Each node holds the resolved thread state, last-seen age, parameters and a `Children` array that -contains the child nodes in the same format — forming a complete, self-contained +contains the child nodes in the same format -- forming a complete, self-contained representation of the thread hierarchy without requiring further registry lookups. @@ -19,7 +19,7 @@ PSObject with the following properties: | Id | System.String | Unique thread GUID | | Name | System.String | Display name of the thread | | Command | System.String | Entry-point command name | -| State | System.String | Resolved state (RUNNING, IDLE, …) | +| State | System.String | Resolved state (RUNNING, IDLE, ...) | | LastSeen | System.Double | Seconds since last heartbeat | | KeepAlive | System.Boolean | Whether the thread is kept alive | | Parameters | System.Hashtable | Parameters passed to the command | @@ -33,6 +33,9 @@ PS> $tree[0].Children .NOTES The function resolves state and last-seen values at call time via `Get-ThreadState` and `Get-ThreadLastSeen`. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Get-ThreadTree() { diff --git a/src/Core/Threading/Private/New-Thread.ps1 b/src/Core/Threading/Private/New-Thread.ps1 index 4b5cdd9..a94782b 100644 --- a/src/Core/Threading/Private/New-Thread.ps1 +++ b/src/Core/Threading/Private/New-Thread.ps1 @@ -8,39 +8,39 @@ registers the thread in the global threading registry and optionally starts it. The function supports keep-alive semantics and parent/child relationships. .PARAMETER Command -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Command | System.String | The command (function) name to execute in the thread | | +| Name | Type | Description | Default | +|---------|---------------|------------------------------------------------------|---------| +| Command | System.String | The command (function) name to execute in the thread | | .PARAMETER Parameters -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Parameters | System.Hashtable | Named parameters passed to the command | @{} | +| Name | Type | Description | Default | +|------------|------------------|----------------------------------------|---------| +| Parameters | System.Hashtable | Named parameters passed to the command | @{} | .PARAMETER ParentThread -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ParentThread | System.String | Optional parent thread id (defaults to current thread) | $null | +| Name | Type | Description | Default | +|--------------|---------------|--------------------------------------------------------|---------| +| ParentThread | System.String | Optional parent thread id (defaults to current thread) | $null | .PARAMETER OverrideName -| Name | Type | Description | Default | -|------|------|-------------|---------| -| OverrideName | System.String | Optional explicit display name for the created thread | $null | +| Name | Type | Description | Default | +|--------------|---------------|-------------------------------------------------------|---------| +| OverrideName | System.String | Optional explicit display name for the created thread | $null | .PARAMETER Start -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Start | System.SwitchParameter | When set, start the thread immediately after creation | $false | +| Name | Type | Description | Default | +|-------|------------------------|-------------------------------------------------------|---------| +| Start | System.SwitchParameter | When set, start the thread immediately after creation | $false | .PARAMETER KeepAlive -| Name | Type | Description | Default | -|------|------|-------------|---------| -| KeepAlive | System.SwitchParameter | When set, the housekeeper may restart the thread on failure | $false | +| Name | Type | Description | Default | +|-----------|------------------------|-------------------------------------------------------------|---------| +| KeepAlive | System.SwitchParameter | When set, the housekeeper may restart the thread on failure | $false | .PARAMETER WaitForJobs -| Name | Type | Description | Default | -|------|------|-------------|---------| -| WaitForJobs | System.SwitchParameter | When set the thread is expected to wait for queued jobs | $false | +| Name | Type | Description | Default | +|-------------|------------------------|---------------------------------------------------------|---------| +| WaitForJobs | System.SwitchParameter | When set the thread is expected to wait for queued jobs | $false | .OUTPUTS System.String. The newly created thread id. @@ -50,6 +50,9 @@ PS> New-Thread -Command 'Start-Worker' -Parameters @{ 'Queue' = $q } -Start .NOTES This helper uses `Set-ThreadData` in the created runspace to initialize thread-local state. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function New-Thread() { diff --git a/src/Core/Threading/Private/New-ThreadPool.ps1 b/src/Core/Threading/Private/New-ThreadPool.ps1 index e54c10e..682d803 100644 --- a/src/Core/Threading/Private/New-ThreadPool.ps1 +++ b/src/Core/Threading/Private/New-ThreadPool.ps1 @@ -8,23 +8,26 @@ instances and caches it on the global runtime variable. If a pool already exists, the cached instance is returned. .PARAMETER MinInstances -| Name | Type | Description | Default | -|------|------|-------------|---------| -| MinInstances | System.Int32 | Minimum number of runspaces in the pool | 1 | +| Name | Type | Description | Default | +|--------------|--------------|-----------------------------------------|---------| +| MinInstances | System.Int32 | Minimum number of runspaces in the pool | 1 | .PARAMETER MaxInstances -| Name | Type | Description | Default | -|------|------|-------------|---------| +| Name | Type | Description | Default | +|--------------|--------------|-----------------------------------------|-----------------------------------------------------------| | MaxInstances | System.Int32 | Maximum number of runspaces in the pool | `(Get-GlobalRuntimeVariable).Public.Threading.MaxThreads` | .OUTPUTS -System.Management.Automation.Runspaces.RunspacePool — The newly created or cached runspace pool. +System.Management.Automation.Runspaces.RunspacePool -- The newly created or cached runspace pool. .EXAMPLE PS> New-ThreadPool -MinInstances 2 -MaxInstances 8 .NOTES The function currently uses the default `InitialSessionState`. Future work may enable JEA. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function New-ThreadPool() { diff --git a/src/Core/Threading/Private/Set-ThreadFrozen.ps1 b/src/Core/Threading/Private/Set-ThreadFrozen.ps1 index 140e660..a9ee047 100644 --- a/src/Core/Threading/Private/Set-ThreadFrozen.ps1 +++ b/src/Core/Threading/Private/Set-ThreadFrozen.ps1 @@ -8,18 +8,21 @@ it exceeds the configured keep-alive threshold, sets the thread state to `FROZEN` and emits a warning log entry. .PARAMETER ThreadId -| Name | Type | Description | Default | -|------|------|-------------|---------| +| Name | Type | Description | Default | +|----------|---------------|-------------------------------------------------------|----------------| | ThreadId | System.String | The thread id to inspect. Defaults to current thread. | (Get-ThreadId) | .OUTPUTS -None — Updates the thread state in the global registry and emits a warning log entry when frozen. +None -- Updates the thread state in the global registry and emits a warning log entry when frozen. .EXAMPLE PS> Set-ThreadFrozen -ThreadId $tid .NOTES This helper is used by the housekeeper loop to detect and flag unresponsive threads. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Set-ThreadFrozen() { diff --git a/src/Core/Threading/Private/Set-ThreadProcessing.ps1 b/src/Core/Threading/Private/Set-ThreadProcessing.ps1 index 8616731..011ffdb 100644 --- a/src/Core/Threading/Private/Set-ThreadProcessing.ps1 +++ b/src/Core/Threading/Private/Set-ThreadProcessing.ps1 @@ -7,13 +7,16 @@ Mark the current thread as processing and refresh its heartbeat. and records the current timestamp in `LastSeen` to indicate activity. .OUTPUTS -None — Modifies `(Get-GlobalRuntimeVariable).Public.Threading.Threads` for the current thread. +None -- Modifies `(Get-GlobalRuntimeVariable).Public.Threading.Threads` for the current thread. .EXAMPLE PS> Set-ThreadProcessing .NOTES Typically called by worker loops when they start handling a job. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Set-ThreadProcessing() { diff --git a/src/Core/Threading/Private/Show-Threads.ps1 b/src/Core/Threading/Private/Show-Threads.ps1 index 7d7fbc6..22aa677 100644 --- a/src/Core/Threading/Private/Show-Threads.ps1 +++ b/src/Core/Threading/Private/Show-Threads.ps1 @@ -5,13 +5,13 @@ Render or return the current thread hierarchy and status. .DESCRIPTION `Show-Threads` builds a complete thread tree via `Get-ThreadTree` and either returns the structured tree objects or renders them as a formatted hierarchy -string and emits it to the logging system — depending on the `-AsObject` +string and emits it to the logging system -- depending on the `-AsObject` switch. .PARAMETER AsObject -| Name | Type | Description | Default | -|----------|-------------------------|----------------------------------------------------|---------| -| AsObject | System.SwitchParameter | Return the tree as PSObjects instead of rendering | $false | +| Name | Type | Description | Default | +|----------|------------------------|---------------------------------------------------|---------| +| AsObject | System.SwitchParameter | Return the tree as PSObjects instead of rendering | $false | .OUTPUTS System.Array when `-AsObject` is set. Returns the root-level thread nodes @@ -31,6 +31,9 @@ PS> $tree[0].Children .NOTES Relies on `Get-ThreadTree` to build the hierarchy and `Write-ThreadTree` to render individual branches. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Show-Threads() { diff --git a/src/Core/Threading/Private/Start-ThreadHouseKeeper.ps1 b/src/Core/Threading/Private/Start-ThreadHouseKeeper.ps1 index 53ec857..337a922 100644 --- a/src/Core/Threading/Private/Start-ThreadHouseKeeper.ps1 +++ b/src/Core/Threading/Private/Start-ThreadHouseKeeper.ps1 @@ -9,13 +9,16 @@ and attempts restarts for keep-alive threads. It sleeps between cycles to reduce resource usage. .OUTPUTS -None — Performs side-effect operations on the global thread registry and logs actions. +None -- Performs side-effect operations on the global thread registry and logs actions. .EXAMPLE PS> Start-ThreadHouseKeeper .NOTES This function is intended to run as a background supervisory thread. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Start-ThreadHouseKeeper() { diff --git a/src/Core/Threading/Private/Stop-Thread.ps1 b/src/Core/Threading/Private/Stop-Thread.ps1 index 0df742b..48910fa 100644 --- a/src/Core/Threading/Private/Stop-Thread.ps1 +++ b/src/Core/Threading/Private/Stop-Thread.ps1 @@ -8,18 +8,21 @@ registry. It validates the provided thread id and returns structured results using `Write-FunctionReturnValue` when errors occur. .PARAMETER ThreadId -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ThreadId | System.String | The id of the thread to stop | $null | +| Name | Type | Description | Default | +|----------|---------------|------------------------------|---------| +| ThreadId | System.String | The id of the thread to stop | $null | .OUTPUTS -System.Management.Automation.PSCustomObject — Strukturierter Rueckgabewert bei Fehler (via Write-FunctionReturnValue); None bei Erfolg. +System.Management.Automation.PSCustomObject -- Strukturierter Rueckgabewert bei Fehler (via Write-FunctionReturnValue); None bei Erfolg. .EXAMPLE PS> Stop-Thread -ThreadId $tid .NOTES The actual runspace shutdown and cleanup is handled by the housekeeper loop. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Stop-Thread() { diff --git a/src/Core/Threading/Private/Test-ThreadRunning.ps1 b/src/Core/Threading/Private/Test-ThreadRunning.ps1 index d31e616..6c5acaf 100644 --- a/src/Core/Threading/Private/Test-ThreadRunning.ps1 +++ b/src/Core/Threading/Private/Test-ThreadRunning.ps1 @@ -9,22 +9,22 @@ checks the thread state and optionally validates TCP/WebSocket connectivity. It also enforces lightweight sleeps to reduce CPU usage. .PARAMETER CheckTcpConnection -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CheckTcpConnection | System.SwitchParameter | When set test the global TCP connection status | $false | +| Name | Type | Description | Default | +|--------------------|------------------------|------------------------------------------------|---------| +| CheckTcpConnection | System.SwitchParameter | When set test the global TCP connection status | $false | .PARAMETER CheckWebSocket -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CheckWebSocket | System.SwitchParameter | When set test the WebSocket connectivity | $false | +| Name | Type | Description | Default | +|----------------|------------------------|------------------------------------------|---------| +| CheckWebSocket | System.SwitchParameter | When set test the WebSocket connectivity | $false | .PARAMETER NoSleep -| Name | Type | Description | Default | -|------|------|-------------|---------| -| NoSleep | System.SwitchParameter | When set skip the default short sleep at loop start | $false | +| Name | Type | Description | Default | +|---------|------------------------|-----------------------------------------------------|---------| +| NoSleep | System.SwitchParameter | When set skip the default short sleep at loop start | $false | .OUTPUTS -System.Boolean — $true when the thread should continue, $false otherwise. +System.Boolean -- $true when the thread should continue, $false otherwise. .EXAMPLE while (Test-ThreadRunning) { Do-Work } @@ -32,13 +32,16 @@ while (Test-ThreadRunning) { Do-Work } .NOTES This function performs multiple side effects (timestamp updates, logging id rotation) and is central to thread lifecycle management. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Test-ThreadRunning() { param ( [switch]$CheckTcpConnection = $false, [switch]$CheckWebSocket = $false, - [switch]$NoSleep = $false + [switch]$NoSleep = $false ); # At first, before we do anything, lets sleep for 100 milliseconds to keep the entire CPU from spiking @@ -62,7 +65,7 @@ function Test-ThreadRunning() # If we are TERMINATED, we should already have reached the ending point, which means we should be fine # If we are in state ZOMBIE, we should return false as this state only applies if we are meant to be KeepAlive # Shutdown simply means we are in the process of stopping, so we should also return false - $ThreadState = $GlobalVariable.Public.Threading.Threads.$ThreadId.State; + $ThreadState = $GlobalVariable.Public.Threading.Threads.$ThreadId.State; switch ($ThreadState) { 'RUNNING' { # If we are a thread that is required to wait for jobs, the first state we reach is RUNNING after @@ -123,7 +126,7 @@ function Test-ThreadRunning() break; }; 'SHUTDOWN' { - # If our thread does close, we should also make sure all Tcp connections are closed properly + # If our thread does close, we should also make sure all Tcp connections are closed properly Close-TCPConnection; # In case we provide a Tcp-Socket, make sure it is closed properly Close-TCPSocket; diff --git a/src/Core/Threading/Private/Write-ThreadTree.ps1 b/src/Core/Threading/Private/Write-ThreadTree.ps1 index 6852bae..12eee4b 100644 --- a/src/Core/Threading/Private/Write-ThreadTree.ps1 +++ b/src/Core/Threading/Private/Write-ThreadTree.ps1 @@ -9,19 +9,19 @@ renders child nodes from the pre-built tree to produce the full hierarchical view. The node is a PSObject as returned by `Get-ThreadTree`. .PARAMETER Node -| Name | Type | Description | Default | -|------|---------------|------------------------------------------|---------| -| Node | PSObject | Tree node as returned by `Get-ThreadTree` | $null | +| Name | Type | Description | Default | +|------|----------|-------------------------------------------|---------| +| Node | PSObject | Tree node as returned by `Get-ThreadTree` | $null | .PARAMETER StringBuilder -| Name | Type | Description | Default | -|---------------|-----------------------------|---------------------------------|---------| -| StringBuilder | System.Text.StringBuilder | The builder to append lines to | $null | +| Name | Type | Description | Default | +|---------------|---------------------------|--------------------------------|---------| +| StringBuilder | System.Text.StringBuilder | The builder to append lines to | $null | .PARAMETER Level -| Name | Type | Description | Default | -|-------|---------------|-------------------------------------|---------| -| Level | System.Int32 | Nesting level for indentation | 0 | +| Name | Type | Description | Default | +|-------|--------------|-------------------------------|---------| +| Level | System.Int32 | Nesting level for indentation | 0 | .OUTPUTS None. Appends formatted lines to the provided `StringBuilder` instance. @@ -32,8 +32,11 @@ Get-ThreadTree | ForEach-Object { Write-ThreadTree -Node $_ -StringBuilder $sb } .NOTES This function does not return a value; it operates by side-effects on the -supplied builder. Child nodes are read directly from `$Node.Children` — no +supplied builder. Child nodes are read directly from `$Node.Children` -- no additional registry lookups are performed. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Write-ThreadTree() { @@ -44,7 +47,10 @@ function Write-ThreadTree() ); $indent = ' ' * ($Level * 4); - $prefix = if ($Level -eq 0) { '' } else { '└── ' }; + $prefix = ''; + if ($Level -ne 0) { + $prefix = [string]::Concat([char]0x2514, [char]0x2500, [char]0x2500, ' '); + } # Show thread parameters if any present $params = ''; diff --git a/src/Core/Threading/Public/Set-ThreadData.ps1 b/src/Core/Threading/Public/Set-ThreadData.ps1 index 5ac2b1b..8854fd3 100644 --- a/src/Core/Threading/Public/Set-ThreadData.ps1 +++ b/src/Core/Threading/Public/Set-ThreadData.ps1 @@ -9,29 +9,29 @@ registers the thread id, validates the requested command and finally invokes it with the supplied parameters. .PARAMETER PublicSpace -| Name | Type | Description | Default | -|------|------|-------------|---------| -| PublicSpace | System.Object | Shared public runtime object to attach to the thread | $null | +| Name | Type | Description | Default | +|-------------|---------------|------------------------------------------------------|---------| +| PublicSpace | System.Object | Shared public runtime object to attach to the thread | $null | .PARAMETER AccessControl -| Name | Type | Description | Default | -|------|------|-------------|---------| -| AccessControl | System.Object | Access control descriptor to attach to protected runtime area | $null | +| Name | Type | Description | Default | +|---------------|---------------|---------------------------------------------------------------|---------| +| AccessControl | System.Object | Access control descriptor to attach to protected runtime area | $null | .PARAMETER ThreadId -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ThreadId | System.String | The thread id assigned by the creator | $null | +| Name | Type | Description | Default | +|----------|---------------|---------------------------------------|---------| +| ThreadId | System.String | The thread id assigned by the creator | $null | .PARAMETER Command -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Command | System.String | The command/function name to execute in the thread | $null | +| Name | Type | Description | Default | +|---------|---------------|----------------------------------------------------|---------| +| Command | System.String | The command/function name to execute in the thread | $null | .PARAMETER Parameters -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Parameters | System.Hashtable | Named parameters to pass to `Command` | @{} | +| Name | Type | Description | Default | +|------------|------------------|---------------------------------------|---------| +| Parameters | System.Hashtable | Named parameters to pass to `Command` | @{} | .OUTPUTS Varies. The invoked `Command` determines output; error conditions return structured cmdlet returns. @@ -44,6 +44,9 @@ Called exclusively by New-Thread; do not invoke directly. Calls New-ModuleBaseEn up the runspace and sets (Get-GlobalRuntimeVariable).Protected.IsBackgroundDaemon to $true so that downstream functions know they are executing in a background context. Thread identity is tracked via Update-LoggingThreadLoggingId for log correlation. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Set-ThreadData() { @@ -56,12 +59,12 @@ function Set-ThreadData() ); # Always ensure no progress is shown in sessions - $ProgressPreference = 'SilentlyContinue'; + $ProgressPreference = 'SilentlyContinue'; # As this is a new thread instance, we will run this function to load our base environment New-ModuleBaseEnvironment; - $GlobalVariable = Get-GlobalRuntimeVariable; + $GlobalVariable = Get-GlobalRuntimeVariable; # Update the logging ID for this thread to ensure logs are properly tagged an traceable # Set it to the provided ThreadId to ensure we can track all logs from the start of the thread @@ -88,8 +91,8 @@ function Set-ThreadData() # TODO: We need to properly set colorized output setting here # Check if the command is directly available in the session or in the script module - $CommandExists = ($null -ne (Get-Command -Name $Command -ErrorAction SilentlyContinue)); - $ScriptModule = $null; + $CommandExists = ($null -ne (Get-Command -Name $Command -ErrorAction SilentlyContinue)); + $ScriptModule = $null; if (-not $CommandExists) { $ScriptModule = Get-Module -Name 'IcingaForWindows' -All | Where-Object { $_.ModuleType -eq 'Script' } | Select-Object -First 1; diff --git a/src/Core/Threading/Public/Show-IcingaThreads.ps1 b/src/Core/Threading/Public/Show-IcingaThreads.ps1 index b929ef2..2d96e7a 100644 --- a/src/Core/Threading/Public/Show-IcingaThreads.ps1 +++ b/src/Core/Threading/Public/Show-IcingaThreads.ps1 @@ -7,9 +7,9 @@ Display the Icinga thread hierarchy. thread hierarchy for the Icinga application by delegating to `Show-Threads`. .PARAMETER AsObject -| Name | Type | Description | Default | -|----------|-------------------------|----------------------------------------------------|---------| -| AsObject | System.SwitchParameter | Return the tree as PSObjects instead of rendering | $false | +| Name | Type | Description | Default | +|----------|------------------------|---------------------------------------------------|---------| +| AsObject | System.SwitchParameter | Return the tree as PSObjects instead of rendering | $false | .OUTPUTS System.Array when `-AsObject` is set. Returns the root-level thread nodes @@ -27,6 +27,9 @@ PS> $tree | Select-Object Name, State, LastSeen .NOTES This wrapper calls `Show-Threads` and exists to provide a user-facing command name for convenience. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Show-IcingaThreads() { diff --git a/src/Core/WebSocket/Private/Add-ModuleWebSocketConfig.ps1 b/src/Core/WebSocket/Private/Add-ModuleWebSocketConfig.ps1 index d5447b6..051be7d 100644 --- a/src/Core/WebSocket/Private/Add-ModuleWebSocketConfig.ps1 +++ b/src/Core/WebSocket/Private/Add-ModuleWebSocketConfig.ps1 @@ -10,32 +10,32 @@ reads the referenced type-specific config via `Read-ModuleConfigFile` and only writes a path pointer to disk. .PARAMETER Name -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Name | System.String | Logical name for the WebSocket config | | +| Name | Type | Description | Default | +|------|---------------|---------------------------------------|---------| +| Name | System.String | Logical name for the WebSocket config | | .PARAMETER Address -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Address | System.String | Remote WebSocket URI (wss://...) | | +| Name | Type | Description | Default | +|---------|---------------|----------------------------------|---------| +| Address | System.String | Remote WebSocket URI (wss://...) | | .PARAMETER Config -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Config | System.String | Path or pointer to the type-specific config | | +| Name | Type | Description | Default | +|--------|---------------|---------------------------------------------|---------| +| Config | System.String | Path or pointer to the type-specific config | | .PARAMETER Type -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Type | System.String | Logical type for the WebSocket config | | +| Name | Type | Description | Default | +|------|---------------|---------------------------------------|---------| +| Type | System.String | Logical type for the WebSocket config | | .PARAMETER Force -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Force | System.SwitchParameter | Overwrite an existing config with the same name | false | +| Name | Type | Description | Default | +|-------|------------------------|-------------------------------------------------|---------| +| Force | System.SwitchParameter | Overwrite an existing config with the same name | false | .OUTPUTS -System.Object — Returns a structured module return indicating success or the validation failure. +System.Object -- Returns a structured module return indicating success or the validation failure. .EXAMPLE PS> Add-ModuleWebSocketConfig -Name 'MyWebSocket' -Address 'wss://example.com' -Config 'configs\mywebsocket.json' -Type MyWebSocket @@ -45,6 +45,9 @@ The persisted file under the config directory contains only the path pointer to the type-specific config (not the full in-memory object). The configuration is stored in `$Global:ModuleName.Public.WebSocket.Config` and accessed via `Get-GlobalRuntimeVariable`. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Add-ModuleWebSocketConfig() { @@ -84,7 +87,7 @@ function Add-ModuleWebSocketConfig() return (Write-FunctionReturnValue -ReturnValue 'WebSocketConfigNameAlreadyExists' -Data @{ 'Name' = $SafeName; } ); } - $WebSocketConfig = [PSCustomObject]@{ + $WebSocketConfig = [PSCustomObject]@{ 'Name' = $SafeName; 'Address' = $Address; 'Type' = $Type; diff --git a/src/Core/WebSocket/Private/Add-ModuleWebSocketMessageToQueue.ps1 b/src/Core/WebSocket/Private/Add-ModuleWebSocketMessageToQueue.ps1 index 2c0ea1c..ec3884b 100644 --- a/src/Core/WebSocket/Private/Add-ModuleWebSocketMessageToQueue.ps1 +++ b/src/Core/WebSocket/Private/Add-ModuleWebSocketMessageToQueue.ps1 @@ -9,17 +9,17 @@ override) and the message payload, logs the enqueue operation and returns a structured module return on error conditions. .PARAMETER Message -| Name | Type | Description | Default | -|---------|--------------|------------------------------------|---------| -| Message | System.String| Message payload to enqueue. | | +| Name | Type | Description | Default | +|---------|---------------|-----------------------------|---------| +| Message | System.String | Message payload to enqueue. | | .PARAMETER OverrideWebSocketName -| Name | Type | Description | Default | -|-----------------------|--------------|-------------------------------------------|---------| -| OverrideWebSocketName | System.String| Optional runtime websocket name override.| | +| Name | Type | Description | Default | +|-----------------------|---------------|-------------------------------------------|---------| +| OverrideWebSocketName | System.String | Optional runtime websocket name override. | | .OUTPUTS -System.Object — Emits module structured return values on error; otherwise the +System.Object -- Emits module structured return values on error; otherwise the message is placed in the BlockingCollection and the function returns without an explicit value. @@ -33,6 +33,9 @@ consumed by `Write-ModuleWebSocket` running in a separate worker thread. The function must be called from within a worker context where `Get-GlobalRuntimeVariable` provides a valid WebSocket name via `Private.WebSocket.Name`. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Add-ModuleWebSocketMessageToQueue() { diff --git a/src/Core/WebSocket/Private/Connect-ModuleWebSocket.ps1 b/src/Core/WebSocket/Private/Connect-ModuleWebSocket.ps1 index cbd1a42..5512cc3 100644 --- a/src/Core/WebSocket/Private/Connect-ModuleWebSocket.ps1 +++ b/src/Core/WebSocket/Private/Connect-ModuleWebSocket.ps1 @@ -10,17 +10,17 @@ use by reader/writer workers. It validates parameters and returns structured module return values. .PARAMETER Name -| Name | Type | Description | Default | -|------|--------------|--------------------------------------|---------| -| Name | System.String| Logical name for the WebSocket entry.| | +| Name | Type | Description | Default | +|------|---------------|---------------------------------------|---------| +| Name | System.String | Logical name for the WebSocket entry. | | .PARAMETER Address -| Name | Type | Description | Default | -|---------|--------------|-------------------------------------------|---------| -| Address | System.String| WebSocket URI to connect to. | | +| Name | Type | Description | Default | +|---------|---------------|------------------------------|---------| +| Address | System.String | WebSocket URI to connect to. | | .OUTPUTS -System.Object — Emits `Write-FunctionReturnValue` results describing success or failure. +System.Object -- Emits `Write-FunctionReturnValue` results describing success or failure. .EXAMPLE PS> Connect-ModuleWebSocket -Name 'MyWebSocket' -Address 'wss://example.com' @@ -30,6 +30,9 @@ Any existing connection is cleaned up via `Disconnect-ModuleWebSocket` before a new one is established. The resulting `ClientWebSocket` and `CancellationTokenSource` are stored in `$Global:ModuleName.Private.WebSocket` and must be accessed via `Get-GlobalRuntimeVariable` from worker threads. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Connect-ModuleWebSocket() { @@ -73,7 +76,7 @@ function Connect-ModuleWebSocket() # cannot establish a connection to the remote server, this function is called frequently # and will then cause endless request progress states to be created $RequestProgress.Dispose(); - $RequestProgress = $null; + $RequestProgress = $null; $GlobalVariable.Private.WebSocket.Name = $Name; $GlobalVariable.Private.WebSocket.ClientWebSocket = $WebSocketClient; diff --git a/src/Core/WebSocket/Private/Disconnect-ModuleWebSocket.ps1 b/src/Core/WebSocket/Private/Disconnect-ModuleWebSocket.ps1 index f8e3368..40398fe 100644 --- a/src/Core/WebSocket/Private/Disconnect-ModuleWebSocket.ps1 +++ b/src/Core/WebSocket/Private/Disconnect-ModuleWebSocket.ps1 @@ -8,7 +8,7 @@ Close and dispose the active WebSocket connection. module results for success, not-connected, and various error conditions. .OUTPUTS -System.Object — Structured `Write-FunctionReturnValue` values describing the outcome. +System.Object -- Structured `Write-FunctionReturnValue` values describing the outcome. .EXAMPLE PS> Disconnect-ModuleWebSocket @@ -18,6 +18,9 @@ This function is safe to call even when no connection exists. It ensures cleanup of any lingering `ClientWebSocket` and `CancellationTokenSource` objects to avoid memory leaks. The function accesses runtime state via `Get-GlobalRuntimeVariable`. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Disconnect-ModuleWebSocket() { @@ -29,7 +32,7 @@ function Disconnect-ModuleWebSocket() $CancelTokenSource = $GlobalVariable.Private.WebSocket.CancellationTokenSource; $CancelTokenSource.Cancel(); - $CloseProgress = $GlobalVariable.Private.WebSocket.ClientWebSocket.CloseAsync( + $CloseProgress = $GlobalVariable.Private.WebSocket.ClientWebSocket.CloseAsync( [System.Net.WebSockets.WebSocketCloseStatus]::NormalClosure, 'Closing WebSocket connection', [System.Threading.CancellationToken]::None @@ -42,7 +45,7 @@ function Disconnect-ModuleWebSocket() # Clear our close progress to avoid memory leaks $CloseProgress.Dispose(); - $CloseProgress = $null; + $CloseProgress = $null; $GlobalVariable.Private.WebSocket.ClientWebSocket.Dispose(); $GlobalVariable.Private.WebSocket.ClientWebSocket = $null; $GlobalVariable.Private.WebSocket.CancellationTokenSource.Dispose(); @@ -60,7 +63,7 @@ function Disconnect-ModuleWebSocket() try { if ($null -ne $GlobalVariable.Private.WebSocket.ClientWebSocket) { $GlobalVariable.Private.WebSocket.ClientWebSocket.Dispose(); - $GlobalVariable.Private.WebSocket.ClientWebSocket = $null; + $GlobalVariable.Private.WebSocket.ClientWebSocket = $null; } if ($null -ne $GlobalVariable.Private.WebSocket.CancellationTokenSource) { diff --git a/src/Core/WebSocket/Private/Get-ModuleCurrentWebSocketConfig.ps1 b/src/Core/WebSocket/Private/Get-ModuleCurrentWebSocketConfig.ps1 index 1d463af..2173e16 100644 --- a/src/Core/WebSocket/Private/Get-ModuleCurrentWebSocketConfig.ps1 +++ b/src/Core/WebSocket/Private/Get-ModuleCurrentWebSocketConfig.ps1 @@ -10,7 +10,7 @@ returns the corresponding configuration object stored in function returns `$null`. .OUTPUTS -System.Management.Automation.PSCustomObject — Returns the WebSocket configuration +System.Management.Automation.PSCustomObject -- Returns the WebSocket configuration object for the current thread, or `$null` when no configuration is available. .EXAMPLE @@ -22,6 +22,9 @@ Relies on global state populated by WebSocket management functions under access to the current connection credentials and settings. The thread-local WebSocket name is read from `$Global:ModuleName.Private.WebSocket.Name` via `Get-GlobalRuntimeVariable`. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Get-ModuleCurrentWebSocketConfig() { diff --git a/src/Core/WebSocket/Private/New-ModuleWebSocketEnvironment.ps1 b/src/Core/WebSocket/Private/New-ModuleWebSocketEnvironment.ps1 index 23fbd05..e10b4e1 100644 --- a/src/Core/WebSocket/Private/New-ModuleWebSocketEnvironment.ps1 +++ b/src/Core/WebSocket/Private/New-ModuleWebSocketEnvironment.ps1 @@ -9,7 +9,7 @@ handler threads for each configured WebSocket instance. The function ensures that the public runtime structure is populated for subsequent operations. .OUTPUTS -System.Object — Returns a structured `Write-FunctionReturnValue` indicating +System.Object -- Returns a structured `Write-FunctionReturnValue` indicating success or the absence of any configurations to initialize. .EXAMPLE @@ -20,6 +20,9 @@ Uses `Read-ModuleWebSocketConfig` to load persisted configurations and `New-Thread` to spawn a `Start-ModuleWebSocketHandler` thread per instance. Each instance receives its own `ReaderWorker` and `WriterWorker` `BlockingCollection` stored in `$Global:ModuleName.Public.WebSocket`. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function New-ModuleWebSocketEnvironment() { diff --git a/src/Core/WebSocket/Private/Read-ModuleWebSocket.ps1 b/src/Core/WebSocket/Private/Read-ModuleWebSocket.ps1 index 26dc6bc..304790a 100644 --- a/src/Core/WebSocket/Private/Read-ModuleWebSocket.ps1 +++ b/src/Core/WebSocket/Private/Read-ModuleWebSocket.ps1 @@ -10,22 +10,22 @@ connection name. It updates thread processing state and handles exceptions by emitting structured module return values. .PARAMETER Name -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Name | System.String | Logical name of the WebSocket connection | | +| Name | Type | Description | Default | +|------|---------------|------------------------------------------|---------| +| Name | System.String | Logical name of the WebSocket connection | | .PARAMETER ClientWebSocket -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ClientWebSocket | System.Net.WebSockets.ClientWebSocket | The active client WebSocket instance | | +| Name | Type | Description | Default | +|-----------------|---------------------------------------|--------------------------------------|---------| +| ClientWebSocket | System.Net.WebSockets.ClientWebSocket | The active client WebSocket instance | | .PARAMETER CancellationTokenSource -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CancellationTokenSource | System.Threading.CancellationTokenSource | Token source used to cancel read operations | | +| Name | Type | Description | Default | +|-------------------------|------------------------------------------|---------------------------------------------|---------| +| CancellationTokenSource | System.Threading.CancellationTokenSource | Token source used to cancel read operations | | .OUTPUTS -System.Object — Emits structured `Write-FunctionReturnValue` values on errors; +System.Object -- Emits structured `Write-FunctionReturnValue` values on errors; otherwise received messages are placed into the named reader worker queue for downstream processing. @@ -40,6 +40,9 @@ reads from the `ClientWebSocket` in a blocking loop. Received messages are placed in the `ReaderWorker` BlockingCollection under `$Global:ModuleName.Public.WebSocket.`. The loop runs until `Test-ThreadRunning -CheckWebSocket` returns `$false`. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Read-ModuleWebSocket() { @@ -88,7 +91,7 @@ function Read-ModuleWebSocket() } while (-not $EndOfMessage -and (Test-ModuleWebSocket)); $RequestProgress.Dispose(); - $RequestProgress = $null; + $RequestProgress = $null; # Log the received message for debugging purposes [string]$ResponseMsg = $ResponseMsgBuilder.ToString(); diff --git a/src/Core/WebSocket/Private/Read-ModuleWebSocketConfig.ps1 b/src/Core/WebSocket/Private/Read-ModuleWebSocketConfig.ps1 index 8a6948f..c6d28e7 100644 --- a/src/Core/WebSocket/Private/Read-ModuleWebSocketConfig.ps1 +++ b/src/Core/WebSocket/Private/Read-ModuleWebSocketConfig.ps1 @@ -9,7 +9,7 @@ referenced type-specific configuration using `Read-ModuleConfigFile`. Parsed configurations are stored in `$Global:ModuleName.Public.WebSocket.Config`. .OUTPUTS -System.Object — Emits structured `Write-FunctionReturnValue` values indicating +System.Object -- Emits structured `Write-FunctionReturnValue` values indicating load results and returns the populated config object on success. .EXAMPLE @@ -20,6 +20,9 @@ Each WebSocket configuration file must include a `Name` property and a `Config` pointer referencing the type-specific configuration file. Parsed configurations are stored in `$Global:ModuleName.Public.WebSocket.Config` and accessed via `Get-GlobalRuntimeVariable`. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Read-ModuleWebSocketConfig() { diff --git a/src/Core/WebSocket/Private/Remove-ModuleWebSocketConfig.ps1 b/src/Core/WebSocket/Private/Remove-ModuleWebSocketConfig.ps1 index 9dab3d0..b01f387 100644 --- a/src/Core/WebSocket/Private/Remove-ModuleWebSocketConfig.ps1 +++ b/src/Core/WebSocket/Private/Remove-ModuleWebSocketConfig.ps1 @@ -8,15 +8,22 @@ named WebSocket configuration from the module config directory. It does not modify in-memory runtime structures. .PARAMETER Name -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Name | System.String | Logical name of the WebSocket config to remove | | +| Name | Type | Description | Default | +|------|---------------|------------------------------------------------|---------| +| Name | System.String | Logical name of the WebSocket config to remove | | .OUTPUTS -System.Object — Emits a structured return value when no name is provided; otherwise it removes the file and returns quietly. +System.Object -- Emits a structured return value when no name is provided; otherwise it removes the file and returns quietly. .EXAMPLE PS> Remove-ModuleWebSocketConfig -Name 'MyWebSocket' + +.NOTES +Removes the JSON configuration file from the `WebSocket` subfolder inside +`Get-ModuleConfigDirectory` via `Remove-SecureItem`. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Remove-ModuleWebSocketConfig() { diff --git a/src/Core/WebSocket/Private/Show-ModuleWebSockets.ps1 b/src/Core/WebSocket/Private/Show-ModuleWebSockets.ps1 index f2bf329..05c07c6 100644 --- a/src/Core/WebSocket/Private/Show-ModuleWebSockets.ps1 +++ b/src/Core/WebSocket/Private/Show-ModuleWebSockets.ps1 @@ -4,17 +4,23 @@ Display the currently configured WebSocket endpoints. .DESCRIPTION `Show-ModuleWebSockets` reads all WebSocket configurations from -`$Global:ModuleName.Public.WebSocket.Config` via `Get-GlobalRuntimeVariable` and +`$Global:IcingaForWindows.Public.WebSocket.Config` via `Get-GlobalRuntimeVariable` and emits them as a formatted output message using `Write-LoggingEntry` at the `Output` level. The function is intended for interactive inspection during runtime and produces no return value. .OUTPUTS -None — Writes the WebSocket configurations as a formatted output entry via +None -- Writes the WebSocket configurations as a formatted output entry via `Write-LoggingEntry`. .EXAMPLE PS> Show-ModuleWebSockets + +.NOTES +Internal implementation behind the public `Show-IcingaWebSockets` cmdlet. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Show-ModuleWebSockets() { diff --git a/src/Core/WebSocket/Private/Start-ModuleWebSocketDaemon.ps1 b/src/Core/WebSocket/Private/Start-ModuleWebSocketDaemon.ps1 index eb1aa2d..67c5cbf 100644 --- a/src/Core/WebSocket/Private/Start-ModuleWebSocketDaemon.ps1 +++ b/src/Core/WebSocket/Private/Start-ModuleWebSocketDaemon.ps1 @@ -8,7 +8,7 @@ background thread that initializes the WebSocket runtime (`New-ModuleWebSocketEn The function returns immediately after the management thread is started. .OUTPUTS -None — Starts a background thread and returns immediately without a return value. +None -- Starts a background thread and returns immediately without a return value. .EXAMPLE PS> Start-ModuleWebSocketDaemon @@ -18,6 +18,9 @@ This helper wraps `New-Thread` to ensure the WebSocket environment is initialized on a separate thread. The background thread executes `New-ModuleWebSocketEnvironment`, which loads all persisted WebSocket configurations and spawns per-instance handler threads. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Start-ModuleWebSocketDaemon() { diff --git a/src/Core/WebSocket/Private/Start-ModuleWebSocketHandler.ps1 b/src/Core/WebSocket/Private/Start-ModuleWebSocketHandler.ps1 index c0d4de9..0e243a5 100644 --- a/src/Core/WebSocket/Private/Start-ModuleWebSocketHandler.ps1 +++ b/src/Core/WebSocket/Private/Start-ModuleWebSocketHandler.ps1 @@ -10,12 +10,12 @@ spawns reader, writer and processing worker threads. The handler runs in a loop and is responsible for reconnection and keep-alive handling. .PARAMETER Name -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Name | System.String | Name of the WebSocket configuration to manage | | +| Name | Type | Description | Default | +|------|---------------|-----------------------------------------------|---------| +| Name | System.String | Name of the WebSocket configuration to manage | | .OUTPUTS -System.Object — Emits structured return codes for validation failures; otherwise +System.Object -- Emits structured return codes for validation failures; otherwise the function runs until the thread manager requests termination. .EXAMPLE @@ -27,6 +27,9 @@ The function expects a corresponding configuration entry in inside a dedicated thread spawned by `New-ModuleWebSocketEnvironment` and drives connection, reconnection, keep-alive handling, as well as spawning of reader, writer and processing worker threads. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Start-ModuleWebSocketHandler() { @@ -39,9 +42,9 @@ function Start-ModuleWebSocketHandler() return (Write-FunctionReturnValue -ReturnValue 'WebSocketHandlerNoNameProvided'); }; - $GlobalVariable = Get-GlobalRuntimeVariable; - [string]$WebSocketAddress = $GlobalVariable.Public.WebSocket.Config.$Name.Address; - [string]$WebSocketType = $GlobalVariable.Public.WebSocket.Config.$Name.Type; + $GlobalVariable = Get-GlobalRuntimeVariable; + [string]$WebSocketAddress = $GlobalVariable.Public.WebSocket.Config.$Name.Address; + [string]$WebSocketType = $GlobalVariable.Public.WebSocket.Config.$Name.Type; # Only test for the thread itself here, as WebSockets will be handled inside the loop # We need to keep this thread active, as it will handle the re-connections and keep-alive events diff --git a/src/Core/WebSocket/Private/Start-ModuleWebSocketReaderWorker.ps1 b/src/Core/WebSocket/Private/Start-ModuleWebSocketReaderWorker.ps1 index f6deab5..62aa976 100644 --- a/src/Core/WebSocket/Private/Start-ModuleWebSocketReaderWorker.ps1 +++ b/src/Core/WebSocket/Private/Start-ModuleWebSocketReaderWorker.ps1 @@ -10,26 +10,33 @@ WebSocket type (for example MyWebSocket), and augments them with manager requests shutdown. .PARAMETER Name -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Name | System.String | Logical name of the WebSocket connection to read from | | +| Name | Type | Description | Default | +|------|---------------|-------------------------------------------------------|---------| +| Name | System.String | Logical name of the WebSocket connection to read from | | .PARAMETER ClientWebSocket -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ClientWebSocket | System.Net.WebSockets.ClientWebSocket | Active client WebSocket instance | | +| Name | Type | Description | Default | +|-----------------|---------------------------------------|----------------------------------|---------| +| ClientWebSocket | System.Net.WebSockets.ClientWebSocket | Active client WebSocket instance | | .PARAMETER CancellationTokenSource -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CancellationTokenSource | System.Threading.CancellationTokenSource | Cancellation token source used to cancel operations | | +| Name | Type | Description | Default | +|-------------------------|------------------------------------------|-----------------------------------------------------|---------| +| CancellationTokenSource | System.Threading.CancellationTokenSource | Cancellation token source used to cancel operations | | .OUTPUTS -System.Object — Emits structured module return values on errors; otherwise +System.Object -- Emits structured module return values on errors; otherwise messages are prepared and enqueued for further processing. .EXAMPLE PS> Start-ModuleWebSocketReaderWorker -Name 'MyWebSocket' -ClientWebSocket $ws -CancellationTokenSource $cts + +.NOTES +Runs on a dedicated background worker runspace managed by `New-Thread` and +exits cleanly when `Test-ThreadRunning -CheckWebSocket` returns `$false`. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Start-ModuleWebSocketReaderWorker() { @@ -45,11 +52,11 @@ function Start-ModuleWebSocketReaderWorker() return; } - [string]$WebSocketName = $GlobalVariable.Private.WebSocket.Name; - [string]$WebSocketType = $GlobalVariable.Public.WebSocket.Config.$WebSocketName.Type; + [string]$WebSocketName = $GlobalVariable.Private.WebSocket.Name; + [string]$WebSocketType = $GlobalVariable.Public.WebSocket.Config.$WebSocketName.Type; # [string]$WebSocketConfig = $GlobalVariable.Public.WebSocket.Config.$WebSocketName.Config; - # If the WebSocket is not open, we don't need to proceed and close the thread + # If the WebSocket is not open, we don't need to proceed and close the thread while (Test-ThreadRunning -CheckWebSocket) { try { [string]$WebSocketMessage = $null; diff --git a/src/Core/WebSocket/Private/Test-ModuleWebSocket.ps1 b/src/Core/WebSocket/Private/Test-ModuleWebSocket.ps1 index 478f5de..d2c4390 100644 --- a/src/Core/WebSocket/Private/Test-ModuleWebSocket.ps1 +++ b/src/Core/WebSocket/Private/Test-ModuleWebSocket.ps1 @@ -4,14 +4,22 @@ Check whether the current WebSocket client is connected and open. .DESCRIPTION `Test-ModuleWebSocket` verifies that a `ClientWebSocket` exists in -`$Global:ModuleName.Private.WebSocket` and that its `State` equals `Open`. -Returns a boolean value indicating whether the WebSocket is connected. +`$Global:IcingaForWindows.Private.WebSocket` via `Get-GlobalRuntimeVariable` and +that its `State` equals `Open`. Returns a boolean value indicating whether the +WebSocket is connected. .OUTPUTS -System.Boolean — $true when the WebSocket connection is active and open; $false otherwise. +System.Boolean -- $true when the WebSocket connection is active and open; $false otherwise. .EXAMPLE PS> if (Test-ModuleWebSocket) { Write-LoggingEntry -Message 'WebSocket connected' -Level 'Output' } + +.NOTES +Reads thread-local `Private.WebSocket.ClientWebSocket` state for the active +WebSocket worker runspace. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Test-ModuleWebSocket() { diff --git a/src/Core/WebSocket/Private/Update-ModuleWebSocketThread.ps1 b/src/Core/WebSocket/Private/Update-ModuleWebSocketThread.ps1 index 3b3a2eb..6eb952e 100644 --- a/src/Core/WebSocket/Private/Update-ModuleWebSocketThread.ps1 +++ b/src/Core/WebSocket/Private/Update-ModuleWebSocketThread.ps1 @@ -5,29 +5,36 @@ Update the global WebSocket thread state for the current runtime. .DESCRIPTION `Update-ModuleWebSocketThread` stores the active WebSocket thread values (`Name`, `ClientWebSocket`, `CancellationTokenSource`) in -`$Global:ModuleName.Private.WebSocket` so other WebSocket helper threads can -access the current connection reference. +`$Global:IcingaForWindows.Private.WebSocket` via `Get-GlobalRuntimeVariable` so +other WebSocket helper functions in the same worker runspace can access the +current connection reference. .PARAMETER Name -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Name | System.String | Logical name of the WebSocket connection | | +| Name | Type | Description | Default | +|------|---------------|------------------------------------------|---------| +| Name | System.String | Logical name of the WebSocket connection | | .PARAMETER ClientWebSocket -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ClientWebSocket | System.Net.WebSockets.ClientWebSocket | Active client WebSocket instance | | +| Name | Type | Description | Default | +|-----------------|---------------------------------------|----------------------------------|---------| +| ClientWebSocket | System.Net.WebSockets.ClientWebSocket | Active client WebSocket instance | | .PARAMETER CancellationTokenSource -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CancellationTokenSource | System.Threading.CancellationTokenSource | Cancellation token source used to cancel reads/writes | | +| Name | Type | Description | Default | +|-------------------------|------------------------------------------|-------------------------------------------------------|---------| +| CancellationTokenSource | System.Threading.CancellationTokenSource | Cancellation token source used to cancel reads/writes | | .OUTPUTS -System.Object — Returns structured `Write-FunctionReturnValue` status codes indicating success or validation failures. +System.Object -- Returns structured `Write-FunctionReturnValue` status codes indicating success or validation failures. .EXAMPLE PS> Update-ModuleWebSocketThread -Name 'MyWebSocket' -ClientWebSocket $ws -CancellationTokenSource $cts + +.NOTES +Populates thread-local `Private.WebSocket` state before reader or writer loops start. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Update-ModuleWebSocketThread() { diff --git a/src/Core/WebSocket/Private/Write-ModuleWebSocket.ps1 b/src/Core/WebSocket/Private/Write-ModuleWebSocket.ps1 index 085c369..5aa4588 100644 --- a/src/Core/WebSocket/Private/Write-ModuleWebSocket.ps1 +++ b/src/Core/WebSocket/Private/Write-ModuleWebSocket.ps1 @@ -9,25 +9,32 @@ active `ClientWebSocket`. The function retries queueing when the socket is not connected and emits structured return values on errors. .PARAMETER Name -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Name | System.String | Logical name of the WebSocket connection to write to | | +| Name | Type | Description | Default | +|------|---------------|------------------------------------------------------|---------| +| Name | System.String | Logical name of the WebSocket connection to write to | | .PARAMETER ClientWebSocket -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ClientWebSocket | System.Net.WebSockets.ClientWebSocket | Active client WebSocket instance | | +| Name | Type | Description | Default | +|-----------------|---------------------------------------|----------------------------------|---------| +| ClientWebSocket | System.Net.WebSockets.ClientWebSocket | Active client WebSocket instance | | .PARAMETER CancellationTokenSource -| Name | Type | Description | Default | -|------|------|-------------|---------| -| CancellationTokenSource | System.Threading.CancellationTokenSource | Token source used to cancel send operations | | +| Name | Type | Description | Default | +|-------------------------|------------------------------------------|---------------------------------------------|---------| +| CancellationTokenSource | System.Threading.CancellationTokenSource | Token source used to cancel send operations | | .OUTPUTS -System.Object — Emits structured `Write-FunctionReturnValue` values on send errors. +System.Object -- Emits structured `Write-FunctionReturnValue` values on send errors. .EXAMPLE PS> Write-ModuleWebSocket -Name 'MyWebSocket' -ClientWebSocket $ws -CancellationTokenSource $cts + +.NOTES +Runs on a dedicated background writer runspace and disposes `SendAsync` task +handles after each frame to prevent memory leaks. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Write-ModuleWebSocket() { @@ -45,7 +52,7 @@ function Write-ModuleWebSocket() [string]$WebSocketName = $GlobalVariable.Private.WebSocket.Name; - # If the WebSocket is not open, we don't need to proceed and close the thread + # If the WebSocket is not open, we don't need to proceed and close the thread while (Test-ThreadRunning -CheckWebSocket) { try { [string]$WebSocketMessage = $null; @@ -75,11 +82,11 @@ function Write-ModuleWebSocket() continue; } - $Bytes = [System.Text.Encoding]::UTF8.GetBytes($WebSocketMessage); + $Bytes = [System.Text.Encoding]::UTF8.GetBytes($WebSocketMessage); [ArraySegment[byte]]$SocketMsg = $Bytes; - $RequestProgress = $GlobalVariable.Private.WebSocket.ClientWebSocket.SendAsync( + $RequestProgress = $GlobalVariable.Private.WebSocket.ClientWebSocket.SendAsync( $SocketMsg, [System.Net.WebSockets.WebSocketMessageType]::Text, $TRUE, diff --git a/src/Core/WebSocket/Public/Add-IcingaWebSocketConfig.ps1 b/src/Core/WebSocket/Public/Add-IcingaWebSocketConfig.ps1 index 17cfb39..9d4dfbd 100644 --- a/src/Core/WebSocket/Public/Add-IcingaWebSocketConfig.ps1 +++ b/src/Core/WebSocket/Public/Add-IcingaWebSocketConfig.ps1 @@ -11,19 +11,19 @@ type-specific config via `Read-ModuleConfigFile` and only writes a path pointer to disk. .PARAMETER Name -| Name | Type | Description | Default | -|------|---------------|----------------------------------------|---------| -| Name | System.String | Logical name for the WebSocket config | | +| Name | Type | Description | Default | +|------|---------------|---------------------------------------|---------| +| Name | System.String | Logical name for the WebSocket config | | .PARAMETER Address -| Name | Type | Description | Default | -|---------|---------------|------------------------------------|---------| -| Address | System.String | Remote WebSocket URI (wss://...) | | +| Name | Type | Description | Default | +|---------|---------------|----------------------------------|---------| +| Address | System.String | Remote WebSocket URI (wss://...) | | .PARAMETER Config -| Name | Type | Description | Default | -|--------|---------------|----------------------------------------------------|---------| -| Config | System.String | Path or pointer to the type-specific config file | | +| Name | Type | Description | Default | +|--------|---------------|--------------------------------------------------|---------| +| Config | System.String | Path or pointer to the type-specific config file | | .PARAMETER Type | Name | Type | Description | Default | @@ -31,12 +31,12 @@ to disk. | Type | System.String | Logical type for the WebSocket config | | .PARAMETER Force -| Name | Type | Description | Default | -|-------|-------------------------|------------------------------------------------|---------| -| Force | System.Management.Automation.SwitchParameter | Overwrite an existing config with the same name | $false | +| Name | Type | Description | Default | +|-------|----------------------------------------------|-------------------------------------------------|---------| +| Force | System.Management.Automation.SwitchParameter | Overwrite an existing config with the same name | $false | .OUTPUTS -System.Object — Returns a structured Icinga return indicating success or the +System.Object -- Returns a structured Icinga return indicating success or the validation failure. .EXAMPLE @@ -47,6 +47,9 @@ The persisted file under the Icinga config directory contains only the path pointer to the type-specific config, not the full in-memory object. Requires read access to the type-specific configuration file referenced by `Config`. Configuration is stored in `$Global:Icinga.Public.WebSocket.Config`. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Add-IcingaWebSocketConfig() { diff --git a/src/Core/WebSocket/Public/Remove-IcingaWebSocketConfig.ps1 b/src/Core/WebSocket/Public/Remove-IcingaWebSocketConfig.ps1 index 6d936f3..900bc77 100644 --- a/src/Core/WebSocket/Public/Remove-IcingaWebSocketConfig.ps1 +++ b/src/Core/WebSocket/Public/Remove-IcingaWebSocketConfig.ps1 @@ -15,7 +15,7 @@ must be restarted separately to reflect the removal. | Name | System.String | Logical name of the WebSocket config to remove | | .OUTPUTS -System.Object — Emits a structured return value when no name is provided; +System.Object -- Emits a structured return value when no name is provided; otherwise removes the file and returns quietly. .EXAMPLE @@ -25,6 +25,9 @@ PS> Remove-IcingaWebSocketConfig -Name 'MyWebSocket' Only the persisted pointer file on disk is removed. The in-memory configuration in `$Global:Icinga.Public.WebSocket.Config` is not modified. No special permissions beyond write access to the Icinga config directory are required. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Remove-IcingaWebSocketConfig() { diff --git a/src/Core/WebSocket/Public/Show-IcingaWebSockets.ps1 b/src/Core/WebSocket/Public/Show-IcingaWebSockets.ps1 index e0b36f9..d650009 100644 --- a/src/Core/WebSocket/Public/Show-IcingaWebSockets.ps1 +++ b/src/Core/WebSocket/Public/Show-IcingaWebSockets.ps1 @@ -10,7 +10,7 @@ and emits them as a formatted output message via `Write-LoggingEntry` at the runtime and produces no return value. .OUTPUTS -None — Writes the WebSocket configurations as a formatted output entry via +None -- Writes the WebSocket configurations as a formatted output entry via `Write-LoggingEntry`. .EXAMPLE @@ -20,6 +20,9 @@ PS> Show-IcingaWebSockets No parameters are required. The output is written through `Write-LoggingEntry` and is not returned to the pipeline. Requires the WebSocket environment to have been initialized via `Start-ModuleWebSocketDaemon` for meaningful output. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Show-IcingaWebSockets() { diff --git a/src/IcingaProtocol/Private/Add-IcingaProtocolClient.ps1 b/src/IcingaProtocol/Private/Add-IcingaProtocolClient.ps1 index 787de63..d6e2e9a 100644 --- a/src/IcingaProtocol/Private/Add-IcingaProtocolClient.ps1 +++ b/src/IcingaProtocol/Private/Add-IcingaProtocolClient.ps1 @@ -18,9 +18,9 @@ to emit a standardized operation result object indicating success or failure. | Address | System.String | String key (typically an IP address) used to index the TcpClient in the connections table. | $null | .PARAMETER TcpClient -| Name | Type | Description | Default | -|-----------|----------------------------------|---------------------------------------------------------|---------| -| TcpClient | System.Net.Sockets.TcpClient | Active TcpClient instance to store in the connections table. | $null | +| Name | Type | Description | Default | +|-----------|------------------------------|--------------------------------------------------------------|---------| +| TcpClient | System.Net.Sockets.TcpClient | Active TcpClient instance to store in the connections table. | $null | .EXAMPLE PS> $tcp = New-Object System.Net.Sockets.TcpClient @@ -33,13 +33,16 @@ PS> Add-IcingaProtocolClient -Address '10.0.0.5' -TcpClient $newTcp Replaces an existing connection entry for the same address with a new TcpClient. .OUTPUTS -PSCustomObject — Return value produced by Write-FunctionReturnValue. +PSCustomObject -- Return value produced by Write-FunctionReturnValue. Possible tokens: IcingaClientAddingFailed (validation failed) or IcingaClientAdded (success). .NOTES This function modifies $Global:IcingaForWindows.Public.IcingaProtocol.Connections directly. The caller is responsible for the lifetime and disposal of the TcpClient objects. No additional connectivity checks are performed; the function only stores the provided instance. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Add-IcingaProtocolClient() { diff --git a/src/IcingaProtocol/Private/Add-IcingaRPCMessageToWorker.ps1 b/src/IcingaProtocol/Private/Add-IcingaRPCMessageToWorker.ps1 index 588f8da..e50b80f 100644 --- a/src/IcingaProtocol/Private/Add-IcingaRPCMessageToWorker.ps1 +++ b/src/IcingaProtocol/Private/Add-IcingaRPCMessageToWorker.ps1 @@ -12,9 +12,9 @@ selection. Null, empty or malformed JSON payloads emit structured return values and are dropped without throwing. .PARAMETER Message -| Name | Type | Description | Default | -|---------|---------------|------------------------------------------------------------------------------|---------| -| Message | System.String | Serialized JSON-RPC message payload to enqueue. Ignored when null or empty. | $null | +| Name | Type | Description | Default | +|---------|---------------|-----------------------------------------------------------------------------|---------| +| Message | System.String | Serialized JSON-RPC message payload to enqueue. Ignored when null or empty. | $null | .OUTPUTS None -- Enqueues the parsed message object into WorkerQueue and returns nothing. @@ -27,6 +27,9 @@ Parses the JSON-RPC message and dispatches it to the next protocol worker queue. .NOTES Caller must ensure WorkerCount and WorkerQueue are initialized in Public.IcingaProtocol before invoking this helper. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Add-IcingaRPCMessageToWorker() { diff --git a/src/IcingaProtocol/Private/Add-IcingaRPCMessageToWriterQueue.ps1 b/src/IcingaProtocol/Private/Add-IcingaRPCMessageToWriterQueue.ps1 index fb33cb6..c09bd20 100644 --- a/src/IcingaProtocol/Private/Add-IcingaRPCMessageToWriterQueue.ps1 +++ b/src/IcingaProtocol/Private/Add-IcingaRPCMessageToWriterQueue.ps1 @@ -14,12 +14,12 @@ current TCP client and writer queue through Get-GlobalRuntimeVariable so that it works correctly inside worker thread runspaces. .PARAMETER MsgObj -| Name | Type | Description | Default | -|--------|---------------|-----------------------------------------------------------------------|---------| +| Name | Type | Description | Default | +|--------|---------------|-------------------------------------------------------------------------|---------| | MsgObj | System.Object | Message object as returned by New-IcingaRPCMessage (@{message;length}). | $null | .OUTPUTS -None — The function enqueues the message or sends it directly; no pipeline output is produced. +None -- The function enqueues the message or sends it directly; no pipeline output is produced. .EXAMPLE PS> Add-IcingaRPCMessageToWriterQueue -MsgObj (New-IcingaRPCMessage -Method 'icinga::Hello') @@ -28,6 +28,9 @@ PS> Add-IcingaRPCMessageToWriterQueue -MsgObj (New-IcingaRPCMessage -Method 'ici This function uses Get-GlobalRuntimeVariable to access global state, making it safe to call from within thread runspaces. The writer queue is keyed by the string representation of the remote endpoint IP address. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Add-IcingaRPCMessageToWriterQueue() { diff --git a/src/IcingaProtocol/Private/ConvertFrom-IcingaProtocolMacros.ps1 b/src/IcingaProtocol/Private/ConvertFrom-IcingaProtocolMacros.ps1 index 5ab6645..be47376 100644 --- a/src/IcingaProtocol/Private/ConvertFrom-IcingaProtocolMacros.ps1 +++ b/src/IcingaProtocol/Private/ConvertFrom-IcingaProtocolMacros.ps1 @@ -24,14 +24,14 @@ Two Icinga 2 delivery modes are supported seamlessly across Windows PowerShell when unprefixed custom variables are present). .PARAMETER ResolvedCommand -| Name | Type | Description | Default | -|-----------------|------------------------------|--------------------------------------------------------------|---------| -| ResolvedCommand | System.Collections.Hashtable | Command descriptor returned by Resolve-IcingaProtocolCommand.| @{} | +| Name | Type | Description | Default | +|-----------------|------------------------------|---------------------------------------------------------------|---------| +| ResolvedCommand | System.Collections.Hashtable | Command descriptor returned by Resolve-IcingaProtocolCommand. | @{} | .PARAMETER Macros -| Name | Type | Description | Default | -|--------|---------------|-----------------------------------------------------------------------|---------| -| Macros | System.Object | Deserialized macros dictionary or object from event::ExecuteCommand. | $null | +| Name | Type | Description | Default | +|--------|---------------|----------------------------------------------------------------------|---------| +| Macros | System.Object | Deserialized macros dictionary or object from event::ExecuteCommand. | $null | .OUTPUTS System.Collections.Hashtable -- Parsed argument bundle containing Status, @@ -48,6 +48,9 @@ Maps the Path macro to Invoke-IcingaCheckDirectory's -Path parameter. Callers must dispose every entry in AllocatedSecureStrings once plugin execution completes. On validation errors, any SecureString allocated earlier in the same call is disposed before returning. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function ConvertFrom-IcingaProtocolMacros() { diff --git a/src/IcingaProtocol/Private/Expand-IcingaProtocolMacroValue.ps1 b/src/IcingaProtocol/Private/Expand-IcingaProtocolMacroValue.ps1 index d04aff3..70cb56c 100644 --- a/src/IcingaProtocol/Private/Expand-IcingaProtocolMacroValue.ps1 +++ b/src/IcingaProtocol/Private/Expand-IcingaProtocolMacroValue.ps1 @@ -17,19 +17,19 @@ table: $false so optional Icinga arguments are cleanly skipped. .PARAMETER Expression -| Name | Type | Description | Default | -|------------|---------------|-----------------------------------------------------------|---------| -| Expression | System.Object | Raw 'value' or 'set_if' expression from ifw_api_arguments.| $null | +| Name | Type | Description | Default | +|------------|---------------|------------------------------------------------------------|---------| +| Expression | System.Object | Raw 'value' or 'set_if' expression from ifw_api_arguments. | $null | .PARAMETER MacroMap -| Name | Type | Description | Default | -|----------|---------------|----------------------------------------------------------|---------| -| MacroMap | System.Object | Case-sensitive OrderedDictionary of macro key/values. | $null | +| Name | Type | Description | Default | +|----------|---------------|-------------------------------------------------------|---------| +| MacroMap | System.Object | Case-sensitive OrderedDictionary of macro key/values. | $null | .PARAMETER MacroIgnoreCase -| Name | Type | Description | Default | -|-----------------|------------------------------|---------------------------------------------------|---------| -| MacroIgnoreCase | System.Collections.Hashtable | Case-insensitive fallback hashtable for macros. | @{} | +| Name | Type | Description | Default | +|-----------------|------------------------------|-------------------------------------------------|---------| +| MacroIgnoreCase | System.Collections.Hashtable | Case-insensitive fallback hashtable for macros. | @{} | .OUTPUTS System.Collections.Hashtable -- Hashtable with keys IsSet (System.Boolean) and @@ -42,6 +42,9 @@ Interpolates the '$address$' and '$port$' tokens in a single pass. .NOTES Pure macro evaluator with no side effects or global state dependencies. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Expand-IcingaProtocolMacroValue() { diff --git a/src/IcingaProtocol/Private/Invoke-IcingaProtocolBinaryProcess.ps1 b/src/IcingaProtocol/Private/Invoke-IcingaProtocolBinaryProcess.ps1 index 5a18d7e..e43efec 100644 --- a/src/IcingaProtocol/Private/Invoke-IcingaProtocolBinaryProcess.ps1 +++ b/src/IcingaProtocol/Private/Invoke-IcingaProtocolBinaryProcess.ps1 @@ -17,19 +17,19 @@ UseShellExecute = $false: 5. Splits output and performance data via Split-IcingaBinaryPluginOutput. .PARAMETER BinaryPath -| Name | Type | Description | Default | -|------------|---------------|-----------------------------------------------------------|---------| -| BinaryPath | System.String | Full canonical path to the approved binary executable. | '' | +| Name | Type | Description | Default | +|------------|---------------|--------------------------------------------------------|---------| +| BinaryPath | System.String | Full canonical path to the approved binary executable. | '' | .PARAMETER CommandName -| Name | Type | Description | Default | -|-------------|---------------|-----------------------------------------------------------|---------| -| CommandName | System.String | Display file name of the binary for status messages. | '' | +| Name | Type | Description | Default | +|-------------|---------------|------------------------------------------------------|---------| +| CommandName | System.String | Display file name of the binary for status messages. | '' | .PARAMETER BinaryArguments -| Name | Type | Description | Default | -|-----------------|-----------------|-------------------------------------------------------|---------| -| BinaryArguments | System.String[] | Ordered CLI argument tokens to pass to the process. | @() | +| Name | Type | Description | Default | +|-----------------|-----------------|-----------------------------------------------------|---------| +| BinaryArguments | System.String[] | Ordered CLI argument tokens to pass to the process. | @() | .PARAMETER TimeoutMs | Name | Type | Description | Default | @@ -52,6 +52,9 @@ Executes check_load.exe with a 60s timeout and splits its Nagios output. .NOTES Always disposes the root Process handle in finally. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Invoke-IcingaProtocolBinaryProcess() { diff --git a/src/IcingaProtocol/Private/Invoke-IcingaProtocolCheckCommand.ps1 b/src/IcingaProtocol/Private/Invoke-IcingaProtocolCheckCommand.ps1 index 459ccc5..975e5d6 100644 --- a/src/IcingaProtocol/Private/Invoke-IcingaProtocolCheckCommand.ps1 +++ b/src/IcingaProtocol/Private/Invoke-IcingaProtocolCheckCommand.ps1 @@ -22,9 +22,9 @@ Returns a plain hashtable of primitive values and arrays so no PowerShell class instance ever crosses runspace boundaries. .PARAMETER Params -| Name | Type | Description | Default | -|--------|---------------|-----------------------------------------------------------------------|---------| -| Params | System.Object | Deserialized params dictionary or object from event::ExecuteCommand. | $null | +| Name | Type | Description | Default | +|--------|---------------|----------------------------------------------------------------------|---------| +| Params | System.Object | Deserialized params dictionary or object from event::ExecuteCommand. | $null | .OUTPUTS System.Collections.Hashtable -- Hashtable containing ExitCode (Int32 0..3), @@ -39,6 +39,9 @@ and rendered command line. .NOTES Runs inside protocol worker threads; accesses runtime state exclusively via Get-GlobalRuntimeVariable. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Invoke-IcingaProtocolCheckCommand() { diff --git a/src/IcingaProtocol/Private/Invoke-IcingaProtocolExternalScript.ps1 b/src/IcingaProtocol/Private/Invoke-IcingaProtocolExternalScript.ps1 index c5a9b19..2a81a7b 100644 --- a/src/IcingaProtocol/Private/Invoke-IcingaProtocolExternalScript.ps1 +++ b/src/IcingaProtocol/Private/Invoke-IcingaProtocolExternalScript.ps1 @@ -12,24 +12,24 @@ CommandLine via Format-ModuleCommandLineArguments, and executes the script in-process via Invoke-ModulePowerShellCommand -UseLastExitCode. .PARAMETER ScriptPath -| Name | Type | Description | Default | -|------------|---------------|---------------------------------------------------------|---------| -| ScriptPath | System.String | Full canonical path to the approved .ps1 check script. | '' | +| Name | Type | Description | Default | +|------------|---------------|--------------------------------------------------------|---------| +| ScriptPath | System.String | Full canonical path to the approved .ps1 check script. | '' | .PARAMETER CommandName -| Name | Type | Description | Default | -|-------------|---------------|---------------------------------------------------------|---------| -| CommandName | System.String | Display file name of the script for error messages. | '' | +| Name | Type | Description | Default | +|-------------|---------------|-----------------------------------------------------|---------| +| CommandName | System.String | Display file name of the script for error messages. | '' | .PARAMETER BinaryArguments -| Name | Type | Description | Default | -|-----------------|-----------------|-----------------------------------------------------|---------| -| BinaryArguments | System.String[] | Ordered CLI tokens produced by macro resolution. | @() | +| Name | Type | Description | Default | +|-----------------|-----------------|--------------------------------------------------|---------| +| BinaryArguments | System.String[] | Ordered CLI tokens produced by macro resolution. | @() | .PARAMETER DefaultCommandLine -| Name | Type | Description | Default | -|--------------------|---------------|---------------------------------------------------------|---------| -| DefaultCommandLine | System.String | Pre-rendered command line when no secret masking occurs.| '' | +| Name | Type | Description | Default | +|--------------------|---------------|----------------------------------------------------------|---------| +| DefaultCommandLine | System.String | Pre-rendered command line when no secret masking occurs. | '' | .OUTPUTS System.Collections.Hashtable -- Hashtable containing ExitCode, Output, @@ -43,6 +43,9 @@ Binds the parameters of check_custom.ps1 and executes it in-process. .NOTES Delegates execution and deterministic SecureString disposal to Invoke-ModulePowerShellCommand. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Invoke-IcingaProtocolExternalScript() { diff --git a/src/IcingaProtocol/Private/New-IcingaAgentEnvironment.ps1 b/src/IcingaProtocol/Private/New-IcingaAgentEnvironment.ps1 index cf08f60..2fcd391 100644 --- a/src/IcingaProtocol/Private/New-IcingaAgentEnvironment.ps1 +++ b/src/IcingaProtocol/Private/New-IcingaAgentEnvironment.ps1 @@ -19,7 +19,7 @@ starts the listener and connector threads. This function must be called once dur process initialization and must not be called again while threads are running. .OUTPUTS -None — Performs initialization and starts background threads. Returns early via +None -- Performs initialization and starts background threads. Returns early via Write-FunctionReturnValue when the certificate file is missing. .EXAMPLE @@ -34,11 +34,14 @@ The PFX is loaded without an explicit password; ensure it is not password-protec Global state modified: $Global:IcingaForWindows.Public.IcingaProtocol.Config, Certificate, Connections and WorkerQueue. Config.WorkerCount must be a positive integer before this function is called. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function New-IcingaAgentEnvironment() { # Read connection configuration - $ConnectionConfig = Read-IcingaProtocolConnection; + $ConnectionConfig = Read-IcingaProtocolConnection; # If we do not provide any connection configuration, it means the master/satellite will connect to us instead if ($null -ne $ConnectionConfig) { diff --git a/src/IcingaProtocol/Private/New-IcingaRPCMessage.ps1 b/src/IcingaProtocol/Private/New-IcingaRPCMessage.ps1 index 023656d..5e67f96 100644 --- a/src/IcingaProtocol/Private/New-IcingaRPCMessage.ps1 +++ b/src/IcingaProtocol/Private/New-IcingaRPCMessage.ps1 @@ -10,17 +10,17 @@ hashtable with the keys message (byte array) and length (integer) ready to be passed to Send-TCPMessage or Add-IcingaRPCMessageToWriterQueue. .PARAMETER Method -| Name | Type | Description | Default | -|--------|---------------|-----------------------------------------------------|---------| -| Method | System.String | JSON-RPC method name (for example icinga::Hello). | | +| Name | Type | Description | Default | +|--------|---------------|---------------------------------------------------|---------| +| Method | System.String | JSON-RPC method name (for example icinga::Hello). | | .PARAMETER Parameters -| Name | Type | Description | Default | -|------------|-------------------------------|------------------------------------------------|---------| -| Parameters | System.Collections.Hashtable | Parameters to include in the RPC params field. | @{} | +| Name | Type | Description | Default | +|------------|------------------------------|------------------------------------------------|---------| +| Parameters | System.Collections.Hashtable | Parameters to include in the RPC params field. | @{} | .OUTPUTS -System.Collections.Hashtable — Hashtable with keys message (System.Byte[]) and length (System.Int32). +System.Collections.Hashtable -- Hashtable with keys message (System.Byte[]) and length (System.Int32). .EXAMPLE PS> New-IcingaRPCMessage -Method 'icinga::Hello' @@ -30,6 +30,9 @@ Returns a length-prefixed encoded message hashtable for the Hello handshake. .NOTES The method call is logged at Debug level via Write-LoggingEntry before the byte encoding step. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function New-IcingaRPCMessage() { @@ -44,9 +47,9 @@ function New-IcingaRPCMessage() 'params' = $Parameters; }; - $JsonMessage = (ConvertTo-ModuleJson -InputObject $MessageHash); - [int]$ByteCount = [System.Text.Encoding]::UTF8.GetByteCount($JsonMessage); - $FormattedMessage = [string]::Format('{0}:{1},', $ByteCount, $JsonMessage); + $JsonMessage = (ConvertTo-ModuleJson -InputObject $MessageHash); + [int]$ByteCount = [System.Text.Encoding]::UTF8.GetByteCount($JsonMessage); + $FormattedMessage = [string]::Format('{0}:{1},', $ByteCount, $JsonMessage); Write-LoggingEntry -Message 'Creating Icinga RPC Message' -Level 'Debug' -Data @{ 'JsonMessage' = $FormattedMessage; }; diff --git a/src/IcingaProtocol/Private/Read-IcingaProtocolConnections.ps1 b/src/IcingaProtocol/Private/Read-IcingaProtocolConnections.ps1 index 6e72a52..d9f0228 100644 --- a/src/IcingaProtocol/Private/Read-IcingaProtocolConnections.ps1 +++ b/src/IcingaProtocol/Private/Read-IcingaProtocolConnections.ps1 @@ -10,7 +10,7 @@ file is not found, the function returns a standardized result object via Write-FunctionReturnValue with return value IcingaClientConfigNotFound. .OUTPUTS -PSCustomObject — Parsed JSON connection configuration. +PSCustomObject -- Parsed JSON connection configuration. Returns a Write-FunctionReturnValue result object when the file is missing. .EXAMPLE @@ -19,6 +19,9 @@ PS> $cfg = Read-IcingaProtocolConnection .NOTES Placeholder substitution uses [System.Net.Dns]::GetHostEntry and GetHostName. The configuration file is read through Read-SecureFile to enforce path approval. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Read-IcingaProtocolConnection() { diff --git a/src/IcingaProtocol/Private/Read-IcingaRPCMessage.ps1 b/src/IcingaProtocol/Private/Read-IcingaRPCMessage.ps1 index c3a9c40..6c96fc4 100644 --- a/src/IcingaProtocol/Private/Read-IcingaRPCMessage.ps1 +++ b/src/IcingaProtocol/Private/Read-IcingaRPCMessage.ps1 @@ -12,12 +12,12 @@ until the buffer is empty, the size prefix is invalid or insufficient data remai for a complete frame. .PARAMETER Buffer -| Name | Type | Description | Default | -|--------|---------------------------|-----------------------------------------------------------------------------|---------| +| Name | Type | Description | Default | +|--------|---------------------------|-------------------------------------------------------------------------------------|---------| | Buffer | System.Text.StringBuilder | Accumulated StringBuilder buffer containing one or more length-prefixed RPC frames. | $null | .OUTPUTS -None — The buffer is modified in place. +None -- The buffer is modified in place. .EXAMPLE PS> Read-IcingaRPCMessage -Buffer $buffer @@ -26,6 +26,9 @@ PS> Read-IcingaRPCMessage -Buffer $buffer Each call may process multiple complete frames in a single pass. Partial frames at the end of the buffer are preserved for the next read cycle. Complete messages are dispatched via Add-IcingaRPCMessageToWorker. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Read-IcingaRPCMessage() { @@ -73,7 +76,7 @@ function Read-IcingaRPCMessage() # Parse the RPC message size prefix without array allocations or Split() [string]$SizeString = $Buffer.ToString(0, $ColonIndex); - [int]$RPCSize = 0; + [int]$RPCSize = 0; if (-not [int]::TryParse($SizeString, [ref]$RPCSize) -or $RPCSize -le 0) { break; } diff --git a/src/IcingaProtocol/Private/Resolve-IcingaProtocolCommand.ps1 b/src/IcingaProtocol/Private/Resolve-IcingaProtocolCommand.ps1 index 6508b2a..0244d93 100644 --- a/src/IcingaProtocol/Private/Resolve-IcingaProtocolCommand.ps1 +++ b/src/IcingaProtocol/Private/Resolve-IcingaProtocolCommand.ps1 @@ -22,14 +22,14 @@ extension, shorthand PowerShell check names such as 'cpu' or 'IcingaCheckCPU' are expanded to 'Invoke-IcingaCheck*' and resolved as PowerShell check commands. .PARAMETER Macros -| Name | Type | Description | Default | -|--------|---------------|-----------------------------------------------------------------------|---------| -| Macros | System.Object | Deserialized macros dictionary or object from event::ExecuteCommand. | $null | +| Name | Type | Description | Default | +|--------|---------------|----------------------------------------------------------------------|---------| +| Macros | System.Object | Deserialized macros dictionary or object from event::ExecuteCommand. | $null | .PARAMETER CheckCommand -| Name | Type | Description | Default | -|--------------|---------------|-------------------------------------------------------------------------------|---------| -| CheckCommand | System.String | Optional Icinga CheckCommand object name (params.command) for error context. | '' | +| Name | Type | Description | Default | +|--------------|---------------|------------------------------------------------------------------------------|---------| +| CheckCommand | System.String | Optional Icinga CheckCommand object name (params.command) for error context. | '' | .OUTPUTS System.Collections.Hashtable -- Resolution descriptor containing Status, Kind, @@ -49,6 +49,9 @@ in Get-ModuleBinaryDirectory. .NOTES Never searches $env:PATH for binaries or scripts. External executables must reside inside Get-ModuleBinaryDirectory. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Resolve-IcingaProtocolCommand() { diff --git a/src/IcingaProtocol/Private/Send-IcingaProtocolCertificateRequest.ps1 b/src/IcingaProtocol/Private/Send-IcingaProtocolCertificateRequest.ps1 index 21ccc0f..31f2e5f 100644 --- a/src/IcingaProtocol/Private/Send-IcingaProtocolCertificateRequest.ps1 +++ b/src/IcingaProtocol/Private/Send-IcingaProtocolCertificateRequest.ps1 @@ -9,12 +9,12 @@ setup and certificate signing request (CSR) workflow. If a ticket is provided it is included in the RPC parameters for auto-signing. .PARAMETER Ticket -| Name | Type | Description | Default | -|--------|---------------|--------------------------------------------|---------| -| Ticket | System.String | The ticket to use for auto-signing. | $null | +| Name | Type | Description | Default | +|--------|---------------|-------------------------------------|---------| +| Ticket | System.String | The ticket to use for auto-signing. | $null | .OUTPUTS -None — Does not return any value. +None -- Does not return any value. .EXAMPLE PS> Send-IcingaProtocolCertificateRequest -Ticket '1234567890abcdef' @@ -23,6 +23,9 @@ Sends a certificate request to the connected Icinga endpoint. .NOTES Requires an active TCP connection to the Icinga endpoint. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Send-IcingaProtocolCertificateRequest() { diff --git a/src/IcingaProtocol/Private/Send-IcingaProtocolCheckResult.ps1 b/src/IcingaProtocol/Private/Send-IcingaProtocolCheckResult.ps1 index f7b46c0..f80e5d0 100644 --- a/src/IcingaProtocol/Private/Send-IcingaProtocolCheckResult.ps1 +++ b/src/IcingaProtocol/Private/Send-IcingaProtocolCheckResult.ps1 @@ -10,12 +10,12 @@ The function validates the provided hashtable and logs an error if it is empty or null. .PARAMETER CheckResult -| Name | Type | Description | Default | -|-------------|-------------------------------|---------------------------------------------------------|---------| -| CheckResult | System.Collections.Hashtable | Check result fields expected by Icinga (host, service, cr). | @{} | +| Name | Type | Description | Default | +|-------------|------------------------------|-------------------------------------------------------------|---------| +| CheckResult | System.Collections.Hashtable | Check result fields expected by Icinga (host, service, cr). | @{} | .OUTPUTS -None — Logs errors via Write-LoggingEntry and enqueues the message through the writer queue. +None -- Logs errors via Write-LoggingEntry and enqueues the message through the writer queue. .EXAMPLE PS> Send-IcingaProtocolCheckResult -CheckResult @{ host = 'myhost'; service = 'ping'; cr = @{ exit_status = 0; output = 'OK' } } @@ -23,6 +23,9 @@ PS> Send-IcingaProtocolCheckResult -CheckResult @{ host = 'myhost'; service = 'p .NOTES Requires New-IcingaRPCMessage and Add-IcingaRPCMessageToWriterQueue to be available. The check result is sent asynchronously via the per-endpoint writer queue. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Send-IcingaProtocolCheckResult() { diff --git a/src/IcingaProtocol/Private/Send-IcingaProtocolHeartbeat.ps1 b/src/IcingaProtocol/Private/Send-IcingaProtocolHeartbeat.ps1 index eb9e318..7bba4a8 100644 --- a/src/IcingaProtocol/Private/Send-IcingaProtocolHeartbeat.ps1 +++ b/src/IcingaProtocol/Private/Send-IcingaProtocolHeartbeat.ps1 @@ -10,7 +10,7 @@ and a timeout parameter of 120 seconds, sends it via the module's TCP send routi updates the global heartbeat timestamp. .OUTPUTS -None — Performs side effects: sends a TCP heartbeat message, writes log entries and updates the global heartbeat timestamp. +None -- Performs side effects: sends a TCP heartbeat message, writes log entries and updates the global heartbeat timestamp. .EXAMPLE PS> Send-IcingaProtocolHeartbeat @@ -22,6 +22,9 @@ Relies on $Global:IcingaForWindows.Private.TCP.HeartbeatTimer and HeartbeatInter being present and correctly configured. Requires Write-LoggingEntry, New-IcingaRPCMessage and Send-TCPMessage. The heartbeat message includes a parameter timeout set to 120 seconds. Time comparisons use Get-Date and TotalSeconds to determine interval expiry. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Send-IcingaProtocolHeartbeat() { @@ -32,8 +35,8 @@ function Send-IcingaProtocolHeartbeat() # Check if we need to send a heartbeat based on the configured interval if ($null -eq $LastHeartbeat -or ($TimeNow - $LastHeartbeat).TotalSeconds -ge $Global:IcingaForWindows.Private.TCP.HeartbeatInterval) { # Send the heartbeat message - Write-LoggingEntry -Message ' → Sending IcingaProtocol Heartbeat' -Level 'Debug'; - $MsgObj = New-IcingaRPCMessage -Method 'event::Heartbeat' -Parameters @{ 'timeout' = 120 }; + Write-LoggingEntry -Message ' -> Sending IcingaProtocol Heartbeat' -Level 'Debug'; + $MsgObj = New-IcingaRPCMessage -Method 'event::Heartbeat' -Parameters @{ 'timeout' = 120 }; Add-IcingaRPCMessageToWriterQueue -MsgObj $MsgObj; # Update the last heartbeat time $Global:IcingaForWindows.Private.TCP.HeartbeatTimer = $TimeNow; diff --git a/src/IcingaProtocol/Private/Send-IcingaProtocolHello.ps1 b/src/IcingaProtocol/Private/Send-IcingaProtocolHello.ps1 index 115768c..aa6306d 100644 --- a/src/IcingaProtocol/Private/Send-IcingaProtocolHello.ps1 +++ b/src/IcingaProtocol/Private/Send-IcingaProtocolHello.ps1 @@ -9,7 +9,7 @@ Send-TCPMessage. Use this to initiate the protocol handshake where required by the remote endpoint, typically before the writer queue is active. .OUTPUTS -None — Sends the Hello frame directly via Send-TCPMessage; no pipeline output. +None -- Sends the Hello frame directly via Send-TCPMessage; no pipeline output. .EXAMPLE PS> Send-IcingaProtocolHello @@ -19,6 +19,9 @@ Sends the Hello message over the current TCP/SSL stream. .NOTES This function bypasses the writer queue and calls Send-TCPMessage directly, making it suitable for early handshake messages before the queue is initialized. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Send-IcingaProtocolHello() { diff --git a/src/IcingaProtocol/Private/Send-IcingaProtocolLogPosition.ps1 b/src/IcingaProtocol/Private/Send-IcingaProtocolLogPosition.ps1 index dbe4715..1665af4 100644 --- a/src/IcingaProtocol/Private/Send-IcingaProtocolLogPosition.ps1 +++ b/src/IcingaProtocol/Private/Send-IcingaProtocolLogPosition.ps1 @@ -9,7 +9,7 @@ log position is automatically set to the current Unix timestamp using Get-IcingaUnixTime. .OUTPUTS -None — Does not return any value. +None -- Does not return any value. .EXAMPLE PS> Send-IcingaProtocolLogPosition @@ -18,6 +18,9 @@ Sends the log position update to the connected Icinga endpoint. .NOTES Requires an active TCP connection to the Icinga endpoint. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Send-IcingaProtocolLogPosition() { diff --git a/src/IcingaProtocol/Private/Split-IcingaBinaryPluginOutput.ps1 b/src/IcingaProtocol/Private/Split-IcingaBinaryPluginOutput.ps1 index a1f5a90..3c27fd7 100644 --- a/src/IcingaProtocol/Private/Split-IcingaBinaryPluginOutput.ps1 +++ b/src/IcingaProtocol/Private/Split-IcingaBinaryPluginOutput.ps1 @@ -12,9 +12,9 @@ scoped and doubled-quote metric labels containing spaces (for example individual elements in the returned PerformanceData array. .PARAMETER RawOutput -| Name | Type | Description | Default | -|-----------|---------------|-----------------------------------------------------------|---------| -| RawOutput | System.String | Raw stdout captured from an external binary or script. | '' | +| Name | Type | Description | Default | +|-----------|---------------|--------------------------------------------------------|---------| +| RawOutput | System.String | Raw stdout captured from an external binary or script. | '' | .OUTPUTS System.Collections.Hashtable -- Hashtable with keys Output (System.String) and @@ -28,6 +28,9 @@ individual performance-data metric strings. .NOTES Pure string parser with no external dependencies or side effects. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Split-IcingaBinaryPluginOutput() { diff --git a/src/IcingaProtocol/Private/Start-IcingaProtocolConnector.ps1 b/src/IcingaProtocol/Private/Start-IcingaProtocolConnector.ps1 index ccf087e..8689dc3 100644 --- a/src/IcingaProtocol/Private/Start-IcingaProtocolConnector.ps1 +++ b/src/IcingaProtocol/Private/Start-IcingaProtocolConnector.ps1 @@ -14,7 +14,7 @@ logged and do not stop the overall loop. The loop pauses for 5 seconds between f scans. Because the function runs indefinitely, it must always be started in a background thread. .OUTPUTS -None — Manages connections, global state and log entries; no pipeline output. +None -- Manages connections, global state and log entries; no pipeline output. .EXAMPLE PS> New-Thread -Command 'Start-IcingaProtocolConnector' -Start @@ -28,6 +28,9 @@ The function is intentionally long-running and blocking; always run it in a back thread. Exceptions during individual connection attempts are logged and do not stop the overall loop. The loop pauses for 5 seconds between full endpoint scans to avoid tight reconnect cycles. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Start-IcingaProtocolConnector() { @@ -69,7 +72,7 @@ function Start-IcingaProtocolConnector() Write-LoggingEntry -Message 'Successfully connected to Icinga endpoint' -Level 'Info' -Data @{ 'EndpointAddress' = "$($EndpointConfig.Address):$($EndpointConfig.Port)"; }; # Start the socket reader in a new thread - New-Thread -Command 'Start-IcingaProtocolSocketReader' -Parameters @{ '-Client' = $TcpClient; 'IsClient' = $true; 'Endpoint' = $EndpointName } -Start; + New-Thread -Command 'Start-IcingaProtocolSocketReader' -Parameters @{ '-Client' = $TcpClient; 'IsClient' = $true; 'Endpoint' = $EndpointName } -Start; } catch { if ($null -ne $TcpClient) { $TcpClient.Dispose(); diff --git a/src/IcingaProtocol/Private/Start-IcingaProtocolHeartbeat.ps1 b/src/IcingaProtocol/Private/Start-IcingaProtocolHeartbeat.ps1 index f57e204..bda5a24 100644 --- a/src/IcingaProtocol/Private/Start-IcingaProtocolHeartbeat.ps1 +++ b/src/IcingaProtocol/Private/Start-IcingaProtocolHeartbeat.ps1 @@ -5,20 +5,20 @@ Starts a recurring heartbeat sender over an established TCP/TLS connection to ke .DESCRIPTION Start-IcingaProtocolHeartbeat validates and registers a provided System.Net.Sockets.TcpClient and System.Net.Security.SslStream for use by the Icinga protocol heartbeat subsystem, then enters a loop that periodically sends heartbeat messages until the TCP connection is lost. The function logs connection loss and other exceptions, closes the TCP connection when the client disconnects, and stops the current Icinga thread. -This function relies on helper functions from the IcingaForWindows module (for example: Set-TCPClientAndStream, Test-TCPConnection, Send-IcingaProtocolHeartbeat, Close-TCPConnection, Stop-Thread, Get-ThreadId and Write-LoggingEntry) to perform its work. It is intended to be used after a successful connection handshake and when you have an active SslStream wrapped around a TcpClient. +This function relies on helper functions from the Icinga for Windows module (for example: Set-TCPClientAndStream, Test-TCPConnection, Send-IcingaProtocolHeartbeat, Close-TCPConnection, Stop-Thread, Get-ThreadId and Write-LoggingEntry) to perform its work. It is intended to be used after a successful connection handshake and when you have an active SslStream wrapped around a TcpClient. .PARAMETER TcpClient -| Name | Type | Description | Default | -|-----------|------------------------------|---------------------------------------------------------------------------|---------| -| TcpClient | System.Net.Sockets.TcpClient | Connected TCP client representing the remote endpoint. Required. | $null | +| Name | Type | Description | Default | +|-----------|------------------------------|------------------------------------------------------------------|---------| +| TcpClient | System.Net.Sockets.TcpClient | Connected TCP client representing the remote endpoint. Required. | $null | .PARAMETER SslStream -| Name | Type | Description | Default | -|-----------|---------------------------------|--------------------------------------------------------------------------|---------| -| SslStream | System.Net.Security.SslStream | SSL/TLS stream wrapping the network stream for secure communication. Required. | $null | +| Name | Type | Description | Default | +|-----------|-------------------------------|--------------------------------------------------------------------------------|---------| +| SslStream | System.Net.Security.SslStream | SSL/TLS stream wrapping the network stream for secure communication. Required. | $null | .OUTPUTS -None — Sends heartbeat messages, writes log entries, closes the connection and stops +None -- Sends heartbeat messages, writes log entries, closes the connection and stops the current thread when the connection terminates. .EXAMPLE @@ -37,6 +37,9 @@ Heartbeats are sent once per second while Test-ThreadRunning -CheckTcpConnection true. MethodInvocationException during send is logged at Info level as a connection loss event. After the loop exits, the TCP connection is closed and the current thread is stopped via Stop-Thread. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Start-IcingaProtocolHeartbeat() { diff --git a/src/IcingaProtocol/Private/Start-IcingaProtocolListener.ps1 b/src/IcingaProtocol/Private/Start-IcingaProtocolListener.ps1 index 07b53f0..5160cc8 100644 --- a/src/IcingaProtocol/Private/Start-IcingaProtocolListener.ps1 +++ b/src/IcingaProtocol/Private/Start-IcingaProtocolListener.ps1 @@ -13,7 +13,7 @@ are caught and logged to keep the listener loop alive. The function runs until t hosting process is stopped and must always be started in a background thread. .OUTPUTS -None — Side-effect driven: opens a network listener, updates global state, writes log entries and spawns threads. +None -- Side-effect driven: opens a network listener, updates global state, writes log entries and spawns threads. .EXAMPLE PS> New-Thread -Command 'Start-IcingaProtocolListener' -Start @@ -26,6 +26,9 @@ and ListenPort. The function is intentionally long-running and blocking; always background thread. Requires Open-TCPSocket, Close-TCPConnection, Test-IcingaProtocolClientStatus, Add-IcingaProtocolClient, New-Thread, Start-IcingaProtocolSocketReader and Write-LoggingEntry. Exceptions are caught per iteration to keep the listener loop alive. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Start-IcingaProtocolListener() { @@ -66,7 +69,7 @@ function Start-IcingaProtocolListener() Add-IcingaProtocolClient -Address $Global:IcingaForWindows.Private.TCP.Client.Client.RemoteEndPoint.Address.ToString() -TcpClient $Global:IcingaForWindows.Private.TCP.Client; # Start the socket reader in a new thread - New-Thread -Command 'Start-IcingaProtocolSocketReader' -Parameters @{ '-Client' = $Global:IcingaForWindows.Private.TCP.Client } -Start; + New-Thread -Command 'Start-IcingaProtocolSocketReader' -Parameters @{ '-Client' = $Global:IcingaForWindows.Private.TCP.Client } -Start; } catch { Write-LoggingEntry -Message 'Exception caught in Icinga Protocol Listener: {0}' -Level 'Error' -Data @{ 'ExceptionMessage' = $_.Exception.Message; }; } diff --git a/src/IcingaProtocol/Private/Start-IcingaProtocolSocketReader.ps1 b/src/IcingaProtocol/Private/Start-IcingaProtocolSocketReader.ps1 index 96ebafd..8041901 100644 --- a/src/IcingaProtocol/Private/Start-IcingaProtocolSocketReader.ps1 +++ b/src/IcingaProtocol/Private/Start-IcingaProtocolSocketReader.ps1 @@ -6,22 +6,22 @@ Starts a background loop that reads JSON-RPC framed messages from an established Start-IcingaProtocolSocketReader initializes and manages reading from a provided System.Net.Sockets.TcpClient. It validates and registers the TCP client in the module's global connection state, spawns a heartbeat sender thread, optionally sends an initial Hello when acting as a client, and then continuously reads from the associated SSL stream. Incoming data is assembled into framed JSON-RPC messages (using a length-prefixed framing scheme), complete messages are enqueued for worker processing, and partial messages are preserved between reads. The reader loop runs until the TCP connection becomes invalid or an unrecoverable read error occurs; on exit, the connection is closed and the reader thread is stopped. .PARAMETER Client -| Name | Type | Description | Default | -|--------|------------------------------|---------------------------------------------------------------------------|---------| +| Name | Type | Description | Default | +|--------|------------------------------|----------------------------------------------------------------------------|---------| | Client | System.Net.Sockets.TcpClient | Established TCP connection to read from. Required; null causes early exit. | $null | .PARAMETER Endpoint -| Name | Type | Description | Default | -|----------|---------------|---------------------------------------------------------------------------------|---------| -| Endpoint | System.String | Endpoint name used for SSL authentication with the IcingaProtocol certificate. | $null | +| Name | Type | Description | Default | +|----------|---------------|--------------------------------------------------------------------------------|---------| +| Endpoint | System.String | Endpoint name used for SSL authentication with the IcingaProtocol certificate. | $null | .PARAMETER IsClient -| Name | Type | Description | Default | -|----------|--------------------------------------------------|----------------------------------------------------------------------|---------| -| IsClient | System.Management.Automation.SwitchParameter | When set, the reader sends an initial Hello after TLS handshake. | $false | +| Name | Type | Description | Default | +|----------|----------------------------------------------|------------------------------------------------------------------|---------| +| IsClient | System.Management.Automation.SwitchParameter | When set, the reader sends an initial Hello after TLS handshake. | $false | .OUTPUTS -None — Enqueues parsed JSON-RPC payloads for worker processing and updates global connection state. +None -- Enqueues parsed JSON-RPC payloads for worker processing and updates global connection state. .EXAMPLE PS> New-Thread -Command 'Start-IcingaProtocolSocketReader' -Parameters @{ '-Client' = $client } -Start @@ -39,6 +39,8 @@ Uses a 4096-byte read buffer per iteration. Partial frames are accumulated and p to Read-IcingaRPCMessage on subsequent reads. Heartbeat and writer threads are started via New-Thread before the read loop begins. +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Start-IcingaProtocolSocketReader() { diff --git a/src/IcingaProtocol/Private/Start-IcingaProtocolSocketWriter.ps1 b/src/IcingaProtocol/Private/Start-IcingaProtocolSocketWriter.ps1 index 933eb61..d0ba616 100644 --- a/src/IcingaProtocol/Private/Start-IcingaProtocolSocketWriter.ps1 +++ b/src/IcingaProtocol/Private/Start-IcingaProtocolSocketWriter.ps1 @@ -15,17 +15,17 @@ a dedicated background thread spawned by Start-IcingaProtocolSocketReader. .PARAMETER TcpClient -| Name | Type | Description | Default | -|-----------|------------------------------|--------------------------------------------------------------------------|---------| -| TcpClient | System.Net.Sockets.TcpClient | Connected TCP client whose remote endpoint identifies the writer queue. | $null | +| Name | Type | Description | Default | +|-----------|------------------------------|-------------------------------------------------------------------------|---------| +| TcpClient | System.Net.Sockets.TcpClient | Connected TCP client whose remote endpoint identifies the writer queue. | $null | .PARAMETER SslStream -| Name | Type | Description | Default | -|-----------|-------------------------------|-------------------------------------------------------------------------|---------| -| SslStream | System.Net.Security.SslStream | Authenticated SSL stream used by Send-TCPMessage to write bytes. | $null | +| Name | Type | Description | Default | +|-----------|-------------------------------|------------------------------------------------------------------|---------| +| SslStream | System.Net.Security.SslStream | Authenticated SSL stream used by Send-TCPMessage to write bytes. | $null | .OUTPUTS -None — Dequeues and sends messages; no pipeline output. +None -- Dequeues and sends messages; no pipeline output. .EXAMPLE PS> New-Thread -Command 'Start-IcingaProtocolSocketWriter' -Parameters @{ '-TcpClient' = $tcp; '-SslStream' = $stream } -Start -WaitForJobs @@ -36,6 +36,9 @@ Starts the writer thread and waits until its queue entry is registered before co The writer queue entry for the endpoint is created inside this function using a ConcurrentQueue-backed BlockingCollection. The WaitForJobs flag on New-Thread ensures the queue slot exists before the first message is enqueued by other threads. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Start-IcingaProtocolSocketWriter() { diff --git a/src/IcingaProtocol/Private/Start-IcingaProtocolWorker.ps1 b/src/IcingaProtocol/Private/Start-IcingaProtocolWorker.ps1 index 5484f53..93c3bd9 100644 --- a/src/IcingaProtocol/Private/Start-IcingaProtocolWorker.ps1 +++ b/src/IcingaProtocol/Private/Start-IcingaProtocolWorker.ps1 @@ -29,6 +29,9 @@ WorkerId must be a valid index into the WorkerQueue ArrayList initialized by New-IcingaAgentEnvironment. Accesses shared state via Get-GlobalRuntimeVariable and nulls all per-iteration reference variables in finally to prevent daemon memory retention. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Start-IcingaProtocolWorker() { diff --git a/src/IcingaProtocol/Private/Stop-IcingaProtocolProcessTree.ps1 b/src/IcingaProtocol/Private/Stop-IcingaProtocolProcessTree.ps1 index cebfa4b..93eef95 100644 --- a/src/IcingaProtocol/Private/Stop-IcingaProtocolProcessTree.ps1 +++ b/src/IcingaProtocol/Private/Stop-IcingaProtocolProcessTree.ps1 @@ -16,9 +16,9 @@ consuming host resources: descendant handle, waits for exit, and disposes all descendant handles. .PARAMETER Process -| Name | Type | Description | Default | -|---------|----------------------------|-----------------------------------------------------|---------| -| Process | System.Diagnostics.Process | Live root Process object whose handle stays open. | $null | +| Name | Type | Description | Default | +|---------|----------------------------|---------------------------------------------------|---------| +| Process | System.Diagnostics.Process | Live root Process object whose handle stays open. | $null | .PARAMETER RootProcessId | Name | Type | Description | Default | @@ -36,6 +36,9 @@ Kills the root process and all descendant processes spawned by it. .NOTES Caller remains responsible for disposing the root Process instance after stream drain completes. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Stop-IcingaProtocolProcessTree() { diff --git a/src/IcingaProtocol/Private/Test-IcingaProtocolClientStatus.ps1 b/src/IcingaProtocol/Private/Test-IcingaProtocolClientStatus.ps1 index 0f9d28c..e9ba046 100644 --- a/src/IcingaProtocol/Private/Test-IcingaProtocolClientStatus.ps1 +++ b/src/IcingaProtocol/Private/Test-IcingaProtocolClientStatus.ps1 @@ -3,15 +3,15 @@ Validates the status of an Icinga protocol TCP client for the specified address and optionally registers a new connection. .DESCRIPTION -Test-IcingaProtocolClientStatus examines the global IcingaForWindows protocol connection table to determine whether a TCP client for the provided Address is present and connected. If Address is null or empty, the function returns an invalid-address result. If a connection entry exists, the function checks the client object and its Connected property and returns a corresponding status. If no entry exists, the function attempts to add a new entry to the global connection table using the $TcpClient variable from the current scope and returns a created status. +Test-IcingaProtocolClientStatus examines the global Icinga for Windows protocol connection table to determine whether a TCP client for the provided Address is present and connected. If Address is null or empty, the function returns an invalid-address result. If a connection entry exists, the function checks the client object and its Connected property and returns a corresponding status. If no entry exists, the function attempts to add a new entry to the global connection table using the $TcpClient variable from the current scope and returns a created status. .PARAMETER Address -| Name | Type | Description | Default | -|---------|---------------|------------------------------------------------------------------------------------------|---------| -| Address | System.String | IP address string used to look up the client in the global connections table. | $null | +| Name | Type | Description | Default | +|---------|---------------|-------------------------------------------------------------------------------|---------| +| Address | System.String | IP address string used to look up the client in the global connections table. | $null | .OUTPUTS -PSCustomObject — Standardized result object from Write-FunctionReturnValue. +PSCustomObject -- Standardized result object from Write-FunctionReturnValue. Possible tokens: IcingaAddressInvalid, IcingaClientReplaced, IcingaClientConnected, IcingaClientCreated. .EXAMPLE @@ -29,6 +29,9 @@ Returns IcingaAddressInvalid when no Address is provided. $Global:IcingaForWindows.Public.IcingaProtocol.Connections using the $TcpClient variable from the caller's scope. - Precondition: $Global:IcingaForWindows.Public.IcingaProtocol.Connections must be an initialized hashtable or dictionary-like object that supports ContainsKey(), indexing, and Add(). - The function relies on client objects exposing a Connected property to determine connectivity. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Test-IcingaProtocolClientStatus() { @@ -44,7 +47,7 @@ function Test-IcingaProtocolClientStatus() # Check if we have an existing connection entry for this client if ($Global:IcingaForWindows.Public.IcingaProtocol.Connections.ContainsKey($Address)) { # Check if the client object is still valid and present - $KnownTcpClient = $Global:IcingaForWindows.Public.IcingaProtocol.Connections[$Address]; + $KnownTcpClient = $Global:IcingaForWindows.Public.IcingaProtocol.Connections[$Address]; [bool]$IsConnected = $false; if ($null -ne $KnownTcpClient -and $null -ne $KnownTcpClient.Client -and $KnownTcpClient.Connected) { diff --git a/src/IcingaProtocol/Public/Import-IcingaCertAuthority.ps1 b/src/IcingaProtocol/Public/Import-IcingaCertAuthority.ps1 index a5ad28a..7097e96 100644 --- a/src/IcingaProtocol/Public/Import-IcingaCertAuthority.ps1 +++ b/src/IcingaProtocol/Public/Import-IcingaCertAuthority.ps1 @@ -10,17 +10,17 @@ CertificateAuthority store (on Windows) or saves it to the module's certificate directory as 'ca.crt' (on Linux/macOS). .PARAMETER Certificate -| Name | Type | Description | Default | -|-------------|---------------|--------------------------------------------|---------| -| Certificate | System.String | The PEM-formatted CA certificate payload. | | +| Name | Type | Description | Default | +|-------------|---------------|-------------------------------------------|---------| +| Certificate | System.String | The PEM-formatted CA certificate payload. | | .PARAMETER Path -| Name | Type | Description | Default | -|------|---------------|-----------------------------------------------------|---------| -| Path | System.String | Local file path or HTTP/HTTPS URL to the CA cert. | | +| Name | Type | Description | Default | +|------|---------------|---------------------------------------------------|---------| +| Path | System.String | Local file path or HTTP/HTTPS URL to the CA cert. | | .OUTPUTS -None — Performs the import or file write without returning a value. +None -- Performs the import or file write without returning a value. .EXAMPLE PS> Import-IcingaCertAuthority -Certificate '-----BEGIN CERTIFICATE-----...' @@ -35,6 +35,9 @@ Downloads and imports the CA certificate from a web server. .NOTES Operates on the CurrentUser CertificateAuthority store to avoid Windows security prompts. Does not require administrative elevation. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Import-IcingaCertAuthority() { @@ -66,14 +69,14 @@ function Import-IcingaCertAuthority() $CertBytes = [System.Text.Encoding]::UTF8.GetBytes($Certificate); $CertObj = [System.Security.Cryptography.X509Certificates.X509Certificate2]::New($CertBytes); - $Store = [System.Security.Cryptography.X509Certificates.X509Store]::New( + $Store = [System.Security.Cryptography.X509Certificates.X509Store]::New( [System.Security.Cryptography.X509Certificates.StoreName]::Root, [System.Security.Cryptography.X509Certificates.StoreLocation]::LocalMachine ); $Store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite); # Only add if it's not already in the store - $Exists = $false; + $Exists = $false; foreach ($Existing in $Store.Certificates) { if ($Existing.Thumbprint -eq $CertObj.Thumbprint) { $Exists = $true; diff --git a/src/IcingaProtocol/Public/New-IcingaProtocolCertificate.ps1 b/src/IcingaProtocol/Public/New-IcingaProtocolCertificate.ps1 index c9da19c..ca58b18 100644 --- a/src/IcingaProtocol/Public/New-IcingaProtocolCertificate.ps1 +++ b/src/IcingaProtocol/Public/New-IcingaProtocolCertificate.ps1 @@ -12,17 +12,17 @@ a passwordless PFX file (on Linux/macOS). When merging on Windows, the old certificate is removed from the store automatically. .PARAMETER CommonName -| Name | Type | Description | Default | -|------------|---------------|--------------------------------------------|---------| -| CommonName | System.String | The common name (CN) for the certificate. | $null | +| Name | Type | Description | Default | +|------------|---------------|-------------------------------------------|---------| +| CommonName | System.String | The common name (CN) for the certificate. | $null | .PARAMETER SignedCert -| Name | Type | Description | Default | -|------------|---------------|--------------------------------------------|---------| -| SignedCert | System.String | The PEM-formatted signed certificate. | $null | +| Name | Type | Description | Default | +|------------|---------------|---------------------------------------|---------| +| SignedCert | System.String | The PEM-formatted signed certificate. | $null | .OUTPUTS -System.Object — Returns a structured result via Write-FunctionReturnValue containing the storage path. +System.Object -- Returns a structured result via Write-FunctionReturnValue containing the storage path. .EXAMPLE PS> New-IcingaProtocolCertificate -CommonName 'IcingaNode' @@ -37,6 +37,9 @@ Merges the signed certificate with the existing private key for 'IcingaNode'. .NOTES Requires administrative privileges on Windows to access the LocalMachine certificate store. Cross-platform compatible; relies on .NET cryptography classes. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function New-IcingaProtocolCertificate() { @@ -54,10 +57,10 @@ function New-IcingaProtocolCertificate() if ([string]::IsNullOrEmpty($SignedCert)) { # Generate a new 4096-bit RSA private key - $rsa = [System.Security.Cryptography.RSA]::Create(4096); + $rsa = [System.Security.Cryptography.RSA]::Create(4096); # Create a new certificate request for the given Common Name - $req = [System.Security.Cryptography.X509Certificates.CertificateRequest]::New( + $req = [System.Security.Cryptography.X509Certificates.CertificateRequest]::New( [string]::Format('CN={0}', $CommonName), $rsa, [System.Security.Cryptography.HashAlgorithmName]::SHA256, @@ -65,7 +68,7 @@ function New-IcingaProtocolCertificate() ); # Create the self-signed certificate, valid for 3 months - $cert = $req.CreateSelfSigned([System.DateTimeOffset]::Now, [System.DateTimeOffset]::Now.AddMonths(3)); + $cert = $req.CreateSelfSigned([System.DateTimeOffset]::Now, [System.DateTimeOffset]::Now.AddMonths(3)); # Export the certificate as a PFX/PKCS#12 payload. # By not providing a password string, the PFX is generated without password encryption. diff --git a/src/IcingaProtocol/Public/New-IcingaProtocolEndpoint.ps1 b/src/IcingaProtocol/Public/New-IcingaProtocolEndpoint.ps1 index c1b4f69..6e1cb5b 100644 --- a/src/IcingaProtocol/Public/New-IcingaProtocolEndpoint.ps1 +++ b/src/IcingaProtocol/Public/New-IcingaProtocolEndpoint.ps1 @@ -7,22 +7,22 @@ Creates a hashtable representing an Icinga Protocol endpoint with the specified This object is typically passed into New-IcingaProtocolEnvironment. .PARAMETER Name -| Name | Type | Description | Default | -|------|---------------|--------------------------------------------|---------| -| Name | System.String | The human-readable name of the endpoint. | | +| Name | Type | Description | Default | +|------|---------------|------------------------------------------|---------| +| Name | System.String | The human-readable name of the endpoint. | | .PARAMETER Address -| Name | Type | Description | Default | -|---------|---------------|--------------------------------------------|---------| -| Address | System.String | The IP address or FQDN of the endpoint. | | +| Name | Type | Description | Default | +|---------|---------------|-----------------------------------------|---------| +| Address | System.String | The IP address or FQDN of the endpoint. | | .PARAMETER Port -| Name | Type | Description | Default | -|------|--------------|--------------------------------------------|---------| -| Port | System.Int32 | The TCP port to connect to. | | +| Name | Type | Description | Default | +|------|--------------|-----------------------------|---------| +| Port | System.Int32 | The TCP port to connect to. | | .OUTPUTS -System.Collections.Hashtable — Returns a hashtable with the endpoint configuration. +System.Collections.Hashtable -- Returns a hashtable with the endpoint configuration. .EXAMPLE PS> New-IcingaProtocolEndpoint -Name 'Master1' -Address '192.168.1.10' -Port 5665 @@ -31,6 +31,9 @@ Creates a new endpoint object for Master1. .NOTES This object is required for configuring the Icinga environment structure. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function New-IcingaProtocolEndpoint() { diff --git a/src/IcingaProtocol/Public/New-IcingaProtocolEnvironment.ps1 b/src/IcingaProtocol/Public/New-IcingaProtocolEnvironment.ps1 index 3546b6f..11557ab 100644 --- a/src/IcingaProtocol/Public/New-IcingaProtocolEnvironment.ps1 +++ b/src/IcingaProtocol/Public/New-IcingaProtocolEnvironment.ps1 @@ -8,32 +8,32 @@ and TLS certificate configuration. It either saves the configuration to 'IcingaP or returns a diff against the current configuration if -DryRun is used. .PARAMETER Endpoints -| Name | Type | Description | Default | -|-----------|--------------|--------------------------------------------|---------| -| Endpoints | System.Array | An array of endpoint hashtables. | @() | +| Name | Type | Description | Default | +|-----------|--------------|----------------------------------|---------| +| Endpoints | System.Array | An array of endpoint hashtables. | @() | .PARAMETER Zone -| Name | Type | Description | Default | -|------|---------------|--------------------------------------------|----------| -| Zone | System.String | The name of the Icinga zone. | 'master' | +| Name | Type | Description | Default | +|------|---------------|------------------------------|----------| +| Zone | System.String | The name of the Icinga zone. | 'master' | .PARAMETER Hostname -| Name | Type | Description | Default | -|----------|---------------|--------------------------------------------|-------------| -| Hostname | System.String | The local hostname for this node. | '$hostname' | +| Name | Type | Description | Default | +|----------|---------------|-----------------------------------|-------------| +| Hostname | System.String | The local hostname for this node. | '$hostname' | .PARAMETER TlsCertConfig -| Name | Type | Description | Default | -|---------------|----------------|--------------------------------------------|---------| -| TlsCertConfig | PSCustomObject | The TLS certificate configuration object. | $null | +| Name | Type | Description | Default | +|---------------|----------------|-------------------------------------------|---------| +| TlsCertConfig | PSCustomObject | The TLS certificate configuration object. | $null | .PARAMETER DryRun -| Name | Type | Description | Default | -|--------|--------|--------------------------------------------|---------| -| DryRun | switch | Outputs a diff without saving the file. | $false | +| Name | Type | Description | Default | +|--------|--------|-----------------------------------------|---------| +| DryRun | switch | Outputs a diff without saving the file. | $false | .OUTPUTS -System.Object — Returns a status object from Write-FunctionReturnValue or a diff string. +System.Object -- Returns a status object from Write-FunctionReturnValue or a diff string. .EXAMPLE PS> $Endpoints = @(New-IcingaProtocolEndpoint -Name 'master' -Address '10.0.0.1' -Port 5665) @@ -43,6 +43,9 @@ Generates the protocol configuration and writes it to disk. .NOTES Writes configuration data to the internal Icinga Protocol connection JSON file. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function New-IcingaProtocolEnvironment() { diff --git a/src/IcingaProtocol/Public/Start-IcingaAgent.ps1 b/src/IcingaProtocol/Public/Start-IcingaAgent.ps1 index 28acb7b..8759f67 100644 --- a/src/IcingaProtocol/Public/Start-IcingaAgent.ps1 +++ b/src/IcingaProtocol/Public/Start-IcingaAgent.ps1 @@ -9,7 +9,7 @@ Use this function to activate the protocol listener, connector and worker threads for Icinga JSON-RPC communication. .OUTPUTS -None — Starts a background thread; no pipeline output. +None -- Starts a background thread; no pipeline output. .EXAMPLE PS> Start-IcingaAgent @@ -18,6 +18,9 @@ PS> Start-IcingaAgent This function requires New-IcingaAgentEnvironment and New-Thread to be available. The agent environment is initialized asynchronously in the spawned thread. Call this once during module startup after global configuration is in place. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Start-IcingaAgent() { diff --git a/src/PerformanceCounter/Private/ConvertTo-IcingaPerformanceCounterInstanceStructure.ps1 b/src/PerformanceCounter/Private/ConvertTo-IcingaPerformanceCounterInstanceStructure.ps1 index 5f830cf..c83ac89 100644 --- a/src/PerformanceCounter/Private/ConvertTo-IcingaPerformanceCounterInstanceStructure.ps1 +++ b/src/PerformanceCounter/Private/ConvertTo-IcingaPerformanceCounterInstanceStructure.ps1 @@ -37,6 +37,9 @@ PS> ConvertTo-IcingaPerformanceCounterInstanceStructure -Result $raw -Counter '\ .NOTES Called by `Get-IcingaPerformanceCounter` when `-StructureByInstance` is set. Pure transform; touches no global state and reads no counters. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function ConvertTo-IcingaPerformanceCounterInstanceStructure() { diff --git a/src/PerformanceCounter/Private/Get-IcingaPerformanceCounterLiteral.ps1 b/src/PerformanceCounter/Private/Get-IcingaPerformanceCounterLiteral.ps1 index 06e064a..ce911ac 100644 --- a/src/PerformanceCounter/Private/Get-IcingaPerformanceCounterLiteral.ps1 +++ b/src/PerformanceCounter/Private/Get-IcingaPerformanceCounterLiteral.ps1 @@ -24,6 +24,9 @@ PS> Get-IcingaPerformanceCounterLiteral -Argument $argumentAst .NOTES Called by `Register-IcingaPerformanceCounterFromComponents`. Returns an empty array when the argument is null or contains no string literals. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Get-IcingaPerformanceCounterLiteral() { diff --git a/src/PerformanceCounter/Private/Get-IcingaPerformanceCounterValue.ps1 b/src/PerformanceCounter/Private/Get-IcingaPerformanceCounterValue.ps1 index 91ad144..e839809 100644 --- a/src/PerformanceCounter/Private/Get-IcingaPerformanceCounterValue.ps1 +++ b/src/PerformanceCounter/Private/Get-IcingaPerformanceCounterValue.ps1 @@ -30,6 +30,9 @@ Returns the processor load of core 0, or the error text if that counter could no .NOTES Pure helper; reads no global state and touches no counters. Intended for use by plugins after they have selected a single counter from a `Get-IcingaPerformanceCounter` result. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Get-IcingaPerformanceCounterValue() { diff --git a/src/PerformanceCounter/Private/New-IcingaPerformanceCounter.ps1 b/src/PerformanceCounter/Private/New-IcingaPerformanceCounter.ps1 index c6bc64f..b902217 100644 --- a/src/PerformanceCounter/Private/New-IcingaPerformanceCounter.ps1 +++ b/src/PerformanceCounter/Private/New-IcingaPerformanceCounter.ps1 @@ -30,6 +30,9 @@ Declares two counters so the daemon keeps them warm and the discovery step can f .NOTES The counters are stored under `(Get-GlobalRuntimeVariable).Public.PerformanceCounter.Registered`. This function does not return counter values -- use `Get-IcingaPerformanceCounter` to read them. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function New-IcingaPerformanceCounter() { diff --git a/src/PerformanceCounter/Private/New-IcingaPerformanceCounterEnvironment.ps1 b/src/PerformanceCounter/Private/New-IcingaPerformanceCounterEnvironment.ps1 index ba038f6..f031f81 100644 --- a/src/PerformanceCounter/Private/New-IcingaPerformanceCounterEnvironment.ps1 +++ b/src/PerformanceCounter/Private/New-IcingaPerformanceCounterEnvironment.ps1 @@ -22,6 +22,9 @@ PS> New-IcingaPerformanceCounterEnvironment .NOTES All shared state is read through `Get-GlobalRuntimeVariable`. The manager is stored on the `Manager` slot of the global store and is only ever touched by the daemon thread. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function New-IcingaPerformanceCounterEnvironment() { diff --git a/src/PerformanceCounter/Private/Read-IcingaPerformanceCounterCache.ps1 b/src/PerformanceCounter/Private/Read-IcingaPerformanceCounterCache.ps1 index 8710830..a1fc2bb 100644 --- a/src/PerformanceCounter/Private/Read-IcingaPerformanceCounterCache.ps1 +++ b/src/PerformanceCounter/Private/Read-IcingaPerformanceCounterCache.ps1 @@ -19,6 +19,9 @@ PS> Read-IcingaPerformanceCounterCache `ConvertFrom-Json` returns a PSCustomObject on both Windows PowerShell 5.1 and PowerShell 7 (the `-AsHashtable` switch is deliberately not used because it is PowerShell 6+ only). Entries are read through the object's properties for cross-version compatibility. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Read-IcingaPerformanceCounterCache() { diff --git a/src/PerformanceCounter/Private/Register-IcingaDefaultPerformanceCounter.ps1 b/src/PerformanceCounter/Private/Register-IcingaDefaultPerformanceCounter.ps1 index bc23681..1a7086e 100644 --- a/src/PerformanceCounter/Private/Register-IcingaDefaultPerformanceCounter.ps1 +++ b/src/PerformanceCounter/Private/Register-IcingaDefaultPerformanceCounter.ps1 @@ -18,6 +18,9 @@ PS> Register-IcingaDefaultPerformanceCounter .NOTES The literal counter list here is what the discovery step reads from the compiled kernel. The set is intentionally minimal and generic; it is an example, not a fixed contract. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Register-IcingaDefaultPerformanceCounter() { diff --git a/src/PerformanceCounter/Private/Register-IcingaPerformanceCounterFromComponents.ps1 b/src/PerformanceCounter/Private/Register-IcingaPerformanceCounterFromComponents.ps1 index afe3cb5..1f4ebe8 100644 --- a/src/PerformanceCounter/Private/Register-IcingaPerformanceCounterFromComponents.ps1 +++ b/src/PerformanceCounter/Private/Register-IcingaPerformanceCounterFromComponents.ps1 @@ -21,6 +21,9 @@ PS> Register-IcingaPerformanceCounterFromComponents .NOTES Only literal array/string arguments are discoverable. The kernel file is produced by `Build-ModuleProject`; if it is missing the discovery step is skipped. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Register-IcingaPerformanceCounterFromComponents() { diff --git a/src/PerformanceCounter/Private/Start-IcingaPerformanceCounterDaemon.ps1 b/src/PerformanceCounter/Private/Start-IcingaPerformanceCounterDaemon.ps1 index cbdcbc1..d23b669 100644 --- a/src/PerformanceCounter/Private/Start-IcingaPerformanceCounterDaemon.ps1 +++ b/src/PerformanceCounter/Private/Start-IcingaPerformanceCounterDaemon.ps1 @@ -25,6 +25,9 @@ PS> Start-IcingaPerformanceCounterDaemon Must run inside a dedicated background runspace created by `New-Thread`. All shared state is accessed through `Get-GlobalRuntimeVariable` because the runspace receives only a snapshot of the runtime at startup. The daemon exits cleanly when `Test-ThreadRunning` returns $false. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Start-IcingaPerformanceCounterDaemon() { diff --git a/src/PerformanceCounter/Private/Test-IcingaPerformanceCounterDaemon.ps1 b/src/PerformanceCounter/Private/Test-IcingaPerformanceCounterDaemon.ps1 index 26973f8..7b02f90 100644 --- a/src/PerformanceCounter/Private/Test-IcingaPerformanceCounterDaemon.ps1 +++ b/src/PerformanceCounter/Private/Test-IcingaPerformanceCounterDaemon.ps1 @@ -18,6 +18,9 @@ PS> if (Test-IcingaPerformanceCounterDaemon) { 'daemon is serving requests' } .NOTES The heartbeat lives at `(Get-GlobalRuntimeVariable).Public.PerformanceCounter.Heartbeat`. A heartbeat older than five seconds is treated as not alive. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Test-IcingaPerformanceCounterDaemon() { diff --git a/src/PerformanceCounter/Private/Update-IcingaPerformanceCounterState.ps1 b/src/PerformanceCounter/Private/Update-IcingaPerformanceCounterState.ps1 index e269891..07df404 100644 --- a/src/PerformanceCounter/Private/Update-IcingaPerformanceCounterState.ps1 +++ b/src/PerformanceCounter/Private/Update-IcingaPerformanceCounterState.ps1 @@ -29,6 +29,9 @@ PS> Update-IcingaPerformanceCounterState Reads configuration (`RefreshIntervalMs`, `EvictionMinutes`) from the store's Config object. Heartbeat is always refreshed so liveness detection stays responsive even under load. The daemon passes its cached store reference to avoid re-resolving it through Get-GlobalRuntimeVariable each cycle. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Update-IcingaPerformanceCounterState() { diff --git a/src/PerformanceCounter/Private/Write-IcingaPerformanceCounterCache.ps1 b/src/PerformanceCounter/Private/Write-IcingaPerformanceCounterCache.ps1 index 782b529..6202ddb 100644 --- a/src/PerformanceCounter/Private/Write-IcingaPerformanceCounterCache.ps1 +++ b/src/PerformanceCounter/Private/Write-IcingaPerformanceCounterCache.ps1 @@ -20,6 +20,9 @@ PS> Write-IcingaPerformanceCounterCache The cache file is `PerformanceCounter.json` under `Get-ModuleCacheDirectory`. Timestamps are stored in ISO 8601 round-trip format so they parse identically on Windows PowerShell 5.1 and PowerShell 7. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Write-IcingaPerformanceCounterCache() { diff --git a/src/PerformanceCounter/Public/Get-IcingaPerformanceCounter.ps1 b/src/PerformanceCounter/Public/Get-IcingaPerformanceCounter.ps1 index ac95969..e18e4e4 100644 --- a/src/PerformanceCounter/Public/Get-IcingaPerformanceCounter.ps1 +++ b/src/PerformanceCounter/Public/Get-IcingaPerformanceCounter.ps1 @@ -64,6 +64,9 @@ A counter without an instance is keyed category-first. .NOTES The request/response transport lives under `(Get-GlobalRuntimeVariable).Public.PerformanceCounter`. Timeouts are logged through `Write-LoggingEntry` at Warning level. No external services are used. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Get-IcingaPerformanceCounter() { diff --git a/src/PerformanceCounter/Public/Show-IcingaPerformanceCounter.ps1 b/src/PerformanceCounter/Public/Show-IcingaPerformanceCounter.ps1 index ff019cd..26b8c56 100644 --- a/src/PerformanceCounter/Public/Show-IcingaPerformanceCounter.ps1 +++ b/src/PerformanceCounter/Public/Show-IcingaPerformanceCounter.ps1 @@ -51,6 +51,9 @@ Lists the concrete per-instance paths that currently exist for the wildcard coun .NOTES Uses `System.Diagnostics.PerformanceCounterCategory` directly. No global state is read or written, and no external services are used. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Show-IcingaPerformanceCounter() { diff --git a/src/PerformanceCounter/Public/Show-IcingaPerformanceCounterDetails.ps1 b/src/PerformanceCounter/Public/Show-IcingaPerformanceCounterDetails.ps1 index 9c50dea..ed2eb35 100644 --- a/src/PerformanceCounter/Public/Show-IcingaPerformanceCounterDetails.ps1 +++ b/src/PerformanceCounter/Public/Show-IcingaPerformanceCounterDetails.ps1 @@ -37,6 +37,9 @@ Shows the live value for a single specified counter. .NOTES This is a thin convenience layer over `Get-IcingaPerformanceCounter`; the same daemon/inline behavior and return shape apply. No external services are used. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Show-IcingaPerformanceCounterDetails() { diff --git a/src/PerformanceCounter/Public/Test-IcingaPerformanceCounterCategory.ps1 b/src/PerformanceCounter/Public/Test-IcingaPerformanceCounterCategory.ps1 index c0d84dc..0a0e819 100644 --- a/src/PerformanceCounter/Public/Test-IcingaPerformanceCounterCategory.ps1 +++ b/src/PerformanceCounter/Public/Test-IcingaPerformanceCounterCategory.ps1 @@ -31,6 +31,9 @@ Extracts the category name from the counter path and returns $true when the cate .NOTES Delegates to `IcingaPerformanceCounter::CategoryExists`. Never throws and reads no global state. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Test-IcingaPerformanceCounterCategory() { diff --git a/src/Plugins/Checks/Public/Invoke-IcingaCheckCPU.ps1 b/src/Plugins/Checks/Public/Invoke-IcingaCheckCPU.ps1 index eade70c..6c928d0 100644 --- a/src/Plugins/Checks/Public/Invoke-IcingaCheckCPU.ps1 +++ b/src/Plugins/Checks/Public/Invoke-IcingaCheckCPU.ps1 @@ -41,14 +41,14 @@ is stored in the thread-local runtime state for the REST API instead. This plugin is Windows-only because it relies on the Windows performance counters. .PARAMETER Warning -| Name | Type | Description | Default | -|---------|---------------|--------------------------------------------------------------------|---------| -| Warning | System.String | Warning threshold in percent, using the Icinga threshold grammar. | | +| Name | Type | Description | Default | +|---------|---------------|-------------------------------------------------------------------|---------| +| Warning | System.String | Warning threshold in percent, using the Icinga threshold grammar. | | .PARAMETER Critical -| Name | Type | Description | Default | -|----------|---------------|---------------------------------------------------------------------|---------| -| Critical | System.String | Critical threshold in percent, using the Icinga threshold grammar. | | +| Name | Type | Description | Default | +|----------|---------------|--------------------------------------------------------------------|---------| +| Critical | System.String | Critical threshold in percent, using the Icinga threshold grammar. | | .PARAMETER Core | Name | Type | Description | Default | @@ -56,9 +56,9 @@ This plugin is Windows-only because it relies on the Windows performance counter | Core | System.String | Core selector: '*' for all cores + totals, '_Total'/'Total' or a core number. | * | .PARAMETER NodeFilter -| Name | Type | Description | Default | -|------------|--------------|---------------------------------------------------------------------------|---------| -| NodeFilter | System.Array | NUMA node IDs to include (wildcards allowed; aliased to SocketFilter). | @() | +| Name | Type | Description | Default | +|------------|--------------|------------------------------------------------------------------------|---------| +| NodeFilter | System.Array | NUMA node IDs to include (wildcards allowed; aliased to SocketFilter). | @() | .PARAMETER OverallOnly | Name | Type | Description | Default | @@ -66,9 +66,9 @@ This plugin is Windows-only because it relies on the Windows performance counter | OverallOnly | System.Management.Automation.SwitchParameter | Collect all cores/nodes, but evaluate Warning/Critical only on Overall Load. | False | .PARAMETER Verbosity -| Name | Type | Description | Default | -|-----------|--------------|------------------------------------------------------------------------------------|---------| -| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config.| 0 | +| Name | Type | Description | Default | +|-----------|--------------|-------------------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | .PARAMETER NoPerfData | Name | Type | Description | Default | @@ -101,6 +101,9 @@ Monitor Users'). Perfdata labels are '_::ifw_cpu::load' with the cor numbered across all nodes, '_total::ifw_cpu::load' and 'totalload::ifw_cpu::load'. The integer exit code is the return value; an Icinga command wrapper is expected to exit with it. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Invoke-IcingaCheckCPU() { diff --git a/src/Plugins/Checks/Public/Invoke-IcingaCheckDirectory.ps1 b/src/Plugins/Checks/Public/Invoke-IcingaCheckDirectory.ps1 index 9a4a91d..39ba36c 100644 --- a/src/Plugins/Checks/Public/Invoke-IcingaCheckDirectory.ps1 +++ b/src/Plugins/Checks/Public/Invoke-IcingaCheckDirectory.ps1 @@ -159,9 +159,9 @@ reported as UNKNOWN with its reason. | OverrideNotFound | System.String | State when nothing matches: Ok, Warning, Critical, Unknown; a missing path counts as empty. | | .PARAMETER Verbosity -| Name | Type | Description | Default | -|-----------|--------------|------------------------------------------------------------------------------------|---------| -| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config.| 0 | +| Name | Type | Description | Default | +|-----------|--------------|-------------------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | .PARAMETER NoPerfData | Name | Type | Description | Default | @@ -190,6 +190,9 @@ Goes critical when no backup file was written within the last day. Windows-only. Reads the file system through Get-IcingaDirectoryInformation; the user needs list permission on every checked directory. The integer exit code is the return value; an Icinga command wrapper is expected to exit with it. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Invoke-IcingaCheckDirectory() { diff --git a/src/Plugins/Checks/Public/Invoke-IcingaCheckMemory.ps1 b/src/Plugins/Checks/Public/Invoke-IcingaCheckMemory.ps1 index addc9fa..96219d7 100644 --- a/src/Plugins/Checks/Public/Invoke-IcingaCheckMemory.ps1 +++ b/src/Plugins/Checks/Public/Invoke-IcingaCheckMemory.ps1 @@ -27,14 +27,14 @@ Performance data uses the labels 'memory::ifw_memory::used', as UNKNOWN with its reason. .PARAMETER Warning -| Name | Type | Description | Default | -|---------|---------------|---------------------------------------------------------------------|---------| -| Warning | System.String | Warning threshold for the used memory, e.g. '80%' or '12GiB'. | | +| Name | Type | Description | Default | +|---------|---------------|---------------------------------------------------------------|---------| +| Warning | System.String | Warning threshold for the used memory, e.g. '80%' or '12GiB'. | | .PARAMETER Critical -| Name | Type | Description | Default | -|----------|---------------|---------------------------------------------------------------------|---------| -| Critical | System.String | Critical threshold for the used memory, e.g. '90%' or '14GiB'. | | +| Name | Type | Description | Default | +|----------|---------------|----------------------------------------------------------------|---------| +| Critical | System.String | Critical threshold for the used memory, e.g. '90%' or '14GiB'. | | .PARAMETER PageFileWarning | Name | Type | Description | Default | @@ -47,29 +47,29 @@ as UNKNOWN with its reason. | PageFileCritical | System.String | Critical threshold for every page file, e.g. '90%' or '3GiB'. | | .PARAMETER MemoryPagesSecWarning -| Name | Type | Description | Default | -|-----------------------|---------------|-----------------------------------------------|---------| -| MemoryPagesSecWarning | System.String | Warning threshold for the memory pages/sec. | | +| Name | Type | Description | Default | +|-----------------------|---------------|---------------------------------------------|---------| +| MemoryPagesSecWarning | System.String | Warning threshold for the memory pages/sec. | | .PARAMETER MemoryPagesSecCritical -| Name | Type | Description | Default | -|------------------------|---------------|-----------------------------------------------|---------| -| MemoryPagesSecCritical | System.String | Critical threshold for the memory pages/sec. | | +| Name | Type | Description | Default | +|------------------------|---------------|----------------------------------------------|---------| +| MemoryPagesSecCritical | System.String | Critical threshold for the memory pages/sec. | | .PARAMETER IncludePageFile -| Name | Type | Description | Default | -|-----------------|--------------|----------------------------------------------------------|---------| -| IncludePageFile | System.Array | Only check page files matching these names (wildcards). | @() | +| Name | Type | Description | Default | +|-----------------|--------------|---------------------------------------------------------|---------| +| IncludePageFile | System.Array | Only check page files matching these names (wildcards). | @() | .PARAMETER ExcludePageFile -| Name | Type | Description | Default | -|-----------------|--------------|------------------------------------------------------|---------| -| ExcludePageFile | System.Array | Skip page files matching these names (wildcards). | @() | +| Name | Type | Description | Default | +|-----------------|--------------|---------------------------------------------------|---------| +| ExcludePageFile | System.Array | Skip page files matching these names (wildcards). | @() | .PARAMETER Verbosity -| Name | Type | Description | Default | -|-----------|--------------|------------------------------------------------------------------------------------|---------| -| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config.| 0 | +| Name | Type | Description | Default | +|-----------|--------------|-------------------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | .PARAMETER NoPerfData | Name | Type | Description | Default | @@ -94,6 +94,9 @@ Windows-only. Reads the '\Memory\Available Bytes' and '\Memory\Pages/sec' performance counters ('Performance Monitor Users') and the Win32_ComputerSystem, Win32_PageFileUsage and Win32_PageFileSetting CIM classes. The integer exit code is the return value; an Icinga command wrapper is expected to exit with it. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Invoke-IcingaCheckMemory() { diff --git a/src/Plugins/Checks/Public/Invoke-IcingaCheckPartitionSpace.ps1 b/src/Plugins/Checks/Public/Invoke-IcingaCheckPartitionSpace.ps1 index 132caa6..2cd5dff 100644 --- a/src/Plugins/Checks/Public/Invoke-IcingaCheckPartitionSpace.ps1 +++ b/src/Plugins/Checks/Public/Invoke-IcingaCheckPartitionSpace.ps1 @@ -66,9 +66,9 @@ Windows-only because it relies on the Win32_Volume CIM class. | SkipUnknown | System.Management.Automation.SwitchParameter | Report OK instead of UNKNOWN for a volume without size data. | False | .PARAMETER Verbosity -| Name | Type | Description | Default | -|-----------|--------------|------------------------------------------------------------------------------------|---------| -| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config.| 0 | +| Name | Type | Description | Default | +|-----------|--------------|-------------------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | .PARAMETER NoPerfData | Name | Type | Description | Default | @@ -97,6 +97,9 @@ Also reports CRITICAL when E: is missing and lists every partition in the output Windows-only. Reads Win32_Volume and MSFT_Partition through Get-IcingaDiskInformation. The integer exit code is the return value; an Icinga command wrapper is expected to exit with it. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Invoke-IcingaCheckPartitionSpace() { diff --git a/src/Plugins/Checks/Public/Invoke-IcingaCheckPerfCounter.ps1 b/src/Plugins/Checks/Public/Invoke-IcingaCheckPerfCounter.ps1 index 8e979d2..69ac4b1 100644 --- a/src/Plugins/Checks/Public/Invoke-IcingaCheckPerfCounter.ps1 +++ b/src/Plugins/Checks/Public/Invoke-IcingaCheckPerfCounter.ps1 @@ -36,9 +36,9 @@ with '%' spelled out as 'percent', for example 'memory::ifw_perfcounter::availablebytes' for a counter without an instance. .PARAMETER PerfCounter -| Name | Type | Description | Default | -|-------------|--------------|---------------------------------------------------------------|---------| -| PerfCounter | System.Array | Counter paths to check, e.g. '\Processor(*)\% Processor Time'.| @() | +| Name | Type | Description | Default | +|-------------|--------------|----------------------------------------------------------------|---------| +| PerfCounter | System.Array | Counter paths to check, e.g. '\Processor(*)\% Processor Time'. | @() | .PARAMETER Warning | Name | Type | Description | Default | @@ -66,9 +66,9 @@ with '%' spelled out as 'percent', for example | IgnoreEmptyChecks | System.Management.Automation.SwitchParameter | Return OK instead of UNKNOWN when no counter remains to check. | False | .PARAMETER Verbosity -| Name | Type | Description | Default | -|-----------|--------------|------------------------------------------------------------------------------------|---------| -| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config.| 0 | +| Name | Type | Description | Default | +|-----------|--------------|-------------------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | .PARAMETER NoPerfData | Name | Type | Description | Default | @@ -92,6 +92,9 @@ Checks two concrete counters against the same critical threshold. Windows-only. Reads the Windows performance counters; the user needs read access to them ('Performance Monitor Users'). The integer exit code is the return value; an Icinga command wrapper is expected to exit with it. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Invoke-IcingaCheckPerfCounter() { diff --git a/src/Plugins/Checks/Public/Invoke-IcingaCheckProcess.ps1 b/src/Plugins/Checks/Public/Invoke-IcingaCheckProcess.ps1 index 73be18d..c62a3fa 100644 --- a/src/Plugins/Checks/Public/Invoke-IcingaCheckProcess.ps1 +++ b/src/Plugins/Checks/Public/Invoke-IcingaCheckProcess.ps1 @@ -29,44 +29,44 @@ Performance data is written for the summary only, with the labels '::ifw_process::cpu', '::memory', '::pagefile', '::threads' and '::count'. .PARAMETER PageFileWarning -| Name | Type | Description | Default | -|-----------------|---------------|-----------------------------------------------------------------|---------| -| PageFileWarning | System.String | Warning threshold for the page file usage of each process. | | +| Name | Type | Description | Default | +|-----------------|---------------|------------------------------------------------------------|---------| +| PageFileWarning | System.String | Warning threshold for the page file usage of each process. | | .PARAMETER PageFileCritical -| Name | Type | Description | Default | -|------------------|---------------|-----------------------------------------------------------------|---------| -| PageFileCritical | System.String | Critical threshold for the page file usage of each process. | | +| Name | Type | Description | Default | +|------------------|---------------|-------------------------------------------------------------|---------| +| PageFileCritical | System.String | Critical threshold for the page file usage of each process. | | .PARAMETER MemoryWarning -| Name | Type | Description | Default | -|---------------|---------------|-------------------------------------------------------------|---------| -| MemoryWarning | System.String | Warning threshold for the memory usage of each process. | | +| Name | Type | Description | Default | +|---------------|---------------|---------------------------------------------------------|---------| +| MemoryWarning | System.String | Warning threshold for the memory usage of each process. | | .PARAMETER MemoryCritical -| Name | Type | Description | Default | -|----------------|---------------|-------------------------------------------------------------|---------| -| MemoryCritical | System.String | Critical threshold for the memory usage of each process. | | +| Name | Type | Description | Default | +|----------------|---------------|----------------------------------------------------------|---------| +| MemoryCritical | System.String | Critical threshold for the memory usage of each process. | | .PARAMETER CPUWarning -| Name | Type | Description | Default | -|------------|---------------|----------------------------------------------------------|---------| -| CPUWarning | System.String | Warning threshold for the CPU usage of each process. | | +| Name | Type | Description | Default | +|------------|---------------|------------------------------------------------------|---------| +| CPUWarning | System.String | Warning threshold for the CPU usage of each process. | | .PARAMETER CPUCritical -| Name | Type | Description | Default | -|-------------|---------------|----------------------------------------------------------|---------| -| CPUCritical | System.String | Critical threshold for the CPU usage of each process. | | +| Name | Type | Description | Default | +|-------------|---------------|-------------------------------------------------------|---------| +| CPUCritical | System.String | Critical threshold for the CPU usage of each process. | | .PARAMETER ThreadCountWarning -| Name | Type | Description | Default | -|--------------------|---------------|------------------------------------------------------------|---------| -| ThreadCountWarning | System.String | Warning threshold for the thread count of each process. | | +| Name | Type | Description | Default | +|--------------------|---------------|---------------------------------------------------------|---------| +| ThreadCountWarning | System.String | Warning threshold for the thread count of each process. | | .PARAMETER ThreadCountCritical -| Name | Type | Description | Default | -|---------------------|---------------|------------------------------------------------------------|---------| -| ThreadCountCritical | System.String | Critical threshold for the thread count of each process. | | +| Name | Type | Description | Default | +|---------------------|---------------|----------------------------------------------------------|---------| +| ThreadCountCritical | System.String | Critical threshold for the thread count of each process. | | .PARAMETER TotalPageFileWarning | Name | Type | Description | Default | @@ -99,14 +99,14 @@ Performance data is written for the summary only, with the labels | TotalCPUCritical | System.String | Critical threshold for the CPU usage of all processes of a name. | | .PARAMETER TotalThreadCountWarning -| Name | Type | Description | Default | -|-------------------------|---------------|-------------------------------------------------------------------|---------| -| TotalThreadCountWarning | System.String | Warning threshold for the thread count of all processes of a name.| | +| Name | Type | Description | Default | +|-------------------------|---------------|--------------------------------------------------------------------|---------| +| TotalThreadCountWarning | System.String | Warning threshold for the thread count of all processes of a name. | | .PARAMETER TotalThreadCountCritical -| Name | Type | Description | Default | -|--------------------------|---------------|--------------------------------------------------------------------|---------| -| TotalThreadCountCritical | System.String | Critical threshold for the thread count of all processes of a name.| | +| Name | Type | Description | Default | +|--------------------------|---------------|---------------------------------------------------------------------|---------| +| TotalThreadCountCritical | System.String | Critical threshold for the thread count of all processes of a name. | | .PARAMETER TotalProcessCountWarning | Name | Type | Description | Default | @@ -129,14 +129,14 @@ Performance data is written for the summary only, with the labels | ExcludeProcess | System.Array | Process names to skip, wildcards allowed. | @() | .PARAMETER OverrideNotFound -| Name | Type | Description | Default | -|------------------|---------------|-------------------------------------------------------------------------------|---------| -| OverrideNotFound | System.String | State for a Process entry without a match: Ok, Warning, Critical or Unknown. | Unknown | +| Name | Type | Description | Default | +|------------------|---------------|------------------------------------------------------------------------------|---------| +| OverrideNotFound | System.String | State for a Process entry without a match: Ok, Warning, Critical or Unknown. | Unknown | .PARAMETER Verbosity -| Name | Type | Description | Default | -|-----------|--------------|------------------------------------------------------------------------------------|---------| -| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config.| 0 | +| Name | Type | Description | Default | +|-----------|--------------|-------------------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | .PARAMETER NoPerfData | Name | Type | Description | Default | @@ -162,6 +162,9 @@ Windows-only. Reads the '\Process(*)' performance counters ('Performance Monitor Users'), '\Memory\Commit Limit' and the Win32_ComputerSystem CIM class through Get-IcingaProcessInformation. The integer exit code is the return value; an Icinga command wrapper is expected to exit with it. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Invoke-IcingaCheckProcess() { diff --git a/src/Plugins/Checks/Public/Invoke-IcingaCheckScheduledTask.ps1 b/src/Plugins/Checks/Public/Invoke-IcingaCheckScheduledTask.ps1 index d462687..3b1d2e7 100644 --- a/src/Plugins/Checks/Public/Invoke-IcingaCheckScheduledTask.ps1 +++ b/src/Plugins/Checks/Public/Invoke-IcingaCheckScheduledTask.ps1 @@ -31,24 +31,24 @@ Performance data uses the labels '::ifw_scheduledtask::state', '::missedruns', '::lasttaskresult', '::lastruntime' and '::nextruntime'. .PARAMETER TaskName -| Name | Type | Description | Default | -|----------|--------------|-------------------------------------------------------------------------------|---------| -| TaskName | System.Array | Task names to check (wildcards allowed; plain names must exist). | @() | +| Name | Type | Description | Default | +|----------|--------------|------------------------------------------------------------------|---------| +| TaskName | System.Array | Task names to check (wildcards allowed; plain names must exist). | @() | .PARAMETER ExcludeTaskName -| Name | Type | Description | Default | -|-----------------|--------------|------------------------------------------------------------------------|---------| -| ExcludeTaskName | System.Array | Task names to exclude from the check (wildcards allowed). | @() | +| Name | Type | Description | Default | +|-----------------|--------------|-----------------------------------------------------------|---------| +| ExcludeTaskName | System.Array | Task names to exclude from the check (wildcards allowed). | @() | .PARAMETER TaskPath -| Name | Type | Description | Default | -|----------|--------------|-------------------------------------------------------------------------------|---------| -| TaskPath | System.Array | Task folder paths to include (wildcards allowed, e.g. '\Icinga\*'). | @() | +| Name | Type | Description | Default | +|----------|--------------|---------------------------------------------------------------------|---------| +| TaskPath | System.Array | Task folder paths to include (wildcards allowed, e.g. '\Icinga\*'). | @() | .PARAMETER ExcludeTaskPath -| Name | Type | Description | Default | -|-----------------|--------------|------------------------------------------------------------------------|---------| -| ExcludeTaskPath | System.Array | Task folder paths to exclude (wildcards allowed). | @() | +| Name | Type | Description | Default | +|-----------------|--------------|---------------------------------------------------|---------| +| ExcludeTaskPath | System.Array | Task folder paths to exclude (wildcards allowed). | @() | .PARAMETER State | Name | Type | Description | Default | @@ -61,49 +61,49 @@ Performance data uses the labels '::ifw_scheduledtask::state', | IgnoreExitCodes | System.Array | Non-zero task exit codes to treat as OK (decimal or hex, e.g. 267009). | @() | .PARAMETER WarningMissedRuns -| Name | Type | Description | Default | -|-------------------|---------------|---------------------------------------------------------------------|---------| -| WarningMissedRuns | System.String | Warning threshold for the number of missed runs. | | +| Name | Type | Description | Default | +|-------------------|---------------|--------------------------------------------------|---------| +| WarningMissedRuns | System.String | Warning threshold for the number of missed runs. | | .PARAMETER CriticalMissedRuns -| Name | Type | Description | Default | -|--------------------|---------------|--------------------------------------------------------------------|---------| -| CriticalMissedRuns | System.String | Critical threshold for the number of missed runs. | | +| Name | Type | Description | Default | +|--------------------|---------------|---------------------------------------------------|---------| +| CriticalMissedRuns | System.String | Critical threshold for the number of missed runs. | | .PARAMETER WarningLastRunTime -| Name | Type | Description | Default | -|--------------------|---------------|--------------------------------------------------------------------|---------| -| WarningLastRunTime | System.String | Warning threshold for the age of the last run (e.g. '1d', '12h'). | | +| Name | Type | Description | Default | +|--------------------|---------------|-------------------------------------------------------------------|---------| +| WarningLastRunTime | System.String | Warning threshold for the age of the last run (e.g. '1d', '12h'). | | .PARAMETER CriticalLastRunTime -| Name | Type | Description | Default | -|---------------------|---------------|-------------------------------------------------------------------|---------| -| CriticalLastRunTime | System.String | Critical threshold for the age of the last run (e.g. '2d', '24h').| | +| Name | Type | Description | Default | +|---------------------|---------------|--------------------------------------------------------------------|---------| +| CriticalLastRunTime | System.String | Critical threshold for the age of the last run (e.g. '2d', '24h'). | | .PARAMETER WarningNextRunTime -| Name | Type | Description | Default | -|--------------------|---------------|--------------------------------------------------------------------|---------| -| WarningNextRunTime | System.String | Warning threshold for the next run offset (e.g. '10m', '-1h:'). | | +| Name | Type | Description | Default | +|--------------------|---------------|-----------------------------------------------------------------|---------| +| WarningNextRunTime | System.String | Warning threshold for the next run offset (e.g. '10m', '-1h:'). | | .PARAMETER CriticalNextRunTime -| Name | Type | Description | Default | -|---------------------|---------------|-------------------------------------------------------------------|---------| -| CriticalNextRunTime | System.String | Critical threshold for the next run offset (e.g. '30m', '-2h:'). | | +| Name | Type | Description | Default | +|---------------------|---------------|------------------------------------------------------------------|---------| +| CriticalNextRunTime | System.String | Critical threshold for the next run offset (e.g. '30m', '-2h:'). | | .PARAMETER IgnoreLastRunTime -| Name | Type | Description | Default | -|-------------------|----------------------------------------------|----------------------------------------------------|---------| -| IgnoreLastRunTime | System.Management.Automation.SwitchParameter | Do not alert on non-zero Last Task Result codes. | False | +| Name | Type | Description | Default | +|-------------------|----------------------------------------------|--------------------------------------------------|---------| +| IgnoreLastRunTime | System.Management.Automation.SwitchParameter | Do not alert on non-zero Last Task Result codes. | False | .PARAMETER MitigateUnknown -| Name | Type | Description | Default | -|-----------------|----------------------------------------------|--------------------------------------------------------------|---------| -| MitigateUnknown | System.Management.Automation.SwitchParameter | Return OK instead of UNKNOWN when no task matches the filter.| False | +| Name | Type | Description | Default | +|-----------------|----------------------------------------------|---------------------------------------------------------------|---------| +| MitigateUnknown | System.Management.Automation.SwitchParameter | Return OK instead of UNKNOWN when no task matches the filter. | False | .PARAMETER OverrideNotFound -| Name | Type | Description | Default | -|------------------|---------------|---------------------------------------------------------------------------|---------| -| OverrideNotFound | System.String | State for missing required tasks ('Ok', 'Warning', 'Critical', 'Unknown').| Unknown | +| Name | Type | Description | Default | +|------------------|---------------|----------------------------------------------------------------------------|---------| +| OverrideNotFound | System.String | State for missing required tasks ('Ok', 'Warning', 'Critical', 'Unknown'). | Unknown | .PARAMETER Verbosity | Name | Type | Description | Default | @@ -131,6 +131,9 @@ Checks all tasks under \Icinga\ for Ready or Running state and warns if a task h .NOTES Windows-only. Queries tasks through Get-IcingaScheduledTask. The integer exit code is the return value; an Icinga command wrapper is expected to exit with it. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Invoke-IcingaCheckScheduledTask() { diff --git a/src/Plugins/Checks/Public/Invoke-IcingaCheckService.ps1 b/src/Plugins/Checks/Public/Invoke-IcingaCheckService.ps1 index fe1ad4b..997e733 100644 --- a/src/Plugins/Checks/Public/Invoke-IcingaCheckService.ps1 +++ b/src/Plugins/Checks/Public/Invoke-IcingaCheckService.ps1 @@ -36,9 +36,9 @@ This plugin is Windows-only because it relies on the Win32_Service CIM class. | Exclude | System.Array | Service names or display names to skip, wildcards allowed. | @() | .PARAMETER Status -| Name | Type | Description | Default | -|--------|-----------------------|----------------------------------------------------------------------------------------------------------------------------------------|------------| -| Status | IcingaServiceStatus[] | Expected status(es) of the given services: Stopped, StartPending, StopPending, Running, ContinuePending, PausePending, Paused, Unknown.| @(Running) | +| Name | Type | Description | Default | +|--------|-----------------------|-----------------------------------------------------------------------------------------------------------------------------------------|------------| +| Status | IcingaServiceStatus[] | Expected status(es) of the given services: Stopped, StartPending, StopPending, Running, ContinuePending, PausePending, Paused, Unknown. | @(Running) | .PARAMETER FilterStartupType | Name | Type | Description | Default | @@ -61,9 +61,9 @@ This plugin is Windows-only because it relies on the Win32_Service CIM class. | OverrideNotFound | System.String | State for a given service that does not exist: Ok, Warning, Critical, Unknown. | Unknown | .PARAMETER Verbosity -| Name | Type | Description | Default | -|-----------|--------------|------------------------------------------------------------------------------------|---------| -| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config.| 0 | +| Name | Type | Description | Default | +|-----------|--------------|-------------------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | .PARAMETER NoPerfData | Name | Type | Description | Default | @@ -94,6 +94,9 @@ Windows-only. Reads the Win32_Service CIM class through Get-IcingaWindowsInformation; a failed query is reported as UNKNOWN with its reason. The integer exit code is the return value; an Icinga command wrapper is expected to exit with it. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Invoke-IcingaCheckService() { diff --git a/src/Plugins/Checks/Public/Invoke-IcingaCheckUptime.ps1 b/src/Plugins/Checks/Public/Invoke-IcingaCheckUptime.ps1 index 7ba70bd..8eb275d 100644 --- a/src/Plugins/Checks/Public/Invoke-IcingaCheckUptime.ps1 +++ b/src/Plugins/Checks/Public/Invoke-IcingaCheckUptime.ps1 @@ -19,19 +19,19 @@ with the counter error. Performance data uses the label 'windows::ifw_uptime::uptime' in seconds. .PARAMETER Warning -| Name | Type | Description | Default | -|---------|---------------|----------------------------------------------------------|---------| -| Warning | System.String | Warning threshold as duration or range, e.g. '1d:'. | | +| Name | Type | Description | Default | +|---------|---------------|-----------------------------------------------------|---------| +| Warning | System.String | Warning threshold as duration or range, e.g. '1d:'. | | .PARAMETER Critical -| Name | Type | Description | Default | -|----------|---------------|----------------------------------------------------------|---------| -| Critical | System.String | Critical threshold as duration or range, e.g. '30m:'. | | +| Name | Type | Description | Default | +|----------|---------------|-------------------------------------------------------|---------| +| Critical | System.String | Critical threshold as duration or range, e.g. '30m:'. | | .PARAMETER Verbosity -| Name | Type | Description | Default | -|-----------|--------------|------------------------------------------------------------------------------------|---------| -| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config.| 0 | +| Name | Type | Description | Default | +|-----------|--------------|-------------------------------------------------------------------------------------|---------| +| Verbosity | System.Int32 | Output detail: 0 problems only, 1 plus affected siblings, 2 all, 3 all plus config. | 0 | .PARAMETER NoPerfData | Name | Type | Description | Default | @@ -56,6 +56,9 @@ Windows-only. Reads the '\System\System Up Time' performance counter; the user needs read access to the performance counters ('Performance Monitor Users'). The integer exit code is the return value; an Icinga command wrapper is expected to exit with it. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Invoke-IcingaCheckUptime() { diff --git a/src/Plugins/Lib/Public/New-IcingaPlugin.ps1 b/src/Plugins/Lib/Public/New-IcingaPlugin.ps1 index 3f3da76..f3f5333 100644 --- a/src/Plugins/Lib/Public/New-IcingaPlugin.ps1 +++ b/src/Plugins/Lib/Public/New-IcingaPlugin.ps1 @@ -16,9 +16,9 @@ in parentheses to chain methods directly, for example positional in the order Name, Value, Unit. .PARAMETER Name -| Name | Type | Description | Default | -|------|---------------|--------------------------------------|---------| -| Name | System.String | Display name of the plugin node. | $null | +| Name | Type | Description | Default | +|------|---------------|----------------------------------|---------| +| Name | System.String | Display name of the plugin node. | $null | .PARAMETER Value | Name | Type | Description | Default | @@ -53,6 +53,9 @@ background thread waits until the main runspace is idle, which stalls daemons an 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. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function New-IcingaPlugin() { diff --git a/src/Plugins/Provider/Disk/Private/Get-IcingaDiskInformation.ps1 b/src/Plugins/Provider/Disk/Private/Get-IcingaDiskInformation.ps1 index f995cc8..7916e29 100644 --- a/src/Plugins/Provider/Disk/Private/Get-IcingaDiskInformation.ps1 +++ b/src/Plugins/Provider/Disk/Private/Get-IcingaDiskInformation.ps1 @@ -32,9 +32,9 @@ DiskInformationDiskQueryFailed), so the log shows where the collection stopped. | Entrypoint | System.String | View to return: 'PhysicalDisk', 'Partition' or 'Volume'. | PhysicalDisk | .PARAMETER SkipPartitionMapping -| Name | Type | Description | Default | -|----------------------|----------------------------------------------|-----------------------------------------------------------------------|---------| -| SkipPartitionMapping | System.Management.Automation.SwitchParameter | Skip querying MSFT_Partition when Entrypoint is set to 'Volume'. | $false | +| Name | Type | Description | Default | +|----------------------|----------------------------------------------|------------------------------------------------------------------|---------| +| SkipPartitionMapping | System.Management.Automation.SwitchParameter | Skip querying MSFT_Partition when Entrypoint is set to 'Volume'. | $false | .OUTPUTS System.Collections.Hashtable -- The entries of the requested view, or an @@ -72,6 +72,9 @@ Windows-only. Reads root/cimv2 (Win32_Volume), root/Microsoft/Windows/Storage (MSFT_Disk, MSFT_PhysicalDisk, MSFT_Partition) and root/wmi (MPIO_DISK_INFO). Standard users can read all of them. Spanned volumes are linked to the first partition reporting them. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Get-IcingaDiskInformation() { diff --git a/src/Plugins/Provider/FileSystem/Private/Get-IcingaDirectoryInformation.ps1 b/src/Plugins/Provider/FileSystem/Private/Get-IcingaDirectoryInformation.ps1 index dff6dad..15de989 100644 --- a/src/Plugins/Provider/FileSystem/Private/Get-IcingaDirectoryInformation.ps1 +++ b/src/Plugins/Provider/FileSystem/Private/Get-IcingaDirectoryInformation.ps1 @@ -128,6 +128,9 @@ Returns every log file larger than 100MB below D:\Logs together with the statist Reads the file system through System.IO.DirectoryInfo; the user needs list permission on every scanned directory. Relative paths are resolved against the current PowerShell file system location. No external services are used. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Get-IcingaDirectoryInformation() { diff --git a/src/Plugins/Provider/Process/Private/Get-IcingaProcessInformation.ps1 b/src/Plugins/Provider/Process/Private/Get-IcingaProcessInformation.ps1 index 3491f13..9b93a75 100644 --- a/src/Plugins/Provider/Process/Private/Get-IcingaProcessInformation.ps1 +++ b/src/Plugins/Provider/Process/Private/Get-IcingaProcessInformation.ps1 @@ -34,9 +34,9 @@ PowerShell 5.1. | Include | System.Array | Only collect processes matching these names (wildcards). | @() | .PARAMETER Exclude -| Name | Type | Description | Default | -|---------|--------------|-----------------------------------------------------|---------| -| Exclude | System.Array | Skip processes matching these names (wildcards). | @() | +| Name | Type | Description | Default | +|---------|--------------|--------------------------------------------------|---------| +| Exclude | System.Array | Skip processes matching these names (wildcards). | @() | .OUTPUTS System.Collections.Hashtable -- Keys Processes, MemoryTotal, CommitLimit and @@ -55,6 +55,9 @@ Returns the summed usage of all PowerShell processes. Windows-only. Reads the '\Process(*)' performance counters ('Performance Monitor Users'), '\Memory\Commit Limit' and the Win32_ComputerSystem CIM class. Without a running daemon the first call in a runspace waits for the counter warm-up. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Get-IcingaProcessInformation() { diff --git a/src/Plugins/Provider/ScheduledTask/Private/Get-IcingaScheduledTask.ps1 b/src/Plugins/Provider/ScheduledTask/Private/Get-IcingaScheduledTask.ps1 index 9307cce..0740fd3 100644 --- a/src/Plugins/Provider/ScheduledTask/Private/Get-IcingaScheduledTask.ps1 +++ b/src/Plugins/Provider/ScheduledTask/Private/Get-IcingaScheduledTask.ps1 @@ -21,9 +21,9 @@ grouped by TaskPath and sorted by TaskName. | TaskName | System.Array | Only collect tasks matching these names (wildcards allowed). | @() | .PARAMETER ExcludeTaskName -| Name | Type | Description | Default | -|-----------------|--------------|--------------------------------------------------------------|---------| -| ExcludeTaskName | System.Array | Skip tasks matching these names (wildcards allowed). | @() | +| Name | Type | Description | Default | +|-----------------|--------------|------------------------------------------------------|---------| +| ExcludeTaskName | System.Array | Skip tasks matching these names (wildcards allowed). | @() | .PARAMETER TaskPath | Name | Type | Description | Default | @@ -31,9 +31,9 @@ grouped by TaskPath and sorted by TaskName. | TaskPath | System.Array | Only collect tasks matching these paths (wildcards allowed). | @() | .PARAMETER ExcludeTaskPath -| Name | Type | Description | Default | -|-----------------|--------------|--------------------------------------------------------------|---------| -| ExcludeTaskPath | System.Array | Skip tasks matching these paths (wildcards allowed). | @() | +| Name | Type | Description | Default | +|-----------------|--------------|------------------------------------------------------|---------| +| ExcludeTaskPath | System.Array | Skip tasks matching these paths (wildcards allowed). | @() | .OUTPUTS System.Collections.Hashtable -- Hashtable with keys Tasks (hashtable keyed by @@ -48,6 +48,9 @@ Returns all scheduled tasks under the \Icinga\ task path hierarchy. .NOTES Windows-only. Relies on Get-ScheduledTask and Get-ScheduledTaskInfo from the ScheduledTasks module. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Get-IcingaScheduledTask() { diff --git a/src/Security/Private/Get-FileEncoding.ps1 b/src/Security/Private/Get-FileEncoding.ps1 index c1e3e84..7704db7 100644 --- a/src/Security/Private/Get-FileEncoding.ps1 +++ b/src/Security/Private/Get-FileEncoding.ps1 @@ -8,18 +8,21 @@ marks (BOM) and falls back to heuristics to distinguish ASCII and UTF8 when no B is present. Returns a short encoding identifier string. .PARAMETER Path -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Path | System.String | Path to the file to inspect | '' | +| Name | Type | Description | Default | +|------|---------------|-----------------------------|---------| +| Path | System.String | Path to the file to inspect | '' | .OUTPUTS -System.String — One of: UTF8-BOM, UTF8, Unicode, BigEndianUnicode, UTF7, UTF32, ASCII. +System.String -- One of: UTF8-BOM, UTF8, Unicode, BigEndianUnicode, UTF7, UTF32, ASCII. .EXAMPLE Get-FileEncoding -Path (Join-Path (Get-ModuleConfigDirectory) 'settings.json') .NOTES - Returns a cmdlet-style error via `Write-FunctionReturnValue` when the file is not found. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Get-FileEncoding() { diff --git a/src/Security/Private/Get-SecureChildItem.ps1 b/src/Security/Private/Get-SecureChildItem.ps1 index 0000277..0ff8aca 100644 --- a/src/Security/Private/Get-SecureChildItem.ps1 +++ b/src/Security/Private/Get-SecureChildItem.ps1 @@ -20,19 +20,19 @@ enumerated child items via -OverrideReturn on success or $null on error. | Filter | System.String | File name filter (for example '*.json'). | '*' | .PARAMETER Include -| Name | Type | Description | Default | -|---------|--------------|-------------------------------------------------|---------| -| Include | System.Array | Additional include patterns for Get-ChildItem. | @() | +| Name | Type | Description | Default | +|---------|--------------|------------------------------------------------|---------| +| Include | System.Array | Additional include patterns for Get-ChildItem. | @() | .PARAMETER File -| Name | Type | Description | Default | -|------|----------------------------------------------|---------------------------|---------| -| File | System.Management.Automation.SwitchParameter | If set, only return files.| $false | +| Name | Type | Description | Default | +|------|----------------------------------------------|----------------------------|---------| +| File | System.Management.Automation.SwitchParameter | If set, only return files. | $false | .PARAMETER Directory -| Name | Type | Description | Default | -|-----------|----------------------------------------------|---------------------------------|---------| -| Directory | System.Management.Automation.SwitchParameter | If set, only return directories.| $false | +| Name | Type | Description | Default | +|-----------|----------------------------------------------|----------------------------------|---------| +| Directory | System.Management.Automation.SwitchParameter | If set, only return directories. | $false | .PARAMETER Recurse | Name | Type | Description | Default | @@ -49,6 +49,9 @@ PS> Get-SecureChildItem -Path (Get-ModuleConfigDirectory) -File .NOTES This helper logs attempted access to unapproved paths and returns AccessViolation. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Get-SecureChildItem() { diff --git a/src/Security/Private/New-SecureItem.ps1 b/src/Security/Private/New-SecureItem.ps1 index b4f80e3..14e3000 100644 --- a/src/Security/Private/New-SecureItem.ps1 +++ b/src/Security/Private/New-SecureItem.ps1 @@ -9,22 +9,22 @@ Returns standardized return values via `Write-FunctionReturnValue` and logs unauthorized attempts. .PARAMETER Path -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Path | System.String | Path to create (file or directory). | $null | +| Name | Type | Description | Default | +|------|---------------|-------------------------------------|---------| +| Path | System.String | Path to create (file or directory). | $null | .PARAMETER ItemType -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ItemType | System.String | 'File' or 'Directory'. | 'File' | +| Name | Type | Description | Default | +|----------|---------------|------------------------|---------| +| ItemType | System.String | 'File' or 'Directory'. | 'File' | .PARAMETER Force -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Force | System.Management.Automation.SwitchParameter | Pass `-Force` to `New-Item` to overwrite existing items. | $false | +| Name | Type | Description | Default | +|-------|----------------------------------------------|----------------------------------------------------------|---------| +| Force | System.Management.Automation.SwitchParameter | Pass `-Force` to `New-Item` to overwrite existing items. | $false | .OUTPUTS -PSCustomObject — Function return value via Write-FunctionReturnValue. +PSCustomObject -- Function return value via Write-FunctionReturnValue. ObjectCreationSucceeded on success (Data contains Path, ItemType and Item). ObjectCreationFailed, AccessViolation or DirectoryArgumentEmpty on errors. @@ -34,6 +34,9 @@ PS> New-SecureItem -Path (Join-Path (Get-ModuleConfigDirectory) 'my.conf') -Item .NOTES Intended for use when module code must create config files; restricts creation to module config directories only. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function New-SecureItem() { diff --git a/src/Security/Private/Read-SecureFile.ps1 b/src/Security/Private/Read-SecureFile.ps1 index c10c1a9..c273278 100644 --- a/src/Security/Private/Read-SecureFile.ps1 +++ b/src/Security/Private/Read-SecureFile.ps1 @@ -9,12 +9,12 @@ assembling the file content. Returns standardized return values via `Write-FunctionReturnValue`. .PARAMETER File -| Name | Type | Description | Default | -|------|------|-------------|---------| -| File | System.String | Path to the file to read. | $null | +| Name | Type | Description | Default | +|------|---------------|---------------------------|---------| +| File | System.String | Path to the file to read. | $null | .OUTPUTS -System.String — File content on success (returned as raw override via Write-FunctionReturnValue). +System.String -- File content on success (returned as raw override via Write-FunctionReturnValue). ObjectReadSucceeded on success (Data contains Path and Content). FileNotFound, AccessViolation or FileLockException on errors. @@ -24,6 +24,9 @@ PS> Read-SecureFile -File (Join-Path (Get-ModuleConfigDirectory) 'settings.json' .NOTES This helper attempts to open the file for up to ~5 seconds before failing with `FileLockException`. Use for reading module configuration files safely. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Read-SecureFile() { @@ -66,8 +69,8 @@ function Read-SecureFile() $UTF8BOM = $TRUE; } - $UTF8Encoding = New-Object System.Text.UTF8Encoding $UTF8BOM; - $FileContent = ''; + $UTF8Encoding = New-Object System.Text.UTF8Encoding $UTF8BOM; + $FileContent = ''; while ($FileStream.Read($ReadArray, 0 , $ReadArray.Length)) { $FileContent = [System.String]::Concat($FileContent, $UTF8Encoding.GetString($ReadArray)); diff --git a/src/Security/Private/Remove-SecureItem.ps1 b/src/Security/Private/Remove-SecureItem.ps1 index cc83bbb..ff40cf5 100644 --- a/src/Security/Private/Remove-SecureItem.ps1 +++ b/src/Security/Private/Remove-SecureItem.ps1 @@ -8,22 +8,22 @@ directories. Logs unauthorized attempts and returns structured return values using `Write-FunctionReturnValue`. .PARAMETER Path -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Path | System.String | Path to remove. | '' | +| Name | Type | Description | Default | +|------|---------------|-----------------|---------| +| Path | System.String | Path to remove. | '' | .PARAMETER Recurse -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Recurse | System.Management.Automation.SwitchParameter | Remove child items recursively. | $false | +| Name | Type | Description | Default | +|---------|----------------------------------------------|---------------------------------|---------| +| Recurse | System.Management.Automation.SwitchParameter | Remove child items recursively. | $false | .PARAMETER Force -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Force | System.Management.Automation.SwitchParameter | Force deletion (pass `-Force` to `Remove-Item`). | $false | +| Name | Type | Description | Default | +|-------|----------------------------------------------|--------------------------------------------------|---------| +| Force | System.Management.Automation.SwitchParameter | Force deletion (pass `-Force` to `Remove-Item`). | $false | .OUTPUTS -PSCustomObject — Function return value via Write-FunctionReturnValue. +PSCustomObject -- Function return value via Write-FunctionReturnValue. RemoveItemSuccess on success (Data contains Path). RemoveItemFailed, AccessViolation, RemoveItemNoPathProvided or RemoveItemPathNotFound on errors. @@ -32,6 +32,9 @@ PS> Remove-SecureItem -Path (Join-Path (Get-ModuleCacheDirectory) 'temp.log') -F .NOTES Intended to limit deletion operations to module-managed directories only. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Remove-SecureItem() { diff --git a/src/Security/Private/Test-SecureApprovedPath.ps1 b/src/Security/Private/Test-SecureApprovedPath.ps1 index 4b6a635..d34c1be 100644 --- a/src/Security/Private/Test-SecureApprovedPath.ps1 +++ b/src/Security/Private/Test-SecureApprovedPath.ps1 @@ -8,17 +8,17 @@ whether the target path starts with any approved path prefix. Logs an audit entry for each check and returns standardized return values. .PARAMETER Path -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Path | System.String | Path to validate. | $null | +| Name | Type | Description | Default | +|------|---------------|-------------------|---------| +| Path | System.String | Path to validate. | $null | .PARAMETER ApprovedPath -| Name | Type | Description | Default | -|------|------|-------------|---------| -| ApprovedPath | System.Array | Array of allowed directory paths (strings). | @() | +| Name | Type | Description | Default | +|--------------|--------------|---------------------------------------------|---------| +| ApprovedPath | System.Array | Array of allowed directory paths (strings). | @() | .OUTPUTS -PSCustomObject — Function return value via Write-FunctionReturnValue. +PSCustomObject -- Function return value via Write-FunctionReturnValue. AccessGranted when the path is within an approved directory. AccessViolation or DirectoryArgumentEmpty otherwise. @@ -27,6 +27,9 @@ PS> Test-SecureApprovedPath -Path (Join-Path (Get-ModuleConfigDirectory) 'x') -A .NOTES Uses `Resolve-Path` to normalize paths; callers should ensure ApprovedPath entries exist. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Test-SecureApprovedPath() { diff --git a/src/Security/Private/Write-SecureFile.ps1 b/src/Security/Private/Write-SecureFile.ps1 index 4e7baa7..88991a1 100644 --- a/src/Security/Private/Write-SecureFile.ps1 +++ b/src/Security/Private/Write-SecureFile.ps1 @@ -10,17 +10,17 @@ and retries on lock for a short period. Returns structured return values via `Write-FunctionReturnValue`. .PARAMETER File -| Name | Type | Description | Default | -|------|------|-------------|---------| -| File | System.String | Target file path to write. | $null | +| Name | Type | Description | Default | +|------|---------------|----------------------------|---------| +| File | System.String | Target file path to write. | $null | .PARAMETER Value -| Name | Type | Description | Default | -|------|------|-------------|---------| -| Value | System.Object | Content to write. Can be hashtable, PSCustomObject, array or string. | (none) | +| Name | Type | Description | Default | +|-------|---------------|----------------------------------------------------------------------|---------| +| Value | System.Object | Content to write. Can be hashtable, PSCustomObject, array or string. | (none) | .OUTPUTS -PSCustomObject — Function return value via Write-FunctionReturnValue. +PSCustomObject -- Function return value via Write-FunctionReturnValue. WriteFileSuccess on success (Data contains Path and Content), WriteFileLockException when the file cannot be opened within the retry window. @@ -30,6 +30,9 @@ PS> Write-SecureFile -File (Join-Path (Get-ModuleConfigDirectory) 'settings.json .NOTES Creates the file if it does not exist by delegating to `New-SecureItem`. Uses UTF8 without BOM when writing bytes. Caller receives the content in the return data. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Write-SecureFile() { diff --git a/src/Tools/Private/ConvertFrom-ModuleBoolean.ps1 b/src/Tools/Private/ConvertFrom-ModuleBoolean.ps1 index 9ad96cc..0931cc8 100644 --- a/src/Tools/Private/ConvertFrom-ModuleBoolean.ps1 +++ b/src/Tools/Private/ConvertFrom-ModuleBoolean.ps1 @@ -12,9 +12,9 @@ are logged through Write-FunctionReturnValue using StringToBoolConversionInvalid and evaluate to $false. .PARAMETER Value -| Name | Type | Description | Default | -|-------|---------------|-----------------------------------------------------------|---------| -| Value | System.Object | Input value from JSON or Icinga macros to convert. | $null | +| Name | Type | Description | Default | +|-------|---------------|----------------------------------------------------|---------| +| Value | System.Object | Input value from JSON or Icinga macros to convert. | $null | .OUTPUTS System.Boolean -- Resolved boolean value ($true or $false). @@ -29,6 +29,9 @@ string truthiness. .NOTES Uses Write-FunctionReturnValue with key StringToBoolConversionInvalidValue when an unrecognized value is supplied. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function ConvertFrom-ModuleBoolean() { diff --git a/src/Tools/Private/ConvertFrom-ModuleJson.ps1 b/src/Tools/Private/ConvertFrom-ModuleJson.ps1 index 8449326..8bd2cdd 100644 --- a/src/Tools/Private/ConvertFrom-ModuleJson.ps1 +++ b/src/Tools/Private/ConvertFrom-ModuleJson.ps1 @@ -10,12 +10,12 @@ which natively returns dictionaries instead of PSCustomObjects. In PowerShell 6 it uses the native ConvertFrom-Json cmdlet with the -AsHashtable switch. .PARAMETER InputObject -| Name | Type | Description | Default | -|-------------|---------------|--------------------------------------------|---------| -| InputObject | System.String | The JSON string to deserialize. | '' | +| Name | Type | Description | Default | +|-------------|---------------|---------------------------------|---------| +| InputObject | System.String | The JSON string to deserialize. | '' | .OUTPUTS -System.Collections.Hashtable — Returns a hashtable (or dictionary) representation of the JSON string. +System.Collections.Hashtable -- Returns a hashtable (or dictionary) representation of the JSON string. Returns `$null` if the input is empty or parsing fails. .EXAMPLE @@ -24,6 +24,9 @@ PS> $hashtable = ConvertFrom-ModuleJson -InputObject '{"key": "value"}' .NOTES In Windows PowerShell 5.1, this function dynamically loads the System.Web.Extensions assembly if it is not already loaded in the current runspace. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function ConvertFrom-ModuleJson() { @@ -43,7 +46,7 @@ function ConvertFrom-ModuleJson() Add-Type -AssemblyName System.Web.Extensions; } - $Serializer = New-Object System.Web.Script.Serialization.JavaScriptSerializer; + $Serializer = New-Object System.Web.Script.Serialization.JavaScriptSerializer; $Serializer.MaxJsonLength = 2147483647; return $Serializer.DeserializeObject($InputObject); diff --git a/src/Tools/Private/ConvertTo-ModuleJson.ps1 b/src/Tools/Private/ConvertTo-ModuleJson.ps1 index 9b9541f..98303a1 100644 --- a/src/Tools/Private/ConvertTo-ModuleJson.ps1 +++ b/src/Tools/Private/ConvertTo-ModuleJson.ps1 @@ -10,12 +10,12 @@ back to System.Web.Script.Serialization.JavaScriptSerializer. In PowerShell 6 and higher, it uses the native ConvertTo-Json cmdlet. .PARAMETER InputObject -| Name | Type | Description | Default | -|-------------|---------------|--------------------------------------------|---------| -| InputObject | System.Object | The object to serialize. | $null | +| Name | Type | Description | Default | +|-------------|---------------|--------------------------|---------| +| InputObject | System.Object | The object to serialize. | $null | .OUTPUTS -System.String — Returns a JSON string representation of the object. +System.String -- Returns a JSON string representation of the object. Returns an empty string if the input is null or serialization fails. .EXAMPLE @@ -24,6 +24,9 @@ PS> $json = ConvertTo-ModuleJson -InputObject @{ key = "value" } .NOTES In Windows PowerShell 5.1, this function dynamically loads the System.Web.Extensions assembly if it is not already loaded. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function ConvertTo-ModuleJson() { @@ -46,7 +49,7 @@ function ConvertTo-ModuleJson() Add-Type -AssemblyName System.Web.Extensions; } - $Serializer = New-Object System.Web.Script.Serialization.JavaScriptSerializer; + $Serializer = New-Object System.Web.Script.Serialization.JavaScriptSerializer; $Serializer.MaxJsonLength = 2147483647; return $Serializer.Serialize($InputObject); diff --git a/src/Tools/Private/ConvertTo-ModuleOrderedDictionary.ps1 b/src/Tools/Private/ConvertTo-ModuleOrderedDictionary.ps1 index 389bc97..7413855 100644 --- a/src/Tools/Private/ConvertTo-ModuleOrderedDictionary.ps1 +++ b/src/Tools/Private/ConvertTo-ModuleOrderedDictionary.ps1 @@ -12,14 +12,14 @@ SkipEmptyKeys is enabled, null, empty and whitespace-only keys (such as Icinga placeholder macros) are omitted. .PARAMETER InputObject -| Name | Type | Description | Default | -|-------------|---------------|-------------------------------------------------|---------| -| InputObject | System.Object | Dictionary or object to copy entries from. | $null | +| Name | Type | Description | Default | +|-------------|---------------|--------------------------------------------|---------| +| InputObject | System.Object | Dictionary or object to copy entries from. | $null | .PARAMETER SkipEmptyKeys -| Name | Type | Description | Default | -|---------------|----------------------------------------------|-------------------------------------------------------|---------| -| SkipEmptyKeys | System.Management.Automation.SwitchParameter | Omit null, empty or whitespace-only keys when set. | $false | +| Name | Type | Description | Default | +|---------------|----------------------------------------------|----------------------------------------------------|---------| +| SkipEmptyKeys | System.Management.Automation.SwitchParameter | Omit null, empty or whitespace-only keys when set. | $false | .OUTPUTS System.Collections.Specialized.OrderedDictionary -- Case-sensitive ordered @@ -32,6 +32,9 @@ Creates an ordinal OrderedDictionary preserving exact key casing. .NOTES Compatible with Windows PowerShell 5.1 and PowerShell 7+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function ConvertTo-ModuleOrderedDictionary() { diff --git a/src/Tools/Private/ConvertTo-ModuleParameterValue.ps1 b/src/Tools/Private/ConvertTo-ModuleParameterValue.ps1 index 7078fa3..f61a10e 100644 --- a/src/Tools/Private/ConvertTo-ModuleParameterValue.ps1 +++ b/src/Tools/Private/ConvertTo-ModuleParameterValue.ps1 @@ -40,6 +40,9 @@ Coerces the string '2' into Int32 2 with Status 'Bound'. .NOTES Callers must call Dispose() on AllocatedSecret when non-null once command execution completes. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function ConvertTo-ModuleParameterValue() { diff --git a/src/Tools/Private/ConvertTo-ModuleSecureString.ps1 b/src/Tools/Private/ConvertTo-ModuleSecureString.ps1 index 7c76ae3..67ad6e2 100644 --- a/src/Tools/Private/ConvertTo-ModuleSecureString.ps1 +++ b/src/Tools/Private/ConvertTo-ModuleSecureString.ps1 @@ -30,6 +30,9 @@ Converts the plain-text string into a SecureString instance. Compatible with Windows PowerShell 5.1 and PowerShell 7+. Callers that allocate temporary SecureString instances for check execution should call Dispose() once the check finishes. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function ConvertTo-ModuleSecureString() { diff --git a/src/Tools/Private/ConvertTo-StringNormalizedArray.ps1 b/src/Tools/Private/ConvertTo-StringNormalizedArray.ps1 index 3ce0bdc..aed1bdf 100644 --- a/src/Tools/Private/ConvertTo-StringNormalizedArray.ps1 +++ b/src/Tools/Private/ConvertTo-StringNormalizedArray.ps1 @@ -10,14 +10,14 @@ This helper is useful for normalizing user lists for case-insensitive or consistent comparisons. .PARAMETER InputArray -| Name | Type | Description | Default | -|------|------|-------------|---------| -| InputArray | System.Object[] | Array of items to normalize; string items will be case-normalized | @() | +| Name | Type | Description | Default | +|------------|-----------------|-------------------------------------------------------------------|---------| +| InputArray | System.Object[] | Array of items to normalize; string items will be case-normalized | @() | .PARAMETER UpperCase -| Name | Type | Description | Default | -|------|------|-------------|---------| -| UpperCase | Switch | When set, convert string items to upper-case instead of lower-case | $false | +| Name | Type | Description | Default | +|-----------|--------|--------------------------------------------------------------------|---------| +| UpperCase | Switch | When set, convert string items to upper-case instead of lower-case | $false | .OUTPUTS Array of the same length with string items converted to the selected case. @@ -30,6 +30,9 @@ $normUpper = ConvertTo-StringNormalizedArray -InputArray @('Alice','BOB') -Upper .NOTES - Non-string items are returned unchanged. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function ConvertTo-StringNormalizedArray() { diff --git a/src/Tools/Private/Format-ModuleCommandLineArguments.ps1 b/src/Tools/Private/Format-ModuleCommandLineArguments.ps1 index 4f1aa99..f4468ac 100644 --- a/src/Tools/Private/Format-ModuleCommandLineArguments.ps1 +++ b/src/Tools/Private/Format-ModuleCommandLineArguments.ps1 @@ -11,9 +11,9 @@ double quotes with preceding backslashes doubled before embedded quotes and before the closing quote. .PARAMETER Arguments -| Name | Type | Description | Default | -|-----------|--------------|-------------------------------------------------|---------| -| Arguments | System.Array | Ordered CLI argument tokens to quote and join. | @() | +| Name | Type | Description | Default | +|-----------|--------------|------------------------------------------------|---------| +| Arguments | System.Array | Ordered CLI argument tokens to quote and join. | @() | .OUTPUTS System.String -- Space-joined, CommandLineToArgvW-compliant argument string. @@ -26,6 +26,9 @@ Quotes tokens containing spaces or quotes while leaving simple tokens intact. .NOTES Pure string formatter with no external dependencies or global state access. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Format-ModuleCommandLineArguments() { diff --git a/src/Tools/Private/Get-ModuleCommandParameterMap.ps1 b/src/Tools/Private/Get-ModuleCommandParameterMap.ps1 index 56e90d5..3136d5e 100644 --- a/src/Tools/Private/Get-ModuleCommandParameterMap.ps1 +++ b/src/Tools/Private/Get-ModuleCommandParameterMap.ps1 @@ -28,6 +28,9 @@ Builds the canonical/alias lookup map and positional list for the command. .NOTES Pure metadata helper with no external dependencies or side effects. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Get-ModuleCommandParameterMap() { diff --git a/src/Tools/Private/Get-ModuleObjectValue.ps1 b/src/Tools/Private/Get-ModuleObjectValue.ps1 index 4016888..fe26164 100644 --- a/src/Tools/Private/Get-ModuleObjectValue.ps1 +++ b/src/Tools/Private/Get-ModuleObjectValue.ps1 @@ -40,6 +40,9 @@ Reads the value of 'Check_Timeout' case-insensitively from the dictionary. .NOTES Compatible with Windows PowerShell 5.1 and PowerShell 7+. Does not mutate global state. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Get-ModuleObjectValue() { diff --git a/src/Tools/Private/Get-NormalizedTextContent.ps1 b/src/Tools/Private/Get-NormalizedTextContent.ps1 index 4cb8f10..20430d7 100644 --- a/src/Tools/Private/Get-NormalizedTextContent.ps1 +++ b/src/Tools/Private/Get-NormalizedTextContent.ps1 @@ -16,7 +16,7 @@ empty input returns an empty string without attempting any conversion. | Content | System.String | The string to normalize. | $null | .OUTPUTS -System.String — Re-serialized JSON string when the input is valid JSON, the +System.String -- Re-serialized JSON string when the input is valid JSON, the original input string when it is not, or an empty string for null or empty input. .EXAMPLE @@ -28,6 +28,9 @@ Returns the JSON re-serialized with ConvertTo-Json formatting. Used by Compare-IcingaTextContent to ensure both sides of a diff use identical formatting before line-level comparison. Relies only on ConvertFrom-Json and ConvertTo-Json from the PowerShell standard library; no external dependencies. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Get-NormalizedTextContent() { diff --git a/src/Tools/Private/Invoke-ModulePowerShellCommand.ps1 b/src/Tools/Private/Invoke-ModulePowerShellCommand.ps1 index 95f1b10..e77aee6 100644 --- a/src/Tools/Private/Invoke-ModulePowerShellCommand.ps1 +++ b/src/Tools/Private/Invoke-ModulePowerShellCommand.ps1 @@ -24,29 +24,29 @@ Get-ModuleBinaryDirectory: | Command | System.String | PowerShell command name or full .ps1 script path to call. | '' | .PARAMETER NamedArguments -| Name | Type | Description | Default | -|----------------|------------------------------|----------------------------------------------|---------| -| NamedArguments | System.Collections.Hashtable | Named parameter splatting hashtable. | @{} | +| Name | Type | Description | Default | +|----------------|------------------------------|--------------------------------------|---------| +| NamedArguments | System.Collections.Hashtable | Named parameter splatting hashtable. | @{} | .PARAMETER PositionalArguments -| Name | Type | Description | Default | -|---------------------|--------------|-------------------------------------------------|---------| -| PositionalArguments | System.Array | Optional positional arguments to pass after @. | @() | +| Name | Type | Description | Default | +|---------------------|--------------|------------------------------------------------|---------| +| PositionalArguments | System.Array | Optional positional arguments to pass after @. | @() | .PARAMETER AllocatedSecrets -| Name | Type | Description | Default | -|------------------|--------------|----------------------------------------------------------|---------| -| AllocatedSecrets | System.Array | Temporary SecureString instances to dispose in finally. | @() | +| Name | Type | Description | Default | +|------------------|--------------|---------------------------------------------------------|---------| +| AllocatedSecrets | System.Array | Temporary SecureString instances to dispose in finally. | @() | .PARAMETER UseLastExitCode -| Name | Type | Description | Default | -|-----------------|----------------------------------------------|-------------------------------------------------------------|---------| -| UseLastExitCode | System.Management.Automation.SwitchParameter | Fall back to $global:LASTEXITCODE for external .ps1 scripts.| $false | +| Name | Type | Description | Default | +|-----------------|----------------------------------------------|--------------------------------------------------------------|---------| +| UseLastExitCode | System.Management.Automation.SwitchParameter | Fall back to $global:LASTEXITCODE for external .ps1 scripts. | $false | .PARAMETER ErrorContext -| Name | Type | Description | Default | -|--------------|---------------|-----------------------------------------------------------------|---------| -| ErrorContext | System.String | Optional custom prefix for [UNKNOWN] unhandled error messages. | '' | +| Name | Type | Description | Default | +|--------------|---------------|----------------------------------------------------------------|---------| +| ErrorContext | System.String | Optional custom prefix for [UNKNOWN] unhandled error messages. | '' | .OUTPUTS System.Collections.Hashtable -- Plain hashtable containing primitive ExitCode, @@ -61,6 +61,9 @@ result hashtable. .NOTES Accesses runtime state exclusively via Get-GlobalRuntimeVariable. Never returns PowerShell class instances across thread boundaries. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Invoke-ModulePowerShellCommand() { diff --git a/src/Tools/Private/Remove-ModuleAmbitiousCharacters.ps1 b/src/Tools/Private/Remove-ModuleAmbitiousCharacters.ps1 index 37df7ee..d59bcfd 100644 --- a/src/Tools/Private/Remove-ModuleAmbitiousCharacters.ps1 +++ b/src/Tools/Private/Remove-ModuleAmbitiousCharacters.ps1 @@ -8,17 +8,17 @@ Windows filenames. Optionally removes whitespace as well. Useful when deriving filenames from user-supplied role names or identifiers. .PARAMETER InputString -| Name | Type | Description | Default | -|------|------|-------------|---------| -| InputString | System.String | Input string to sanitize. | $null | +| Name | Type | Description | Default | +|-------------|---------------|---------------------------|---------| +| InputString | System.String | Input string to sanitize. | $null | .PARAMETER RemoveSpaces -| Name | Type | Description | Default | -|------|------|-------------|---------| -| RemoveSpaces | System.Management.Automation.SwitchParameter | Remove all whitespace characters when set. | $false | +| Name | Type | Description | Default | +|--------------|----------------------------------------------|--------------------------------------------|---------| +| RemoveSpaces | System.Management.Automation.SwitchParameter | Remove all whitespace characters when set. | $false | .OUTPUTS -System.String — The sanitized string suitable for use as a filename. +System.String -- The sanitized string suitable for use as a filename. .EXAMPLE PS> Remove-ModuleAmbitiousCharacters -InputString 'Admin Role #1' -RemoveSpaces @@ -26,6 +26,9 @@ PS> Remove-ModuleAmbitiousCharacters -InputString 'Admin Role #1' -RemoveSpaces .NOTES Only removes a restricted set of characters; callers may perform additional normalization (lowercasing, trimming) if needed. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Remove-ModuleAmbitiousCharacters() { diff --git a/src/Tools/Private/Test-ModuleWildcardMatch.ps1 b/src/Tools/Private/Test-ModuleWildcardMatch.ps1 index 7d81845..460a4c7 100644 --- a/src/Tools/Private/Test-ModuleWildcardMatch.ps1 +++ b/src/Tools/Private/Test-ModuleWildcardMatch.ps1 @@ -9,9 +9,9 @@ Write-FunctionReturnValue (ArrayFilterInvalidPattern) and counts as no match, so a broken filter argument never aborts a plugin. .PARAMETER Value -| Name | Type | Description | Default | -|-------|---------------|----------------------|---------| -| Value | System.String | The value to test. | | +| Name | Type | Description | Default | +|-------|---------------|--------------------|---------| +| Value | System.String | The value to test. | | .PARAMETER Pattern | Name | Type | Description | Default | @@ -28,6 +28,9 @@ Returns $true. .NOTES Internal helper of Test-IcingaArrayFilter. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Test-ModuleWildcardMatch() { diff --git a/src/Tools/Public/Compare-IcingaTextContent.ps1 b/src/Tools/Public/Compare-IcingaTextContent.ps1 index 940e117..3d9a0f6 100644 --- a/src/Tools/Public/Compare-IcingaTextContent.ps1 +++ b/src/Tools/Public/Compare-IcingaTextContent.ps1 @@ -21,22 +21,22 @@ tools or modules are required. | NewConfig | System.String | The new content as a JSON string or plain text. | $null | .PARAMETER OldConfig -| Name | Type | Description | Default | -|-----------|---------------|-------------------------------------------------------|---------| -| OldConfig | System.String | The baseline content as a JSON string or plain text. | $null | +| Name | Type | Description | Default | +|-----------|---------------|------------------------------------------------------|---------| +| OldConfig | System.String | The baseline content as a JSON string or plain text. | $null | .PARAMETER OldFile -| Name | Type | Description | Default | -|---------|---------------|-----------------------------------------------------------------------|---------| -| OldFile | System.String | File path to the baseline; read via Read-SecureFile when provided. | $null | +| Name | Type | Description | Default | +|---------|---------------|--------------------------------------------------------------------|---------| +| OldFile | System.String | File path to the baseline; read via Read-SecureFile when provided. | $null | .PARAMETER Colorized -| Name | Type | Description | Default | -|-----------|----------------------------------------------|----------------------------------------------------------------|---------| +| Name | Type | Description | Default | +|-----------|----------------------------------------------|---------------------------------------------------------------|---------| | Colorized | System.Management.Automation.SwitchParameter | When set, embeds ANSI color codes (green/red/cyan) in output. | $false | .OUTPUTS -System.Collections.Hashtable — Always returns @{ ExitCode = System.Int32; Output = System.String }. +System.Collections.Hashtable -- Always returns @{ ExitCode = System.Int32; Output = System.String }. ExitCode is 0 when both inputs are identical after normalization, 1 when they differ. Output is an empty string when identical; otherwise a unified diff with header lines (--- old / +++ new), @@ hunk headers and +/-/space-prefixed content lines. @@ -61,6 +61,9 @@ paths outside those locations will cause -OldFile to resolve to an empty baselin matrix; inputs beyond a few thousand lines will consume significant memory, which is acceptable for config-file comparison. No external binaries, modules, or .NET packages beyond the PowerShell standard library are used. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Compare-IcingaTextContent() { @@ -102,11 +105,11 @@ function Compare-IcingaTextContent() [int]$OldCount = $OldLines.Count; [int]$NewCount = $NewLines.Count; - # Build the LCS table — O(m*n) time and space. - # Use a jagged int[][] instead of int[,] — New-Object 'int[,]' is unreliable + # Build the LCS table -- O(m*n) time and space. + # Use a jagged int[][] instead of int[,] -- New-Object 'int[,]' is unreliable # in PS5 and causes the array to be typed as System.Object[], which turns # two-index access into array slicing instead of element lookup. - $LCS = New-Object 'int[][]' ($OldCount + 1); + $LCS = New-Object 'int[][]' ($OldCount + 1); for ($i = 0; $i -le $OldCount; $i++) { $LCS[$i] = New-Object 'int[]' ($NewCount + 1); } @@ -187,7 +190,7 @@ function Compare-IcingaTextContent() } # Merge adjacent change positions into hunk ranges with context padding. - $HunkRanges = New-Object System.Collections.ArrayList; + $HunkRanges = New-Object System.Collections.ArrayList; [int]$HunkStart = [Math]::Max(0, [int]$ChangeIdxList[0] - $ContextSize); [int]$HunkEnd = [Math]::Min($TotalEntries - 1, [int]$ChangeIdxList[0] + $ContextSize); @@ -212,7 +215,7 @@ function Compare-IcingaTextContent() [string]$Cyan = "${Esc}[36m"; [string]$Reset = "${Esc}[0m"; - $OutputParts = New-Object System.Collections.ArrayList; + $OutputParts = New-Object System.Collections.ArrayList; if ($Colorized) { [void]$OutputParts.Add("${Red}--- old${Reset}"); @@ -259,7 +262,7 @@ function Compare-IcingaTextContent() } for ($idx = [int]$Hunk.S; $idx -le [int]$Hunk.E; $idx++) { - $DE = $DiffEntries[$idx]; + $DE = $DiffEntries[$idx]; [string]$DiffLine = "$($DE.Type)$($DE.Line)"; if ($Colorized) { diff --git a/src/Tools/Public/ConvertTo-IcingaSortedArray.ps1 b/src/Tools/Public/ConvertTo-IcingaSortedArray.ps1 index 8d350bf..d7faab6 100644 --- a/src/Tools/Public/ConvertTo-IcingaSortedArray.ps1 +++ b/src/Tools/Public/ConvertTo-IcingaSortedArray.ps1 @@ -18,9 +18,9 @@ Hashtables are read by key, every other object (including CIM instances) by member name. .PARAMETER InputObject -| Name | Type | Description | Default | -|-------------|--------------|------------------------|---------| -| InputObject | System.Array | The elements to sort. | @() | +| Name | Type | Description | Default | +|-------------|--------------|-----------------------|---------| +| InputObject | System.Array | The elements to sort. | @() | .PARAMETER Property | Name | Type | Description | Default | @@ -48,6 +48,9 @@ Sorts Win32_Service instances by their name. .NOTES No external dependencies. Replaces 'Sort-Object -Property { ... }' in plugin code. The verb follows the approved PowerShell verbs; 'Sort' is not one of them. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function ConvertTo-IcingaSortedArray() { diff --git a/src/Tools/Public/ConvertTo-IcingaUnit.ps1 b/src/Tools/Public/ConvertTo-IcingaUnit.ps1 index 3deb493..0a9f6d4 100644 --- a/src/Tools/Public/ConvertTo-IcingaUnit.ps1 +++ b/src/Tools/Public/ConvertTo-IcingaUnit.ps1 @@ -73,6 +73,9 @@ The conversion logic lives in the IcingaUnit class. Failures are surfaced throug Write-FunctionReturnValue, which logs at the severity registered for each return code in Set-InternalExitCodes (Error for failures, Debug for the successful conversion). No external services, credentials or configuration files are used. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function ConvertTo-IcingaUnit() { diff --git a/src/Tools/Public/Get-IcingaUnixTime.ps1 b/src/Tools/Public/Get-IcingaUnixTime.ps1 index 0287f89..9b639c3 100644 --- a/src/Tools/Public/Get-IcingaUnixTime.ps1 +++ b/src/Tools/Public/Get-IcingaUnixTime.ps1 @@ -11,9 +11,9 @@ millisecond precision as a Double, matching the timestamp format expected by Icinga 2 check result payloads (execution_start and execution_end). .PARAMETER Milliseconds -| Name | Type | Description | Default | -|--------------|----------------------------------------------|-------------------------------------------------------------------------------|---------| -| Milliseconds | System.Management.Automation.SwitchParameter | When set, returns fractional Unix seconds with millisecond precision (Double).| $false | +| Name | Type | Description | Default | +|--------------|----------------------------------------------|--------------------------------------------------------------------------------|---------| +| Milliseconds | System.Management.Automation.SwitchParameter | When set, returns fractional Unix seconds with millisecond precision (Double). | $false | .OUTPUTS System.ValueType -- System.Int32 whole Unix seconds by default, or System.Double @@ -33,6 +33,9 @@ Returns the current UTC Unix time in seconds with millisecond precision. .NOTES Uses System.DateTimeOffset.UtcNow across Windows PowerShell 5.1 and PowerShell 7+. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Get-IcingaUnixTime() { diff --git a/src/Tools/Public/Get-IcingaWindowsInformation.ps1 b/src/Tools/Public/Get-IcingaWindowsInformation.ps1 index 5ca9ca4..2b61b99 100644 --- a/src/Tools/Public/Get-IcingaWindowsInformation.ps1 +++ b/src/Tools/Public/Get-IcingaWindowsInformation.ps1 @@ -23,14 +23,14 @@ query (WindowsInformationQueried), a missing class name the ReturnCode of the IcingaError. .PARAMETER ClassName -| Name | Type | Description | Default | -|-----------|---------------|-----------------------------------------|---------| -| ClassName | System.String | Name of the CIM class to query. | | +| Name | Type | Description | Default | +|-----------|---------------|---------------------------------|---------| +| ClassName | System.String | Name of the CIM class to query. | | .PARAMETER Namespace -| Name | Type | Description | Default | -|-----------|---------------|--------------------------------|------------| -| Namespace | System.String | CIM namespace of the class. | root/cimv2 | +| Name | Type | Description | Default | +|-----------|---------------|-----------------------------|------------| +| Namespace | System.String | CIM namespace of the class. | root/cimv2 | .PARAMETER Filter | Name | Type | Description | Default | @@ -62,6 +62,9 @@ Windows-only, uses the local CIM provider. The required permissions depend on the class; standard users can read most root/cimv2 classes. Unknown classes and namespaces are logged at Debug level only, because optional classes are probed on purpose. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Get-IcingaWindowsInformation() { diff --git a/src/Tools/Public/Join-WebPath.ps1 b/src/Tools/Public/Join-WebPath.ps1 index 8b7a285..2bd9474 100644 --- a/src/Tools/Public/Join-WebPath.ps1 +++ b/src/Tools/Public/Join-WebPath.ps1 @@ -7,13 +7,13 @@ Combines a base path and additional child path segments, handling trailing and l URL query parameters and avoiding duplicate slashes. Preserves scheme endings like '://'. .PARAMETER Path -| Name | Type | Description | Default | -|------|---------------|------------------------------|---------| +| Name | Type | Description | Default | +|------|---------------|---------------------------------|---------| | Path | System.String | Base path or URL to start from. | $null | .PARAMETER ChildPath -| Name | Type | Description | Default | -|-----------|--------------|--------------------------------------------------------------------------------------|---------| +| Name | Type | Description | Default | +|-----------|--------------|-------------------------------------------------------------------------------------|---------| | ChildPath | System.Array | Child path segments to append. Segments may start with /, ? or & for query strings. | $null | .EXAMPLE @@ -27,10 +27,13 @@ PS> Join-WebPath -Path 'http://example.com' -ChildPath @('search', '?q=test', '& Returns 'http://example.com/search?q=test&page=2'. .OUTPUTS -System.String — The assembled web path or URL. +System.String -- The assembled web path or URL. .NOTES No external dependencies. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Join-WebPath() { @@ -48,7 +51,7 @@ function Join-WebPath() [int]$Length = $Path.Length; [int]$Slash = $Path.LastIndexOf('/') + 1; - # If the last character is a slash, remove it — but preserve scheme endings like '://' + # If the last character is a slash, remove it -- but preserve scheme endings like '://' if ($Length -eq $Slash -and -not $Path.EndsWith('://')) { $Path = $Path.Substring(0, $Path.Length - 1); } diff --git a/src/Tools/Public/Resolve-IcingaIPAddress.ps1 b/src/Tools/Public/Resolve-IcingaIPAddress.ps1 index 25d4213..46eb4a2 100644 --- a/src/Tools/Public/Resolve-IcingaIPAddress.ps1 +++ b/src/Tools/Public/Resolve-IcingaIPAddress.ps1 @@ -11,8 +11,8 @@ On failure or exception, the function uses the module's Write-FunctionReturnValu mechanism to emit a standardized return value and typically returns $null. .PARAMETER Address -| Name | Type | Description | Default | -|---------|---------------|------------------------------------------------------------------------------|---------| +| Name | Type | Description | Default | +|---------|---------------|---------------------------------------------------------------------------------|---------| | Address | System.String | Hostname or IP address to resolve. Empty or null triggers IPAddressLookupEmpty. | $null | .EXAMPLE @@ -27,7 +27,7 @@ PS> Resolve-IcingaIPAddress -Address '192.0.2.1' Returns '192.0.2.1' unchanged since the input is already a valid IPv4 literal. .OUTPUTS -System.String — IPv4 or IPv6 address string on success. +System.String -- IPv4 or IPv6 address string on success. Returns $null via Write-FunctionReturnValue on failure with tokens IPAddressLookupEmpty, IPAddressLookupFailure, IPAddressLookupFailedForV4AndV6 or IPAddressLookupException. @@ -37,6 +37,9 @@ DNS resolution is performed via [System.Net.Dns]::GetHostAddresses. IPv4 address are preferred; the function returns the first IPv4 found, otherwise the first IPv6. Simple regex literal checks are performed before DNS resolution to avoid unnecessary lookups. Error conditions are surfaced via Write-FunctionReturnValue. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Resolve-IcingaIPAddress() { diff --git a/src/Tools/Public/Test-IcingaArrayFilter.ps1 b/src/Tools/Public/Test-IcingaArrayFilter.ps1 index ed4f8ab..50b3cad 100644 --- a/src/Tools/Public/Test-IcingaArrayFilter.ps1 +++ b/src/Tools/Public/Test-IcingaArrayFilter.ps1 @@ -17,19 +17,19 @@ wildcard pattern is logged through Write-FunctionReturnValue pattern. .PARAMETER InputObject -| Name | Type | Description | Default | -|-------------|---------------|----------------------------------------------|---------| -| InputObject | System.Object | Value, or array of values, to test. | $null | +| Name | Type | Description | Default | +|-------------|---------------|-------------------------------------|---------| +| InputObject | System.Object | Value, or array of values, to test. | $null | .PARAMETER Include -| Name | Type | Description | Default | -|---------|--------------|--------------------------------------------------------|---------| -| Include | System.Array | Wildcard patterns of which at least one has to match. | @() | +| Name | Type | Description | Default | +|---------|--------------|-------------------------------------------------------|---------| +| Include | System.Array | Wildcard patterns of which at least one has to match. | @() | .PARAMETER Exclude -| Name | Type | Description | Default | -|---------|--------------|-----------------------------------------------|---------| -| Exclude | System.Array | Wildcard patterns of which none may match. | @() | +| Name | Type | Description | Default | +|---------|--------------|--------------------------------------------|---------| +| Exclude | System.Array | Wildcard patterns of which none may match. | @() | .OUTPUTS System.Boolean -- For a single value, whether it passes the filters. @@ -49,6 +49,9 @@ Returns the array @('C', 'E'). No external dependencies. A $null value never passes. Used by the plugins for their -Include/-Exclude parameters, which must not rely on script blocks so the plugins stay usable in JEA sessions. + +SPDX-FileCopyrightText: 2026 Icinga GmbH +SPDX-License-Identifier: GPL-3.0-or-later #> function Test-IcingaArrayFilter() {