Skip to content

Add IcingaPerformanceCounter - #19

Merged
LordHepipud merged 2 commits into
mainfrom
feature/add-icingaperformancecounter
Nov 12, 2026
Merged

LordHepipud merged 2 commits into
mainfrom
feature/add-icingaperformancecounter

Conversation

@fthomys

@fthomys fthomys commented Aug 25, 2026

Copy link
Copy Markdown
Member

Adds central perfcounter support: a background daemon owns all PerformanceCounter handles while callers use GUID request/pull queues (inline fallback with no daemon), so there are no races on the non-thread-safe counters. Includes wildcard/instance reconciliation (removable disks), a single shared 250 ms warm-up per batch, AST-based counter discovery with a self-maintaining JSON cache, and Get-/Show- functions. Runs on PowerShell 5.1 and 7.

@cla-bot cla-bot Bot added the cla/signed CLA is signed by all contributors of a PR label Aug 25, 2026
@fthomys
fthomys requested a review from LordHepipud August 25, 2026 13:08
@fthomys
fthomys force-pushed the feature/add-icingaperformancecounter branch 6 times, most recently from dac33cc to 7972e65 Compare August 27, 2026 10:59
@fthomys
fthomys force-pushed the feature/add-icingaperformancecounter branch 2 times, most recently from 3e96052 to 246f6fb Compare October 2, 2026 13:23
@fthomys

fthomys commented Oct 2, 2026 •

Copy link
Copy Markdown
Member Author

Summary of recent changes:

  • All PerformanceCounter handles live on the daemon thread. Other threads send requests through concurrent queues in Public.PerformanceCounter and wait for the answer with a timeout. Neither PS classes nor PerformanceCounter are thread safe, so nothing is shared.
  • Without a daemon, Get-IcingaPerformanceCounter keeps one manager per runspace in module scope, so only the first read pays the warm-up. Without the global store it falls back to a one-shot ResolveOnce.
  • Counters are found at startup by scanning the built kernel for literal New-IcingaPerformanceCounter calls (nothing is executed), plus a JSON cache of requested counters. Unused counters are evicted after 60 minutes.
  • -StructureByInstance returns [instance][category][counter] for plugins.
  • Resolve reads every handle only once per request, also when wildcard and single instance paths overlap. A second NextValue right after the first returns a wrong rate.
  • ParsePath rejects broken parentheses and empty categories. Expanded paths are built by format instead of Replace('*'), which broke counter names containing a *.
  • The manager is created with ('IcingaPerformanceCounter' -as [type])::new(). With the class literal, 5.1 used the main runspace type inside the daemon and every call stalled (CPU check about 880 ms, now 29-122 ms).
  • TryRemove uses typed out refs, [ref]$null fails on PS7 for value types.

@fthomys
fthomys force-pushed the feature/add-icingaperformancecounter branch from 246f6fb to 28690f0 Compare October 2, 2026 14:41
…1 runspace isolation, and developer docs

Summary
-------
Hardens the Icinga Performance Counter subsystem with local-host path
normalization, non-throwing category existence checks, detailed priming/refresh
error propagation, Windows PowerShell 5.1 runspace class isolation, full
CLAUDE.md code-styling compliance, Pester test coverage, and comprehensive
technical and developer documentation.

What Changed & Why
------------------
1. Local Host Path Parsing & Canonical Handle Normalization
   - What: Extended `IcingaPerformanceCounter::ParsePath([string]$Path)` to
     accept and strip local machine prefixes (`\\.\`, `\\localhost\`,
     `\\127.0.0.1\`, `\\::1\`, and `\\<Environment.MachineName>\`, matched
     case-insensitively) while continuing to reject remote host paths
     (`\\remote-host\...`) and malformed path segments.
   - What: Added `IcingaPerformanceCounter::NormalizePath([string]$Path)` and
     wired it into `CreateEntry`, `Warmup`, `ReadPath`, `Resolve`, and
     `Reconcile`.
   - Why: Windows tools, WMI/CIM providers, and administrators frequently copy
     counter paths containing a leading `\\.\` or `\\<ComputerName>\` prefix.
     Previously, `ParsePath` rejected any path with more than three backslash-
     separated segments. Normalizing local prefixes internally ensures that
     `\Memory\Available Bytes` and `\\.\Memory\Available Bytes` share a single
     underlying `IcingaPerformanceCounterEntry` handle while `Resolve()` still
     keys its outer result hashtable by the exact path string requested by the
     caller.

2. Category Existence Checks & Granular Error Diagnostics
   - What: Added `IcingaPerformanceCounter::CategoryExists([string]$Category)`
     and the public cmdlet `Test-IcingaPerformanceCounterCategory`, accepting
     either a plain category name (`'Processor'`) or a full counter path
     (`'\Processor(*)\% Processor Time'`, `'\\.\Memory\Available Bytes'`).
   - What: Added `LastError` tracking to `IcingaPerformanceCounterEntry` and
     `IcingaPerformanceCounterCategory` plus `$Manager.GetCategoryError([string]$Category)`.
     When `Prime()` or `Refresh()` fails, the underlying OS/.NET exception
     message is captured and surfaced in the leaf result's `error` field instead
     of falling back to a generic `'Counter not initialized'` string.
   - Why: Providers for optional Windows Server roles (such as Hyper-V, IIS, or
     SQL Server) need a fast, non-throwing way to check whether a counter
     category is installed before querying it, and operators need the exact OS
     error message when a category or counter name cannot be initialized.

3. Windows PowerShell 5.1 Runspace Class Isolation (Deadlock Fix)
   - What: Updated `build/Build-ModuleProject.ps1`, `build/Invoke-ModuleTests.ps1`,
     and `IcingaForWindows.psm1` to compile all class definitions into
     `lib\IcingaForWindows.Classes.ps1` separate from `lib\IcingaForWindows.Kernel.ps1`.
     On Windows PowerShell 5.1 (`$PSVersionTable.PSEdition -eq 'Desktop'`),
     `IcingaForWindows.psm1` appends a per-runspace GUID comment before calling
     `[ScriptBlock]::Create(...)` when loading `IcingaForWindows.Classes.ps1`.
   - What: Replaced all compile-time PowerShell class type literals inside
     `src/Classes/Icinga/IcingaPerformanceCounter.ps1`, `src/PerformanceCounter/`,
     and `src/Tools/Public/ConvertTo-IcingaUnit.ps1` with runtime type lookups
     (`'IcingaPerformanceCounter' -as [type]`, `'IcingaPerformanceCounterEntry' -as [type]`,
     `'IcingaPerformanceCounterCategory' -as [type]`, `'IcingaUnit' -as [type]`)
     and `[System.Collections.Concurrent.ConcurrentDictionary[string, object]]`.
   - What: Added `Tests/ClassLiteral.Tests.ps1` to statically verify via AST
     that no PowerShell class literals are used in functions or inside
     `IcingaPerformanceCounter.ps1`.
   - Why: Windows PowerShell 5.1 caches compiled class types across runspaces
     when identical script text is dot-sourced, binding every class method to the
     `SessionStateInternal` of the runspace that compiled it first. When the
     background Performance Counter daemon thread invoked methods on a class
     bound to the main runspace while the main runspace was blocked inside
     `Get-IcingaPerformanceCounter` waiting on `$ResponseQueue.TryTake(...)`,
     PowerShell 5.1 attempted to marshal the daemon's method call back onto the
     blocked main thread, causing a 5000 ms request timeout. Generating a unique
     class scriptblock per runspace and resolving class types dynamically via
     `-as [type]` gives each runspace its own isolated class types and eliminates
     cross-runspace marshaling.

4. Code Styling & Documentation
   - What: Aligned all Performance Counter class, public, private, and test files
     with the repository's `CLAUDE.md` code-styling rules (Allman braces,
     single-line `if`/`elseif` statements, vertical `=` alignment, aligned
     Markdown `.PARAMETER` tables, ASCII `--` in help blocks, UTF-8 without BOM).
   - What: Regenerated `docs/Icinga.PerformanceCounter.md` and `docs/index.md`
     to include `Test-IcingaPerformanceCounterCategory`.
   - What: Added comprehensive English developer documentation under
     `docs/Developer/PerformanceCounter/`:
     * `01-Technical-Architecture-and-Reference.md` (architecture diagram,
       global state, execution modes, AST discovery & cache lifecycle, path
       normalization rules, complete class/cmdlet reference, and PS 5.1 runspace
       isolation internals).
     * `02-Usability-and-Developer-Guide.md` (interactive discovery workflow,
       supported path formats, default vs. `-StructureByInstance` output shapes,
       static AST pre-declaration rules, safe value/error extraction, provider
       recipes, and troubleshooting FAQ).

@LordHepipud LordHepipud left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks!

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

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants