From 28690f006512a3d93403921a809e4dfe45c3c72e Mon Sep 17 00:00:00 2001 From: Fabian Thomys Date: Thu, 27 Aug 2026 12:59:51 +0200 Subject: [PATCH 1/2] Add IcingaPerformanceCounter --- IcingaForWindows.psm1 | 16 + Tests/Get-IcingaPerformanceCounter.Tests.ps1 | 215 +++ Tests/PerformanceCounter.Tests.ps1 | 143 ++ docs/Icinga.PerformanceCounter.md | 730 +++++++++++ docs/index.md | 11 +- .../Icinga/IcingaPerformanceCounter.ps1 | 1164 +++++++++++++++++ ...ngaPerformanceCounterInstanceStructure.ps1 | 94 ++ .../Get-IcingaPerformanceCounterLiteral.ps1 | 53 + .../Get-IcingaPerformanceCounterValue.ps1 | 50 + .../Private/New-IcingaPerformanceCounter.ps1 | 57 + ...ew-IcingaPerformanceCounterEnvironment.ps1 | 62 + .../Read-IcingaPerformanceCounterCache.ps1 | 66 + ...gister-IcingaDefaultPerformanceCounter.ps1 | 30 + ...IcingaPerformanceCounterFromComponents.ps1 | 83 ++ .../Start-IcingaPerformanceCounterDaemon.ps1 | 65 + .../Test-IcingaPerformanceCounterDaemon.ps1 | 39 + .../Update-IcingaPerformanceCounterState.ps1 | 83 ++ .../Write-IcingaPerformanceCounterCache.ps1 | 54 + .../Public/Get-IcingaPerformanceCounter.ps1 | 152 +++ .../Public/Show-IcingaPerformanceCounter.ps1 | 133 ++ .../Show-IcingaPerformanceCounterDetails.ps1 | 63 + 21 files changed, 3358 insertions(+), 5 deletions(-) create mode 100644 Tests/Get-IcingaPerformanceCounter.Tests.ps1 create mode 100644 Tests/PerformanceCounter.Tests.ps1 create mode 100644 docs/Icinga.PerformanceCounter.md create mode 100644 src/Classes/Icinga/IcingaPerformanceCounter.ps1 create mode 100644 src/PerformanceCounter/Private/ConvertTo-IcingaPerformanceCounterInstanceStructure.ps1 create mode 100644 src/PerformanceCounter/Private/Get-IcingaPerformanceCounterLiteral.ps1 create mode 100644 src/PerformanceCounter/Private/Get-IcingaPerformanceCounterValue.ps1 create mode 100644 src/PerformanceCounter/Private/New-IcingaPerformanceCounter.ps1 create mode 100644 src/PerformanceCounter/Private/New-IcingaPerformanceCounterEnvironment.ps1 create mode 100644 src/PerformanceCounter/Private/Read-IcingaPerformanceCounterCache.ps1 create mode 100644 src/PerformanceCounter/Private/Register-IcingaDefaultPerformanceCounter.ps1 create mode 100644 src/PerformanceCounter/Private/Register-IcingaPerformanceCounterFromComponents.ps1 create mode 100644 src/PerformanceCounter/Private/Start-IcingaPerformanceCounterDaemon.ps1 create mode 100644 src/PerformanceCounter/Private/Test-IcingaPerformanceCounterDaemon.ps1 create mode 100644 src/PerformanceCounter/Private/Update-IcingaPerformanceCounterState.ps1 create mode 100644 src/PerformanceCounter/Private/Write-IcingaPerformanceCounterCache.ps1 create mode 100644 src/PerformanceCounter/Public/Get-IcingaPerformanceCounter.ps1 create mode 100644 src/PerformanceCounter/Public/Show-IcingaPerformanceCounter.ps1 create mode 100644 src/PerformanceCounter/Public/Show-IcingaPerformanceCounterDetails.ps1 diff --git a/IcingaForWindows.psm1 b/IcingaForWindows.psm1 index b83c177..8be4fa4 100644 --- a/IcingaForWindows.psm1 +++ b/IcingaForWindows.psm1 @@ -144,6 +144,21 @@ function New-ModuleBaseEnvironment() 'Queue' = (New-Object System.Collections.Concurrent.BlockingCollection[PSObject] -ArgumentList (New-Object System.Collections.Concurrent.ConcurrentQueue[PSObject])); 'Level' = 'Info'; }; + 'PerformanceCounter' = [PSCustomObject]@{ + # Thread-safe transport only. The counter manager class is created lazily + # by the daemon once the kernel (and thus the class type) is dot-sourced. + 'RequestQueue' = (New-Object System.Collections.Concurrent.BlockingCollection[PSObject] -ArgumentList (New-Object System.Collections.Concurrent.ConcurrentQueue[PSObject])); + 'PendingRequests' = (New-Object 'System.Collections.Concurrent.ConcurrentDictionary[string, System.Collections.Concurrent.BlockingCollection[PSObject]]'); + 'Registered' = (New-Object 'System.Collections.Concurrent.ConcurrentDictionary[string, datetime]'); + 'Manager' = $null; + 'Heartbeat' = $null; + 'LastRefresh' = $null; + 'Config' = [PSCustomObject]@{ + 'WarmupMilliseconds' = 250; + 'RefreshIntervalMs' = 1000; + 'EvictionMinutes' = 60; + }; + }; 'External' = $null; 'ReturnCodes' = $null; } @@ -388,6 +403,7 @@ function Use-IcingaForWindows() New-Thread -Command 'Start-LoggingDaemon' -KeepAlive -WaitForJobs -Start; New-Thread -Command 'Start-ModuleGarbageCollector' -KeepAlive -Start; New-Thread -Command 'Start-ThreadHouseKeeper' -Start; + New-Thread -Command 'Start-IcingaPerformanceCounterDaemon' -KeepAlive -WaitForJobs -Start; New-Thread -Command 'Start-RestApiDaemon' -Start; New-Thread -Command 'Start-ModuleWebSocketDaemon' -Start; New-Thread -Command 'Start-IcingaAgent' -Start; diff --git a/Tests/Get-IcingaPerformanceCounter.Tests.ps1 b/Tests/Get-IcingaPerformanceCounter.Tests.ps1 new file mode 100644 index 0000000..17b25b5 --- /dev/null +++ b/Tests/Get-IcingaPerformanceCounter.Tests.ps1 @@ -0,0 +1,215 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Get-IcingaPerformanceCounter' { + BeforeAll { + # The IcingaPerformanceCounter class is compiled into the module-scoped kernel and is + # not visible in the test scope. Grab the Script module so we can construct it and call + # private functions in their own scope (see the testing-module-scoped-classes pattern). + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | Select-Object -First 1; + } + + Context 'Uniform result contract' { + It 'Returns the five-key result hashtable for a stable counter' { + $result = Get-IcingaPerformanceCounter -Counter '\Memory\Available Bytes'; + $entry = $result['\Memory\Available Bytes']; + ($entry.Keys | Sort-Object) -join ',' | Should -Be 'error,help,sample,type,value'; + } + + It 'Reports a plausible value and no error for a valid counter' { + $result = Get-IcingaPerformanceCounter -Counter '\Memory\Available Bytes'; + $entry = $result['\Memory\Available Bytes']; + $entry.error | Should -BeNullOrEmpty; + [decimal]$entry.value | Should -BeGreaterThan 0; + } + + It 'Returns a nested hashtable keyed by instance for a wildcard counter' { + $result = Get-IcingaPerformanceCounter -Counter '\PhysicalDisk(*)\Disk Reads/sec'; + $group = $result['\PhysicalDisk(*)\Disk Reads/sec']; + $group | Should -BeOfType 'System.Collections.Hashtable'; + $group.Keys.Count | Should -BeGreaterThan 0; + } + + It 'Returns an empty hashtable when no counter is requested' { + (Get-IcingaPerformanceCounter -Counter @()).Count | Should -Be 0; + } + } + + Context 'Error handling never throws' { + It 'Surfaces an unknown counter through the error key instead of throwing' { + $result = Get-IcingaPerformanceCounter -Counter '\ThisCategoryDoesNotExist\Nope'; + $entry = $result['\ThisCategoryDoesNotExist\Nope']; + $entry | Should -Not -BeNullOrEmpty; + $entry.error | Should -Not -BeNullOrEmpty; + } + } + + Context 'Path parsing' { + It 'Parses a category, instance and counter' { + $parsed = & $script:IcingaModule { [IcingaPerformanceCounter]::ParsePath('\PhysicalDisk(0 C:)\Disk Reads/sec') }; + $parsed.Category | Should -Be 'PhysicalDisk'; + $parsed.Instance | Should -Be '0 C:'; + $parsed.Counter | Should -Be 'Disk Reads/sec'; + $parsed.Valid | Should -Be $true; + } + + It 'Parses a single-instance counter' { + $parsed = & $script:IcingaModule { [IcingaPerformanceCounter]::ParsePath('\Memory\Available Bytes') }; + $parsed.Category | Should -Be 'Memory'; + $parsed.Instance | Should -Be ''; + $parsed.Valid | Should -Be $true; + } + + It 'Marks a malformed path as invalid without throwing' { + $parsed = & $script:IcingaModule { [IcingaPerformanceCounter]::ParsePath('not a counter path') }; + $parsed.Valid | Should -Be $false; + } + + It 'Marks paths with unclosed or misplaced parentheses as invalid' { + $unclosed = & $script:IcingaModule { [IcingaPerformanceCounter]::ParsePath('\Processor(\% Processor Time') }; + $unclosed.Valid | Should -Be $false; + + $unopened = & $script:IcingaModule { [IcingaPerformanceCounter]::ParsePath('\Processor)\% Processor Time') }; + $unopened.Valid | Should -Be $false; + + $noCat = & $script:IcingaModule { [IcingaPerformanceCounter]::ParsePath('\(_Total)\% Processor Time') }; + $noCat.Valid | Should -Be $false; + } + } + + Context 'Registration keeps counters warm' { + It 'New-IcingaPerformanceCounter registers the requested paths' { + $registered = & $script:IcingaModule { + New-IcingaPerformanceCounter -Counter @('\Processor(_Total)\% Processor Time'); + (Get-GlobalRuntimeVariable).Public.PerformanceCounter.Registered.ContainsKey('\Processor(_Total)\% Processor Time'); + }; + $registered | Should -Be $true; + } + + It 'Get-IcingaPerformanceCounter refreshes the last-seen timestamp' { + $seen = & $script:IcingaModule { + Get-IcingaPerformanceCounter -Counter '\Memory\Available Bytes' | Out-Null; + (Get-GlobalRuntimeVariable).Public.PerformanceCounter.Registered.ContainsKey('\Memory\Available Bytes'); + }; + $seen | Should -Be $true; + } + } + + Context 'Show-IcingaPerformanceCounter browse' { + It 'Lists performance counter categories' { + (Show-IcingaPerformanceCounter).Count | Should -BeGreaterThan 5; + } + + It 'Lists counter paths within a category' { + (Show-IcingaPerformanceCounter -Category 'Memory').Count | Should -BeGreaterThan 1; + } + + It 'Lists live instances for a wildcard counter' { + (Show-IcingaPerformanceCounter -Counter '\Processor(*)\% Processor Time').Count | Should -BeGreaterThan 0; + } + } + + Context 'StructureByInstance reshaping' { + It 'Keys instanced counters by instance, category then counter' { + $result = Get-IcingaPerformanceCounter -Counter '\Processor(*)\% Processor Time' -StructureByInstance; + $result.ContainsKey('_Total') | Should -Be $true; + $result['_Total']['Processor']['% Processor Time'].ContainsKey('value') | Should -Be $true; + } + + It 'Keys non-instanced counters by category then counter' { + $result = Get-IcingaPerformanceCounter -Counter '\Memory\Available Bytes' -StructureByInstance; + $result.ContainsKey('Memory') | Should -Be $true; + [decimal]$result['Memory']['Available Bytes'].value | Should -BeGreaterThan 0; + } + + It 'Combines instanced and non-instanced counters in one structure' { + $result = Get-IcingaPerformanceCounter -Counter '\Processor(*)\% Processor Time', '\Memory\Available Bytes' -StructureByInstance; + $result['_Total']['Processor']['% Processor Time'].ContainsKey('value') | Should -Be $true; + [decimal]$result['Memory']['Available Bytes'].value | Should -BeGreaterThan 0; + } + + It 'Keeps accurate values when wildcard and individual instance paths are mixed' { + $result = Get-IcingaPerformanceCounter -Counter '\Processor(*)\% Processor Time', '\Processor(_Total)\% Processor Time' -StructureByInstance; + $result.ContainsKey('_Total') | Should -Be $true; + $result['_Total']['Processor']['% Processor Time'].ContainsKey('value') | Should -Be $true; + } + } + + Context 'Category snapshots for wildcard paths' { + It 'Reads every process instance, including the own process' { + $group = (Get-IcingaPerformanceCounter -Counter '\Process(*)\ID Process')['\Process(*)\ID Process']; + [int[]]$Ids = @($group.Values | ForEach-Object { [int]$_.value }); + $Ids | Should -Contain $PID; + } + + It 'Reports plausible memory and thread values for the own process' { + $result = Get-IcingaPerformanceCounter -Counter '\Process(*)\ID Process', '\Process(*)\Working Set - Private', '\Process(*)\Thread Count' -StructureByInstance; + $own = @($result.Values | Where-Object { $null -ne $_['Process'] -and [int]$_['Process']['ID Process'].value -eq $PID })[0]; + [decimal]$own['Process']['Working Set - Private'].value | Should -BeGreaterThan 0; + [decimal]$own['Process']['Thread Count'].value | Should -BeGreaterThan 0; + $own['Process']['Thread Count'].help | Should -Not -BeNullOrEmpty; + } + + It 'Returns the live instances of the category' { + $group = (Get-IcingaPerformanceCounter -Counter '\Processor(*)\% Processor Time')['\Processor(*)\% Processor Time']; + $expected = @((New-Object System.Diagnostics.PerformanceCounterCategory('Processor')).GetInstanceNames() | ForEach-Object { '\Processor({0})\% Processor Time' -f $_ } | Sort-Object); + @($group.Keys | Sort-Object) | Should -Be $expected; + } + + It 'Calculates rate counters between two snapshots' { + $group = (Get-IcingaPerformanceCounter -Counter '\Processor(*)\% Processor Time')['\Processor(*)\% Processor Time']; + foreach ($entry in $group.Values) { + $entry.error | Should -BeNullOrEmpty; + [decimal]$entry.value | Should -BeGreaterOrEqual 0; + [decimal]$entry.value | Should -BeLessOrEqual 100; + } + } + + It 'Reports an error for every instance of an unknown counter' { + $group = (Get-IcingaPerformanceCounter -Counter '\Processor(*)\No Such Counter')['\Processor(*)\No Such Counter']; + $group.Count | Should -BeGreaterThan 0; + foreach ($entry in $group.Values) { + $entry.error | Should -Match 'does not exist'; + } + } + + It 'Returns no instances for an unknown category' { + (Get-IcingaPerformanceCounter -Counter '\IcingaNoSuchCategory(*)\Counter')['\IcingaNoSuchCategory(*)\Counter'].Count | Should -Be 0; + } + + It 'Returns no instances for a single-instance category' { + (Get-IcingaPerformanceCounter -Counter '\Memory(*)\Available Bytes')['\Memory(*)\Available Bytes'].Count | Should -Be 0; + } + } + + Context 'Get-IcingaPerformanceCounterValue' { + It 'Returns the numeric value for a healthy counter' { + $data = Get-IcingaPerformanceCounter -Counter '\Memory\Available Bytes' -StructureByInstance; + $value = & $script:IcingaModule { param($o) Get-IcingaPerformanceCounterValue -InputObject $o } $data['Memory']['Available Bytes']; + $value | Should -BeOfType 'System.Decimal'; + $value | Should -BeGreaterThan 0; + } + + It 'Returns the error string when the counter reported an error' { + $data = Get-IcingaPerformanceCounter -Counter '\Processor(999)\% Processor Time' -StructureByInstance; + $value = & $script:IcingaModule { param($o) Get-IcingaPerformanceCounterValue -InputObject $o } $data['999']['Processor']['% Processor Time']; + $value | Should -BeOfType 'System.String'; + $value | Should -Not -BeNullOrEmpty; + } + + It 'Returns $null for input that is not a counter value object' { + $value = & $script:IcingaModule { Get-IcingaPerformanceCounterValue -InputObject 42 }; + $value | Should -BeNullOrEmpty; + } + } + + Context 'Show-IcingaPerformanceCounterDetails' { + It 'Returns the value for a specific counter' { + $result = Show-IcingaPerformanceCounterDetails -Counter '\Memory\Available Bytes'; + [decimal]$result['\Memory\Available Bytes'].value | Should -BeGreaterThan 0; + } + } +} diff --git a/Tests/PerformanceCounter.Tests.ps1 b/Tests/PerformanceCounter.Tests.ps1 new file mode 100644 index 0000000..cc0dcb5 --- /dev/null +++ b/Tests/PerformanceCounter.Tests.ps1 @@ -0,0 +1,143 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Performance counter subsystem performance' { + BeforeAll { + $script:IcingaModule = Get-Module -Name 'IcingaForWindows' -All | + Where-Object { $_.ModuleType -eq 'Script' } | Select-Object -First 1; + } + + Context 'Batch warm-up uses a single shared sleep' { + It 'Warms eight counters in far less than eight warm-up windows' { + # The manager must prime a batch of new counters and then sleep once, not once per + # counter. With a 250 ms window, eight counters warmed serially would cost ~2000 ms; + # the batched implementation must stay well under that. + $elapsed = & $script:IcingaModule { + $counters = @( + '\Processor(_Total)\% Processor Time', + '\Processor(_Total)\% Idle Time', + '\Processor(_Total)\% User Time', + '\Processor(_Total)\% Privileged Time', + '\Memory\Available Bytes', + '\Memory\Committed Bytes', + '\Memory\Cache Bytes', + '\System\Processor Queue Length' + ); + + # Pre-initialize the perflib for these categories in a throwaway manager (no sleep) so + # the measurement below is not dominated by the one-time first-access cost, which is + # large on Windows PowerShell 5.1 and would otherwise mask the batching behavior. + $warm = [IcingaPerformanceCounter]::new(); + $warm.WarmupMilliseconds = 0; + $warm.Warmup([string[]]$counters); + $warm.Dispose(); + + $manager = [IcingaPerformanceCounter]::new(); + $manager.WarmupMilliseconds = 250; + $ms = (Measure-Command { $manager.Warmup([string[]]$counters) }).TotalMilliseconds; + $manager.Dispose(); + $ms; + }; + + # Eight counters warmed serially would cost ~2000 ms (8 x 250 ms). With one shared sleep + # and the perflib already initialized, the batch stays comfortably under a single second. + $elapsed | Should -BeLessThan 1000; + } + } + + Context 'Warm reads are fast' { + It 'Reads an already-warm counter without an extra warm-up sleep' { + $elapsed = & $script:IcingaModule { + $manager = [IcingaPerformanceCounter]::new(); + $manager.WarmupMilliseconds = 250; + $manager.Warmup([string[]]@('\Memory\Available Bytes')); + # Do one throwaway read first to absorb first-access perflib init and JIT, so the + # measurement isolates the warm-read cost and proves no warm-up sleep is paid again. + $manager.Resolve([string[]]@('\Memory\Available Bytes')) | Out-Null; + $ms = (Measure-Command { $manager.Resolve([string[]]@('\Memory\Available Bytes')) }).TotalMilliseconds; + $manager.Dispose(); + $ms; + }; + + # Comfortably below the 250 ms warm-up window: a warm read must not sleep. + $elapsed | Should -BeLessThan 150; + } + } + + Context 'Category snapshots' { + It 'Reads wildcard paths through one snapshot per category without counter handles' { + $state = & $script:IcingaModule { + $manager = [IcingaPerformanceCounter]::new(); + $manager.WarmupMilliseconds = 250; + $manager.Warmup([string[]]@('\Process(*)\ID Process', '\Process(*)\Thread Count', '\Memory\Available Bytes')); + $state = @{ 'Categories' = @($manager.Categories.Keys); 'Counters' = @($manager.Counters.Keys); }; + $manager.Dispose(); + $state; + }; + + $state['Categories'] | Should -Be @('Process'); + $state['Counters'] | Should -Be @('\Memory\Available Bytes'); + } + + It 'Reads five counters of every process quickly once warm' { + $elapsed = & $script:IcingaModule { + [string[]]$counters = @( + '\Process(*)\ID Process', + '\Process(*)\% Processor Time', + '\Process(*)\Working Set - Private', + '\Process(*)\Page File Bytes', + '\Process(*)\Thread Count' + ); + $manager = [IcingaPerformanceCounter]::new(); + $manager.WarmupMilliseconds = 250; + $manager.Resolve($counters) | Out-Null; + $ms = (Measure-Command { $manager.Resolve($counters) }).TotalMilliseconds; + $manager.Dispose(); + $ms; + }; + + $elapsed | Should -BeLessThan 300; + } + + It 'Drops the snapshot of a category that is no longer registered' { + $counts = & $script:IcingaModule { + $manager = [IcingaPerformanceCounter]::new(); + $manager.WarmupMilliseconds = 0; + $manager.Reconcile([string[]]@('\Processor(*)\% Processor Time')); + $before = $manager.Categories.Count; + $manager.Reconcile([string[]]@()); + $after = $manager.Categories.Count; + $manager.Dispose(); + @($before, $after); + }; + + $counts | Should -Be @(1, 0); + } + } + + Context 'Handle lifecycle does not leak' { + It 'Keeps the OS handle count bounded across many transient reads' { + $isSafe = & $script:IcingaModule { + [System.GC]::Collect(); + Start-Sleep -Milliseconds 500; + $handlesBefore = (Get-Process -Id $PID).HandleCount; + + for ($i = 0; $i -lt 30; $i++) { + [IcingaPerformanceCounter]::ResolveOnce([string[]]@('\Memory\Available Bytes', '\Processor(_Total)\% Processor Time'), 20) | Out-Null; + } + + [System.GC]::Collect(); + Start-Sleep -Milliseconds 500; + $handlesAfter = (Get-Process -Id $PID).HandleCount; + + Write-Host ([string]::Format('PerformanceCounter Handles Before: {0}, After: {1}', $handlesBefore, $handlesAfter)); + + ($handlesAfter -le ($handlesBefore + 100)); + }; + + $isSafe | Should -Be $true; + } + } +} diff --git a/docs/Icinga.PerformanceCounter.md b/docs/Icinga.PerformanceCounter.md new file mode 100644 index 0000000..0d51885 --- /dev/null +++ b/docs/Icinga.PerformanceCounter.md @@ -0,0 +1,730 @@ +# Icinga.PerformanceCounter + +*Auto-generated from `src/PerformanceCounter/`. Do not edit by hand -- run `build/Build-ModuleDocs.ps1` to regenerate.* + +## Public functions + +- [Get-IcingaPerformanceCounter](#get-icingaperformancecounter) +- [Show-IcingaPerformanceCounter](#show-icingaperformancecounter) +- [Show-IcingaPerformanceCounterDetails](#show-icingaperformancecounterdetails) + +## Private helpers + +- [ConvertTo-IcingaPerformanceCounterInstanceStructure](#convertto-icingaperformancecounterinstancestructure) +- [Get-IcingaPerformanceCounterLiteral](#get-icingaperformancecounterliteral) +- [Get-IcingaPerformanceCounterValue](#get-icingaperformancecountervalue) +- [New-IcingaPerformanceCounter](#new-icingaperformancecounter) +- [New-IcingaPerformanceCounterEnvironment](#new-icingaperformancecounterenvironment) +- [Read-IcingaPerformanceCounterCache](#read-icingaperformancecountercache) +- [Register-IcingaDefaultPerformanceCounter](#register-icingadefaultperformancecounter) +- [Register-IcingaPerformanceCounterFromComponents](#register-icingaperformancecounterfromcomponents) +- [Start-IcingaPerformanceCounterDaemon](#start-icingaperformancecounterdaemon) +- [Test-IcingaPerformanceCounterDaemon](#test-icingaperformancecounterdaemon) +- [Update-IcingaPerformanceCounterState](#update-icingaperformancecounterstate) +- [Write-IcingaPerformanceCounterCache](#write-icingaperformancecountercache) + +--- + +### Get-IcingaPerformanceCounter + +*Public function* + +**Synopsis:** Read one or more Windows performance counters and return their current values + +#### Description + +`Get-IcingaPerformanceCounter` returns the current values of the requested counter paths. By default +the result is a hashtable keyed by the requested path: a concrete path maps to a flat result +hashtable with the keys value, sample, help, type and error; a wildcard path (instance '*') maps to a +nested hashtable keyed by each live instance path. + +With `-StructureByInstance` the result is reshaped for easier plugin consumption: counters with an +instance are keyed instance-first (`$out[Instance][Category][Counter]`), counters without an instance +are keyed category-first (`$out[Category][Counter]`), and the leaf is always the uniform value +hashtable. + +When the performance-counter daemon is running the read is dispatched through a request/pull queue: +the function generates a request id, registers a single-slot response queue, enqueues the request and +blocks on the response for up to the given timeout. All counter access happens on the daemon thread, +so there are no races on the underlying counter handles. When no daemon is running the function uses a +persistent per-runspace manager kept in module scope, so repeated reads stay warm and only the first +read of a new counter pays the warm-up sleep. + +Requesting a counter also refreshes its last-seen timestamp in the registry, keeping actively used +counters warm and out of the eviction path. + +#### Parameters + +**`$Counter`** + +| Name | Type | Description | Default | +|---------|--------------|----------------------------------------------------------------|---------| +| Counter | System.Array | One or more counter paths to read, e.g. '\Processor(*)\...'. | @() | + +**`$TimeoutMs`** + +| Name | Type | Description | Default | +|-----------|--------------|-------------------------------------------------------------|---------| +| TimeoutMs | System.Int32 | Milliseconds to wait for the daemon response before giving up.| 5000 | + +**`$StructureByInstance`** + +| Name | Type | Description | Default | +|---------------------|----------------------------------------------|--------------------------------------------------------------------------|---------| +| StructureByInstance | System.Management.Automation.SwitchParameter | Reshape the result to instance/category/counter (category/counter when no instance). | $false | + +#### Outputs + +System.Collections.Hashtable — By default keyed by requested path (flat for concrete paths, nested for +wildcard paths). With `-StructureByInstance`, keyed by instance then category then counter, or by +category then counter for counters without an instance. Returns an empty hashtable when no counter is +requested, or $null when the daemon request times out. + +#### Examples + +```powershell +PS> Get-IcingaPerformanceCounter -Counter '\Processor(_Total)\% Processor Time' + +Reads a single counter and returns its value hashtable. +``` + +```powershell +PS> $cpu = Get-IcingaPerformanceCounter -Counter '\Processor(*)\% Processor Time' -StructureByInstance +PS> $cpu.'0'.'Processor'.'% Processor Time'.value + +Reads every processor instance and addresses one core by instance, category and counter name. +``` + +```powershell +PS> $mem = Get-IcingaPerformanceCounter -Counter '\Memory\Pages/sec' -StructureByInstance +PS> $mem.'Memory'.'Pages/sec'.value + +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. + +*Source: [src/PerformanceCounter/Public/Get-IcingaPerformanceCounter.ps1](../../src/PerformanceCounter/Public/Get-IcingaPerformanceCounter.ps1)* + +--- + +### Show-IcingaPerformanceCounter + +*Public function* + +**Synopsis:** Browse performance counter categories, counters and live instances + +#### Description + +`Show-IcingaPerformanceCounter` is a stateless introspection helper that queries Windows +performance counter metadata directly. It has three modes selected by the parameters passed: + +- With no arguments it lists all counter categories, optionally filtered by `-Filter` using + wildcard matching. +- With `-Category` it lists the counter paths inside that category, emitting '\Category(*)\Counter' + for multi-instance categories and '\Category\Counter' for single-instance categories. +- With `-Counter` (a wildcard path) it lists the concrete counter paths for every live instance. + +Because it only reads metadata it is safe to call from any thread and does not require the +daemon. Errors are logged and yield an empty result rather than throwing. + +#### Parameters + +**`$Category`** + +| Name | Type | Description | Default | +|----------|---------------|----------------------------------------------------------|---------| +| Category | System.String | List the counters within this category. | $null | + +**`$Counter`** + +| Name | Type | Description | Default | +|---------|---------------|-----------------------------------------------------------------|---------| +| Counter | System.String | Wildcard counter path whose live instances should be listed. | $null | + +**`$Filter`** + +| Name | Type | Description | Default | +|--------|---------------|------------------------------------------------------------|---------| +| Filter | System.String | Wildcard filter applied when listing categories. | $null | + +#### Outputs + +System.Array — Category names, counter paths, or instance paths depending on the mode. + +#### Examples + +```powershell +PS> Show-IcingaPerformanceCounter + +Lists all performance counter categories. +``` + +```powershell +PS> Show-IcingaPerformanceCounter -Category 'Processor' + +Lists the counter paths available in the Processor category. +``` + +```powershell +PS> Show-IcingaPerformanceCounter -Counter '\PhysicalDisk(*)\Disk Reads/sec' + +Lists the concrete per-instance paths that currently exist for the wildcard counter. +``` + +#### Notes + +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)* + +--- + +### Show-IcingaPerformanceCounterDetails + +*Public function* + +**Synopsis:** Show live values for the registered performance counters, or a filtered subset + +#### Description + +`Show-IcingaPerformanceCounterDetails` returns the current values of performance counters +through `Get-IcingaPerformanceCounter`. Called without arguments it dumps every counter +currently registered in the global store. Passing `-Counter` narrows the output to the given +paths. The result keeps the uniform shape: a hashtable keyed by counter path with flat value +hashtables for concrete paths and nested hashtables for wildcard paths. + +#### Parameters + +**`$Counter`** + +| Name | Type | Description | Default | +|---------|--------------|--------------------------------------------------------------------|---------| +| Counter | System.Array | Counter paths to show. Empty shows all registered counters. | @() | + +**`$StructureByInstance`** + +| Name | Type | Description | Default | +|---------------------|----------------------------------------------|--------------------------------------------------------------------------|---------| +| StructureByInstance | System.Management.Automation.SwitchParameter | Reshape the result to instance/category/counter, forwarded to Get-IcingaPerformanceCounter. | $false | + +#### Outputs + +System.Collections.Hashtable — Keyed by counter path; values as returned by +`Get-IcingaPerformanceCounter`. With `-StructureByInstance`, keyed by instance/category/counter. +Empty when nothing is registered and nothing is requested. + +#### Examples + +```powershell +PS> Show-IcingaPerformanceCounterDetails + +Shows live values for every registered counter. +``` + +```powershell +PS> Show-IcingaPerformanceCounterDetails -Counter '\Processor(_Total)\% Processor Time' + +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. + +*Source: [src/PerformanceCounter/Public/Show-IcingaPerformanceCounterDetails.ps1](../../src/PerformanceCounter/Public/Show-IcingaPerformanceCounterDetails.ps1)* + +--- + +### ConvertTo-IcingaPerformanceCounterInstanceStructure + +*Private function* + +**Synopsis:** Reshape a flat performance counter result into an instance/category/counter structure + +#### Description + +`ConvertTo-IcingaPerformanceCounterInstanceStructure` transforms the default result of +`Get-IcingaPerformanceCounter` (a hashtable keyed by the requested counter path) into a nested +structure that is easier to consume when writing plugins. + +Counters that carry an instance are keyed instance-first, then category, then counter name: +`$out[Instance][Category][Counter]`. Counters without an instance are keyed category-first, then +counter name: `$out[Category][Counter]`. In both cases the leaf is the uniform value hashtable +(`value`, `sample`, `help`, `type`, `error`), so `$out['0']['Processor']['% Processor Time'].value` +and `$out['Memory']['Pages/sec'].value` both work. Wildcard requests are expanded so each live +instance becomes its own top-level key (for example CPU cores `0`, `1`, `_Total`). + +The requested paths are re-parsed to decide the shape, so the transform never has to guess whether a +nested value is a value hashtable or an instance group. + +#### Parameters + +**`$Result`** + +| Name | Type | Description | Default | +|--------|-----------------------------|------------------------------------------------------------|---------| +| Result | System.Collections.Hashtable| The result returned by the manager, keyed by requested path.| @{ } | + +**`$Counter`** + +| Name | Type | Description | Default | +|---------|--------------|---------------------------------------------------------|---------| +| Counter | System.Array | The originally requested counter paths, used to drive the reshape. | @() | + +#### Outputs + +System.Collections.Hashtable — Nested structure keyed by instance/category or category, with the +uniform value hashtable at the leaf. + +#### Examples + +```powershell +PS> ConvertTo-IcingaPerformanceCounterInstanceStructure -Result $raw -Counter '\Processor(*)\% Processor Time' +``` + +#### Notes + +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)* + +--- + +### Get-IcingaPerformanceCounterLiteral + +*Private function* + +**Synopsis:** Extract literal counter path strings from an AST argument node + +#### Description + +`Get-IcingaPerformanceCounterLiteral` walks an argument's abstract syntax tree and +collects the value of every string constant it contains. It is used by the startup +discovery step to read the literal counter list passed to a `New-IcingaPerformanceCounter` +call without executing any component code. Non-literal arguments (variables, expressions) +contribute no values, which is intentional — only statically declarable counters are +discovered. + +#### Parameters + +**`$Argument`** + +| Name | Type | Description | Default | +|----------|---------------------------------------------|---------------------------------------------|---------| +| Argument | System.Management.Automation.Language.Ast | The AST node of the `-Counter` argument. | $null | + +#### Outputs + +System.Array — The literal string values found in the argument, or an empty array. + +#### Examples + +```powershell +PS> Get-IcingaPerformanceCounterLiteral -Argument $argumentAst +``` + +#### Notes + +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)* + +--- + +### Get-IcingaPerformanceCounterValue + +*Private function* + +**Synopsis:** Return the value of a performance counter result, or its error when one is present + +#### Description + +`Get-IcingaPerformanceCounterValue` extracts the usable result from a single performance counter value +object (the leaf hashtable produced by `Get-IcingaPerformanceCounter`, containing the keys value, +sample, help, type and error). If the counter reported an error the error message is returned; +otherwise the numeric value is returned. This lets a plugin drill down to a single counter and get +back either a number to threshold against or the error text to surface, in one call. + +Because the value is always numeric and the error is always a string, callers can tell the two apart +with a simple type check (`$result -is [string]` means an error was returned). + +#### Parameters + +**`$InputObject`** + +| Name | Type | Description | Default | +|-------------|---------------|----------------------------------------------------------------------|---------| +| InputObject | System.Object | A single counter value object (the leaf hashtable of a counter read). | $null | + +#### Outputs + +System.Object — The counter value (typically System.Decimal), or the error message (System.String) +when the counter reported one. Returns $null when the input is not a counter value object. + +#### Examples + +```powershell +PS> $data = Get-IcingaPerformanceCounter -Counter '\Processor(*)\% Processor Time' -StructureByInstance +PS> Get-IcingaPerformanceCounterValue -InputObject $data.'0'.'Processor'.'% Processor Time' + +Returns the processor load of core 0, or the error text if that counter could not be read. +``` + +#### 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. + +*Source: [src/PerformanceCounter/Private/Get-IcingaPerformanceCounterValue.ps1](../../src/PerformanceCounter/Private/Get-IcingaPerformanceCounterValue.ps1)* + +--- + +### New-IcingaPerformanceCounter + +*Private function* + +**Synopsis:** Declare and keep-alive a set of performance counters for a component + +#### Description + +`New-IcingaPerformanceCounter` registers the given counter paths in the global +performance-counter store so the background daemon initializes, warms and keeps them +available. Calling it refreshes each counter's last-seen timestamp, which both prevents +eviction of actively-used counters and drives the self-maintaining cache file. + +Components declare the counters they need by calling this function with a literal list. +At module start the discovery step statically scans the compiled kernel for these calls +and seeds the registry from the extracted counter paths, so a declared counter is warm +before it is ever requested. The function only writes to the thread-safe registry +dictionary, so it is safe to call from any thread. + +#### Parameters + +**`$Counter`** + +| Name | Type | Description | Default | +|---------|---------------|---------------------------------------------------------|---------| +| Counter | System.Array | One or more counter paths to register, e.g. '\Cat\Ctr'. | @() | + +#### Outputs + +None — Registers the counter paths in the global store. + +#### Examples + +```powershell +PS> New-IcingaPerformanceCounter -Counter @('\Processor(*)\% Processor Time', '\Memory\Available Bytes') + +Declares two counters so the daemon keeps them warm and the discovery step can find them. +``` + +#### Notes + +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)* + +--- + +### New-IcingaPerformanceCounterEnvironment + +*Private function* + +**Synopsis:** Initialize the performance counter manager, cache and warm counter set + +#### Description + +`New-IcingaPerformanceCounterEnvironment` prepares the performance-counter subsystem for +the daemon. It creates the central manager instance the first time it runs (the class type +is available because the kernel has been dot-sourced by then), loads the persisted cache, +runs component discovery to register statically declared counters, and reconciles the +manager so every registered counter is warmed in a single batch. It also stamps the initial +heartbeat and refresh timestamps. + +This function is expected to run inside the performance-counter daemon runspace, before the +daemon enters its processing loop, so the manager is created and used on a single thread. + +#### Outputs + +None — Populates `(Get-GlobalRuntimeVariable).Public.PerformanceCounter`. + +#### Examples + +```powershell +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. + +*Source: [src/PerformanceCounter/Private/New-IcingaPerformanceCounterEnvironment.ps1](../../src/PerformanceCounter/Private/New-IcingaPerformanceCounterEnvironment.ps1)* + +--- + +### Read-IcingaPerformanceCounterCache + +*Private function* + +**Synopsis:** Load the registered performance counters from the cache file + +#### Description + +`Read-IcingaPerformanceCounterCache` reads the persisted counter cache written by +`Write-IcingaPerformanceCounterCache` and merges its entries into the global registry. +It runs during performance-counter environment initialization so counters learned in +previous runs are warmed immediately at startup. A missing, empty or corrupt cache file +is ignored silently so a bad cache never blocks the daemon. + +#### Outputs + +None — Populates `(Get-GlobalRuntimeVariable).Public.PerformanceCounter.Registered`. + +#### Examples + +```powershell +PS> Read-IcingaPerformanceCounterCache +``` + +#### Notes + +`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. + +*Source: [src/PerformanceCounter/Private/Read-IcingaPerformanceCounterCache.ps1](../../src/PerformanceCounter/Private/Read-IcingaPerformanceCounterCache.ps1)* + +--- + +### Register-IcingaDefaultPerformanceCounter + +*Private function* + +**Synopsis:** Declare the default set of performance counters shipped with the module + +#### Description + +`Register-IcingaDefaultPerformanceCounter` declares a small, broadly-available set of +performance counters (processor, memory and physical disk) by calling +`New-IcingaPerformanceCounter`. It serves as the reference example of how a component +declares the counters it needs and gives the startup discovery step and the warm-up path a +concrete set to work with. Additional components declare their own counters the same way. + +#### Outputs + +None — Registers the default counter paths in the global store. + +#### Examples + +```powershell +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. + +*Source: [src/PerformanceCounter/Private/Register-IcingaDefaultPerformanceCounter.ps1](../../src/PerformanceCounter/Private/Register-IcingaDefaultPerformanceCounter.ps1)* + +--- + +### Register-IcingaPerformanceCounterFromComponents + +*Private function* + +**Synopsis:** Discover component-declared performance counters by scanning the compiled kernel + +#### Description + +`Register-IcingaPerformanceCounterFromComponents` parses the compiled module kernel +(`lib\IcingaForWindows.Kernel.ps1`, which contains every source file concatenated) and +finds all calls to `New-IcingaPerformanceCounter`. For each call it extracts the literal +counter paths passed to the `-Counter` parameter and registers them in the global store. +No component code is executed — the declaration is read statically from the syntax tree. + +This runs once during performance-counter environment initialization so that every +counter any component declares is warmed as soon as the daemon starts. + +#### Outputs + +None — Populates `(Get-GlobalRuntimeVariable).Public.PerformanceCounter.Registered`. + +#### Examples + +```powershell +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. + +*Source: [src/PerformanceCounter/Private/Register-IcingaPerformanceCounterFromComponents.ps1](../../src/PerformanceCounter/Private/Register-IcingaPerformanceCounterFromComponents.ps1)* + +--- + +### Start-IcingaPerformanceCounterDaemon + +*Private function* + +**Synopsis:** Background daemon that serves performance counter requests and maintains the registry + +#### Description + +`Start-IcingaPerformanceCounterDaemon` initializes the performance-counter environment and +then runs the request/refresh loop while `Test-ThreadRunning` is true. Each cycle it blocks +briefly on the request queue; when a request arrives it resolves the requested counters +through the central manager and pushes the result into the caller's pending response queue, +keyed by the request id. When idle (and on a throttled interval) it runs the maintenance +step which refreshes the heartbeat, reconciles transient instances, evicts unused counters +and persists the cache. + +Because every performance counter handle is created, sampled and disposed here on this one +thread, callers never touch the non-thread-safe counter objects directly — they exchange +data through the thread-safe queues only. + +#### Outputs + +None — Operates for side effects (serves requests and maintains counters). + +#### Examples + +```powershell +PS> Start-IcingaPerformanceCounterDaemon +``` + +#### Notes + +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. + +*Source: [src/PerformanceCounter/Private/Start-IcingaPerformanceCounterDaemon.ps1](../../src/PerformanceCounter/Private/Start-IcingaPerformanceCounterDaemon.ps1)* + +--- + +### Test-IcingaPerformanceCounterDaemon + +*Private function* + +**Synopsis:** Determine whether the performance counter daemon is currently alive + +#### Description + +`Test-IcingaPerformanceCounterDaemon` checks the heartbeat timestamp the daemon refreshes +on every loop cycle. If the heartbeat is recent the daemon is considered alive and callers +route their reads through the request/response queue; otherwise `Get-IcingaPerformanceCounter` +falls back to a synchronous inline read. Using the heartbeat keeps the check decoupled from +the thread registry. + +#### Outputs + +System.Boolean — $true when the daemon heartbeat is recent, otherwise $false. + +#### Examples + +```powershell +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. + +*Source: [src/PerformanceCounter/Private/Test-IcingaPerformanceCounterDaemon.ps1](../../src/PerformanceCounter/Private/Test-IcingaPerformanceCounterDaemon.ps1)* + +--- + +### Update-IcingaPerformanceCounterState + +*Private function* + +**Synopsis:** Refresh, reconcile, evict and persist the performance counter state + +#### Description + +`Update-IcingaPerformanceCounterState` is the periodic maintenance step run by the +performance-counter daemon. On every call it refreshes the daemon heartbeat. When the +configured refresh interval has elapsed it additionally evicts counters that have not been +requested for longer than the eviction window, reconciles the manager against the current +registration set (adding new instances and disposing vanished ones such as a removed disk), +takes a fresh sample of every counter to keep rate values current, and persists the cache +file. + +Extracting this maintenance out of the daemon loop keeps the loop body small and lets the +throttling logic live in one place. + +#### Parameters + +**`$Store`** + +| Name | Type | Description | Default | +|-------|---------------|-------------------------------------------------------------------------|---------| +| Store | System.Object | The performance-counter store to operate on. Resolved from the runtime when omitted. | $null | + +#### Outputs + +None — Mutates the global performance-counter store and writes the cache file. + +#### Examples + +```powershell +PS> Update-IcingaPerformanceCounterState +``` + +#### Notes + +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. + +*Source: [src/PerformanceCounter/Private/Update-IcingaPerformanceCounterState.ps1](../../src/PerformanceCounter/Private/Update-IcingaPerformanceCounterState.ps1)* + +--- + +### Write-IcingaPerformanceCounterCache + +*Private function* + +**Synopsis:** Persist the registered performance counters to the cache file + +#### Description + +`Write-IcingaPerformanceCounterCache` serializes the registered counter paths and their +last-seen timestamps to a JSON file in the module cache directory. The daemon calls this +each refresh cycle so the warm counter set survives restarts and self-maintains — new +counters are added and stale ones drop out over time. The file is written atomically by +writing to a temporary file and renaming it into place. + +#### Outputs + +None — Writes the cache file to disk. + +#### Examples + +```powershell +PS> Write-IcingaPerformanceCounterCache +``` + +#### Notes + +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. + +*Source: [src/PerformanceCounter/Private/Write-IcingaPerformanceCounterCache.ps1](../../src/PerformanceCounter/Private/Write-IcingaPerformanceCounterCache.ps1)* + + diff --git a/docs/index.md b/docs/index.md index 9f7e949..ace2960 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,6 +1,6 @@ # Icinga API Reference -*Auto-generated on 2026-08-18 17:35:01.* +*Auto-generated on 2026-08-27 15:12:43.* | Component | Public functions | Private helpers | |-----------|------------------|-----------------| @@ -14,13 +14,14 @@ | [Icinga.Core.Threading](Icinga.Core.Threading.md) | 2 | 14 | | [Icinga.Core.WebSocket](Icinga.Core.WebSocket.md) | 3 | 16 | | [Icinga.IcingaProtocol](Icinga.IcingaProtocol.md) | 5 | 19 | +| [Icinga.PerformanceCounter](Icinga.PerformanceCounter.md) | 3 | 12 | | [Icinga.Security](Icinga.Security.md) | 0 | 7 | | [Icinga.Tools](Icinga.Tools.md) | 5 | 5 | ## Totals -- Components: 12 -- Documented functions: 147 -- Public: 24 -- Private: 123 +- Components: 13 +- Documented functions: 162 +- Public: 27 +- Private: 135 diff --git a/src/Classes/Icinga/IcingaPerformanceCounter.ps1 b/src/Classes/Icinga/IcingaPerformanceCounter.ps1 new file mode 100644 index 0000000..251910b --- /dev/null +++ b/src/Classes/Icinga/IcingaPerformanceCounter.ps1 @@ -0,0 +1,1164 @@ +<# +.SYNOPSIS +Live wrapper around a single Windows performance counter handle + +.DESCRIPTION +IcingaPerformanceCounterEntry owns exactly one `System.Diagnostics.PerformanceCounter` +handle for a fully-qualified counter path (category, optional instance, counter). It +implements the prime-then-read pattern required for accurate rate counters: `Prime` +takes the first (throwaway) sample, and `Read` takes the second sample and returns the +uniform value hashtable. The class never throws on counter errors — failures are +surfaced through the `error` key of the returned hashtable — and disposes its handle +through `Dispose`. + +The handle is created and read on a single thread only (the performance-counter +daemon, or a transient one-shot resolver). The class holds no global state and is +therefore safe to construct in any runspace, mirroring the IcingaUnit class. + +.OUTPUTS +IcingaPerformanceCounterEntry — A single initialized counter wrapper. + +.EXAMPLE +PS> [IcingaPerformanceCounterEntry]::new('\Processor(_Total)\% Processor Time', '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. +#> +class IcingaPerformanceCounterEntry +{ + [string]$FullName = ''; + [string]$Category = ''; + [string]$Instance = ''; + [string]$Counter = ''; + [System.Diagnostics.PerformanceCounter]$Handle = $null; + [bool]$Primed = $false; + + <# + .SYNOPSIS + Create a counter entry for a fully-qualified counter path + + .DESCRIPTION + Stores the parsed components of a counter path. The underlying handle is created + lazily on the first `Prime` call, not in the constructor. + + .PARAMETER FullName + | Name | Type | Description | Default | + |----------|---------------|----------------------------------------------------|---------| + | FullName | System.String | The complete counter path, e.g. '\Cat(Inst)\Ctr'. | | + + .PARAMETER Category + | Name | Type | Description | Default | + |----------|---------------|-----------------------------------|---------| + | Category | System.String | The performance counter category. | | + + .PARAMETER Instance + | Name | Type | Description | Default | + |----------|---------------|----------------------------------------------------|---------| + | Instance | System.String | The instance name, or empty for single-instance. | | + + .PARAMETER Counter + | Name | Type | Description | Default | + |---------|---------------|---------------------------|---------| + | Counter | System.String | The counter name to read. | | + + .OUTPUTS + IcingaPerformanceCounterEntry — The configured, not-yet-primed entry. + + .EXAMPLE + PS> [IcingaPerformanceCounterEntry]::new('\Memory\Available Bytes', 'Memory', '', 'Available Bytes') + #> + IcingaPerformanceCounterEntry([string]$FullName, [string]$Category, [string]$Instance, [string]$Counter) + { + $this.FullName = $FullName; + $this.Category = $Category; + $this.Instance = $Instance; + $this.Counter = $Counter; + } + + <# + .SYNOPSIS + Create the handle and take the first (priming) sample + + .DESCRIPTION + Instantiates the `System.Diagnostics.PerformanceCounter` handle on first use and + calls `NextValue`/`NextSample` once to prime rate counters. The first sample of a + rate counter is meaningless, so callers must wait a short interval before calling + `Read`. Priming errors are swallowed and surface later through `Read`. + + .OUTPUTS + None — Populates the `Handle` field and sets `Primed`. + + .EXAMPLE + PS> $entry.Prime() + + .NOTES + Callers are expected to batch a single shared sleep after priming many entries, + rather than sleeping per entry. + #> + [void] Prime() + { + if ($null -eq $this.Handle) { + $this.Handle = New-Object System.Diagnostics.PerformanceCounter; + $this.Handle.CategoryName = $this.Category; + $this.Handle.CounterName = $this.Counter; + + if (-not [string]::IsNullOrEmpty($this.Instance)) { + $this.Handle.InstanceName = $this.Instance; + } + } + + try { + $this.Handle.NextValue() | Out-Null; + $this.Handle.NextSample() | Out-Null; + } catch { + # A priming failure is reported on the next Read call through the error key. + $Error.Clear(); + } + + $this.Primed = $true; + } + + <# + .SYNOPSIS + Read the current counter value as the uniform result hashtable + + .DESCRIPTION + Takes the second sample of the counter and returns a hashtable with the fixed keys + `value`, `sample`, `help`, `type` and `error`. `value` is rounded to six decimals. + The method never throws — any exception is captured into the `error` key while the + remaining keys keep their defaults. + + .OUTPUTS + System.Collections.Hashtable — Keys value, sample, help, type, error. + + .EXAMPLE + PS> $result = $entry.Read() + #> + [hashtable] Read() + { + [hashtable]$Result = @{ + 'value' = [decimal]0; + 'sample' = $null; + 'help' = $null; + 'type' = $null; + 'error' = $null; + }; + + if ($null -eq $this.Handle) { + $Result['error'] = 'Counter not initialized'; + return $Result; + } + + try { + $CounterValue = $this.Handle.NextValue(); + if ($null -eq $CounterValue) { + $CounterValue = 0; + } + + $Result['value'] = [math]::Round([decimal]$CounterValue, 6); + $Result['sample'] = $this.Handle.NextSample(); + $Result['help'] = $this.Handle.CounterHelp; + $Result['type'] = [string]$this.Handle.CounterType; + } catch { + $Result['error'] = $_.Exception.Message; + } + + return $Result; + } + + <# + .SYNOPSIS + Release the underlying performance counter handle + + .DESCRIPTION + Disposes the `System.Diagnostics.PerformanceCounter` handle and clears the field so + the entry can be safely discarded. Safe to call multiple times. + + .OUTPUTS + None — Releases the native handle. + + .EXAMPLE + PS> $entry.Dispose() + #> + [void] Dispose() + { + if ($null -ne $this.Handle) { + $this.Handle.Dispose(); + $this.Handle = $null; + } + } +} + +<# +.SYNOPSIS +Snapshot reader for every instance and counter of one performance counter category + +.DESCRIPTION +IcingaPerformanceCounterCategory reads a whole category with one `ReadCategory` call +and keeps the previous and the current snapshot. A value is calculated from both +snapshots exactly like `PerformanceCounter.NextValue` calculates it from its last two +samples, so rate counters such as '% Processor Time' need no handle per instance. + +Wildcard counter paths ('\Process(*)\% Processor Time') are read through this class. +Every `NextValue` of a single handle reads the complete category data from the system, +so one handle per instance costs one category read per instance and refresh. For a +category with hundreds of instances (Process) that took seconds per refresh, while one +`ReadCategory` returns all instances and counters in a few milliseconds. + +Instances are matched between the two snapshots by name. In categories with an +'ID Process' counter (Process, Thread) an instance whose process id changed between +the snapshots is treated as new, because Windows renumbers 'name#n' instances when a +process with the same name exits; its rate counters then read 0 until the next +snapshot. + +.OUTPUTS +IcingaPerformanceCounterCategory — The snapshot reader of one category. + +.EXAMPLE +PS> $Snapshot = [IcingaPerformanceCounterCategory]::new('Process') +PS> $Snapshot.Prime(); Start-Sleep -Milliseconds 250; $Snapshot.Refresh() +PS> $Snapshot.Read('svchost', '% Processor Time') + +.NOTES +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. +#> +class IcingaPerformanceCounterCategory +{ + [string]$Category = ''; + [System.Diagnostics.PerformanceCounterCategory]$Reader = $null; + [System.Diagnostics.InstanceDataCollectionCollection]$Previous = $null; + [System.Diagnostics.InstanceDataCollectionCollection]$Current = $null; + [datetime]$ReadTime = [datetime]::MinValue; + [hashtable]$Help = $null; + [string]$LastError = ''; + + <# + .SYNOPSIS + Create a snapshot reader for a category + + .DESCRIPTION + Stores the category name. The category is read for the first time by `Prime`. + + .PARAMETER Category + | Name | Type | Description | Default | + |----------|---------------|-----------------------------------|---------| + | Category | System.String | The performance counter category. | | + + .OUTPUTS + IcingaPerformanceCounterCategory — The not yet primed reader. + + .EXAMPLE + PS> [IcingaPerformanceCounterCategory]::new('Processor Information') + #> + IcingaPerformanceCounterCategory([string]$Category) + { + $this.Category = $Category; + } + + <# + .SYNOPSIS + Take the first snapshot of the category + + .DESCRIPTION + Reads the category once. Rate counters need a second snapshot before they return a + meaningful value, so callers wait a short interval and call `Refresh`. A category + that cannot be read is remembered in `LastError` instead of throwing. + + .OUTPUTS + None — Populates the current snapshot. + + .EXAMPLE + PS> $Snapshot.Prime() + #> + [void] Prime() + { + try { + $this.Reader = New-Object System.Diagnostics.PerformanceCounterCategory($this.Category); + $this.Current = $this.Reader.ReadCategory(); + $this.ReadTime = [datetime]::UtcNow; + $this.LastError = ''; + } catch { + $this.LastError = $_.Exception.Message; + $Error.Clear(); + } + } + + <# + .SYNOPSIS + Take a new snapshot and keep the current one as the previous snapshot + + .DESCRIPTION + Values are calculated over the interval between the two snapshots. A failed read + keeps both snapshots and stores the reason in `LastError`. + + .OUTPUTS + None — Advances the snapshots. + + .EXAMPLE + PS> $Snapshot.Refresh() + #> + [void] Refresh() + { + if ($null -eq $this.Reader -or $null -eq $this.Current) { + $this.Prime(); + return; + } + + try { + $Snapshot = $this.Reader.ReadCategory(); + $this.Previous = $this.Current; + $this.Current = $Snapshot; + $this.ReadTime = [datetime]::UtcNow; + $this.LastError = ''; + } catch { + $this.LastError = $_.Exception.Message; + $Error.Clear(); + } + } + + <# + .SYNOPSIS + Return the age of the current snapshot in milliseconds + + .DESCRIPTION + Returns the milliseconds since the last successful read, or the largest double when + the category was never read. + + .OUTPUTS + System.Double — Age of the current snapshot. + + .EXAMPLE + PS> $Snapshot.AgeMilliseconds() + #> + [double] AgeMilliseconds() + { + if ($null -eq $this.Current) { + return [double]::MaxValue; + } + + return ([datetime]::UtcNow - $this.ReadTime).TotalMilliseconds; + } + + <# + .SYNOPSIS + Return the instance names of the current snapshot + + .DESCRIPTION + Returns every instance name with its original casing. The pseudo instance that + .NET reports for single-instance categories is left out, so a single-instance + category returns no instances, like `GetInstanceNames`. + + .OUTPUTS + System.String[] — The instance names of the current snapshot. + + .EXAMPLE + PS> $Snapshot.GetInstanceNames() + #> + [string[]] GetInstanceNames() + { + $Names = New-Object 'System.Collections.Generic.List[string]'; + + if ($null -eq $this.Current) { + return $Names.ToArray(); + } + + foreach ($Collection in $this.Current.Values) { + foreach ($Data in $Collection.Values) { + if ($Data.InstanceName -ne 'systemdiagnosticsperfcounterlibsingleinstance') { + $Names.Add($Data.InstanceName); + } + } + + # Every counter of a snapshot holds the same instances. + break; + } + + return $Names.ToArray(); + } + + <# + .SYNOPSIS + Read one counter of one instance as the uniform result hashtable + + .DESCRIPTION + Calculates the value from the previous and the current snapshot and returns a + hashtable with the keys `value`, `sample`, `help`, `type` and `error`, the same + shape as IcingaPerformanceCounterEntry.Read. Without a usable previous sample the + value is calculated from the current sample alone. The method never throws. + + .PARAMETER Instance + | Name | Type | Description | Default | + |----------|---------------|-----------------------|---------| + | Instance | System.String | The instance to read. | | + + .PARAMETER Counter + | Name | Type | Description | Default | + |---------|---------------|----------------------|---------| + | Counter | System.String | The counter to read. | | + + .OUTPUTS + System.Collections.Hashtable — Keys value, sample, help, type, error. + + .EXAMPLE + PS> $Snapshot.Read('_Total', '% Processor Time') + #> + [hashtable] Read([string]$Instance, [string]$Counter) + { + [hashtable]$Result = @{ + 'value' = [decimal]0; + 'sample' = $null; + 'help' = $null; + 'type' = $null; + 'error' = $null; + }; + + if ($null -eq $this.Current) { + if ([string]::IsNullOrEmpty($this.LastError)) { + $Result['error'] = 'Counter not initialized'; + } else { + $Result['error'] = $this.LastError; + } + + return $Result; + } + + $Collection = $this.Current[$Counter]; + + if ($null -eq $Collection) { + $Result['error'] = [string]::Format('The counter "{0}" does not exist in the category "{1}"', $Counter, $this.Category); + return $Result; + } + + $Data = $Collection[$Instance]; + + if ($null -eq $Data) { + $Result['error'] = [string]::Format('The instance "{0}" does not exist in the category "{1}"', $Instance, $this.Category); + return $Result; + } + + try { + $Sample = $Data.Sample; + $PreviousData = $this.FindPrevious($Instance, $Counter); + [double]$Value = 0; + + if ($null -eq $PreviousData) { + $Value = [System.Diagnostics.CounterSample]::Calculate($Sample); + } else { + $Value = [System.Diagnostics.CounterSample]::Calculate($PreviousData.Sample, $Sample); + } + + $Result['value'] = [math]::Round([decimal]$Value, 6); + $Result['sample'] = $Sample; + $Result['help'] = $this.GetHelp($Counter, $Instance); + $Result['type'] = [string]$Sample.CounterType; + } catch { + $Result['error'] = $_.Exception.Message; + } + + return $Result; + } + + <# + .SYNOPSIS + Find the previous instance data of a counter that belongs to the same instance + + .DESCRIPTION + Returns the instance data of the previous snapshot, or $null when there is no + previous snapshot, the instance is new, or (in categories with an 'ID Process' + counter) the name now belongs to a different process. + + .PARAMETER Instance + | Name | Type | Description | Default | + |----------|---------------|--------------------|---------| + | Instance | System.String | The instance name. | | + + .PARAMETER Counter + | Name | Type | Description | Default | + |---------|---------------|-------------------|---------| + | Counter | System.String | The counter name. | | + + .OUTPUTS + System.Diagnostics.InstanceData — The previous data, or $null. + + .EXAMPLE + PS> $Snapshot.FindPrevious('svchost#3', '% Processor Time') + #> + hidden [System.Diagnostics.InstanceData] FindPrevious([string]$Instance, [string]$Counter) + { + if ($null -eq $this.Previous) { + return $null; + } + + $Collection = $this.Previous[$Counter]; + + if ($null -eq $Collection) { + return $null; + } + + $Data = $Collection[$Instance]; + + if ($null -eq $Data) { + return $null; + } + + $PreviousIds = $this.Previous['ID Process']; + $CurrentIds = $this.Current['ID Process']; + + if ($null -ne $PreviousIds -and $null -ne $CurrentIds) { + $PreviousId = $PreviousIds[$Instance]; + $CurrentId = $CurrentIds[$Instance]; + + if ($null -eq $PreviousId -or $null -eq $CurrentId -or $PreviousId.RawValue -ne $CurrentId.RawValue) { + return $null; + } + } + + return $Data; + } + + <# + .SYNOPSIS + Return the help text of a counter + + .DESCRIPTION + Reads the help texts of all counters of the category once, through the handles + returned by `GetCounters` for the given instance, and disposes those handles right + away. Later calls answer from the cached texts. + + .PARAMETER Counter + | Name | Type | Description | Default | + |---------|---------------|-------------------|---------| + | Counter | System.String | The counter name. | | + + .PARAMETER Instance + | Name | Type | Description | Default | + |----------|---------------|---------------------------------------------|---------| + | Instance | System.String | An existing instance used to list counters. | | + + .OUTPUTS + System.String — The help text, or $null when it cannot be read. + + .EXAMPLE + PS> $Snapshot.GetHelp('% Processor Time', '_Total') + #> + hidden [string] GetHelp([string]$Counter, [string]$Instance) + { + if ($null -eq $this.Help) { + $this.Help = @{ }; + + try { + foreach ($Handle in $this.Reader.GetCounters($Instance)) { + $this.Help[$Handle.CounterName] = $Handle.CounterHelp; + $Handle.Dispose(); + } + } catch { + # Help texts are informational only; the value stays valid without them. + $Error.Clear(); + } + } + + return $this.Help[$Counter]; + } +} + +<# +.SYNOPSIS +Central, thread-confined registry and reader for Windows performance counters + +.DESCRIPTION +IcingaPerformanceCounter is the manager that owns every live counter handle for the +module. Concrete counter paths get one handle each; wildcard instance paths are read +through one IcingaPerformanceCounterCategory snapshot per category, because a handle +reads the whole category on every sample and large categories (Process) would cost one +category read per instance. New counters and categories are primed with a single +shared warm-up sleep, values are returned in the uniform result shape, rate counters +are kept warm, and transient instances (a removable disk appearing or disappearing) +are picked up by the category snapshots. + +The manager is created and used exclusively on the performance-counter daemon thread, +so its internal `ConcurrentDictionary` is never mutated concurrently. Callers on other +threads never touch the manager directly — they exchange requests and responses through +the thread-safe queues in the global runtime store. The self-contained one-shot +`ResolveOnce` supports command-line usage where no daemon is running. + +.OUTPUTS +IcingaPerformanceCounter — The counter manager instance. + +.EXAMPLE +PS> $manager = [IcingaPerformanceCounter]::new() +PS> $manager.Resolve(@('\Processor(_Total)\% Processor Time')) + +.NOTES +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. +#> +class IcingaPerformanceCounter +{ + [System.Collections.Concurrent.ConcurrentDictionary[string, IcingaPerformanceCounterEntry]]$Counters = $null; + [System.Collections.Concurrent.ConcurrentDictionary[string, IcingaPerformanceCounterCategory]]$Categories = $null; + [int]$WarmupMilliseconds = 250; + + <# + .SYNOPSIS + Create an empty counter manager + + .DESCRIPTION + Initializes the thread-safe registries for counter handles and category snapshots. + Nothing is read until `Warmup`, `Resolve` or `Reconcile` is called. + + .OUTPUTS + IcingaPerformanceCounter — An empty manager. + + .EXAMPLE + PS> [IcingaPerformanceCounter]::new() + #> + IcingaPerformanceCounter() + { + $this.Counters = New-Object 'System.Collections.Concurrent.ConcurrentDictionary[string, IcingaPerformanceCounterEntry]'; + $this.Categories = New-Object 'System.Collections.Concurrent.ConcurrentDictionary[string, IcingaPerformanceCounterCategory]'; + } + + <# + .SYNOPSIS + Parse a counter path into its category, instance and counter components + + .DESCRIPTION + Splits a fully-qualified counter path of the form '\Category\Counter' or + '\Category(Instance)\Counter' into its parts. Returns a hashtable with `Category`, + `Instance`, `Counter` and a `Valid` flag. Invalid input yields `Valid = $false` + instead of throwing. + + .PARAMETER Path + | Name | Type | Description | Default | + |------|---------------|------------------------------------|---------| + | Path | System.String | The counter path string to parse. | | + + .OUTPUTS + System.Collections.Hashtable — Keys Category, Instance, Counter, Valid. + + .EXAMPLE + PS> [IcingaPerformanceCounter]::ParsePath('\PhysicalDisk(0 C:)\Disk Reads/sec') + #> + static [hashtable] ParsePath([string]$Path) + { + [hashtable]$Result = @{ + 'Category' = ''; + 'Instance' = ''; + 'Counter' = ''; + 'Valid' = $false; + }; + + if ([string]::IsNullOrEmpty($Path)) { + return $Result; + } + + [string[]]$Parts = $Path.Split('\'); + + # A valid path starts with a backslash, so the first split element is empty and + # there are at least three elements: '', category(+instance), counter. + if ($Parts.Count -lt 3 -or -not [string]::IsNullOrEmpty($Parts[0])) { + return $Result; + } + + [string]$CategoryPart = $Parts[1]; + $Result['Counter'] = $Parts[2]; + + if ($CategoryPart.Contains('(') -or $CategoryPart.Contains(')')) { + [int]$Open = $CategoryPart.IndexOf('('); + [int]$Close = $CategoryPart.LastIndexOf(')'); + + if ($Open -gt 0 -and $Close -gt $Open -and $Close -eq ($CategoryPart.Length - 1)) { + $Result['Category'] = $CategoryPart.Substring(0, $Open); + $Result['Instance'] = $CategoryPart.Substring($Open + 1, $Close - $Open - 1); + } else { + return $Result; + } + } else { + $Result['Category'] = $CategoryPart; + } + + if (-not [string]::IsNullOrEmpty($Result['Category']) -and -not [string]::IsNullOrEmpty($Result['Counter'])) { + $Result['Valid'] = $true; + } + + return $Result; + } + + <# + .SYNOPSIS + Expand a counter path into the concrete per-instance paths that exist right now + + .DESCRIPTION + For a wildcard path (instance '*') this queries the live instance names of the + category and returns one full path per instance. For a concrete or single-instance + path it returns the path unchanged. Categories that cannot be read yield an empty + array rather than throwing. + + .PARAMETER Path + | Name | Type | Description | Default | + |------|---------------|--------------------------------------|---------| + | Path | System.String | The (possibly wildcard) counter path.| | + + .OUTPUTS + System.String[] — The concrete counter paths currently present. + + .EXAMPLE + PS> $manager.ExpandPath('\PhysicalDisk(*)\Disk Reads/sec') + #> + [string[]] ExpandPath([string]$Path) + { + $Parsed = [IcingaPerformanceCounter]::ParsePath($Path); + + if (-not $Parsed.Valid) { + return @(); + } + + if ($Parsed.Instance -ne '*') { + return @($Path); + } + + [string[]]$Expanded = @(); + + try { + $CategoryObject = New-Object System.Diagnostics.PerformanceCounterCategory($Parsed.Category); + foreach ($InstanceName in $CategoryObject.GetInstanceNames()) { + $Expanded += ('\{0}({1})\{2}' -f $Parsed.Category, $InstanceName, $Parsed.Counter); + } + } catch { + # The category is not available on this system; report no live instances. + $Expanded = @(); + } + + return $Expanded; + } + + <# + .SYNOPSIS + Build a counter entry for a concrete counter path + + .DESCRIPTION + Parses the path and constructs an IcingaPerformanceCounterEntry. Returns `$null` for + invalid paths so the caller can skip them. + + .PARAMETER Path + | Name | Type | Description | Default | + |------|---------------|---------------------------------|---------| + | Path | System.String | The concrete counter path. | | + + .OUTPUTS + IcingaPerformanceCounterEntry — The new entry, or $null when the path is invalid. + + .EXAMPLE + PS> $manager.CreateEntry('\Memory\Available Bytes') + #> + [IcingaPerformanceCounterEntry] CreateEntry([string]$Path) + { + $Parsed = [IcingaPerformanceCounter]::ParsePath($Path); + + if (-not $Parsed.Valid) { + return $null; + } + + return [IcingaPerformanceCounterEntry]::new($Path, $Parsed.Category, $Parsed.Instance, $Parsed.Counter); + } + + <# + .SYNOPSIS + Ensure the given counter paths are initialized and primed + + .DESCRIPTION + Creates and primes a handle for every new concrete path and a category snapshot for + every new category of a wildcard path, then performs a single shared warm-up sleep + if anything was primed. Known counters and categories are left untouched, so + repeated calls are cheap. + + .PARAMETER Paths + | Name | Type | Description | Default | + |-------|-----------------|------------------------------------------|---------| + | Paths | System.String[] | The counter paths to ensure are warm. | | + + .OUTPUTS + None — Populates the internal registry. + + .EXAMPLE + PS> $manager.Warmup(@('\Processor(_Total)\% Processor Time')) + + .NOTES + The single shared sleep is the reason a batch of counters costs one warm-up interval + instead of one interval per counter. + #> + [void] Warmup([string[]]$Paths) + { + [bool]$PrimedAny = $false; + + foreach ($Path in $Paths) { + $Parsed = [IcingaPerformanceCounter]::ParsePath($Path); + + if (-not $Parsed.Valid) { + continue; + } + + if ($Parsed.Instance -eq '*') { + if ($this.AddCategory($Parsed.Category)) { + $PrimedAny = $true; + } + + continue; + } + + if (-not $this.Counters.ContainsKey($Path)) { + $Entry = $this.CreateEntry($Path); + + if ($null -ne $Entry -and $this.Counters.TryAdd($Path, $Entry)) { + $Entry.Prime(); + $PrimedAny = $true; + } + } + } + + if ($PrimedAny) { + Start-Sleep -Milliseconds $this.WarmupMilliseconds; + } + } + + <# + .SYNOPSIS + Create and prime the snapshot of a category if it does not exist yet + + .DESCRIPTION + Adds a category snapshot to the registry and takes its first read. Returns $true + when a new snapshot was primed, so the caller knows a warm-up sleep is needed. + + .PARAMETER Category + | Name | Type | Description | Default | + |----------|---------------|-----------------------------------|---------| + | Category | System.String | The performance counter category. | | + + .OUTPUTS + System.Boolean — $true when a new snapshot was created and primed. + + .EXAMPLE + PS> $manager.AddCategory('Process') + #> + [bool] AddCategory([string]$Category) + { + if ($this.Categories.ContainsKey($Category)) { + return $false; + } + + $Snapshot = [IcingaPerformanceCounterCategory]::new($Category); + + if (-not $this.Categories.TryAdd($Category, $Snapshot)) { + return $false; + } + + $Snapshot.Prime(); + + return $true; + } + + <# + .SYNOPSIS + Read a single concrete counter path from the registry + + .DESCRIPTION + Returns the uniform result hashtable for a concrete counter path. If the path is not + present in the registry, a result with a populated `error` key is returned. + + .PARAMETER Path + | Name | Type | Description | Default | + |------|---------------|----------------------------|---------| + | Path | System.String | The concrete counter path. | | + + .OUTPUTS + System.Collections.Hashtable — Keys value, sample, help, type, error. + + .EXAMPLE + PS> $manager.ReadPath('\Memory\Available Bytes') + #> + [hashtable] ReadPath([string]$Path) + { + if ($this.Counters.ContainsKey($Path)) { + $Entry = $this.Counters[$Path]; + + if ($null -ne $Entry) { + return $Entry.Read(); + } + } + + return @{ + 'value' = [decimal]0; + 'sample' = $null; + 'help' = $null; + 'type' = $null; + 'error' = 'Counter not initialized'; + }; + } + + <# + .SYNOPSIS + Warm up and read a set of counter paths into the uniform result structure + + .DESCRIPTION + Ensures every requested counter is warm, then reads it. A concrete path maps to its + flat five-key hashtable; a wildcard path maps to a nested hashtable keyed by each + instance path of the category snapshot. The outer hashtable is keyed by the + originally requested path so callers can correlate requests and responses. + + A category snapshot that is at least `WarmupMilliseconds` old is refreshed before it + is read, once per request. Values are therefore always calculated over at least that + interval; the daemon additionally refreshes every snapshot on each `Sample`. + + .PARAMETER Paths + | Name | Type | Description | Default | + |-------|-----------------|------------------------------------|---------| + | Paths | System.String[] | The counter paths to read. | | + + .OUTPUTS + System.Collections.Hashtable — Keyed by requested path; flat or nested per path. + + .EXAMPLE + PS> $manager.Resolve(@('\PhysicalDisk(*)\Disk Reads/sec')) + #> + [hashtable] Resolve([string[]]$Paths) + { + $this.Warmup($Paths); + + [hashtable]$Result = @{ }; + [hashtable]$ReadCache = @{ }; + + foreach ($Path in $Paths) { + $Parsed = [IcingaPerformanceCounter]::ParsePath($Path); + + if ($Parsed.Valid -and $Parsed.Instance -eq '*') { + [hashtable]$Group = @{ }; + $Snapshot = $null; + + if ($this.Categories.ContainsKey($Parsed.Category)) { + $Snapshot = $this.Categories[$Parsed.Category]; + } + + if ($null -ne $Snapshot) { + if ($Snapshot.AgeMilliseconds() -ge $this.WarmupMilliseconds) { + $Snapshot.Refresh(); + } + + foreach ($InstanceName in $Snapshot.GetInstanceNames()) { + $Expanded = ('\{0}({1})\{2}' -f $Parsed.Category, $InstanceName, $Parsed.Counter); + + if (-not $ReadCache.ContainsKey($Expanded)) { + $ReadCache[$Expanded] = $Snapshot.Read($InstanceName, $Parsed.Counter); + } + + $Group[$Expanded] = $ReadCache[$Expanded]; + } + } + + $Result[$Path] = $Group; + } else { + if (-not $ReadCache.ContainsKey($Path)) { + $ReadCache[$Path] = $this.ReadPath($Path); + } + + $Result[$Path] = $ReadCache[$Path]; + } + } + + return $Result; + } + + <# + .SYNOPSIS + Take a fresh sample of every registered counter to keep rate values current + + .DESCRIPTION + Calls `NextValue` on each live handle and refreshes every category snapshot, so the + next read computes an accurate rate over the refresh interval. Sampling errors are + ignored — dead instances are removed separately by `Reconcile`, and a category + snapshot keeps its last read when a refresh fails. + + .OUTPUTS + None — Advances the internal sample of every counter. + + .EXAMPLE + PS> $manager.Sample() + #> + [void] Sample() + { + foreach ($Key in @($this.Counters.Keys)) { + $Entry = $this.Counters[$Key]; + + if ($null -ne $Entry -and $null -ne $Entry.Handle) { + try { + $Entry.Handle.NextValue() | Out-Null; + } catch { + # Ignore; Reconcile drops instances that no longer exist. + $Error.Clear(); + } + } + } + + foreach ($Key in @($this.Categories.Keys)) { + $Snapshot = $this.Categories[$Key]; + + if ($null -ne $Snapshot) { + $Snapshot.Refresh(); + } + } + } + + <# + .SYNOPSIS + Synchronize the live registry with the currently registered counter paths + + .DESCRIPTION + Adds and primes a handle for every registered concrete path and a category snapshot + for every category of a registered wildcard path, and removes handles and snapshots + that are no longer wanted (a counter that was evicted from the registration list). + Instances that appear or disappear, such as a newly inserted removable disk, are + covered by the category snapshots. New handles and snapshots share a single warm-up + sleep. + + .PARAMETER RegisteredPaths + | Name | Type | Description | Default | + |-----------------|-----------------|-----------------------------------------------|---------| + | RegisteredPaths | System.String[] | The counter paths that should be kept warm. | | + + .OUTPUTS + None — Adds and removes counter handles to match the desired set. + + .EXAMPLE + PS> $manager.Reconcile(@('\PhysicalDisk(*)\Disk Reads/sec')) + #> + [void] Reconcile([string[]]$RegisteredPaths) + { + $Desired = New-Object 'System.Collections.Generic.HashSet[string]'; + $DesiredCategories = New-Object 'System.Collections.Generic.HashSet[string]'; + + foreach ($Path in $RegisteredPaths) { + $Parsed = [IcingaPerformanceCounter]::ParsePath($Path); + + if (-not $Parsed.Valid) { + continue; + } + + if ($Parsed.Instance -eq '*') { + [void]$DesiredCategories.Add($Parsed.Category); + } else { + [void]$Desired.Add($Path); + } + } + + [bool]$PrimedAny = $false; + + foreach ($Category in $DesiredCategories) { + if ($this.AddCategory($Category)) { + $PrimedAny = $true; + } + } + + foreach ($Wanted in $Desired) { + if (-not $this.Counters.ContainsKey($Wanted)) { + $Entry = $this.CreateEntry($Wanted); + + if ($null -ne $Entry -and $this.Counters.TryAdd($Wanted, $Entry)) { + $Entry.Prime(); + $PrimedAny = $true; + } + } + } + + if ($PrimedAny) { + Start-Sleep -Milliseconds $this.WarmupMilliseconds; + } + + foreach ($Key in @($this.Counters.Keys)) { + if (-not $Desired.Contains($Key)) { + [IcingaPerformanceCounterEntry]$Stale = $null; + + if ($this.Counters.TryRemove($Key, [ref]$Stale) -and $null -ne $Stale) { + $Stale.Dispose(); + } + } + } + + foreach ($Key in @($this.Categories.Keys)) { + if (-not $DesiredCategories.Contains($Key)) { + [IcingaPerformanceCounterCategory]$StaleCategory = $null; + $this.Categories.TryRemove($Key, [ref]$StaleCategory) | Out-Null; + } + } + } + + <# + .SYNOPSIS + Dispose every counter handle and clear the registry + + .DESCRIPTION + Releases all native performance counter handles held by the manager and empties the + handle and category registries. Called on daemon shutdown and by the transient + one-shot resolver. + + .OUTPUTS + None — Releases all native handles. + + .EXAMPLE + PS> $manager.Dispose() + #> + [void] Dispose() + { + foreach ($Key in @($this.Counters.Keys)) { + $Entry = $this.Counters[$Key]; + + if ($null -ne $Entry) { + $Entry.Dispose(); + } + } + + $this.Counters.Clear(); + $this.Categories.Clear(); + } + + <# + .SYNOPSIS + Resolve counter values once without a shared registry or background daemon + + .DESCRIPTION + Creates a throwaway manager, warms and reads the requested counters on the calling + thread, disposes every handle, and returns the uniform result structure. This is the + inline fallback used when no performance-counter daemon is running (for example a + plugin invoked once from the command line). Because it is fully self-contained it + shares no state with the daemon and is safe on any thread. + + .PARAMETER Paths + | Name | Type | Description | Default | + |-------|-----------------|-----------------------------------|---------| + | Paths | System.String[] | The counter paths to read once. | | + + .PARAMETER WarmupMilliseconds + | Name | Type | Description | Default | + |--------------------|--------------|---------------------------------------------|---------| + | WarmupMilliseconds | System.Int32 | Shared warm-up sleep between the two samples.| 250 | + + .OUTPUTS + System.Collections.Hashtable — Same shape as Resolve. + + .EXAMPLE + PS> [IcingaPerformanceCounter]::ResolveOnce(@('\Processor(_Total)\% Processor Time'), 250) + #> + static [hashtable] ResolveOnce([string[]]$Paths, [int]$WarmupMilliseconds) + { + $Manager = [IcingaPerformanceCounter]::new(); + $Manager.WarmupMilliseconds = $WarmupMilliseconds; + + try { + return $Manager.Resolve($Paths); + } finally { + $Manager.Dispose(); + } + } +} diff --git a/src/PerformanceCounter/Private/ConvertTo-IcingaPerformanceCounterInstanceStructure.ps1 b/src/PerformanceCounter/Private/ConvertTo-IcingaPerformanceCounterInstanceStructure.ps1 new file mode 100644 index 0000000..0ece3c7 --- /dev/null +++ b/src/PerformanceCounter/Private/ConvertTo-IcingaPerformanceCounterInstanceStructure.ps1 @@ -0,0 +1,94 @@ +<# +.SYNOPSIS +Reshape a flat performance counter result into an instance/category/counter structure + +.DESCRIPTION +`ConvertTo-IcingaPerformanceCounterInstanceStructure` transforms the default result of +`Get-IcingaPerformanceCounter` (a hashtable keyed by the requested counter path) into a nested +structure that is easier to consume when writing plugins. + +Counters that carry an instance are keyed instance-first, then category, then counter name: +`$out[Instance][Category][Counter]`. Counters without an instance are keyed category-first, then +counter name: `$out[Category][Counter]`. In both cases the leaf is the uniform value hashtable +(`value`, `sample`, `help`, `type`, `error`), so `$out['0']['Processor']['% Processor Time'].value` +and `$out['Memory']['Pages/sec'].value` both work. Wildcard requests are expanded so each live +instance becomes its own top-level key (for example CPU cores `0`, `1`, `_Total`). + +The requested paths are re-parsed to decide the shape, so the transform never has to guess whether a +nested value is a value hashtable or an instance group. + +.PARAMETER Result +| Name | Type | Description | Default | +|--------|-----------------------------|------------------------------------------------------------|---------| +| Result | System.Collections.Hashtable| The result returned by the manager, keyed by requested path.| @{ } | + +.PARAMETER Counter +| Name | Type | Description | Default | +|---------|--------------|---------------------------------------------------------|---------| +| Counter | System.Array | The originally requested counter paths, used to drive the reshape. | @() | + +.OUTPUTS +System.Collections.Hashtable — Nested structure keyed by instance/category or category, with the +uniform value hashtable at the leaf. + +.EXAMPLE +PS> ConvertTo-IcingaPerformanceCounterInstanceStructure -Result $raw -Counter '\Processor(*)\% Processor Time' + +.NOTES +Called by `Get-IcingaPerformanceCounter` when `-StructureByInstance` is set. Pure transform; touches +no global state and reads no counters. +#> +function ConvertTo-IcingaPerformanceCounterInstanceStructure() +{ + param ( + [hashtable]$Result = @{ }, + [array]$Counter = @() + ); + + [hashtable]$Structured = @{ }; + + if ($null -eq $Result) { + return $Structured; + } + + foreach ($RequestedPath in $Counter) { + if ([string]::IsNullOrEmpty($RequestedPath) -or -not $Result.ContainsKey($RequestedPath)) { + continue; + } + + $Entry = $Result[$RequestedPath]; + $Parsed = [IcingaPerformanceCounter]::ParsePath($RequestedPath); + + # Normalize to a set of concrete "counter path -> value hashtable" pairs. A wildcard result + # is already keyed by each expanded path; a concrete request maps to a single pair. + [hashtable]$Concrete = @{ }; + + if ($Parsed.Instance -eq '*') { + $Concrete = $Entry; + } else { + $Concrete[$RequestedPath] = $Entry; + } + + foreach ($ConcretePath in $Concrete.Keys) { + $Path = [IcingaPerformanceCounter]::ParsePath($ConcretePath); + $Value = $Concrete[$ConcretePath]; + + if (-not [string]::IsNullOrEmpty($Path.Instance)) { + if (-not $Structured.ContainsKey($Path.Instance)) { + $Structured[$Path.Instance] = @{ }; + } + if (-not $Structured[$Path.Instance].ContainsKey($Path.Category)) { + $Structured[$Path.Instance][$Path.Category] = @{ }; + } + $Structured[$Path.Instance][$Path.Category][$Path.Counter] = $Value; + } else { + if (-not $Structured.ContainsKey($Path.Category)) { + $Structured[$Path.Category] = @{ }; + } + $Structured[$Path.Category][$Path.Counter] = $Value; + } + } + } + + return $Structured; +} diff --git a/src/PerformanceCounter/Private/Get-IcingaPerformanceCounterLiteral.ps1 b/src/PerformanceCounter/Private/Get-IcingaPerformanceCounterLiteral.ps1 new file mode 100644 index 0000000..af8936d --- /dev/null +++ b/src/PerformanceCounter/Private/Get-IcingaPerformanceCounterLiteral.ps1 @@ -0,0 +1,53 @@ +<# +.SYNOPSIS +Extract literal counter path strings from an AST argument node + +.DESCRIPTION +`Get-IcingaPerformanceCounterLiteral` walks an argument's abstract syntax tree and +collects the value of every string constant it contains. It is used by the startup +discovery step to read the literal counter list passed to a `New-IcingaPerformanceCounter` +call without executing any component code. Non-literal arguments (variables, expressions) +contribute no values, which is intentional — only statically declarable counters are +discovered. + +.PARAMETER Argument +| Name | Type | Description | Default | +|----------|---------------------------------------------|---------------------------------------------|---------| +| Argument | System.Management.Automation.Language.Ast | The AST node of the `-Counter` argument. | $null | + +.OUTPUTS +System.Array — The literal string values found in the argument, or an empty array. + +.EXAMPLE +PS> Get-IcingaPerformanceCounterLiteral -Argument $argumentAst + +.NOTES +Called by `Register-IcingaPerformanceCounterFromComponents`. Returns an empty array when +the argument is null or contains no string literals. +#> +function Get-IcingaPerformanceCounterLiteral() +{ + param ( + [System.Management.Automation.Language.Ast]$Argument = $null + ); + + [array]$Values = @(); + + if ($null -eq $Argument) { + return $Values; + } + + $Strings = $Argument.FindAll( + { + param ($Node) + $Node -is [System.Management.Automation.Language.StringConstantExpressionAst] + }, + $true + ); + + foreach ($String in $Strings) { + $Values += $String.Value; + } + + return $Values; +} diff --git a/src/PerformanceCounter/Private/Get-IcingaPerformanceCounterValue.ps1 b/src/PerformanceCounter/Private/Get-IcingaPerformanceCounterValue.ps1 new file mode 100644 index 0000000..d9d6e34 --- /dev/null +++ b/src/PerformanceCounter/Private/Get-IcingaPerformanceCounterValue.ps1 @@ -0,0 +1,50 @@ +<# +.SYNOPSIS +Return the value of a performance counter result, or its error when one is present + +.DESCRIPTION +`Get-IcingaPerformanceCounterValue` extracts the usable result from a single performance counter value +object (the leaf hashtable produced by `Get-IcingaPerformanceCounter`, containing the keys value, +sample, help, type and error). If the counter reported an error the error message is returned; +otherwise the numeric value is returned. This lets a plugin drill down to a single counter and get +back either a number to threshold against or the error text to surface, in one call. + +Because the value is always numeric and the error is always a string, callers can tell the two apart +with a simple type check (`$result -is [string]` means an error was returned). + +.PARAMETER InputObject +| Name | Type | Description | Default | +|-------------|---------------|----------------------------------------------------------------------|---------| +| InputObject | System.Object | A single counter value object (the leaf hashtable of a counter read). | $null | + +.OUTPUTS +System.Object — The counter value (typically System.Decimal), or the error message (System.String) +when the counter reported one. Returns $null when the input is not a counter value object. + +.EXAMPLE +PS> $data = Get-IcingaPerformanceCounter -Counter '\Processor(*)\% Processor Time' -StructureByInstance +PS> Get-IcingaPerformanceCounterValue -InputObject $data.'0'.'Processor'.'% Processor Time' + +Returns the processor load of core 0, or the error text if that counter could not be read. + +.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. +#> +function Get-IcingaPerformanceCounterValue() +{ + param ( + $InputObject = $null + ); + + if ($null -eq $InputObject -or $InputObject -isnot [hashtable]) { + return $null; + } + + # An error always wins over the value so problems are never hidden behind a default 0. + if (-not [string]::IsNullOrEmpty([string]$InputObject['error'])) { + return $InputObject['error']; + } + + return $InputObject['value']; +} diff --git a/src/PerformanceCounter/Private/New-IcingaPerformanceCounter.ps1 b/src/PerformanceCounter/Private/New-IcingaPerformanceCounter.ps1 new file mode 100644 index 0000000..518ded0 --- /dev/null +++ b/src/PerformanceCounter/Private/New-IcingaPerformanceCounter.ps1 @@ -0,0 +1,57 @@ +<# +.SYNOPSIS +Declare and keep-alive a set of performance counters for a component + +.DESCRIPTION +`New-IcingaPerformanceCounter` registers the given counter paths in the global +performance-counter store so the background daemon initializes, warms and keeps them +available. Calling it refreshes each counter's last-seen timestamp, which both prevents +eviction of actively-used counters and drives the self-maintaining cache file. + +Components declare the counters they need by calling this function with a literal list. +At module start the discovery step statically scans the compiled kernel for these calls +and seeds the registry from the extracted counter paths, so a declared counter is warm +before it is ever requested. The function only writes to the thread-safe registry +dictionary, so it is safe to call from any thread. + +.PARAMETER Counter +| Name | Type | Description | Default | +|---------|---------------|---------------------------------------------------------|---------| +| Counter | System.Array | One or more counter paths to register, e.g. '\Cat\Ctr'. | @() | + +.OUTPUTS +None — Registers the counter paths in the global store. + +.EXAMPLE +PS> New-IcingaPerformanceCounter -Counter @('\Processor(*)\% Processor Time', '\Memory\Available Bytes') + +Declares two counters so the daemon keeps them warm and the discovery step can find them. + +.NOTES +The counters are stored under `(Get-GlobalRuntimeVariable).Public.PerformanceCounter.Registered`. +This function does not return counter values — use `Get-IcingaPerformanceCounter` to read them. +#> +function New-IcingaPerformanceCounter() +{ + param ( + [array]$Counter = @() + ); + + if ($null -eq $Counter -or $Counter.Count -eq 0) { + return; + } + + $Store = (Get-GlobalRuntimeVariable).Public.PerformanceCounter; + + if ($null -eq $Store) { + return; + } + + [datetime]$Now = (Get-Date); + + foreach ($Path in $Counter) { + if (-not [string]::IsNullOrEmpty($Path)) { + $Store.Registered[$Path] = $Now; + } + } +} diff --git a/src/PerformanceCounter/Private/New-IcingaPerformanceCounterEnvironment.ps1 b/src/PerformanceCounter/Private/New-IcingaPerformanceCounterEnvironment.ps1 new file mode 100644 index 0000000..6d6a8e7 --- /dev/null +++ b/src/PerformanceCounter/Private/New-IcingaPerformanceCounterEnvironment.ps1 @@ -0,0 +1,62 @@ +<# +.SYNOPSIS +Initialize the performance counter manager, cache and warm counter set + +.DESCRIPTION +`New-IcingaPerformanceCounterEnvironment` prepares the performance-counter subsystem for +the daemon. It creates the central manager instance the first time it runs (the class type +is available because the kernel has been dot-sourced by then), loads the persisted cache, +runs component discovery to register statically declared counters, and reconciles the +manager so every registered counter is warmed in a single batch. It also stamps the initial +heartbeat and refresh timestamps. + +This function is expected to run inside the performance-counter daemon runspace, before the +daemon enters its processing loop, so the manager is created and used on a single thread. + +.OUTPUTS +None — Populates `(Get-GlobalRuntimeVariable).Public.PerformanceCounter`. + +.EXAMPLE +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. +#> +function New-IcingaPerformanceCounterEnvironment() +{ + $Store = (Get-GlobalRuntimeVariable).Public.PerformanceCounter; + + if ($null -eq $Store) { + return; + } + + # Create the central manager once the class type is available (post kernel load). + # The class is looked up by name at runtime on purpose: the compiled kernel is shared + # between runspaces, and on Windows PowerShell 5.1 a [IcingaPerformanceCounter] literal + # in it yields the main runspace's class type inside the daemon runspace. Every manager + # method then runs through the main runspace and stalls while the main thread waits for + # the daemon's response. The runtime lookup returns this runspace's own class type. + if ($null -eq $Store.Manager) { + $Store.Manager = ('IcingaPerformanceCounter' -as [type])::new(); + $Store.Manager.WarmupMilliseconds = $Store.Config.WarmupMilliseconds; + } + + # Seed the registry from the persisted cache and from component declarations. + Read-IcingaPerformanceCounterCache; + Register-IcingaPerformanceCounterFromComponents; + + # Warm up everything currently registered in a single batch. + [string[]]$Registered = @($Store.Registered.Keys); + + if ($Registered.Count -gt 0) { + $Store.Manager.Reconcile($Registered); + } + + $Store.Heartbeat = (Get-Date); + $Store.LastRefresh = (Get-Date); + + Write-LoggingEntry -Message 'Performance counter environment initialized' -Level 'Info' -Data @{ + 'RegisteredCounters' = $Registered.Count; + }; +} diff --git a/src/PerformanceCounter/Private/Read-IcingaPerformanceCounterCache.ps1 b/src/PerformanceCounter/Private/Read-IcingaPerformanceCounterCache.ps1 new file mode 100644 index 0000000..bc9f680 --- /dev/null +++ b/src/PerformanceCounter/Private/Read-IcingaPerformanceCounterCache.ps1 @@ -0,0 +1,66 @@ +<# +.SYNOPSIS +Load the registered performance counters from the cache file + +.DESCRIPTION +`Read-IcingaPerformanceCounterCache` reads the persisted counter cache written by +`Write-IcingaPerformanceCounterCache` and merges its entries into the global registry. +It runs during performance-counter environment initialization so counters learned in +previous runs are warmed immediately at startup. A missing, empty or corrupt cache file +is ignored silently so a bad cache never blocks the daemon. + +.OUTPUTS +None — Populates `(Get-GlobalRuntimeVariable).Public.PerformanceCounter.Registered`. + +.EXAMPLE +PS> Read-IcingaPerformanceCounterCache + +.NOTES +`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. +#> +function Read-IcingaPerformanceCounterCache() +{ + $Store = (Get-GlobalRuntimeVariable).Public.PerformanceCounter; + + if ($null -eq $Store) { + return; + } + + [string]$CacheFile = Join-Path -Path (Get-ModuleCacheDirectory) -ChildPath 'PerformanceCounter.json'; + + if (-not (Test-Path -Path $CacheFile)) { + return; + } + + [string]$Content = Get-Content -Path $CacheFile -Raw -Encoding UTF8; + + if ([string]::IsNullOrEmpty($Content)) { + return; + } + + $Parsed = $null; + + try { + $Parsed = ConvertFrom-Json -InputObject $Content; + } catch { + # A corrupt cache file must never block startup; discard it. + return; + } + + if ($null -eq $Parsed) { + return; + } + + foreach ($Property in $Parsed.PSObject.Properties) { + [datetime]$Timestamp = (Get-Date); + [datetime]$ParsedTime = [datetime]::MinValue; + + if ([datetime]::TryParse([string]$Property.Value, [ref]$ParsedTime)) { + $Timestamp = $ParsedTime; + } + + $Store.Registered[$Property.Name] = $Timestamp; + } +} diff --git a/src/PerformanceCounter/Private/Register-IcingaDefaultPerformanceCounter.ps1 b/src/PerformanceCounter/Private/Register-IcingaDefaultPerformanceCounter.ps1 new file mode 100644 index 0000000..3ef297c --- /dev/null +++ b/src/PerformanceCounter/Private/Register-IcingaDefaultPerformanceCounter.ps1 @@ -0,0 +1,30 @@ +<# +.SYNOPSIS +Declare the default set of performance counters shipped with the module + +.DESCRIPTION +`Register-IcingaDefaultPerformanceCounter` declares a small, broadly-available set of +performance counters (processor, memory and physical disk) by calling +`New-IcingaPerformanceCounter`. It serves as the reference example of how a component +declares the counters it needs and gives the startup discovery step and the warm-up path a +concrete set to work with. Additional components declare their own counters the same way. + +.OUTPUTS +None — Registers the default counter paths in the global store. + +.EXAMPLE +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. +#> +function Register-IcingaDefaultPerformanceCounter() +{ + New-IcingaPerformanceCounter -Counter @( + '\Processor(_Total)\% Processor Time', + '\Memory\Available Bytes', + '\PhysicalDisk(*)\Disk Reads/sec', + '\PhysicalDisk(*)\Disk Writes/sec' + ); +} diff --git a/src/PerformanceCounter/Private/Register-IcingaPerformanceCounterFromComponents.ps1 b/src/PerformanceCounter/Private/Register-IcingaPerformanceCounterFromComponents.ps1 new file mode 100644 index 0000000..2a2e45b --- /dev/null +++ b/src/PerformanceCounter/Private/Register-IcingaPerformanceCounterFromComponents.ps1 @@ -0,0 +1,83 @@ +<# +.SYNOPSIS +Discover component-declared performance counters by scanning the compiled kernel + +.DESCRIPTION +`Register-IcingaPerformanceCounterFromComponents` parses the compiled module kernel +(`lib\IcingaForWindows.Kernel.ps1`, which contains every source file concatenated) and +finds all calls to `New-IcingaPerformanceCounter`. For each call it extracts the literal +counter paths passed to the `-Counter` parameter and registers them in the global store. +No component code is executed — the declaration is read statically from the syntax tree. + +This runs once during performance-counter environment initialization so that every +counter any component declares is warmed as soon as the daemon starts. + +.OUTPUTS +None — Populates `(Get-GlobalRuntimeVariable).Public.PerformanceCounter.Registered`. + +.EXAMPLE +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. +#> +function Register-IcingaPerformanceCounterFromComponents() +{ + $Store = (Get-GlobalRuntimeVariable).Public.PerformanceCounter; + + if ($null -eq $Store) { + return; + } + + [string]$KernelPath = Join-Path -Path (Get-ModuleRootDirectory) -ChildPath (Join-Path -Path 'lib' -ChildPath 'IcingaForWindows.Kernel.ps1'); + + if (-not (Test-Path -Path $KernelPath)) { + return; + } + + $Tokens = $null; + $Errors = $null; + $Ast = [System.Management.Automation.Language.Parser]::ParseFile($KernelPath, [ref]$Tokens, [ref]$Errors); + + $Calls = $Ast.FindAll( + { + param ($Node) + $Node -is [System.Management.Automation.Language.CommandAst] -and + $Node.GetCommandName() -eq 'New-IcingaPerformanceCounter' + }, + $true + ); + + [datetime]$Now = (Get-Date); + + foreach ($Call in $Calls) { + $Elements = $Call.CommandElements; + + for ($Index = 0; $Index -lt $Elements.Count; $Index++) { + $Element = $Elements[$Index]; + + if ($Element -isnot [System.Management.Automation.Language.CommandParameterAst]) { + continue; + } + + if ($Element.ParameterName -ine 'Counter') { + continue; + } + + # The argument can be attached to the parameter (-Counter:@(...)) or be the + # following command element (-Counter @(...)). + $Argument = $Element.Argument; + + if ($null -eq $Argument -and ($Index + 1) -lt $Elements.Count) { + $Argument = $Elements[$Index + 1]; + } + + foreach ($Path in (Get-IcingaPerformanceCounterLiteral -Argument $Argument)) { + if (-not [string]::IsNullOrEmpty($Path)) { + $Store.Registered[$Path] = $Now; + } + } + } + } +} diff --git a/src/PerformanceCounter/Private/Start-IcingaPerformanceCounterDaemon.ps1 b/src/PerformanceCounter/Private/Start-IcingaPerformanceCounterDaemon.ps1 new file mode 100644 index 0000000..52f2384 --- /dev/null +++ b/src/PerformanceCounter/Private/Start-IcingaPerformanceCounterDaemon.ps1 @@ -0,0 +1,65 @@ +<# +.SYNOPSIS +Background daemon that serves performance counter requests and maintains the registry + +.DESCRIPTION +`Start-IcingaPerformanceCounterDaemon` initializes the performance-counter environment and +then runs the request/refresh loop while `Test-ThreadRunning` is true. Each cycle it blocks +briefly on the request queue; when a request arrives it resolves the requested counters +through the central manager and pushes the result into the caller's pending response queue, +keyed by the request id. When idle (and on a throttled interval) it runs the maintenance +step which refreshes the heartbeat, reconciles transient instances, evicts unused counters +and persists the cache. + +Because every performance counter handle is created, sampled and disposed here on this one +thread, callers never touch the non-thread-safe counter objects directly — they exchange +data through the thread-safe queues only. + +.OUTPUTS +None — Operates for side effects (serves requests and maintains counters). + +.EXAMPLE +PS> Start-IcingaPerformanceCounterDaemon + +.NOTES +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. +#> +function Start-IcingaPerformanceCounterDaemon() +{ + New-IcingaPerformanceCounterEnvironment; + + # Resolve the shared runtime references once. Set-ThreadData wires the shared Public space into + # this runspace before the daemon starts and the store/manager references never change again, so + # there is no reason to call Get-GlobalRuntimeVariable on every loop iteration. + $Store = (Get-GlobalRuntimeVariable).Public.PerformanceCounter; + $Manager = $Store.Manager; + + while (Test-ThreadRunning) { + $Request = $null; + $Response = $null; + + # This is a WaitForJobs thread, so its state must be refreshed on every cycle, + # whether a request is processed or the thread is idle waiting on the queue. + # Skipping it on idle cycles trips the ThreadWaitForJobMisconfiguration warning + # (mirrors the Set-ThreadProcessing call in Start-LoggingDaemon's timeout branch). + Set-ThreadProcessing; + + if ($Store.RequestQueue.TryTake([ref]$Request, 500)) { + if ($null -ne $Manager -and $null -ne $Request) { + $Response = $Manager.Resolve([string[]]$Request.Counter); + } + + if ($null -ne $Request -and $Store.PendingRequests.ContainsKey($Request.RequestId)) { + $Store.PendingRequests[$Request.RequestId].Add($Response); + } + } + + # Periodic maintenance: heartbeat, refresh, reconcile, eviction and cache persistence. + Update-IcingaPerformanceCounterState -Store $Store; + + $Request = $null; + $Response = $null; + } +} diff --git a/src/PerformanceCounter/Private/Test-IcingaPerformanceCounterDaemon.ps1 b/src/PerformanceCounter/Private/Test-IcingaPerformanceCounterDaemon.ps1 new file mode 100644 index 0000000..68dc863 --- /dev/null +++ b/src/PerformanceCounter/Private/Test-IcingaPerformanceCounterDaemon.ps1 @@ -0,0 +1,39 @@ +<# +.SYNOPSIS +Determine whether the performance counter daemon is currently alive + +.DESCRIPTION +`Test-IcingaPerformanceCounterDaemon` checks the heartbeat timestamp the daemon refreshes +on every loop cycle. If the heartbeat is recent the daemon is considered alive and callers +route their reads through the request/response queue; otherwise `Get-IcingaPerformanceCounter` +falls back to a synchronous inline read. Using the heartbeat keeps the check decoupled from +the thread registry. + +.OUTPUTS +System.Boolean — $true when the daemon heartbeat is recent, otherwise $false. + +.EXAMPLE +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. +#> +function Test-IcingaPerformanceCounterDaemon() +{ + $Store = (Get-GlobalRuntimeVariable).Public.PerformanceCounter; + + if ($null -eq $Store) { + return $false; + } + + if ($null -eq $Store.Heartbeat) { + return $false; + } + + if (((Get-Date) - $Store.Heartbeat).TotalSeconds -gt 5) { + return $false; + } + + return $true; +} diff --git a/src/PerformanceCounter/Private/Update-IcingaPerformanceCounterState.ps1 b/src/PerformanceCounter/Private/Update-IcingaPerformanceCounterState.ps1 new file mode 100644 index 0000000..b0a664e --- /dev/null +++ b/src/PerformanceCounter/Private/Update-IcingaPerformanceCounterState.ps1 @@ -0,0 +1,83 @@ +<# +.SYNOPSIS +Refresh, reconcile, evict and persist the performance counter state + +.DESCRIPTION +`Update-IcingaPerformanceCounterState` is the periodic maintenance step run by the +performance-counter daemon. On every call it refreshes the daemon heartbeat. When the +configured refresh interval has elapsed it additionally evicts counters that have not been +requested for longer than the eviction window, reconciles the manager against the current +registration set (adding new instances and disposing vanished ones such as a removed disk), +takes a fresh sample of every counter to keep rate values current, and persists the cache +file. + +Extracting this maintenance out of the daemon loop keeps the loop body small and lets the +throttling logic live in one place. + +.PARAMETER Store +| Name | Type | Description | Default | +|-------|---------------|-------------------------------------------------------------------------|---------| +| Store | System.Object | The performance-counter store to operate on. Resolved from the runtime when omitted. | $null | + +.OUTPUTS +None — Mutates the global performance-counter store and writes the cache file. + +.EXAMPLE +PS> Update-IcingaPerformanceCounterState + +.NOTES +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. +#> +function Update-IcingaPerformanceCounterState() +{ + param ( + $Store = $null + ); + + if ($null -eq $Store) { + $Store = (Get-GlobalRuntimeVariable).Public.PerformanceCounter; + } + + if ($null -eq $Store) { + return; + } + + # Always refresh the heartbeat so callers can detect the daemon is alive. + $Store.Heartbeat = (Get-Date); + + $Manager = $Store.Manager; + + if ($null -eq $Manager) { + return; + } + + # Throttle the heavier maintenance to the configured refresh interval. + if ($null -ne $Store.LastRefresh -and ((Get-Date) - $Store.LastRefresh).TotalMilliseconds -lt $Store.Config.RefreshIntervalMs) { + return; + } + + # Evict counters that have not been requested within the eviction window. + [datetime]$Threshold = (Get-Date).AddMinutes(-1 * $Store.Config.EvictionMinutes); + + foreach ($Key in @($Store.Registered.Keys)) { + $LastSeen = $Store.Registered[$Key]; + + if ($null -ne $LastSeen -and $LastSeen -lt $Threshold) { + # TValue is a value type (datetime), so the out-ref must be a typed variable; + # [ref]$null only binds for reference-type dictionary values. + [datetime]$Removed = [datetime]::MinValue; + $Store.Registered.TryRemove($Key, [ref]$Removed) | Out-Null; + } + } + + [string[]]$Registered = @($Store.Registered.Keys); + + $Manager.Reconcile($Registered); + $Manager.Sample(); + + Write-IcingaPerformanceCounterCache; + + $Store.LastRefresh = (Get-Date); +} diff --git a/src/PerformanceCounter/Private/Write-IcingaPerformanceCounterCache.ps1 b/src/PerformanceCounter/Private/Write-IcingaPerformanceCounterCache.ps1 new file mode 100644 index 0000000..019a820 --- /dev/null +++ b/src/PerformanceCounter/Private/Write-IcingaPerformanceCounterCache.ps1 @@ -0,0 +1,54 @@ +<# +.SYNOPSIS +Persist the registered performance counters to the cache file + +.DESCRIPTION +`Write-IcingaPerformanceCounterCache` serializes the registered counter paths and their +last-seen timestamps to a JSON file in the module cache directory. The daemon calls this +each refresh cycle so the warm counter set survives restarts and self-maintains — new +counters are added and stale ones drop out over time. The file is written atomically by +writing to a temporary file and renaming it into place. + +.OUTPUTS +None — Writes the cache file to disk. + +.EXAMPLE +PS> Write-IcingaPerformanceCounterCache + +.NOTES +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. +#> +function Write-IcingaPerformanceCounterCache() +{ + $Store = (Get-GlobalRuntimeVariable).Public.PerformanceCounter; + + if ($null -eq $Store) { + return; + } + + [string]$CacheDir = Get-ModuleCacheDirectory; + + if (-not (Test-Path -Path $CacheDir)) { + New-Item -Path $CacheDir -ItemType Directory -Force | Out-Null; + } + + [string]$CacheFile = Join-Path -Path $CacheDir -ChildPath 'PerformanceCounter.json'; + [string]$TempFile = Join-Path -Path $CacheDir -ChildPath 'PerformanceCounter.json.tmp'; + + [hashtable]$Data = @{ }; + + foreach ($Key in @($Store.Registered.Keys)) { + $Timestamp = $Store.Registered[$Key]; + + if ($null -ne $Timestamp) { + $Data[$Key] = $Timestamp.ToString('o'); + } + } + + [string]$Json = ConvertTo-Json -InputObject $Data -Depth 5; + + Set-Content -Path $TempFile -Value $Json -Encoding UTF8; + Move-Item -Path $TempFile -Destination $CacheFile -Force; +} diff --git a/src/PerformanceCounter/Public/Get-IcingaPerformanceCounter.ps1 b/src/PerformanceCounter/Public/Get-IcingaPerformanceCounter.ps1 new file mode 100644 index 0000000..66c5462 --- /dev/null +++ b/src/PerformanceCounter/Public/Get-IcingaPerformanceCounter.ps1 @@ -0,0 +1,152 @@ +<# +.SYNOPSIS +Read one or more Windows performance counters and return their current values + +.DESCRIPTION +`Get-IcingaPerformanceCounter` returns the current values of the requested counter paths. By default +the result is a hashtable keyed by the requested path: a concrete path maps to a flat result +hashtable with the keys value, sample, help, type and error; a wildcard path (instance '*') maps to a +nested hashtable keyed by each live instance path. + +With `-StructureByInstance` the result is reshaped for easier plugin consumption: counters with an +instance are keyed instance-first (`$out[Instance][Category][Counter]`), counters without an instance +are keyed category-first (`$out[Category][Counter]`), and the leaf is always the uniform value +hashtable. + +When the performance-counter daemon is running the read is dispatched through a request/pull queue: +the function generates a request id, registers a single-slot response queue, enqueues the request and +blocks on the response for up to the given timeout. All counter access happens on the daemon thread, +so there are no races on the underlying counter handles. When no daemon is running the function uses a +persistent per-runspace manager kept in module scope, so repeated reads stay warm and only the first +read of a new counter pays the warm-up sleep. + +Requesting a counter also refreshes its last-seen timestamp in the registry, keeping actively used +counters warm and out of the eviction path. + +.PARAMETER Counter +| Name | Type | Description | Default | +|---------|--------------|----------------------------------------------------------------|---------| +| Counter | System.Array | One or more counter paths to read, e.g. '\Processor(*)\...'. | @() | + +.PARAMETER TimeoutMs +| Name | Type | Description | Default | +|-----------|--------------|-------------------------------------------------------------|---------| +| TimeoutMs | System.Int32 | Milliseconds to wait for the daemon response before giving up.| 5000 | + +.PARAMETER StructureByInstance +| Name | Type | Description | Default | +|---------------------|----------------------------------------------|--------------------------------------------------------------------------|---------| +| StructureByInstance | System.Management.Automation.SwitchParameter | Reshape the result to instance/category/counter (category/counter when no instance). | $false | + +.OUTPUTS +System.Collections.Hashtable — By default keyed by requested path (flat for concrete paths, nested for +wildcard paths). With `-StructureByInstance`, keyed by instance then category then counter, or by +category then counter for counters without an instance. Returns an empty hashtable when no counter is +requested, or $null when the daemon request times out. + +.EXAMPLE +PS> Get-IcingaPerformanceCounter -Counter '\Processor(_Total)\% Processor Time' + +Reads a single counter and returns its value hashtable. + +.EXAMPLE +PS> $cpu = Get-IcingaPerformanceCounter -Counter '\Processor(*)\% Processor Time' -StructureByInstance +PS> $cpu.'0'.'Processor'.'% Processor Time'.value + +Reads every processor instance and addresses one core by instance, category and counter name. + +.EXAMPLE +PS> $mem = Get-IcingaPerformanceCounter -Counter '\Memory\Pages/sec' -StructureByInstance +PS> $mem.'Memory'.'Pages/sec'.value + +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. +#> +function Get-IcingaPerformanceCounter() +{ + param ( + [array]$Counter = @(), + [int]$TimeoutMs = 5000, + [switch]$StructureByInstance = $false + ); + + if ($null -eq $Counter -or $Counter.Count -eq 0) { + return @{ }; + } + + $Store = (Get-GlobalRuntimeVariable).Public.PerformanceCounter; + $Result = $null; + + if ($null -eq $Store) { + # The environment is not initialized at all; do a fully transient read. + $Result = [IcingaPerformanceCounter]::ResolveOnce([string[]]$Counter, 250); + } else { + # Keep the requested counters alive in the registry and cache. + [datetime]$Now = (Get-Date); + + foreach ($Path in $Counter) { + if (-not [string]::IsNullOrEmpty($Path)) { + $Store.Registered[$Path] = $Now; + } + } + + if (Test-IcingaPerformanceCounterDaemon) { + # Daemon is alive: dispatch through the request/response queue. + [string]$RequestId = (New-Guid).ToString(); + $ResponseQueue = [System.Collections.Concurrent.BlockingCollection[PSObject]]::New(1); + + $Store.PendingRequests[$RequestId] = $ResponseQueue; + + try { + $Store.RequestQueue.Add( + [PSCustomObject]@{ + 'RequestId' = $RequestId; + 'Counter' = [string[]]$Counter; + } + ); + + $Response = $null; + + if ($ResponseQueue.TryTake([ref]$Response, $TimeoutMs)) { + $Result = $Response; + } else { + Write-LoggingEntry -Message 'Get-IcingaPerformanceCounter: Request timed out' -Level 'Warning' -Data @{ + 'RequestId' = $RequestId; + 'Counter' = $Counter; + 'TimeoutMs' = $TimeoutMs; + }; + + return $null; + } + } finally { + [System.Collections.Concurrent.BlockingCollection[PSObject]]$RemovedQueue = $null; + [void]$Store.PendingRequests.TryRemove($RequestId, [ref]$RemovedQueue); + $ResponseQueue.Dispose(); + } + } else { + # Inline fallback: no live daemon. Keep a persistent per-runspace manager in module scope + # so counters stay warm across calls and only the first read of a new counter pays the + # warm-up sleep. A runspace runs one pipeline at a time and each runspace has its own + # module scope, so this manager is never accessed concurrently and needs no lock. Living + # in module scope (rather than the global store) also means it works without rebuilding + # the global runtime state. + if ($null -eq $script:IcingaPerformanceCounterInlineManager) { + # Looked up by name so a thread runspace gets its own class type instead of the + # main runspace's one (see New-IcingaPerformanceCounterEnvironment). + $script:IcingaPerformanceCounterInlineManager = ('IcingaPerformanceCounter' -as [type])::new(); + } + + $script:IcingaPerformanceCounterInlineManager.WarmupMilliseconds = $Store.Config.WarmupMilliseconds; + $Result = $script:IcingaPerformanceCounterInlineManager.Resolve([string[]]$Counter); + } + } + + if ($StructureByInstance -and $null -ne $Result) { + return (ConvertTo-IcingaPerformanceCounterInstanceStructure -Result $Result -Counter $Counter); + } + + return $Result; +} diff --git a/src/PerformanceCounter/Public/Show-IcingaPerformanceCounter.ps1 b/src/PerformanceCounter/Public/Show-IcingaPerformanceCounter.ps1 new file mode 100644 index 0000000..b1ea258 --- /dev/null +++ b/src/PerformanceCounter/Public/Show-IcingaPerformanceCounter.ps1 @@ -0,0 +1,133 @@ +<# +.SYNOPSIS +Browse performance counter categories, counters and live instances + +.DESCRIPTION +`Show-IcingaPerformanceCounter` is a stateless introspection helper that queries Windows +performance counter metadata directly. It has three modes selected by the parameters passed: + +- With no arguments it lists all counter categories, optionally filtered by `-Filter` using + wildcard matching. +- With `-Category` it lists the counter paths inside that category, emitting '\Category(*)\Counter' + for multi-instance categories and '\Category\Counter' for single-instance categories. +- With `-Counter` (a wildcard path) it lists the concrete counter paths for every live instance. + +Because it only reads metadata it is safe to call from any thread and does not require the +daemon. Errors are logged and yield an empty result rather than throwing. + +.PARAMETER Category +| Name | Type | Description | Default | +|----------|---------------|----------------------------------------------------------|---------| +| Category | System.String | List the counters within this category. | $null | + +.PARAMETER Counter +| Name | Type | Description | Default | +|---------|---------------|-----------------------------------------------------------------|---------| +| Counter | System.String | Wildcard counter path whose live instances should be listed. | $null | + +.PARAMETER Filter +| Name | Type | Description | Default | +|--------|---------------|------------------------------------------------------------|---------| +| Filter | System.String | Wildcard filter applied when listing categories. | $null | + +.OUTPUTS +System.Array — Category names, counter paths, or instance paths depending on the mode. + +.EXAMPLE +PS> Show-IcingaPerformanceCounter + +Lists all performance counter categories. + +.EXAMPLE +PS> Show-IcingaPerformanceCounter -Category 'Processor' + +Lists the counter paths available in the Processor category. + +.EXAMPLE +PS> Show-IcingaPerformanceCounter -Counter '\PhysicalDisk(*)\Disk Reads/sec' + +Lists the concrete per-instance paths that currently exist for the wildcard counter. + +.NOTES +Uses `System.Diagnostics.PerformanceCounterCategory` directly. No global state is read or +written, and no external services are used. +#> +function Show-IcingaPerformanceCounter() +{ + param ( + [string]$Category = $null, + [string]$Counter = $null, + [string]$Filter = $null + ); + + # Mode: list live instance paths for a wildcard counter. + if (-not [string]::IsNullOrEmpty($Counter)) { + [array]$Instances = @(); + $Parsed = [IcingaPerformanceCounter]::ParsePath($Counter); + + if (-not $Parsed.Valid) { + return $Instances; + } + + try { + $CategoryObject = New-Object System.Diagnostics.PerformanceCounterCategory($Parsed.Category); + + foreach ($InstanceName in $CategoryObject.GetInstanceNames()) { + $Instances += ('\{0}({1})\{2}' -f $Parsed.Category, $InstanceName, $Parsed.Counter); + } + } catch { + Write-LoggingEntry -Message 'Show-IcingaPerformanceCounter: Failed to read counter instances' -Level 'Warning' -Data @{ + 'Counter' = $Counter; + 'Exception' = $_.Exception.Message; + }; + } + + return ($Instances | Sort-Object); + } + + # Mode: list counter paths inside a category. + if (-not [string]::IsNullOrEmpty($Category)) { + [array]$Counters = @(); + + try { + $CategoryObject = New-Object System.Diagnostics.PerformanceCounterCategory($Category); + $InstanceNames = $CategoryObject.GetInstanceNames(); + + if ($null -ne $InstanceNames -and $InstanceNames.Count -gt 0) { + foreach ($CounterObject in $CategoryObject.GetCounters($InstanceNames[0])) { + $Counters += ('\{0}(*)\{1}' -f $Category, $CounterObject.CounterName); + $CounterObject.Dispose(); + } + } else { + foreach ($CounterObject in $CategoryObject.GetCounters()) { + $Counters += ('\{0}\{1}' -f $Category, $CounterObject.CounterName); + $CounterObject.Dispose(); + } + } + } catch { + Write-LoggingEntry -Message 'Show-IcingaPerformanceCounter: Failed to read category counters' -Level 'Warning' -Data @{ + 'Category' = $Category; + 'Exception' = $_.Exception.Message; + }; + } + + return ($Counters | Sort-Object -Unique); + } + + # Mode: list categories, optionally filtered. + [array]$Categories = @(); + + try { + foreach ($CategoryObject in [System.Diagnostics.PerformanceCounterCategory]::GetCategories()) { + if ([string]::IsNullOrEmpty($Filter) -or $CategoryObject.CategoryName -like $Filter) { + $Categories += $CategoryObject.CategoryName; + } + } + } catch { + Write-LoggingEntry -Message 'Show-IcingaPerformanceCounter: Failed to read counter categories' -Level 'Warning' -Data @{ + 'Exception' = $_.Exception.Message; + }; + } + + return ($Categories | Sort-Object); +} diff --git a/src/PerformanceCounter/Public/Show-IcingaPerformanceCounterDetails.ps1 b/src/PerformanceCounter/Public/Show-IcingaPerformanceCounterDetails.ps1 new file mode 100644 index 0000000..8c7c121 --- /dev/null +++ b/src/PerformanceCounter/Public/Show-IcingaPerformanceCounterDetails.ps1 @@ -0,0 +1,63 @@ +<# +.SYNOPSIS +Show live values for the registered performance counters, or a filtered subset + +.DESCRIPTION +`Show-IcingaPerformanceCounterDetails` returns the current values of performance counters +through `Get-IcingaPerformanceCounter`. Called without arguments it dumps every counter +currently registered in the global store. Passing `-Counter` narrows the output to the given +paths. The result keeps the uniform shape: a hashtable keyed by counter path with flat value +hashtables for concrete paths and nested hashtables for wildcard paths. + +.PARAMETER Counter +| Name | Type | Description | Default | +|---------|--------------|--------------------------------------------------------------------|---------| +| Counter | System.Array | Counter paths to show. Empty shows all registered counters. | @() | + +.PARAMETER StructureByInstance +| Name | Type | Description | Default | +|---------------------|----------------------------------------------|--------------------------------------------------------------------------|---------| +| StructureByInstance | System.Management.Automation.SwitchParameter | Reshape the result to instance/category/counter, forwarded to Get-IcingaPerformanceCounter. | $false | + +.OUTPUTS +System.Collections.Hashtable — Keyed by counter path; values as returned by +`Get-IcingaPerformanceCounter`. With `-StructureByInstance`, keyed by instance/category/counter. +Empty when nothing is registered and nothing is requested. + +.EXAMPLE +PS> Show-IcingaPerformanceCounterDetails + +Shows live values for every registered counter. + +.EXAMPLE +PS> Show-IcingaPerformanceCounterDetails -Counter '\Processor(_Total)\% Processor Time' + +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. +#> +function Show-IcingaPerformanceCounterDetails() +{ + param ( + [array]$Counter = @(), + [switch]$StructureByInstance = $false + ); + + [array]$Requested = $Counter; + + if ($null -eq $Requested -or $Requested.Count -eq 0) { + $Store = (Get-GlobalRuntimeVariable).Public.PerformanceCounter; + + if ($null -ne $Store) { + $Requested = @($Store.Registered.Keys); + } + } + + if ($null -eq $Requested -or $Requested.Count -eq 0) { + return @{ }; + } + + return (Get-IcingaPerformanceCounter -Counter $Requested -StructureByInstance:$StructureByInstance); +} From ad4ddd893d5c45fc78eebb775ead8ff7b52213c7 Mon Sep 17 00:00:00 2001 From: Lord Hepipud Date: Thu, 12 Nov 2026 17:52:29 +0100 Subject: [PATCH 2/2] Enhance PerformanceCounter path normalization, category checks, PS 5.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 `\\\`, 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 `\\\` 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). --- IcingaForWindows.psm1 | 19 +- Tests/ClassLiteral.Tests.ps1 | 99 ++++ Tests/Get-IcingaPerformanceCounter.Tests.ps1 | 60 ++- build/Build-ModuleProject.ps1 | 103 +++- build/Invoke-ModuleTests.ps1 | 9 +- ...01-Technical-Architecture-and-Reference.md | 325 ++++++++++++ .../02-Usability-and-Developer-Guide.md | 388 ++++++++++++++ docs/Icinga.PerformanceCounter.md | 483 ++++++++++-------- docs/index.md | 8 +- .../Icinga/IcingaPerformanceCounter.ps1 | 454 +++++++++++----- ...ngaPerformanceCounterInstanceStructure.ps1 | 22 +- .../Get-IcingaPerformanceCounterLiteral.ps1 | 10 +- .../Get-IcingaPerformanceCounterValue.ps1 | 6 +- .../Private/New-IcingaPerformanceCounter.ps1 | 10 +- ...ew-IcingaPerformanceCounterEnvironment.ps1 | 2 +- .../Read-IcingaPerformanceCounterCache.ps1 | 2 +- ...gister-IcingaDefaultPerformanceCounter.ps1 | 2 +- ...IcingaPerformanceCounterFromComponents.ps1 | 17 +- .../Start-IcingaPerformanceCounterDaemon.ps1 | 4 +- .../Test-IcingaPerformanceCounterDaemon.ps1 | 2 +- .../Update-IcingaPerformanceCounterState.ps1 | 11 +- .../Write-IcingaPerformanceCounterCache.ps1 | 7 +- .../Public/Get-IcingaPerformanceCounter.ps1 | 29 +- .../Public/Show-IcingaPerformanceCounter.ps1 | 26 +- .../Show-IcingaPerformanceCounterDetails.ps1 | 14 +- .../Test-IcingaPerformanceCounterCategory.ps1 | 44 ++ src/Tools/Public/ConvertTo-IcingaUnit.ps1 | 28 +- 27 files changed, 1700 insertions(+), 484 deletions(-) create mode 100644 Tests/ClassLiteral.Tests.ps1 create mode 100644 docs/Developer/PerformanceCounter/01-Technical-Architecture-and-Reference.md create mode 100644 docs/Developer/PerformanceCounter/02-Usability-and-Developer-Guide.md create mode 100644 src/PerformanceCounter/Public/Test-IcingaPerformanceCounterCategory.ps1 diff --git a/IcingaForWindows.psm1 b/IcingaForWindows.psm1 index 8be4fa4..60a3138 100644 --- a/IcingaForWindows.psm1 +++ b/IcingaForWindows.psm1 @@ -446,7 +446,24 @@ All custom declarations must be added above this comment block. #> New-ModuleBaseEnvironment; -[string]$KernelPath = Join-Path -Path (Get-ModuleRootDirectory) -ChildPath (Join-Path -Path 'lib' -ChildPath 'IcingaForWindows.Kernel.ps1'); +[string]$ClassesPath = Join-Path -Path (Get-ModuleRootDirectory) -ChildPath (Join-Path -Path 'lib' -ChildPath 'IcingaForWindows.Classes.ps1'); +[string]$KernelPath = Join-Path -Path (Get-ModuleRootDirectory) -ChildPath (Join-Path -Path 'lib' -ChildPath 'IcingaForWindows.Kernel.ps1'); + +if (Test-Path -Path $ClassesPath) { + # Windows PowerShell 5.1 reuses the compiled class types when the same class + # content is loaded again by a thread runspace and binds their methods to the + # runspace that loaded it last. Class methods called on the main thread then run + # inside a busy daemon runspace, which hangs or corrupts the call. A unique copy + # of the class content per runspace gives every runspace its own class types. + # In PowerShell Core (PS 7+), class method dispatch is runspace-independent. + if ($PSVersionTable.PSEdition -eq 'Desktop') { + . ([ScriptBlock]::Create([System.IO.File]::ReadAllText($ClassesPath) + [System.Environment]::NewLine + '# ' + [System.Guid]::NewGuid().ToString())); + } else { + . $ClassesPath; + } +} else { + Write-Warning "Icinga for Windows classes file not found at '$ClassesPath'. Run Build-ModuleProject first."; +} if (Test-Path -Path $KernelPath) { . $KernelPath; diff --git a/Tests/ClassLiteral.Tests.ps1 b/Tests/ClassLiteral.Tests.ps1 new file mode 100644 index 0000000..28642db --- /dev/null +++ b/Tests/ClassLiteral.Tests.ps1 @@ -0,0 +1,99 @@ +$ModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\IcingaForWindows.psd1'; +if (-not (Get-Module -Name 'IcingaForWindows')) { + Import-Module -Name $ModulePath -Force -Global; +} + +Describe 'Class literals in functions' { + BeforeAll { + # Every runspace shares the compiled kernel, so a class literal inside a + # function resolves to the class type of the main runspace. In a thread on + # Windows PowerShell 5.1 every method of such an object waits for the main + # runspace, and type checks no longer match the thread's own objects. + # 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')); + [string[]]$script:ClassNames = @(); + + foreach ($File in (Get-ChildItem -Path (Join-Path -Path $script:SourceRoot -ChildPath 'Classes') -Filter '*.ps1' -Recurse)) { + $Ast = [System.Management.Automation.Language.Parser]::ParseFile($File.FullName, [ref]$null, [ref]$null); + + foreach ($Definition in $Ast.FindAll({ param ($Node) $Node -is [System.Management.Automation.Language.TypeDefinitionAst] -and $Node.IsClass }, $true)) { + $script:ClassNames += $Definition.Name; + } + } + } + + It 'reads the class names from the class files' { + $script:ClassNames | Should -Contain 'IcingaPerformanceCounter'; + $script:ClassNames | Should -Contain 'IcingaUnit'; + } + + It 'finds no class literal in a function outside src/Classes' { + [string[]]$Violations = @(); + [string[]]$Skipped = @( + (Join-Path -Path $script:SourceRoot -ChildPath 'Classes'), + (Join-Path -Path $script:SourceRoot -ChildPath 'analyze') + ); + + foreach ($File in (Get-ChildItem -Path $script:SourceRoot -Filter '*.ps1' -Recurse)) { + [bool]$Skip = $false; + + foreach ($Folder in $Skipped) { + if ($File.FullName.StartsWith($Folder + [System.IO.Path]::DirectorySeparatorChar, [System.StringComparison]::OrdinalIgnoreCase)) { + $Skip = $true; + } + } + + if ($Skip) { + continue; + } + + $Ast = [System.Management.Automation.Language.Parser]::ParseFile($File.FullName, [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) { + $TypeName = $Node.TypeName; + + while ($TypeName -is [System.Management.Automation.Language.ArrayTypeName]) { + $TypeName = $TypeName.ElementType; + } + + if ($script:ClassNames -contains $TypeName.Name) { + $Violations += ('{0}:{1} [{2}]' -f $File.FullName.Substring($script:SourceRoot.Length + 1), $Node.Extent.StartLineNumber, $TypeName.Name); + } + } + } + + $Violations | Should -BeNullOrEmpty -Because ("functions must not use class literals:`n" + ($Violations -join "`n")); + } + + It 'finds no PowerShell class literal inside IcingaPerformanceCounter.ps1' { + [string]$PerfClassFile = Join-Path -Path $script:SourceRoot -ChildPath 'Classes\Icinga\IcingaPerformanceCounter.ps1'; + [string[]]$Violations = @(); + $Ast = [System.Management.Automation.Language.Parser]::ParseFile($PerfClassFile, [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) { + $TypeName = $Node.TypeName; + + while ($TypeName -is [System.Management.Automation.Language.ArrayTypeName]) { + $TypeName = $TypeName.ElementType; + } + + if ($script:ClassNames -contains $TypeName.Name) { + $Violations += ('IcingaPerformanceCounter.ps1:{0} [{1}]' -f $Node.Extent.StartLineNumber, $TypeName.Name); + } + + if ($TypeName -is [System.Management.Automation.Language.GenericTypeName]) { + foreach ($GenArg in $TypeName.GenericArguments) { + if ($script:ClassNames -contains $GenArg.Name) { + $Violations += ('IcingaPerformanceCounter.ps1:{0} [{1}]' -f $Node.Extent.StartLineNumber, $GenArg.Name); + } + } + } + } + + $Violations | Should -BeNullOrEmpty -Because ("IcingaPerformanceCounter.ps1 must use runtime lookups ('...' -as [type]) for PS 5.1 runspace isolation:`n" + ($Violations -join "`n")); + } +} diff --git a/Tests/Get-IcingaPerformanceCounter.Tests.ps1 b/Tests/Get-IcingaPerformanceCounter.Tests.ps1 index 17b25b5..9322eb5 100644 --- a/Tests/Get-IcingaPerformanceCounter.Tests.ps1 +++ b/Tests/Get-IcingaPerformanceCounter.Tests.ps1 @@ -75,9 +75,44 @@ Describe 'Get-IcingaPerformanceCounter' { $unopened = & $script:IcingaModule { [IcingaPerformanceCounter]::ParsePath('\Processor)\% Processor Time') }; $unopened.Valid | Should -Be $false; - $noCat = & $script:IcingaModule { [IcingaPerformanceCounter]::ParsePath('\(_Total)\% Processor Time') }; + $noCat = & $script:IcingaModule { [IcingaPerformanceCounter]::ParsePath('\(_Total)\% Processor Time') }; $noCat.Valid | Should -Be $false; } + + It 'Accepts and normalizes local machine prefixes (\\.\, \\localhost\, \\\)' { + $dot = & $script:IcingaModule { [IcingaPerformanceCounter]::ParsePath('\\.\Memory\Available Bytes') }; + $dot.Valid | Should -Be $true; + $dot.Category | Should -Be 'Memory'; + $dot.Instance | Should -Be ''; + $dot.Counter | Should -Be 'Available Bytes'; + + $localhost = & $script:IcingaModule { [IcingaPerformanceCounter]::ParsePath('\\localhost\Processor(_Total)\% Processor Time') }; + $localhost.Valid | Should -Be $true; + $localhost.Category | Should -Be 'Processor'; + $localhost.Instance | Should -Be '_Total'; + $localhost.Counter | Should -Be '% Processor Time'; + + $machinePath = ('\\{0}\PhysicalDisk(*)\Disk Reads/sec' -f [System.Environment]::MachineName); + $machine = & $script:IcingaModule { param($p) [IcingaPerformanceCounter]::ParsePath($p) } $machinePath; + $machine.Valid | Should -Be $true; + $machine.Category | Should -Be 'PhysicalDisk'; + $machine.Instance | Should -Be '*'; + $machine.Counter | Should -Be 'Disk Reads/sec'; + + $normalized = & $script:IcingaModule { [IcingaPerformanceCounter]::NormalizePath('\\.\Processor(_Total)\% Processor Time') }; + $normalized | Should -Be '\Processor(_Total)\% Processor Time'; + } + + It 'Rejects remote machine prefixes and extra path segments' { + $remote = & $script:IcingaModule { [IcingaPerformanceCounter]::ParsePath('\\REMOTE-SERVER-99\Memory\Available Bytes') }; + $remote.Valid | Should -Be $false; + + $emptyMachine = & $script:IcingaModule { [IcingaPerformanceCounter]::ParsePath('\\\Memory\Available Bytes') }; + $emptyMachine.Valid | Should -Be $false; + + $extraSegment = & $script:IcingaModule { [IcingaPerformanceCounter]::ParsePath('\Memory\Available Bytes\Extra') }; + $extraSegment.Valid | Should -Be $false; + } } Context 'Registration keeps counters warm' { @@ -140,7 +175,7 @@ Describe 'Get-IcingaPerformanceCounter' { Context 'Category snapshots for wildcard paths' { It 'Reads every process instance, including the own process' { - $group = (Get-IcingaPerformanceCounter -Counter '\Process(*)\ID Process')['\Process(*)\ID Process']; + $group = (Get-IcingaPerformanceCounter -Counter '\Process(*)\ID Process')['\Process(*)\ID Process']; [int[]]$Ids = @($group.Values | ForEach-Object { [int]$_.value }); $Ids | Should -Contain $PID; } @@ -212,4 +247,25 @@ Describe 'Get-IcingaPerformanceCounter' { [decimal]$result['\Memory\Available Bytes'].value | Should -BeGreaterThan 0; } } + + Context 'Test-IcingaPerformanceCounterCategory and category error inspection' { + It 'Returns false for empty, malformed or non-existent categories' { + (Test-IcingaPerformanceCounterCategory -Category '') | Should -Be $false; + (Test-IcingaPerformanceCounterCategory -Category 'IcingaNoSuchCategory') | Should -Be $false; + (Test-IcingaPerformanceCounterCategory -Category '\IcingaNoSuchCategory(*)\Counter') | Should -Be $false; + (Test-IcingaPerformanceCounterCategory -Category '\\REMOTE-HOST\Processor\Counter') | Should -Be $false; + } + + It 'Records the category error on a failed wildcard category snapshot' { + $err = & $script:IcingaModule { + $manager = [IcingaPerformanceCounter]::new(); + $manager.WarmupMilliseconds = 0; + $manager.Resolve([string[]]@('\IcingaNoSuchCategory(*)\Counter')) | Out-Null; + $msg = $manager.GetCategoryError('IcingaNoSuchCategory'); + $manager.Dispose(); + return $msg; + }; + $err | Should -Not -BeNullOrEmpty; + } + } } diff --git a/build/Build-ModuleProject.ps1 b/build/Build-ModuleProject.ps1 index 9369344..db01bd0 100644 --- a/build/Build-ModuleProject.ps1 +++ b/build/Build-ModuleProject.ps1 @@ -56,6 +56,46 @@ function Read-IcingaSourceFile() return $FileContent; } +function Remove-IcingaComments() +{ + [CmdletBinding()] + param ( + [string]$Content = '' + ); + + if ([string]::IsNullOrWhiteSpace($Content)) { + return ''; + } + + $Tokens = $null; + $Errors = $null; + [void][System.Management.Automation.Language.Parser]::ParseInput($Content, [ref]$Tokens, [ref]$Errors); + + if ($null -eq $Tokens -or $Tokens.Count -eq 0) { + return $Content; + } + + $CommentTokens = @($Tokens | Where-Object { [string]$_.Kind -eq 'Comment' } | Sort-Object -Property { $_.Extent.StartOffset } -Descending); + + if ($CommentTokens.Count -eq 0) { + return $Content; + } + + [System.Text.StringBuilder]$Builder = New-Object System.Text.StringBuilder($Content); + + foreach ($token in $CommentTokens) { + $start = $token.Extent.StartOffset; + $length = $token.Extent.EndOffset - $start; + $Builder.Remove($start, $length) | Out-Null; + } + + [string]$Result = $Builder.ToString(); + $Result = [regex]::Replace($Result, '(?m)^\s+$', ''); + $Result = [regex]::Replace($Result, '(\r?\n){3,}', "$1$1"); + + return $Result.Trim(); +} + function Write-IcingaSourceFile() { [CmdletBinding()] @@ -152,12 +192,43 @@ if (Test-Path $OutputPath) { Write-Host " * Output directory ready: $OutputPath" -ForegroundColor Green; -# Build single consolidated module file -Write-Host "`n[3/4] Building single consolidated module..." -ForegroundColor Yellow; +# Build consolidated classes and kernel files +Write-Host "`n[3/4] Building consolidated classes and kernel modules..." -ForegroundColor Yellow; + +[string]$ClassesModuleName = 'IcingaForWindows.Classes.ps1'; +[string]$ClassesOutput = Join-Path -Path $OutputPath -ChildPath $ClassesModuleName; +[System.Text.StringBuilder]$ClassesContent = New-Object System.Text.StringBuilder; + +# Add classes header +$ClassesContent.AppendLine('<#') | Out-Null; +$ClassesContent.AppendLine('.SYNOPSIS') | Out-Null; +$ClassesContent.AppendLine(' Icinga for Windows - Classes Module') | Out-Null; +$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('#>') | Out-Null; +$ClassesContent.AppendLine() | Out-Null; + +# Append all classes sorted alphabetically (stripped of comments for minimal runtime memory) +Write-Host " * Appending $($Components['Classes'].Count) class file(s) (minified)..." -ForegroundColor White; +foreach ($classFile in ($Components['Classes'] | Sort-Object)) { + $FileContent = Read-IcingaSourceFile -Path $classFile; + $CleanContent = Remove-IcingaComments -Content $FileContent; + if (-not [string]::IsNullOrWhiteSpace($CleanContent)) { + $ClassesContent.AppendLine($CleanContent) | Out-Null; + $ClassesContent.AppendLine() | Out-Null; + } +} + +Set-Content -Path $ClassesOutput -Value $ClassesContent.ToString() -Encoding UTF8 -Force; +Write-Host " * Classes file built successfully: $ClassesModuleName" -ForegroundColor Green; -[string]$SingleModuleName = 'IcingaForWindows.Kernel.ps1'; -[string]$ModuleOutput = Join-Path -Path $OutputPath -ChildPath $SingleModuleName; -[hashtable]$FncCache = @{ }; +# 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; @@ -173,21 +244,15 @@ $ModuleContent.AppendLine(" Source: $ModuleBasePath\src") | Out-Null; $ModuleContent.AppendLine('#>') | Out-Null; $ModuleContent.AppendLine() | Out-Null; -# Append all classes first so their type definitions are parsed before any -# function that references them within the single dot-sourced kernel file. -Write-Host " * Appending $($Components['Classes'].Count) class file(s)..." -ForegroundColor White; -foreach ($classFile in ($Components['Classes'] | Sort-Object)) { - $FileContent = Read-IcingaSourceFile -Path $classFile; - $ModuleContent.AppendLine($FileContent) | Out-Null; - $ModuleContent.AppendLine() | Out-Null; -} - -# Append all private functions once -Write-Host " * Appending $($Components['Private'].Count) private function file(s)..." -ForegroundColor White; +# Append all private functions once (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']) { - $FileContent = Read-IcingaSourceFile -Path $privateFile; - $ModuleContent.AppendLine($FileContent) | Out-Null; - $ModuleContent.AppendLine() | Out-Null; + $FileContent = Read-IcingaSourceFile -Path $privateFile; + $CleanContent = Remove-IcingaComments -Content $FileContent; + if (-not [string]::IsNullOrWhiteSpace($CleanContent)) { + $ModuleContent.AppendLine($CleanContent) | Out-Null; + $ModuleContent.AppendLine() | Out-Null; + } } # Append all public functions once diff --git a/build/Invoke-ModuleTests.ps1 b/build/Invoke-ModuleTests.ps1 index 45c4476..73eb70d 100644 --- a/build/Invoke-ModuleTests.ps1 +++ b/build/Invoke-ModuleTests.ps1 @@ -68,10 +68,11 @@ if (-not (Test-Path -Path $Path)) { throw "Test path not found: $Path"; } -# Ensure the compiled kernel artifact exists before running tests -$KernelPath = Join-Path -Path $ModuleBasePath -ChildPath (Join-Path -Path 'lib' -ChildPath 'IcingaForWindows.Kernel.ps1'); -if (-not (Test-Path -Path $KernelPath)) { - Write-Host 'Kernel artifact not found, building module first...' -ForegroundColor Yellow; +# Ensure the compiled kernel and classes artifacts exist before running tests +$KernelPath = Join-Path -Path $ModuleBasePath -ChildPath (Join-Path -Path 'lib' -ChildPath 'IcingaForWindows.Kernel.ps1'); +$ClassesPath = Join-Path -Path $ModuleBasePath -ChildPath (Join-Path -Path 'lib' -ChildPath 'IcingaForWindows.Classes.ps1'); +if (-not (Test-Path -Path $KernelPath) -or -not (Test-Path -Path $ClassesPath)) { + Write-Host 'Kernel or classes artifact not found, building module first...' -ForegroundColor Yellow; & (Join-Path -Path $PSScriptRoot -ChildPath 'Build-ModuleProject.ps1') -ModuleBasePath $ModuleBasePath -SkipTests; } diff --git a/docs/Developer/PerformanceCounter/01-Technical-Architecture-and-Reference.md b/docs/Developer/PerformanceCounter/01-Technical-Architecture-and-Reference.md new file mode 100644 index 0000000..5f28b27 --- /dev/null +++ b/docs/Developer/PerformanceCounter/01-Technical-Architecture-and-Reference.md @@ -0,0 +1,325 @@ +# Performance Counter Technical Architecture and Reference + +The Icinga for Windows Performance Counter subsystem provides a thread-safe, zero-configuration, low-latency abstraction over `.NET` Windows Performance Counters (`System.Diagnostics.PerformanceCounter` and `System.Diagnostics.PerformanceCounterCategory`). + +It is designed around four core architectural principles: + +1. **Single-Thread Handle Ownership:** `.NET` performance counter instances are not thread-safe. When the background daemon is running, all counter handles and category snapshots are owned, sampled, reconciled, and disposed exclusively by the dedicated daemon thread. Callers across any number of worker threads communicate with the daemon strictly via lock-free concurrent queues. +2. **Two-Tier Sampling Strategy:** + - **Concrete Counter Paths** (`\Category\Counter` or `\Category(Instance)\Counter`) are backed by persistent `System.Diagnostics.PerformanceCounter` handles (`IcingaPerformanceCounterEntry`). + - **Wildcard Counter Paths** (`\Category(*)\Counter`) are backed by category-level bulk snapshots (`IcingaPerformanceCounterCategory` wrapping `PerformanceCounterCategory.ReadCategory()`). Instead of allocating and warming dozens or hundreds of individual handles per process or disk, a single kernel transition captures the entire category table and computes cooked values across consecutive `InstanceDataCollectionCollection` snapshots using `CounterSample.Calculate`. +3. **Proactive Warm-Up via Static AST Discovery and Persistent Caching:** Rate-based counters (such as `% Processor Time` or `Disk Reads/sec`) require two samples separated by a time delta (`WarmupMilliseconds`, default `250 ms`) to produce a meaningful non-zero value. To eliminate this delay during check execution, the subsystem discovers statically declared counters from `lib\IcingaForWindows.Kernel.ps1` via PowerShell AST parsing at startup and merges them with the self-maintaining `PerformanceCounter.json` cache file. All known counters are warmed in a single shared batch before the first check runs. +4. **Windows PowerShell 5.1 Runspace Isolation:** PowerShell classes carry runspace affinity to the `SessionStateInternal` in which their scriptblock was compiled. Calling a method on a class instance created from another runspace's type object marshals execution back to the origin runspace, which deadlocks when the origin runspace is blocked waiting on a daemon queue response. The subsystem compiles class definitions into a dedicated `lib\IcingaForWindows.Classes.ps1` file loaded with a unique scriptblock cachebuster per runspace on Windows PowerShell 5.1 (`Desktop` edition) and resolves all class types dynamically via `'ClassName' -as [type]`. + +--- + +## 1. High-Level Architecture + +```mermaid +flowchart TD + subgraph Startup["Daemon Initialization (New-IcingaPerformanceCounterEnvironment)"] + CacheFile["Cache File (PerformanceCounter.json)"] -->|"Read-IcingaPerformanceCounterCache"| Reg + KernelAst["Kernel AST (lib/IcingaForWindows.Kernel.ps1)"] -->|"Register-IcingaPerformanceCounterFromComponents"| Reg + CompCall["New-IcingaPerformanceCounter (Runtime)"] --> Reg + Reg["$Store.Registered (ConcurrentDictionary[string, datetime])"] -->|"Reconcile & Batch Warmup"| Mgr["$Store.Manager (IcingaPerformanceCounter)"] + end + + subgraph Callers["Caller Runspaces (Checks / Providers / Interactive Shell)"] + GetCmd["Get-IcingaPerformanceCounter"] + ShowDetails["Show-IcingaPerformanceCounterDetails"] + ShowCmd["Show-IcingaPerformanceCounter"] + TestCat["Test-IcingaPerformanceCounterCategory"] + ShowDetails --> GetCmd + end + + subgraph Transport["Global Store ($Global:IcingaForWindows.Public.PerformanceCounter)"] + ReqQ["RequestQueue (BlockingCollection[PSObject])"] + PendQ["PendingRequests (ConcurrentDictionary[string, BlockingCollection[PSObject]])"] + end + + subgraph Daemon["Background Daemon Thread (Start-IcingaPerformanceCounterDaemon)"] + Loop["TryTake(500ms) Loop"] + Maint["Update-IcingaPerformanceCounterState"] + Entries["$Manager.Counters (IcingaPerformanceCounterEntry)"] + Cats["$Manager.Categories (IcingaPerformanceCounterCategory)"] + Loop --> Mgr + Loop --> Maint + Maint -->|"Evict, Reconcile, Sample, Write Cache"| Mgr + Mgr --> Entries + Mgr --> Cats + end + + GetCmd -->|"1. Refresh Last-Seen"| Reg + GetCmd -->|"2. Enqueue RequestId + Counter"| ReqQ + ReqQ -->|"3. Dequeue"| Loop + Mgr -->|"4. Resolve Result"| PendQ + PendQ -->|"5. TryTake(TimeoutMs)"| GetCmd +``` + +--- + +## 2. Global Runtime State + +The global state is initialized in [`IcingaForWindows.psm1`](../../../IcingaForWindows.psm1) inside `New-ModuleBaseEnvironment` at `$Global:IcingaForWindows.Public.PerformanceCounter` (accessed via `(Get-GlobalRuntimeVariable).Public.PerformanceCounter`): + +| Property | Type | Initial Value | Description | +| :--- | :--- | :--- | :--- | +| `RequestQueue` | `System.Collections.Concurrent.BlockingCollection[PSObject]` | Empty queue backed by `ConcurrentQueue[PSObject]` | FIFO queue through which callers submit counter read requests (`[PSCustomObject]@{ RequestId = [string]; Counter = [string[]] }`) to the daemon thread. | +| `PendingRequests` | `System.Collections.Concurrent.ConcurrentDictionary[string, System.Collections.Concurrent.BlockingCollection[PSObject]]` | Empty dictionary | Maps each in-flight `RequestId` (GUID string) to a single-slot (`BoundedCapacity = 1`) `BlockingCollection[PSObject]` created by the caller to receive its response. | +| `Registered` | `System.Collections.Concurrent.ConcurrentDictionary[string, datetime]` | Empty dictionary | Maps each registered counter path to its last-seen `[datetime]` timestamp. Updated by `New-IcingaPerformanceCounter`, `Get-IcingaPerformanceCounter`, `Read-IcingaPerformanceCounterCache`, and `Register-IcingaPerformanceCounterFromComponents`. | +| `Manager` | `object` (`IcingaPerformanceCounter`) | `$null` | The central manager instance created lazily inside `New-IcingaPerformanceCounterEnvironment` on the daemon thread. Never accessed directly by non-daemon threads. | +| `Heartbeat` | `System.Nullable[datetime]` (`$null` or `[datetime]`) | `$null` | Timestamp updated by `New-IcingaPerformanceCounterEnvironment` and on every iteration of `Update-IcingaPerformanceCounterState`. Used by `Test-IcingaPerformanceCounterDaemon` to determine whether the daemon is alive. | +| `LastRefresh` | `System.Nullable[datetime]` (`$null` or `[datetime]`) | `$null` | Timestamp of the last heavy maintenance pass (`Reconcile`, `Sample`, cache write) inside `Update-IcingaPerformanceCounterState`. | +| `Config` | `PSCustomObject` | See table below | Tunable timing and eviction parameters for the subsystem. | + +### Configuration Parameters (`$Store.Config`) + +| Setting | Type | Default | Description | +| :--- | :--- | :--- | :--- | +| `WarmupMilliseconds` | `System.Int32` | `250` | Delay in milliseconds waited once after priming one or more newly added counters or category snapshots before taking the second sample, and minimum age before a wildcard category snapshot is refreshed during `Resolve()`. | +| `RefreshIntervalMs` | `System.Int32` | `1000` | Minimum interval in milliseconds between heavy daemon maintenance runs (eviction, reconciliation, background sampling, and cache file writes) in `Update-IcingaPerformanceCounterState`. | +| `EvictionMinutes` | `System.Int32` | `60` | Time window in minutes after which a registered counter path that has not been requested or refreshed is evicted from `$Store.Registered` and disposed by the manager. | + +--- + +## 3. Execution Modes + +When `Get-IcingaPerformanceCounter` is called, it selects one of three execution paths depending on the runtime environment state: + +### Mode 1: Daemon Queue Dispatch (Primary Production Mode) +Used when `$Store` exists and `Test-IcingaPerformanceCounterDaemon` returns `$true` (meaning `$Store.Heartbeat` is non-null and not older than **5 seconds**). + +1. Each requested path in `-Counter` has its timestamp updated in `$Store.Registered[$Path] = (Get-Date)`. +2. A unique `[string]$RequestId = (New-Guid).ToString()` is generated. +3. A bounded single-item response queue (`[System.Collections.Concurrent.BlockingCollection[PSObject]]::new(1)`) is registered at `$Store.PendingRequests[$RequestId]`. +4. The request payload (`[PSCustomObject]@{ RequestId = $RequestId; Counter = [string[]]$Counter }`) is added to `$Store.RequestQueue`. +5. The caller blocks on `$ResponseQueue.TryTake([ref]$Response, $TimeoutMs)` (default `5000 ms`). +6. If the daemon responds in time, `$Response` is returned (and optionally reshaped if `-StructureByInstance` is set). If `TryTake` times out, a `Warning` entry (`Get-IcingaPerformanceCounter: Request timed out`) is written via `Write-LoggingEntry` and `$null` is returned. +7. A `finally` block always removes `$RequestId` from `$Store.PendingRequests` and disposes `$ResponseQueue`. + +### Mode 2: Persistent Per-Runspace Inline Fallback +Used when `$Store` is initialized (`Use-IcingaForWindows` has run), but the background daemon is not running or its heartbeat is older than 5 seconds (for example in interactive CLI sessions started without `-RunBackgroundDaemons`). + +1. Each requested path is recorded in `$Store.Registered[$Path] = (Get-Date)`. +2. The function lazily initializes a module-scoped manager instance `$script:IcingaPerformanceCounterInlineManager = ('IcingaPerformanceCounter' -as [type])::new()`. +3. Because each PowerShell runspace has its own isolated `$script:` module scope and executes one pipeline at a time, `$script:IcingaPerformanceCounterInlineManager` is never accessed concurrently and requires no locking. +4. Counter handles and category snapshots remain warm in `$script:IcingaPerformanceCounterInlineManager` across repeated calls within that runspace; only the first read of a newly requested counter pays the `WarmupMilliseconds` sleep. + +### Mode 3: Transient One-Shot Read (`ResolveOnce`) +Used when `$Store` is `$null` (the global runtime variable has not been initialized at all). + +1. Calls `('IcingaPerformanceCounter' -as [type])::ResolveOnce([string[]]$Counter, 250)`. +2. Creates a temporary `IcingaPerformanceCounter` instance, primes all requested paths, sleeps `250 ms` once, reads the counters, and disposes all handles immediately in a `finally` block. + +--- + +## 4. Startup Discovery, Cache Persistence, and Maintenance Lifecycle + +### 4.1 Environment Initialization (`New-IcingaPerformanceCounterEnvironment`) +Executed once at the start of `Start-IcingaPerformanceCounterDaemon`: + +1. Instantiates `$Store.Manager = ('IcingaPerformanceCounter' -as [type])::new()` and copies `$Store.Config.WarmupMilliseconds` to `$Store.Manager.WarmupMilliseconds`. +2. Calls `Read-IcingaPerformanceCounterCache` to load previously persisted counter paths and timestamps from `\PerformanceCounter.json` into `$Store.Registered`. Missing, empty, or corrupt JSON files are silently ignored so a damaged cache never blocks startup. +3. Calls `Register-IcingaPerformanceCounterFromComponents` to statically scan `lib\IcingaForWindows.Kernel.ps1` using `[System.Management.Automation.Language.Parser]::ParseFile(...)`. Every `CommandAst` calling `New-IcingaPerformanceCounter` is inspected, and all `StringConstantExpressionAst` literals passed to `-Counter` (both `-Counter @(...)` and `-Counter:@(...)`) are extracted via `Get-IcingaPerformanceCounterLiteral` and added to `$Store.Registered` without executing any component code. +4. Calls `$Store.Manager.Reconcile(@($Store.Registered.Keys))`, which primes all discovered concrete counters and wildcard categories and sleeps **once** (`WarmupMilliseconds`) for the entire startup batch. +5. Sets `$Store.Heartbeat = (Get-Date)` and `$Store.LastRefresh = (Get-Date)` and logs an `Info` message (`Performance counter environment initialized`). + +### 4.2 Periodic Maintenance (`Update-IcingaPerformanceCounterState`) +Called on every cycle of `Start-IcingaPerformanceCounterDaemon` (after `RequestQueue.TryTake([ref]$Request, 500)`): + +1. **Heartbeat Refresh (Every Cycle):** Updates `$Store.Heartbeat = (Get-Date)` unconditionally so `Test-IcingaPerformanceCounterDaemon` remains accurate even when the daemon is busy serving requests. +2. **Throttling Check:** If `$Store.LastRefresh` is less than `$Store.Config.RefreshIntervalMs` (`1000 ms`) ago, returns immediately. +3. **Eviction:** Computes `$Threshold = (Get-Date).AddMinutes(-1 * $Store.Config.EvictionMinutes)`. Any key in `$Store.Registered` whose last-seen timestamp is older than `$Threshold` is removed via `$Store.Registered.TryRemove($Key, [ref]$Removed)`. +4. **Reconciliation (`$Manager.Reconcile($Registered)`):** + - Primes any newly registered concrete paths or wildcard categories in a single batch. + - Disposes and removes any concrete counter handles or category snapshots that are no longer in `$Registered`. +5. **Background Sampling (`$Manager.Sample()`):** + - Calls `$Entry.Handle.NextValue()` on every concrete counter entry and `$Snapshot.Refresh()` on every category snapshot so rate counters continuously track recent activity between check invocations. +6. **Atomic Cache Persistence (`Write-IcingaPerformanceCounterCache`):** + - Serializes `$Store.Registered` (with ISO 8601 round-trip `'o'` timestamps) to `\PerformanceCounter.json.tmp` (`UTF8`) and atomically renames it over `PerformanceCounter.json` via `Move-Item -Force`. +7. **Timestamp Update:** Sets `$Store.LastRefresh = (Get-Date)`. + +--- + +## 5. Path Parsing, Normalization, and Local Host Handling + +`IcingaPerformanceCounter::ParsePath([string]$Path)` and `IcingaPerformanceCounter::NormalizePath([string]$Path)` enforce a strict canonical path grammar: + +- **Accepted Machine Prefixes (Local Host Only):** + - Machine-less paths starting with a single backslash: `\Category\Counter` or `\Category(Instance)\Counter` + - Local machine prefixes starting with `\\`: + - `\\.\Category\Counter` + - `\\localhost\Category\Counter` (case-insensitive) + - `\\127.0.0.1\Category\Counter` + - `\\::1\Category\Counter` + - `\\\Category\Counter` (case-insensitive match against `[System.Environment]::MachineName`) +- **Rejected Paths (`Valid = $false`):** + - Null, empty, or paths not starting with `\` + - Remote machine paths (`\\remote-host\Category\Counter`) + - Paths that do not split into exactly three segments (`''`, ``, ``) + - Empty category or counter names + - Malformed instance parentheses (such as `Category(Instance` without closing `)`, trailing characters after `)`, empty category before `(`, or empty instance name `Category()`) +- **Canonical Normalization (`NormalizePath`):** + - Strips any valid local machine prefix so that `\\.\Memory\Available Bytes`, `\\localhost\Memory\Available Bytes`, and `\Memory\Available Bytes` all normalize to `\Memory\Available Bytes`. + - Internally, `IcingaPerformanceCounter` normalizes concrete counter paths in `CreateEntry`, `Warmup`, `ReadPath`, `Resolve`, and `Reconcile` so a counter requested under both `\Memory\Available Bytes` and `\\.\Memory\Available Bytes` shares a single underlying `IcingaPerformanceCounterEntry` handle while `Resolve()` still keys its outer return hashtable by the exact path string requested by the caller. + +--- + +## 6. Class Reference (`src/Classes/Icinga/IcingaPerformanceCounter.ps1`) + +All three classes are defined in [`src/Classes/Icinga/IcingaPerformanceCounter.ps1`](../../../src/Classes/Icinga/IcingaPerformanceCounter.ps1). + +### 6.1 Class `IcingaPerformanceCounterEntry` + +Represents a single concrete performance counter path backed by a persistent `System.Diagnostics.PerformanceCounter` handle. + +#### Properties + +| Property | Type | Default | Description | +| :--- | :--- | :--- | :--- | +| `FullName` | `[string]` | `''` | Canonical counter path (`\Category\Counter` or `\Category(Instance)\Counter`). | +| `Category` | `[string]` | `''` | Performance counter category name. | +| `Instance` | `[string]` | `''` | Instance name, or `''` for single-instance categories. | +| `Counter` | `[string]` | `''` | Counter name within the category. | +| `Handle` | `[System.Diagnostics.PerformanceCounter]` | `$null` | Underlying `.NET` performance counter handle. Created lazily by `Prime()`. | +| `Primed` | `[bool]` | `$false` | `$true` once `Prime()` has successfully created and sampled the handle. | +| `LastError` | `[string]` | `''` | Exact exception message captured if `Prime()` failed; surfaced by `Read()` when `Handle` is `$null`. | + +#### Constructor + +- `IcingaPerformanceCounterEntry([string]$FullName, [string]$Category, [string]$Instance, [string]$Counter)` + Assigns the four path metadata properties without touching the OS counter API. + +#### Methods + +| Method Signature | Return Type | Description | +| :--- | :--- | :--- | +| `[void] Prime()` | `void` | No-op if `$this.Primed` is already `$true`. Otherwise creates `[System.Diagnostics.PerformanceCounter]::new()`, assigns `CategoryName`, `CounterName`, and (when `$this.Instance` is non-empty) `InstanceName`, calls `NextValue()` and `NextSample()` to establish baseline sample state, sets `LastError = ''`, and marks `Primed = $true`. On exception, records `$_.Exception.Message` in `LastError` and calls `$Error.Clear()`. | +| `[hashtable] Read()` | `[hashtable]` | Returns the uniform 5-key result hashtable (`value`, `sample`, `help`, `type`, `error`). If `$null -eq $this.Handle`, sets `error` to `$this.LastError` (or `'Counter not initialized'` if `LastError` is empty). Otherwise calls `$this.Handle.NextValue()` (coalescing `$null` to `0`), rounds `value` to 6 decimal places via `[math]::Round([decimal]$CounterValue, 6)`, and populates `sample` (`NextSample()`), `help` (`CounterHelp`), and `type` (`[string]$this.Handle.CounterType`). Any exception is caught into `error` and `$Error.Clear()` is called. | +| `[void] Dispose()` | `void` | Calls `$this.Handle.Dispose()` (ignoring errors) and sets `$this.Handle = $null`. | + +--- + +### 6.2 Class `IcingaPerformanceCounterCategory` + +Maintains two consecutive category-wide `InstanceDataCollectionCollection` snapshots (`Previous` and `Current`) for a performance counter category using `PerformanceCounterCategory.ReadCategory()`, enabling bulk wildcard (`*`) reads across all live instances in a single kernel call. + +#### Properties + +| Property | Type | Default | Description | +| :--- | :--- | :--- | :--- | +| `Category` | `[string]` | `''` | Name of the Windows performance counter category. | +| `Reader` | `[System.Diagnostics.PerformanceCounterCategory]` | `$null` | Category reader object initialized by `Prime()`. | +| `Previous` | `[System.Diagnostics.InstanceDataCollectionCollection]` | `$null` | Preceding category snapshot used as the baseline sample for rate counters. | +| `Current` | `[System.Diagnostics.InstanceDataCollectionCollection]` | `$null` | Most recent category snapshot captured by `Prime()` or `Refresh()`. | +| `ReadTime` | `[datetime]` | `[datetime]::MinValue` | UTC timestamp (`[datetime]::UtcNow`) when `Current` was captured. | +| `Help` | `[hashtable]` | `$null` | Lazily populated cache mapping `CounterName -> CounterHelp` for this category. | +| `LastError` | `[string]` | `''` | Exact exception message captured if `Prime()` or `Refresh()` failed. | + +#### Constructor + +- `IcingaPerformanceCounterCategory([string]$Category)` + Stores `$this.Category = $Category`. + +#### Methods + +| Method Signature | Return Type | Description | +| :--- | :--- | :--- | +| `[void] Prime()` | `void` | Creates `[System.Diagnostics.PerformanceCounterCategory]::new($this.Category)`, reads the initial snapshot via `$this.Reader.ReadCategory()` into `$this.Current`, sets `$this.ReadTime = [datetime]::UtcNow`, and clears `LastError = ''`. On exception, stores `$_.Exception.Message` in `LastError` and calls `$Error.Clear()`. | +| `[void] Refresh()` | `void` | If `$null -eq $this.Reader -or $null -eq $this.Current`, delegates to `$this.Prime()` and returns. Otherwise captures `$Snapshot = $this.Reader.ReadCategory()`, rotates `$this.Previous = $this.Current` and `$this.Current = $Snapshot`, updates `$this.ReadTime = [datetime]::UtcNow`, and clears `LastError = ''`. On exception, preserves the existing snapshots, stores `$_.Exception.Message` in `LastError`, and calls `$Error.Clear()`. | +| `[double] AgeMilliseconds()` | `[double]` | Returns `[double]::MaxValue` if `$null -eq $this.Current`; otherwise returns `([datetime]::UtcNow - $this.ReadTime).TotalMilliseconds`. | +| `[string[]] GetInstanceNames()` | `[string[]]` | Returns all live instance names from the first `InstanceDataCollection` in `$this.Current.Values`, filtering out the internal `.NET` sentinel `'systemdiagnosticsperfcounterlibsingleinstance'`. Returns an empty `[string[]]` if `$null -eq $this.Current`. | +| `[hashtable] Read([string]$Instance, [string]$Counter)` | `[hashtable]` | Computes and returns the uniform 5-key result hashtable for `$Instance` and `$Counter` from `$this.Previous` and `$this.Current`:
1. If `$null -eq $this.Current`, returns `error = $this.LastError` (or `'Counter not initialized'`).
2. If `$this.Current.Contains($Counter)` is `$false`, returns `error = 'The counter "{0}" does not exist in the category "{1}"'`.
3. If `$Collection.Contains($Instance)` is `$false`, returns `error = 'The instance "{0}" does not exist in the category "{1}"'`.
4. Looks up `$PreviousData = $this.FindPrevious($Instance, $Counter)` and computes `$Value` via `[System.Diagnostics.CounterSample]::Calculate($Sample)` (when `$null -eq $PreviousData`) or `[System.Diagnostics.CounterSample]::Calculate($PreviousData.Sample, $Sample)`, rounded to 6 decimal places (`[math]::Round([decimal]$Value, 6)`).
5. Populates `sample = $Sample`, `help = $this.GetHelp($Counter, $Instance)`, and `type = [string]$Sample.CounterType`. | +| `hidden [System.Diagnostics.InstanceData] FindPrevious([string]$Instance, [string]$Counter)` | `[System.Diagnostics.InstanceData]` | Looks up the matching `InstanceData` in `$this.Previous`. For categories that expose an `'ID Process'` counter (such as `Process`), verifies that `$PreviousId.RawValue -eq $CurrentId.RawValue`. If a process exited and Windows renumbered remaining `name#n` instances (e.g. `svchost#3`), the PID mismatch causes `FindPrevious` to return `$null` so `Read()` treats it as a newly appeared instance instead of computing a bogus rate across two different processes. | +| `hidden [string] GetHelp([string]$Counter, [string]$Instance)` | `[string]` | Lazily populates `$this.Help` once per category by calling `$this.Reader.GetCounters($Instance)` (or `GetCounters()`), copying each handle's `CounterName` -> `CounterHelp` into `$this.Help`, and immediately calling `$Handle.Dispose()` on every temporary handle. Subsequent reads look up `$this.Help[$Counter]` in memory. | + +--- + +### 6.3 Class `IcingaPerformanceCounter` + +Central coordinator that owns all concrete counter entries (`Counters`) and category snapshots (`Categories`). + +#### Properties + +| Property | Type | Default | Description | +| :--- | :--- | :--- | :--- | +| `Counters` | `[System.Collections.Concurrent.ConcurrentDictionary[string, object]]` | Empty dictionary | Maps normalized concrete counter paths (`\Category\Counter` or `\Category(Instance)\Counter`) to `IcingaPerformanceCounterEntry` instances. | +| `Categories` | `[System.Collections.Concurrent.ConcurrentDictionary[string, object]]` | Empty dictionary | Maps category names (`Processor`, `PhysicalDisk`, etc.) to `IcingaPerformanceCounterCategory` instances. | +| `WarmupMilliseconds` | `[int]` | `250` | Milliseconds to sleep once after priming new counters/categories, and minimum category snapshot age before `Resolve()` triggers a `Refresh()`. | + +#### Constructor + +- `IcingaPerformanceCounter()` + Initializes `$this.Counters` and `$this.Categories` as empty `ConcurrentDictionary[string, object]` instances. + +#### Static Methods + +| Method Signature | Return Type | Description | +| :--- | :--- | :--- | +| `static [hashtable] ParsePath([string]$Path)` | `[hashtable]` | Parses `$Path` into `@{ 'Category' = [string]; 'Instance' = [string]; 'Counter' = [string]; 'Valid' = [bool] }`. Accepts and strips local host prefixes (`\\.\`, `\\localhost\`, `\\127.0.0.1\`, `\\::1\`, `\\\`). | +| `static [string] NormalizePath([string]$Path)` | `[string]` | Returns the canonical machine-less counter path (`\Category\Counter` or `\Category(Instance)\Counter`), or `$Path` unchanged if `ParsePath($Path).Valid` is `$false`. | +| `static [bool] CategoryExists([string]$Category)` | `[bool]` | Accepts either a category name (`'Processor'`) or a full counter path (`'\Processor(*)\% Processor Time'`, `'\\.\Memory\Available Bytes'`). Returns `$true` if `[System.Diagnostics.PerformanceCounterCategory]::new($TargetCategory).CategoryType` succeeds, or `$false` if the category does not exist, the path is invalid, or access fails. Never throws. | +| `static [hashtable] ResolveOnce([string[]]$Paths, [int]$WarmupMilliseconds)` | `[hashtable]` | Creates a temporary `IcingaPerformanceCounter` instance, sets `WarmupMilliseconds`, calls `$Manager.Resolve($Paths)`, and disposes the manager in a `finally` block. | + +#### Instance Methods + +| Method Signature | Return Type | Description | +| :--- | :--- | :--- | +| `[string] GetCategoryError([string]$Category)` | `[string]` | Returns `'Category name is empty'` if `$Category` is null/whitespace, returns `$Snapshot.LastError` if `$Category` is registered in `$this.Categories` and has a recorded error, or returns `''`. | +| `[string[]] ExpandPath([string]$Path)` | `[string[]]` | Returns `@()` if `$Path` is invalid, or `@($Path)` if `$Path` is not a wildcard (`*`). For wildcard paths (`\Category(*)\Counter`), ensures the category exists in `$this.Categories` (via `AddCategory`) and expands all live instances from `$Snapshot.GetInstanceNames()` into concrete `\Category(Instance)\Counter` paths. | +| `[object] CreateEntry([string]$Path)` | `[object]` (`IcingaPerformanceCounterEntry`) | Normalizes `$Path` and returns a new `IcingaPerformanceCounterEntry` instance, or `$null` if `$Path` is invalid. | +| `[void] Warmup([string[]]$Paths)` | `void` | Iterates `$Paths`: primes any new wildcard categories via `AddCategory($Parsed.Category)` and creates/primes any new normalized concrete entries in `$this.Counters`. If at least one category or concrete counter was newly primed, sleeps **once** for `$this.WarmupMilliseconds`. | +| `[bool] AddCategory([string]$Category)` | `[bool]` | Returns `$false` if `$Category` is already present in `$this.Categories`. Otherwise creates an `IcingaPerformanceCounterCategory`, calls `Prime()`, stores it in `$this.Categories[$Category]`, and returns `$true`. | +| `[hashtable] ReadPath([string]$Path)` | `[hashtable]` | Normalizes `$Path`, looks up the entry in `$this.Counters`, and calls `$Entry.Read()`. If no entry exists, returns the uniform 5-key hashtable with `error = 'Counter not initialized'`. | +| `[hashtable] Resolve([string[]]$Paths)` | `[hashtable]` | Main query entry point:
1. Calls `$this.Warmup($Paths)`.
2. Maintains a per-call `$ReadCache` so duplicate paths in `$Paths` are only read once.
3. For wildcard paths (`Instance -eq '*'`): refreshes `$Snapshot` if `$Snapshot.AgeMilliseconds() -ge $this.WarmupMilliseconds`, then populates a nested hashtable keyed by each expanded concrete path (`\Category(Instance)\Counter`).
4. For concrete paths: normalizes the path for `$ReadCache` and `ReadPath`, and stores the flat 5-key result hashtable under the caller's original `$Path`. | +| `[void] Sample()` | `void` | Background maintenance sampler: calls `$Entry.Handle.NextValue()` on all primed concrete entries and `$Snapshot.Refresh()` on all category snapshots. | +| `[void] Reconcile([string[]]$RegisteredPaths)` | `void` | Synchronizes `$this.Counters` and `$this.Categories` with `$RegisteredPaths`:
1. Builds `$Desired` (normalized concrete paths) and `$DesiredCategories` (wildcard category names).
2. Primes any newly added categories or concrete entries and sleeps once (`$this.WarmupMilliseconds`) if anything was newly primed, then calls `$Snapshot.Refresh()` on newly primed categories.
3. Removes and disposes any concrete entries not in `$Desired` and removes any categories not in `$DesiredCategories`. | +| `[void] Dispose()` | `void` | Disposes every `IcingaPerformanceCounterEntry` in `$this.Counters` and clears both `$this.Counters` and `$this.Categories`. | + +--- + +## 7. Public and Private Cmdlet Reference + +### 7.1 Public Cmdlets (`src/PerformanceCounter/Public/`) + +| Cmdlet | Parameters | Return Type | Description | +| :--- | :--- | :--- | :--- | +| [`Get-IcingaPerformanceCounter`](../../../src/PerformanceCounter/Public/Get-IcingaPerformanceCounter.ps1) | `-Counter [array] = @()`
`-TimeoutMs [int] = 5000`
`-StructureByInstance [switch] = $false` | `[hashtable]` or `$null` | Reads one or more concrete or wildcard performance counter paths. Refreshes registration timestamps, dispatches via the daemon queue (or inline per-runspace manager / transient fallback), and optionally reshapes output via `ConvertTo-IcingaPerformanceCounterInstanceStructure`. Returns `@{ }` when `-Counter` is empty, or `$null` when a daemon request times out. | +| [`Show-IcingaPerformanceCounter`](../../../src/PerformanceCounter/Public/Show-IcingaPerformanceCounter.ps1) | `-Category [string] = $null`
`-Counter [string] = $null`
`-Filter [string] = $null` | `[array]` | Stateless metadata browser using `System.Diagnostics.PerformanceCounterCategory`:
1. With `-Counter`: expands a wildcard path into sorted live concrete instance paths (`\Category(Instance)\Counter`), returning `@()` if the path is invalid or fails.
2. With `-Category`: lists sorted unique counter paths in that category (`\Category(*)\Counter` for multi-instance categories, `\Category\Counter` for single-instance categories), disposing temporary counter handles immediately.
3. With no arguments (or `-Filter`): lists sorted category names matching `-like $Filter`. | +| [`Show-IcingaPerformanceCounterDetails`](../../../src/PerformanceCounter/Public/Show-IcingaPerformanceCounterDetails.ps1) | `-Counter [array] = @()`
`-StructureByInstance [switch] = $false` | `[hashtable]` | Returns live values via `Get-IcingaPerformanceCounter`. When `-Counter` is omitted or empty, reads all counter paths currently registered in `$Store.Registered.Keys`. | +| [`Test-IcingaPerformanceCounterCategory`](../../../src/PerformanceCounter/Public/Test-IcingaPerformanceCounterCategory.ps1) | `-Category [string] = ''` | `[bool]` | Checks whether a performance counter category (passed as a plain category name or a full counter path) exists and is accessible on the local system by delegating to `IcingaPerformanceCounter::CategoryExists($Category)`. Never throws. | + +### 7.2 Private Cmdlets (`src/PerformanceCounter/Private/`) + +| Cmdlet | Parameters | Return Type | Description | +| :--- | :--- | :--- | :--- | +| [`ConvertTo-IcingaPerformanceCounterInstanceStructure`](../../../src/PerformanceCounter/Private/ConvertTo-IcingaPerformanceCounterInstanceStructure.ps1) | `-Result [hashtable] = @{ }`
`-Counter [array] = @()` | `[hashtable]` | Reshapes the path-keyed hashtable from `Get-IcingaPerformanceCounter` into an instance-first structure (`$Structured[Instance][Category][Counter]`) for counters with an instance, and a category-first structure (`$Structured[Category][Counter]`) for single-instance counters. | +| [`Get-IcingaPerformanceCounterLiteral`](../../../src/PerformanceCounter/Private/Get-IcingaPerformanceCounterLiteral.ps1) | `-Argument [System.Management.Automation.Language.Ast] = $null` | `[array]` | Walks `$Argument.FindAll(...)` and returns the `.Value` of every `StringConstantExpressionAst` node inside the AST node. | +| [`Get-IcingaPerformanceCounterValue`](../../../src/PerformanceCounter/Private/Get-IcingaPerformanceCounterValue.ps1) | `-InputObject [object] = $null` | `[object]` (`[decimal]`, `[string]`, or `$null`) | Extracts the usable result from a single counter leaf hashtable: returns `$null` if `$InputObject` is null or not a `[hashtable]`, returns `$InputObject['error']` (`[string]`) when non-empty, or returns `$InputObject['value']` (`[decimal]`). | +| [`New-IcingaPerformanceCounter`](../../../src/PerformanceCounter/Private/New-IcingaPerformanceCounter.ps1) | `-Counter [array] = @()` | `void` | Registers each non-empty path in `$Store.Registered[$Path] = (Get-Date)`. Also serves as the static AST marker scanned by `Register-IcingaPerformanceCounterFromComponents`. | +| [`New-IcingaPerformanceCounterEnvironment`](../../../src/PerformanceCounter/Private/New-IcingaPerformanceCounterEnvironment.ps1) | *(None)* | `void` | Initializes `$Store.Manager`, loads `PerformanceCounter.json`, discovers component counters from the kernel AST, reconciles and warms the initial counter set in one batch, and stamps `$Store.Heartbeat` and `$Store.LastRefresh`. | +| [`Read-IcingaPerformanceCounterCache`](../../../src/PerformanceCounter/Private/Read-IcingaPerformanceCounterCache.ps1) | *(None)* | `void` | Reads `\PerformanceCounter.json` via `ConvertFrom-Json` and merges all counter paths and parsed timestamps into `$Store.Registered`. | +| [`Register-IcingaDefaultPerformanceCounter`](../../../src/PerformanceCounter/Private/Register-IcingaDefaultPerformanceCounter.ps1) | *(None)* | `void` | Reference declaration calling `New-IcingaPerformanceCounter` with four default paths: `\Processor(_Total)\% Processor Time`, `\Memory\Available Bytes`, `\PhysicalDisk(*)\Disk Reads/sec`, and `\PhysicalDisk(*)\Disk Writes/sec`. | +| [`Register-IcingaPerformanceCounterFromComponents`](../../../src/PerformanceCounter/Private/Register-IcingaPerformanceCounterFromComponents.ps1) | *(None)* | `void` | Parses `lib\IcingaForWindows.Kernel.ps1` into an AST, locates all `CommandAst` invocations of `New-IcingaPerformanceCounter`, extracts literal `-Counter` strings via `Get-IcingaPerformanceCounterLiteral`, and registers them in `$Store.Registered`. | +| [`Start-IcingaPerformanceCounterDaemon`](../../../src/PerformanceCounter/Private/Start-IcingaPerformanceCounterDaemon.ps1) | *(None)* | `void` | Background daemon entry point. Calls `New-IcingaPerformanceCounterEnvironment`, then loops while `Test-ThreadRunning` is `$true`: calls `Set-ThreadProcessing`, waits up to `500 ms` on `$Store.RequestQueue.TryTake`, resolves requests via `$Manager.Resolve`, pushes responses to `$Store.PendingRequests[$Request.RequestId]`, and runs `Update-IcingaPerformanceCounterState -Store $Store`. | +| [`Test-IcingaPerformanceCounterDaemon`](../../../src/PerformanceCounter/Private/Test-IcingaPerformanceCounterDaemon.ps1) | *(None)* | `[bool]` | Returns `$true` if `$Store` and `$Store.Heartbeat` are non-null and `((Get-Date) - $Store.Heartbeat).TotalSeconds -le 5`; otherwise returns `$false`. | +| [`Update-IcingaPerformanceCounterState`](../../../src/PerformanceCounter/Private/Update-IcingaPerformanceCounterState.ps1) | `-Store [object] = $null` | `void` | Updates `$Store.Heartbeat` on every call. Once `$Store.Config.RefreshIntervalMs` has elapsed since `$Store.LastRefresh`, evicts stale entries older than `EvictionMinutes`, calls `$Manager.Reconcile($Registered)` and `$Manager.Sample()`, persists the cache via `Write-IcingaPerformanceCounterCache`, and updates `$Store.LastRefresh`. | +| [`Write-IcingaPerformanceCounterCache`](../../../src/PerformanceCounter/Private/Write-IcingaPerformanceCounterCache.ps1) | *(None)* | `void` | Writes `$Store.Registered` as ISO 8601 (`'o'`) JSON to `\PerformanceCounter.json.tmp` and atomically moves it to `PerformanceCounter.json`. | + +--- + +## 8. Windows PowerShell 5.1 Runspace and Class Isolation Internals + +### The Runspace Affinity Problem in PowerShell 5.1 +In Windows PowerShell 5.1 (`$PSVersionTable.PSEdition -eq 'Desktop'`), two subtle engine behaviors interact when PowerShell classes are used inside background runspaces (`New-Thread`): + +1. **Process-Wide ScriptBlock AST & Type Caching:** When multiple runspaces dot-source the same `.ps1` file or compile identical source text via `[ScriptBlock]::Create($Source)`, PowerShell 5.1 hits its process-wide scriptblock cache and reuses the exact same compiled `.NET` class types across runspaces. Each PowerShell class type holds an internal reference to the `SessionStateInternal` of the runspace that first compiled it (typically the main interactive runspace). +2. **Cross-Runspace Method Marshaling Deadlock:** When the background daemon thread calls a method (such as `Resolve()`, `Reconcile()`, or `ParsePath()`) on a class bound to the main runspace's `SessionStateInternal`, PowerShell attempts to marshal that method call back onto the main runspace thread. If the main thread is simultaneously blocked inside `Get-IcingaPerformanceCounter` waiting on `$ResponseQueue.TryTake([ref]$Response, $TimeoutMs)`, the daemon thread stalls waiting for the main runspace, and `Get-IcingaPerformanceCounter` times out after `5000 ms`. + +### How Icinga for Windows Solves It +1. **Separated Class Library (`lib\IcingaForWindows.Classes.ps1`):** + `Build-ModuleProject` compiles all files under `src\Classes\` into `lib\IcingaForWindows.Classes.ps1` (separate from `lib\IcingaForWindows.Kernel.ps1`, which contains all functions). +2. **Per-Runspace Class Compilation (`IcingaForWindows.psm1`):** + When `IcingaForWindows.psm1` is imported into a runspace on Windows PowerShell 5.1 (`$PSVersionTable.PSEdition -eq 'Desktop'`), it appends a unique GUID comment (`[System.Environment]::NewLine + '# ' + [System.Guid]::NewGuid().ToString()`) to the source of `lib\IcingaForWindows.Classes.ps1` before dot-sourcing `. ([ScriptBlock]::Create(...))`. This bypasses the process-wide scriptblock cache and forces Windows PowerShell 5.1 to emit fresh class types bound to each runspace's own `SessionStateInternal`. +3. **Runtime Type Resolution (`'ClassName' -as [type]`):** + Inside both `src\Classes\Icinga\IcingaPerformanceCounter.ps1` and all functions in `src\PerformanceCounter\`, PowerShell class type literals (`[IcingaPerformanceCounter]`, `[IcingaPerformanceCounterEntry]`, `[IcingaPerformanceCounterCategory]`) are never used in method bodies or property constraints. Instead, types are resolved at runtime via `'IcingaPerformanceCounter' -as [type]`, `'IcingaPerformanceCounterEntry' -as [type]`, and `'IcingaPerformanceCounterCategory' -as [type]`, ensuring every runspace always resolves and invokes its own runspace-local class type. diff --git a/docs/Developer/PerformanceCounter/02-Usability-and-Developer-Guide.md b/docs/Developer/PerformanceCounter/02-Usability-and-Developer-Guide.md new file mode 100644 index 0000000..7312353 --- /dev/null +++ b/docs/Developer/PerformanceCounter/02-Usability-and-Developer-Guide.md @@ -0,0 +1,388 @@ +# Performance Counter Usability and Developer Guide + +This guide explains how to discover, query, pre-declare, and process Windows Performance Counters in Icinga for Windows, both interactively on the command line and inside data providers or check plugins. + +For internal class specifications, daemon architecture, and runspace isolation details, see [`01-Technical-Architecture-and-Reference.md`](01-Technical-Architecture-and-Reference.md). + +--- + +## 1. Quick Start: Interactive Discovery and Inspection + +Icinga for Windows provides four public cmdlets for working with performance counters: + +| Cmdlet | Purpose | +| :--- | :--- | +| `Show-IcingaPerformanceCounter` | Browse available categories, counter paths within a category, or live instances for a wildcard counter. | +| `Test-IcingaPerformanceCounterCategory` | Check whether a performance counter category exists on the local machine without throwing exceptions. | +| `Get-IcingaPerformanceCounter` | Read live values for one or more concrete or wildcard performance counter paths. | +| `Show-IcingaPerformanceCounterDetails` | Inspect live values for all currently registered counters (or a filtered subset). | + +### Step 1: Browse Categories (`Show-IcingaPerformanceCounter`) +List all performance counter categories on the system, or filter them using a wildcard pattern (`-Filter`): + +```powershell +# List all available categories on the machine +Show-IcingaPerformanceCounter + +# Filter categories by wildcard +Show-IcingaPerformanceCounter -Filter '*Disk*' +``` + +Example output: +```text +LogicalDisk +PhysicalDisk +``` + +### Step 2: List Counters Inside a Category (`-Category`) +Pass `-Category` to inspect all counter paths exposed by that category. Multi-instance categories automatically emit wildcard paths (`\Category(*)\Counter`), while single-instance categories emit direct paths (`\Category\Counter`): + +```powershell +# Multi-instance category (emits '\Processor(*)\...') +Show-IcingaPerformanceCounter -Category 'Processor' + +# Single-instance category (emits '\Memory\...') +Show-IcingaPerformanceCounter -Category 'Memory' +``` + +### Step 3: List Live Instances for a Wildcard Path (`-Counter`) +Pass a wildcard path to `-Counter` to see the exact per-instance counter paths that currently exist on the system: + +```powershell +Show-IcingaPerformanceCounter -Counter '\PhysicalDisk(*)\Disk Reads/sec' +``` + +Example output: +```text +\PhysicalDisk(0 C:)\Disk Reads/sec +\PhysicalDisk(_Total)\Disk Reads/sec +``` + +### Step 4: Inspect Registered Counters (`Show-IcingaPerformanceCounterDetails`) +To see the live values of all counters currently registered in the Icinga for Windows store (or a specific subset): + +```powershell +# Dump all registered counters +Show-IcingaPerformanceCounterDetails + +# Dump all registered counters reshaped by instance/category +Show-IcingaPerformanceCounterDetails -StructureByInstance +``` + +--- + +## 2. Supported Counter Path Formats + +`Get-IcingaPerformanceCounter` and `Test-IcingaPerformanceCounterCategory` accept standard Windows Performance Counter paths in the following formats: + +| Format | Example | Description | +| :--- | :--- | :--- | +| **Single-Instance Path** | `\Memory\Available Bytes` | Reads a counter from a category that has no instances. | +| **Concrete Instance Path** | `\Processor(_Total)\% Processor Time` | Reads a specific named instance (`_Total`, `0`, `0 C:`, etc.). | +| **Wildcard Instance Path** | `\Processor(*)\% Processor Time` | Reads all live instances of the category in a single category snapshot. | +| **Local Host Prefixed Path** | `\\.\Memory\Available Bytes`
`\\localhost\Memory\Available Bytes`
`\\127.0.0.1\Memory\Available Bytes`
`\\::1\Memory\Available Bytes`
`\\MY-SERVER\Memory\Available Bytes` | Local machine prefixes (`.`, `localhost`, `127.0.0.1`, `::1`, or `[System.Environment]::MachineName`, case-insensitive) are automatically accepted and normalized internally so they share the same underlying counter handle as machine-less paths. | + +> [!NOTE] +> Remote machine paths (such as `\\other-server\Memory\Available Bytes`) are intentionally rejected (`Valid = $false`) and return `'Counter not initialized'` in the counter result's `error` field. + +--- + +## 3. Understanding Result Shapes + +### 3.1 The Uniform Leaf Value Hashtable +Every individual counter read—whether concrete or expanded from a wildcard, and regardless of whether `-StructureByInstance` is used—produces a uniform **5-key leaf hashtable**: + +| Key | Type | Description | +| :--- | :--- | :--- | +| `value` | `System.Decimal` | The calculated counter value rounded to at most 6 decimal places (`0` if an error occurred). | +| `sample` | `System.Diagnostics.CounterSample` | The raw `.NET` `CounterSample` struct (`RawValue`, `BaseValue`, `TimeStamp`, `CounterType`, etc.), or `$null` on error. | +| `help` | `System.String` | Localized description text (`CounterHelp`) for this counter from the Windows counter library, or `$null` on error. | +| `type` | `System.String` | String name of the `System.Diagnostics.PerformanceCounterType` (for example `'Timer100Ns'`, `'NumberOfItems64'`, `'RateOfCountsPerSecond64'`), or `$null` on error. | +| `error` | `System.String` | `$null` when the read succeeded, or a descriptive error message when the counter/category/instance could not be read. | + +--- + +### 3.2 Default Output Shape (Keyed by Requested Path) +Without `-StructureByInstance`, `Get-IcingaPerformanceCounter` returns a hashtable keyed by the exact path string you requested: + +- **Concrete path** -> maps directly to the 5-key leaf hashtable. +- **Wildcard path (`*`)** -> maps to a nested hashtable keyed by each expanded concrete instance path (`\Category(Instance)\Counter`), where each value is the 5-key leaf hashtable. + +```powershell +$Result = Get-IcingaPerformanceCounter -Counter @( + '\Memory\Available Bytes', + '\Processor(*)\% Processor Time' +); + +# 1. Concrete counter access: +$Result['\Memory\Available Bytes'].value +$Result['\Memory\Available Bytes'].error + +# 2. Wildcard counter access (nested under the wildcard path): +$Result['\Processor(*)\% Processor Time']['\Processor(_Total)\% Processor Time'].value +$Result['\Processor(*)\% Processor Time']['\Processor(0)\% Processor Time'].value +``` + +--- + +### 3.3 Instance-Structured Output (`-StructureByInstance`) +When writing providers or plugins that combine multiple counters (for example reading both `% Processor Time` and `% Idle Time` across all CPU cores, or reading multiple `Memory` counters), `-StructureByInstance` reshapes the output into a clean hierarchy: + +- **Counters WITH an instance** (concrete or wildcard) are grouped **Instance -> Category -> Counter**: + ```powershell + $Result[Instance][Category][Counter] + ``` +- **Counters WITHOUT an instance** (single-instance categories) are grouped **Category -> Counter**: + ```powershell + $Result[Category][Counter] + ``` + +#### Example: Single-Instance Category (`Memory`) with `-StructureByInstance` +```powershell +$Mem = Get-IcingaPerformanceCounter -Counter @( + '\Memory\Available Bytes', + '\Memory\Pages/sec' +) -StructureByInstance; + +# Keyed by: $Mem[Category][Counter] +$AvailableBytes = $Mem['Memory']['Available Bytes'].value; +$PagesPerSec = $Mem['Memory']['Pages/sec'].value; +``` + +#### Example: Multi-Instance Category (`Processor(*)`) with `-StructureByInstance` +```powershell +$Cpu = Get-IcingaPerformanceCounter -Counter @( + '\Processor(*)\% Processor Time', + '\Processor(*)\% User Time' +) -StructureByInstance; + +# Keyed by: $Cpu[Instance][Category][Counter] +$TotalLoad = $Cpu['_Total']['Processor']['% Processor Time'].value; +$Core0Load = $Cpu['0']['Processor']['% Processor Time'].value; +$Core0User = $Cpu['0']['Processor']['% User Time'].value; + +# Iterate over all discovered CPU instances: +foreach ($InstanceName in $Cpu.Keys) { + $Load = $Cpu[$InstanceName]['Processor']['% Processor Time'].value; + Write-Host "Instance ${InstanceName}: ${Load}%"; +} +``` + +> [!IMPORTANT] +> **Avoid chaining `.Values` on multi-counter hashtables!** +> In interactive one-liners you might see `(Get-IcingaPerformanceCounter -Counter '\Memory\Available Bytes' -StructureByInstance).Values.'Available Bytes'.value`. While `.Values` works when only a single category is in the hashtable, `$Mem['Memory']['Available Bytes'].value` is strongly recommended in scripts and providers because it explicitly addresses the category key and never breaks when additional categories or instances are present. + +--- + +## 4. Pre-Declaring Counters for Zero-Latency Reads + +### Why Pre-Declare Counters? +Windows rate counters (such as `\Processor(_Total)\% Processor Time` or `\PhysicalDisk(*)\Disk Reads/sec`) compute rates between two consecutive samples separated by `WarmupMilliseconds` (`250 ms`). + +If a counter is requested for the very first time during a check execution, the first call has to prime the counter and sleep `250 ms`. By declaring your component's counters via `New-IcingaPerformanceCounter`, Icinga for Windows automatically discovers them at startup by parsing the AST of `lib\IcingaForWindows.Kernel.ps1` and warms all of them in a single shared batch when the daemon starts. + +### How to Declare Counters (`New-IcingaPerformanceCounter`) +Create a registration function in your provider or component (or call `New-IcingaPerformanceCounter` inside your provider initialization) passing a **literal array of strings** to `-Counter`: + +```powershell +function Register-IcingaProviderCpuPerformanceCounter() +{ + New-IcingaPerformanceCounter -Counter @( + '\Processor(*)\% Processor Time', + '\Processor(*)\% Interrupt Time', + '\Processor(*)\% Privileged Time', + '\Processor(*)\% User Time' + ); +} +``` + +### Static AST Discovery Rules (Dos and Don'ts) +During `New-IcingaPerformanceCounterEnvironment`, `Register-IcingaPerformanceCounterFromComponents` parses `lib\IcingaForWindows.Kernel.ps1` using the PowerShell language parser **without executing any functions**. It looks for `New-IcingaPerformanceCounter` command ASTs and extracts every `StringConstantExpressionAst` inside the `-Counter` argument. + +```powershell +# GOOD: Literal string array attached to -Counter (discovered statically at startup) +New-IcingaPerformanceCounter -Counter @( + '\Memory\Available Bytes', + '\Memory\Committed Bytes' +); + +# GOOD: Single literal string (discovered statically at startup) +New-IcingaPerformanceCounter -Counter '\System\Processor Queue Length'; + +# NOT DISCOVERED AT STARTUP: Variables or dynamic expressions +# (Will still register at runtime when the function executes, but cannot be extracted statically by the AST scanner) +$MyCounters = @('\Memory\Available Bytes'); +New-IcingaPerformanceCounter -Counter $MyCounters; +``` + +> [!TIP] +> After adding or modifying `New-IcingaPerformanceCounter` calls in `src\`, run `Build-ModuleProject` (or `build\Build-ModuleProject.ps1`) to regenerate `lib\IcingaForWindows.Kernel.ps1` so the static AST scanner sees your changes. + +--- + +## 5. Safe Value Extraction and Error Handling + +### 5.1 Checking Category Existence (`Test-IcingaPerformanceCounterCategory`) +Before querying counters that belong to optional Windows Server roles, features, or third-party applications (such as Hyper-V, IIS, Exchange, or SQL Server), use `Test-IcingaPerformanceCounterCategory` to verify that the category is installed on the host: + +```powershell +# Pass a plain category name: +if (-not (Test-IcingaPerformanceCounterCategory -Category 'Hyper-V Virtual Machine Health Summary')) { + # Role is not installed or category is unavailable + return; +} + +# Or pass a full counter path directly (local host prefixes and wildcards are supported): +if (Test-IcingaPerformanceCounterCategory -Category '\Processor(*)\% Processor Time') { + # Category 'Processor' exists +} +``` + +### 5.2 Extracting Values vs. Errors (`Get-IcingaPerformanceCounterValue`) +When a counter read fails (for example because a counter name is misspelled or an instance disappeared), the leaf hashtable always has `value = 0` and a non-empty `error` string. + +If you only read `.value` without checking `.error`, a broken or missing counter can silently look like a `0` measurement! + +Use the private helper `Get-IcingaPerformanceCounterValue` (or check `.error` explicitly) to ensure errors are never masked by a default `0`: + +- If `error` is non-empty, `Get-IcingaPerformanceCounterValue` returns the **error message (`[string]`)**. +- If `error` is `$null` or empty, `Get-IcingaPerformanceCounterValue` returns the **numeric value (`[decimal]`)**. +- If `$InputObject` is `$null` or not a `[hashtable]`, it returns `$null`. + +```powershell +$Counters = Get-IcingaPerformanceCounter -Counter '\Memory\Available Bytes' -StructureByInstance; +$Leaf = $Counters['Memory']['Available Bytes']; + +$ValueOrError = Get-IcingaPerformanceCounterValue -InputObject $Leaf; + +if ($null -eq $ValueOrError) { + Write-Warning 'Counter request timed out or returned no data.'; +} elseif ($ValueOrError -is [string]) { + Write-Warning "Failed to read counter: $ValueOrError"; +} else { + # $ValueOrError is a [decimal] ready for threshold comparison + Write-Host "Available Memory: $ValueOrError bytes"; +} +``` + +--- + +## 6. Practical Provider and Plugin Recipes + +### Recipe 1: Reading Single-Instance Counters (Memory Provider Pattern) +```powershell +function Get-MyMemoryMetrics() +{ + [array]$CounterPaths = @( + '\Memory\Available Bytes', + '\Memory\Committed Bytes', + '\Memory\Pages/sec' + ); + + $Data = Get-IcingaPerformanceCounter -Counter $CounterPaths -StructureByInstance; + + if ($null -eq $Data -or -not $Data.ContainsKey('Memory')) { + return @{ + 'Error' = 'Failed to query Memory performance counters.'; + }; + } + + $Memory = $Data['Memory']; + $Result = @{ }; + + foreach ($CounterName in $Memory.Keys) { + $Extracted = Get-IcingaPerformanceCounterValue -InputObject $Memory[$CounterName]; + + if ($Extracted -is [string]) { + Write-LoggingEntry -Message 'Memory counter read error' -Level 'Warning' -Data @{ + 'Counter' = $CounterName; + 'Error' = $Extracted; + }; + $Result[$CounterName] = $null; + } else { + $Result[$CounterName] = $Extracted; + } + } + + return $Result; +} +``` + +### Recipe 2: Reading Multi-Instance Wildcard Counters (Per-Core CPU or Disk Metrics) +```powershell +function Get-MyDiskThroughput() +{ + [array]$CounterPaths = @( + '\PhysicalDisk(*)\Disk Reads/sec', + '\PhysicalDisk(*)\Disk Writes/sec' + ); + + $Data = Get-IcingaPerformanceCounter -Counter $CounterPaths -StructureByInstance; + [hashtable]$Disks = @{ }; + + if ($null -eq $Data) { + return $Disks; + } + + foreach ($Instance in $Data.Keys) { + if (-not $Data[$Instance].ContainsKey('PhysicalDisk')) { + continue; + } + + $DiskCategory = $Data[$Instance]['PhysicalDisk']; + $ReadsPerSec = Get-IcingaPerformanceCounterValue -InputObject $DiskCategory['Disk Reads/sec']; + $WritesPerSec = Get-IcingaPerformanceCounterValue -InputObject $DiskCategory['Disk Writes/sec']; + + $Disks[$Instance] = @{ + 'ReadsPerSec' = $ReadsPerSec; + 'WritesPerSec' = $WritesPerSec; + }; + } + + return $Disks; +} +``` + +### Recipe 3: Guarding Optional Role Counters (`Test-IcingaPerformanceCounterCategory`) +```powershell +function Get-MyHyperVHealth() +{ + [string]$CategoryName = 'Hyper-V Virtual Machine Health Summary'; + + if (-not (Test-IcingaPerformanceCounterCategory -Category $CategoryName)) { + return @{ + 'Supported' = $false; + 'Reason' = ('Performance counter category "{0}" is not installed on this system.' -f $CategoryName); + }; + } + + $Data = Get-IcingaPerformanceCounter -Counter @( + '\Hyper-V Virtual Machine Health Summary\Health Ok', + '\Hyper-V Virtual Machine Health Summary\Health Critical' + ) -StructureByInstance; + + return @{ + 'Supported' = $true; + 'HealthOk' = Get-IcingaPerformanceCounterValue -InputObject $Data[$CategoryName]['Health Ok']; + 'HealthCritical' = Get-IcingaPerformanceCounterValue -InputObject $Data[$CategoryName]['Health Critical']; + }; +} +``` + +--- + +## 7. Troubleshooting and FAQ + +### Q1: Why does `Get-IcingaPerformanceCounter` return `value = 0` when I type an invalid counter name? +To guarantee a predictable schema for plugins, every counter leaf always contains the five keys `value`, `sample`, `help`, `type`, and `error`, with `value` initialized to `[decimal]0`. When a category, counter, or instance does not exist, the OS exception is captured into the `error` key rather than throwing a terminating exception that would abort an entire batch of counters. Always inspect `.error` or use `Get-IcingaPerformanceCounterValue`. + +### Q2: Do I need the background daemon running to use `Get-IcingaPerformanceCounter`? +No. +- When the daemon is running (`Use-IcingaForWindows -RunBackgroundDaemons`), requests are served with zero warm-up sleep by the background daemon thread. +- When the daemon is **not** running (`Use-IcingaForWindows -NoNewShell` without `-RunBackgroundDaemons`), `Get-IcingaPerformanceCounter` automatically falls back to a persistent per-runspace manager (`$script:IcingaPerformanceCounterInlineManager`). The first call for a new counter sleeps `250 ms` (`WarmupMilliseconds`), and all subsequent calls in that shell session reuse the warm handles immediately. + +### Q3: How long are unused counters kept in memory and in `PerformanceCounter.json`? +By default, any counter path that has not been requested via `Get-IcingaPerformanceCounter` or refreshed via `New-IcingaPerformanceCounter` for **60 minutes** (`$Store.Config.EvictionMinutes = 60`) is automatically evicted during the daemon's periodic maintenance pass (`Update-IcingaPerformanceCounterState`), its `.NET` handle is disposed, and `PerformanceCounter.json` is atomically rewritten without the stale entry. + +### Q4: How are short-lived or renumbered process instances (`svchost#1`, `svchost#2`) handled in wildcard queries? +When querying `\Process(*)\% Processor Time`, Windows names duplicate process instances `name#1`, `name#2`, etc. If `svchost#1` exits, Windows shifts `svchost#2` into `svchost#1`. `IcingaPerformanceCounterCategory.FindPrevious` automatically compares the `'ID Process'` raw value between the `Previous` and `Current` category snapshots whenever `'ID Process'` is present in the category. If the process ID changed between snapshots, the previous sample is discarded for that instance so a rate is never calculated across two unrelated processes. diff --git a/docs/Icinga.PerformanceCounter.md b/docs/Icinga.PerformanceCounter.md index 0d51885..f78559b 100644 --- a/docs/Icinga.PerformanceCounter.md +++ b/docs/Icinga.PerformanceCounter.md @@ -7,6 +7,7 @@ - [Get-IcingaPerformanceCounter](#get-icingaperformancecounter) - [Show-IcingaPerformanceCounter](#show-icingaperformancecounter) - [Show-IcingaPerformanceCounterDetails](#show-icingaperformancecounterdetails) +- [Test-IcingaPerformanceCounterCategory](#test-icingaperformancecountercategory) ## Private helpers @@ -33,78 +34,78 @@ #### Description -`Get-IcingaPerformanceCounter` returns the current values of the requested counter paths. By default -the result is a hashtable keyed by the requested path: a concrete path maps to a flat result -hashtable with the keys value, sample, help, type and error; a wildcard path (instance '*') maps to a -nested hashtable keyed by each live instance path. - -With `-StructureByInstance` the result is reshaped for easier plugin consumption: counters with an -instance are keyed instance-first (`$out[Instance][Category][Counter]`), counters without an instance -are keyed category-first (`$out[Category][Counter]`), and the leaf is always the uniform value -hashtable. - -When the performance-counter daemon is running the read is dispatched through a request/pull queue: -the function generates a request id, registers a single-slot response queue, enqueues the request and -blocks on the response for up to the given timeout. All counter access happens on the daemon thread, -so there are no races on the underlying counter handles. When no daemon is running the function uses a -persistent per-runspace manager kept in module scope, so repeated reads stay warm and only the first -read of a new counter pays the warm-up sleep. - -Requesting a counter also refreshes its last-seen timestamp in the registry, keeping actively used +`Get-IcingaPerformanceCounter` returns the current values of the requested counter paths. By default +the result is a hashtable keyed by the requested path: a concrete path maps to a flat result +hashtable with the keys value, sample, help, type and error; a wildcard path (instance '*') maps to a +nested hashtable keyed by each live instance path. + +With `-StructureByInstance` the result is reshaped for easier plugin consumption: counters with an +instance are keyed instance-first (`$out[Instance][Category][Counter]`), counters without an instance +are keyed category-first (`$out[Category][Counter]`), and the leaf is always the uniform value +hashtable. + +When the performance-counter daemon is running the read is dispatched through a request/pull queue: +the function generates a request id, registers a single-slot response queue, enqueues the request and +blocks on the response for up to the given timeout. All counter access happens on the daemon thread, +so there are no races on the underlying counter handles. When no daemon is running the function uses a +persistent per-runspace manager kept in module scope, so repeated reads stay warm and only the first +read of a new counter pays the warm-up sleep. + +Requesting a counter also refreshes its last-seen timestamp in the registry, keeping actively used counters warm and out of the eviction path. #### Parameters **`$Counter`** -| Name | Type | Description | Default | -|---------|--------------|----------------------------------------------------------------|---------| -| Counter | System.Array | One or more counter paths to read, e.g. '\Processor(*)\...'. | @() | +| Name | Type | Description | Default | +|---------|--------------|--------------------------------------------------------------|---------| +| Counter | System.Array | One or more counter paths to read, e.g. '\Processor(*)\...'. | @() | **`$TimeoutMs`** -| Name | Type | Description | Default | -|-----------|--------------|-------------------------------------------------------------|---------| -| TimeoutMs | System.Int32 | Milliseconds to wait for the daemon response before giving up.| 5000 | +| Name | Type | Description | Default | +|-----------|--------------|----------------------------------------------------------------|---------| +| TimeoutMs | System.Int32 | Milliseconds to wait for the daemon response before giving up. | 5000 | **`$StructureByInstance`** -| Name | Type | Description | Default | -|---------------------|----------------------------------------------|--------------------------------------------------------------------------|---------| -| StructureByInstance | System.Management.Automation.SwitchParameter | Reshape the result to instance/category/counter (category/counter when no instance). | $false | +| Name | Type | Description | Default | +|---------------------|----------------------------------------------|--------------------------------------------------------------------------------------|---------| +| StructureByInstance | System.Management.Automation.SwitchParameter | Reshape the result to instance/category/counter (category/counter when no instance). | $false | #### Outputs -System.Collections.Hashtable — By default keyed by requested path (flat for concrete paths, nested for -wildcard paths). With `-StructureByInstance`, keyed by instance then category then counter, or by -category then counter for counters without an instance. Returns an empty hashtable when no counter is +System.Collections.Hashtable -- By default keyed by requested path (flat for concrete paths, nested for +wildcard paths). With `-StructureByInstance`, keyed by instance then category then counter, or by +category then counter for counters without an instance. Returns an empty hashtable when no counter is requested, or $null when the daemon request times out. #### Examples ```powershell -PS> Get-IcingaPerformanceCounter -Counter '\Processor(_Total)\% Processor Time' - +PS> Get-IcingaPerformanceCounter -Counter '\Processor(_Total)\% Processor Time' + Reads a single counter and returns its value hashtable. ``` ```powershell -PS> $cpu = Get-IcingaPerformanceCounter -Counter '\Processor(*)\% Processor Time' -StructureByInstance -PS> $cpu.'0'.'Processor'.'% Processor Time'.value - +PS> $cpu = Get-IcingaPerformanceCounter -Counter '\Processor(*)\% Processor Time' -StructureByInstance +PS> $cpu.'0'.'Processor'.'% Processor Time'.value + Reads every processor instance and addresses one core by instance, category and counter name. ``` ```powershell -PS> $mem = Get-IcingaPerformanceCounter -Counter '\Memory\Pages/sec' -StructureByInstance -PS> $mem.'Memory'.'Pages/sec'.value - +PS> $mem = Get-IcingaPerformanceCounter -Counter '\Memory\Pages/sec' -StructureByInstance +PS> $mem.'Memory'.'Pages/sec'.value + A counter without an instance is keyed category-first. ``` #### Notes -The request/response transport lives under `(Get-GlobalRuntimeVariable).Public.PerformanceCounter`. +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)* @@ -119,65 +120,65 @@ Timeouts are logged through `Write-LoggingEntry` at Warning level. No external s #### Description -`Show-IcingaPerformanceCounter` is a stateless introspection helper that queries Windows -performance counter metadata directly. It has three modes selected by the parameters passed: - -- With no arguments it lists all counter categories, optionally filtered by `-Filter` using - wildcard matching. -- With `-Category` it lists the counter paths inside that category, emitting '\Category(*)\Counter' - for multi-instance categories and '\Category\Counter' for single-instance categories. -- With `-Counter` (a wildcard path) it lists the concrete counter paths for every live instance. - -Because it only reads metadata it is safe to call from any thread and does not require the +`Show-IcingaPerformanceCounter` is a stateless introspection helper that queries Windows +performance counter metadata directly. It has three modes selected by the parameters passed: + +- With no arguments it lists all counter categories, optionally filtered by `-Filter` using + wildcard matching. +- With `-Category` it lists the counter paths inside that category, emitting '\Category(*)\Counter' + for multi-instance categories and '\Category\Counter' for single-instance categories. +- With `-Counter` (a wildcard path) it lists the concrete counter paths for every live instance. + +Because it only reads metadata it is safe to call from any thread and does not require the daemon. Errors are logged and yield an empty result rather than throwing. #### Parameters **`$Category`** -| Name | Type | Description | Default | -|----------|---------------|----------------------------------------------------------|---------| -| Category | System.String | List the counters within this category. | $null | +| Name | Type | Description | Default | +|----------|---------------|-----------------------------------------|---------| +| Category | System.String | List the counters within this category. | $null | **`$Counter`** -| Name | Type | Description | Default | -|---------|---------------|-----------------------------------------------------------------|---------| -| Counter | System.String | Wildcard counter path whose live instances should be listed. | $null | +| Name | Type | Description | Default | +|---------|---------------|--------------------------------------------------------------|---------| +| Counter | System.String | Wildcard counter path whose live instances should be listed. | $null | **`$Filter`** -| Name | Type | Description | Default | -|--------|---------------|------------------------------------------------------------|---------| -| Filter | System.String | Wildcard filter applied when listing categories. | $null | +| Name | Type | Description | Default | +|--------|---------------|--------------------------------------------------|---------| +| Filter | System.String | Wildcard filter applied when listing categories. | $null | #### Outputs -System.Array — Category names, counter paths, or instance paths depending on the mode. +System.Array -- Category names, counter paths, or instance paths depending on the mode. #### Examples ```powershell -PS> Show-IcingaPerformanceCounter - +PS> Show-IcingaPerformanceCounter + Lists all performance counter categories. ``` ```powershell -PS> Show-IcingaPerformanceCounter -Category 'Processor' - +PS> Show-IcingaPerformanceCounter -Category 'Processor' + Lists the counter paths available in the Processor category. ``` ```powershell -PS> Show-IcingaPerformanceCounter -Counter '\PhysicalDisk(*)\Disk Reads/sec' - +PS> Show-IcingaPerformanceCounter -Counter '\PhysicalDisk(*)\Disk Reads/sec' + Lists the concrete per-instance paths that currently exist for the wildcard counter. ``` #### Notes -Uses `System.Diagnostics.PerformanceCounterCategory` directly. No global state is read or +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)* @@ -192,55 +193,105 @@ written, and no external services are used. #### Description -`Show-IcingaPerformanceCounterDetails` returns the current values of performance counters -through `Get-IcingaPerformanceCounter`. Called without arguments it dumps every counter -currently registered in the global store. Passing `-Counter` narrows the output to the given -paths. The result keeps the uniform shape: a hashtable keyed by counter path with flat value +`Show-IcingaPerformanceCounterDetails` returns the current values of performance counters +through `Get-IcingaPerformanceCounter`. Called without arguments it dumps every counter +currently registered in the global store. Passing `-Counter` narrows the output to the given +paths. The result keeps the uniform shape: a hashtable keyed by counter path with flat value hashtables for concrete paths and nested hashtables for wildcard paths. #### Parameters **`$Counter`** -| Name | Type | Description | Default | -|---------|--------------|--------------------------------------------------------------------|---------| -| Counter | System.Array | Counter paths to show. Empty shows all registered counters. | @() | +| Name | Type | Description | Default | +|---------|--------------|-------------------------------------------------------------|---------| +| Counter | System.Array | Counter paths to show. Empty shows all registered counters. | @() | **`$StructureByInstance`** -| Name | Type | Description | Default | -|---------------------|----------------------------------------------|--------------------------------------------------------------------------|---------| -| StructureByInstance | System.Management.Automation.SwitchParameter | Reshape the result to instance/category/counter, forwarded to Get-IcingaPerformanceCounter. | $false | +| Name | Type | Description | Default | +|---------------------|----------------------------------------------|---------------------------------------------------------------------------------------------|---------| +| StructureByInstance | System.Management.Automation.SwitchParameter | Reshape the result to instance/category/counter, forwarded to Get-IcingaPerformanceCounter. | $false | #### Outputs -System.Collections.Hashtable — Keyed by counter path; values as returned by -`Get-IcingaPerformanceCounter`. With `-StructureByInstance`, keyed by instance/category/counter. +System.Collections.Hashtable -- Keyed by counter path; values as returned by +`Get-IcingaPerformanceCounter`. With `-StructureByInstance`, keyed by instance/category/counter. Empty when nothing is registered and nothing is requested. #### Examples ```powershell -PS> Show-IcingaPerformanceCounterDetails - +PS> Show-IcingaPerformanceCounterDetails + Shows live values for every registered counter. ``` ```powershell -PS> Show-IcingaPerformanceCounterDetails -Counter '\Processor(_Total)\% Processor Time' - +PS> Show-IcingaPerformanceCounterDetails -Counter '\Processor(_Total)\% Processor Time' + Shows the live value for a single specified counter. ``` #### Notes -This is a thin convenience layer over `Get-IcingaPerformanceCounter`; the same daemon/inline +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)* --- +### Test-IcingaPerformanceCounterCategory + +*Public function* + +**Synopsis:** Check whether a Windows performance counter category exists on the local system + +#### Description + +`Test-IcingaPerformanceCounterCategory` checks whether the given performance counter category +is present and accessible on the local system. It accepts either a plain category name +(such as 'Processor' or 'Memory') or a full counter path (such as +'\Processor(*)\% Processor Time' or '\\.\Processor(_Total)\% Processor Time'). + +Because it only queries category metadata and never throws, it is safe to call from any +thread or provider before reading optional role counters (such as Hyper-V, IIS or MSSQL). + +#### Parameters + +**`$Category`** + +| Name | Type | Description | Default | +|----------|---------------|-----------------------------------------------------------|---------| +| Category | System.String | The category name or counter path to check for existence. | | + +#### Outputs + +System.Boolean -- $true when the category exists and is accessible on this system; $false otherwise. + +#### Examples + +```powershell +PS> Test-IcingaPerformanceCounterCategory -Category 'Processor' + +Returns $true when the 'Processor' performance counter category exists on the system. +``` + +```powershell +PS> Test-IcingaPerformanceCounterCategory -Category '\Hyper-V Virtual Machine Health Summary(*)\Health Critical' + +Extracts the category name from the counter path and returns $true when the category exists. +``` + +#### Notes + +Delegates to `IcingaPerformanceCounter::CategoryExists`. Never throws and reads no global state. + +*Source: [src/PerformanceCounter/Public/Test-IcingaPerformanceCounterCategory.ps1](../../src/PerformanceCounter/Public/Test-IcingaPerformanceCounterCategory.ps1)* + +--- + ### ConvertTo-IcingaPerformanceCounterInstanceStructure *Private function* @@ -249,37 +300,37 @@ behavior and return shape apply. No external services are used. #### Description -`ConvertTo-IcingaPerformanceCounterInstanceStructure` transforms the default result of -`Get-IcingaPerformanceCounter` (a hashtable keyed by the requested counter path) into a nested -structure that is easier to consume when writing plugins. - -Counters that carry an instance are keyed instance-first, then category, then counter name: -`$out[Instance][Category][Counter]`. Counters without an instance are keyed category-first, then -counter name: `$out[Category][Counter]`. In both cases the leaf is the uniform value hashtable -(`value`, `sample`, `help`, `type`, `error`), so `$out['0']['Processor']['% Processor Time'].value` -and `$out['Memory']['Pages/sec'].value` both work. Wildcard requests are expanded so each live -instance becomes its own top-level key (for example CPU cores `0`, `1`, `_Total`). - -The requested paths are re-parsed to decide the shape, so the transform never has to guess whether a +`ConvertTo-IcingaPerformanceCounterInstanceStructure` transforms the default result of +`Get-IcingaPerformanceCounter` (a hashtable keyed by the requested counter path) into a nested +structure that is easier to consume when writing plugins. + +Counters that carry an instance are keyed instance-first, then category, then counter name: +`$out[Instance][Category][Counter]`. Counters without an instance are keyed category-first, then +counter name: `$out[Category][Counter]`. In both cases the leaf is the uniform value hashtable +(`value`, `sample`, `help`, `type`, `error`), so `$out['0']['Processor']['% Processor Time'].value` +and `$out['Memory']['Pages/sec'].value` both work. Wildcard requests are expanded so each live +instance becomes its own top-level key (for example CPU cores `0`, `1`, `_Total`). + +The requested paths are re-parsed to decide the shape, so the transform never has to guess whether a nested value is a value hashtable or an instance group. #### Parameters **`$Result`** -| Name | Type | Description | Default | -|--------|-----------------------------|------------------------------------------------------------|---------| -| Result | System.Collections.Hashtable| The result returned by the manager, keyed by requested path.| @{ } | +| Name | Type | Description | Default | +|--------|------------------------------|--------------------------------------------------------------|---------| +| Result | System.Collections.Hashtable | The result returned by the manager, keyed by requested path. | @{ } | **`$Counter`** -| Name | Type | Description | Default | -|---------|--------------|---------------------------------------------------------|---------| -| Counter | System.Array | The originally requested counter paths, used to drive the reshape. | @() | +| Name | Type | Description | Default | +|---------|--------------|--------------------------------------------------------------------|---------| +| Counter | System.Array | The originally requested counter paths, used to drive the reshape. | @() | #### Outputs -System.Collections.Hashtable — Nested structure keyed by instance/category or category, with the +System.Collections.Hashtable -- Nested structure keyed by instance/category or category, with the uniform value hashtable at the leaf. #### Examples @@ -290,7 +341,7 @@ PS> ConvertTo-IcingaPerformanceCounterInstanceStructure -Result $raw -Counter '\ #### Notes -Called by `Get-IcingaPerformanceCounter` when `-StructureByInstance` is set. Pure transform; touches +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)* @@ -305,24 +356,24 @@ no global state and reads no counters. #### Description -`Get-IcingaPerformanceCounterLiteral` walks an argument's abstract syntax tree and -collects the value of every string constant it contains. It is used by the startup -discovery step to read the literal counter list passed to a `New-IcingaPerformanceCounter` -call without executing any component code. Non-literal arguments (variables, expressions) -contribute no values, which is intentional — only statically declarable counters are +`Get-IcingaPerformanceCounterLiteral` walks an argument's abstract syntax tree and +collects the value of every string constant it contains. It is used by the startup +discovery step to read the literal counter list passed to a `New-IcingaPerformanceCounter` +call without executing any component code. Non-literal arguments (variables, expressions) +contribute no values, which is intentional -- only statically declarable counters are discovered. #### Parameters **`$Argument`** -| Name | Type | Description | Default | -|----------|---------------------------------------------|---------------------------------------------|---------| -| Argument | System.Management.Automation.Language.Ast | The AST node of the `-Counter` argument. | $null | +| Name | Type | Description | Default | +|----------|-------------------------------------------|------------------------------------------|---------| +| Argument | System.Management.Automation.Language.Ast | The AST node of the `-Counter` argument. | $null | #### Outputs -System.Array — The literal string values found in the argument, or an empty array. +System.Array -- The literal string values found in the argument, or an empty array. #### Examples @@ -332,7 +383,7 @@ PS> Get-IcingaPerformanceCounterLiteral -Argument $argumentAst #### Notes -Called by `Register-IcingaPerformanceCounterFromComponents`. Returns an empty array when +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)* @@ -347,40 +398,40 @@ the argument is null or contains no string literals. #### Description -`Get-IcingaPerformanceCounterValue` extracts the usable result from a single performance counter value -object (the leaf hashtable produced by `Get-IcingaPerformanceCounter`, containing the keys value, -sample, help, type and error). If the counter reported an error the error message is returned; -otherwise the numeric value is returned. This lets a plugin drill down to a single counter and get -back either a number to threshold against or the error text to surface, in one call. - -Because the value is always numeric and the error is always a string, callers can tell the two apart +`Get-IcingaPerformanceCounterValue` extracts the usable result from a single performance counter value +object (the leaf hashtable produced by `Get-IcingaPerformanceCounter`, containing the keys value, +sample, help, type and error). If the counter reported an error the error message is returned; +otherwise the numeric value is returned. This lets a plugin drill down to a single counter and get +back either a number to threshold against or the error text to surface, in one call. + +Because the value is always numeric and the error is always a string, callers can tell the two apart with a simple type check (`$result -is [string]` means an error was returned). #### Parameters **`$InputObject`** -| Name | Type | Description | Default | -|-------------|---------------|----------------------------------------------------------------------|---------| +| Name | Type | Description | Default | +|-------------|---------------|-----------------------------------------------------------------------|---------| | InputObject | System.Object | A single counter value object (the leaf hashtable of a counter read). | $null | #### Outputs -System.Object — The counter value (typically System.Decimal), or the error message (System.String) +System.Object -- The counter value (typically System.Decimal), or the error message (System.String) when the counter reported one. Returns $null when the input is not a counter value object. #### Examples ```powershell -PS> $data = Get-IcingaPerformanceCounter -Counter '\Processor(*)\% Processor Time' -StructureByInstance -PS> Get-IcingaPerformanceCounterValue -InputObject $data.'0'.'Processor'.'% Processor Time' - +PS> $data = Get-IcingaPerformanceCounter -Counter '\Processor(*)\% Processor Time' -StructureByInstance +PS> Get-IcingaPerformanceCounterValue -InputObject $data.'0'.'Processor'.'% Processor Time' + Returns the processor load of core 0, or the error text if that counter could not be read. ``` #### Notes -Pure helper; reads no global state and touches no counters. Intended for use by plugins after they +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)* @@ -395,41 +446,41 @@ have selected a single counter from a `Get-IcingaPerformanceCounter` result. #### Description -`New-IcingaPerformanceCounter` registers the given counter paths in the global -performance-counter store so the background daemon initializes, warms and keeps them -available. Calling it refreshes each counter's last-seen timestamp, which both prevents -eviction of actively-used counters and drives the self-maintaining cache file. - -Components declare the counters they need by calling this function with a literal list. -At module start the discovery step statically scans the compiled kernel for these calls -and seeds the registry from the extracted counter paths, so a declared counter is warm -before it is ever requested. The function only writes to the thread-safe registry +`New-IcingaPerformanceCounter` registers the given counter paths in the global +performance-counter store so the background daemon initializes, warms and keeps them +available. Calling it refreshes each counter's last-seen timestamp, which both prevents +eviction of actively-used counters and drives the self-maintaining cache file. + +Components declare the counters they need by calling this function with a literal list. +At module start the discovery step statically scans the compiled kernel for these calls +and seeds the registry from the extracted counter paths, so a declared counter is warm +before it is ever requested. The function only writes to the thread-safe registry dictionary, so it is safe to call from any thread. #### Parameters **`$Counter`** -| Name | Type | Description | Default | -|---------|---------------|---------------------------------------------------------|---------| -| Counter | System.Array | One or more counter paths to register, e.g. '\Cat\Ctr'. | @() | +| Name | Type | Description | Default | +|---------|--------------|---------------------------------------------------------|---------| +| Counter | System.Array | One or more counter paths to register, e.g. '\Cat\Ctr'. | @() | #### Outputs -None — Registers the counter paths in the global store. +None -- Registers the counter paths in the global store. #### Examples ```powershell -PS> New-IcingaPerformanceCounter -Counter @('\Processor(*)\% Processor Time', '\Memory\Available Bytes') - +PS> New-IcingaPerformanceCounter -Counter @('\Processor(*)\% Processor Time', '\Memory\Available Bytes') + Declares two counters so the daemon keeps them warm and the discovery step can find them. ``` #### Notes -The counters are stored under `(Get-GlobalRuntimeVariable).Public.PerformanceCounter.Registered`. -This function does not return counter values — use `Get-IcingaPerformanceCounter` to read them. +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)* @@ -443,19 +494,19 @@ This function does not return counter values — use `Get-IcingaPerformanceCount #### Description -`New-IcingaPerformanceCounterEnvironment` prepares the performance-counter subsystem for -the daemon. It creates the central manager instance the first time it runs (the class type -is available because the kernel has been dot-sourced by then), loads the persisted cache, -runs component discovery to register statically declared counters, and reconciles the -manager so every registered counter is warmed in a single batch. It also stamps the initial -heartbeat and refresh timestamps. - -This function is expected to run inside the performance-counter daemon runspace, before the +`New-IcingaPerformanceCounterEnvironment` prepares the performance-counter subsystem for +the daemon. It creates the central manager instance the first time it runs (the class type +is available because the kernel has been dot-sourced by then), loads the persisted cache, +runs component discovery to register statically declared counters, and reconciles the +manager so every registered counter is warmed in a single batch. It also stamps the initial +heartbeat and refresh timestamps. + +This function is expected to run inside the performance-counter daemon runspace, before the daemon enters its processing loop, so the manager is created and used on a single thread. #### Outputs -None — Populates `(Get-GlobalRuntimeVariable).Public.PerformanceCounter`. +None -- Populates `(Get-GlobalRuntimeVariable).Public.PerformanceCounter`. #### Examples @@ -465,7 +516,7 @@ PS> New-IcingaPerformanceCounterEnvironment #### Notes -All shared state is read through `Get-GlobalRuntimeVariable`. The manager is stored on the +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)* @@ -480,15 +531,15 @@ All shared state is read through `Get-GlobalRuntimeVariable`. The manager is sto #### Description -`Read-IcingaPerformanceCounterCache` reads the persisted counter cache written by -`Write-IcingaPerformanceCounterCache` and merges its entries into the global registry. -It runs during performance-counter environment initialization so counters learned in -previous runs are warmed immediately at startup. A missing, empty or corrupt cache file +`Read-IcingaPerformanceCounterCache` reads the persisted counter cache written by +`Write-IcingaPerformanceCounterCache` and merges its entries into the global registry. +It runs during performance-counter environment initialization so counters learned in +previous runs are warmed immediately at startup. A missing, empty or corrupt cache file is ignored silently so a bad cache never blocks the daemon. #### Outputs -None — Populates `(Get-GlobalRuntimeVariable).Public.PerformanceCounter.Registered`. +None -- Populates `(Get-GlobalRuntimeVariable).Public.PerformanceCounter.Registered`. #### Examples @@ -498,8 +549,8 @@ PS> Read-IcingaPerformanceCounterCache #### Notes -`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 +`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. *Source: [src/PerformanceCounter/Private/Read-IcingaPerformanceCounterCache.ps1](../../src/PerformanceCounter/Private/Read-IcingaPerformanceCounterCache.ps1)* @@ -514,15 +565,15 @@ PowerShell 7 (the `-AsHashtable` switch is deliberately not used because it is P #### Description -`Register-IcingaDefaultPerformanceCounter` declares a small, broadly-available set of -performance counters (processor, memory and physical disk) by calling -`New-IcingaPerformanceCounter`. It serves as the reference example of how a component -declares the counters it needs and gives the startup discovery step and the warm-up path a +`Register-IcingaDefaultPerformanceCounter` declares a small, broadly-available set of +performance counters (processor, memory and physical disk) by calling +`New-IcingaPerformanceCounter`. It serves as the reference example of how a component +declares the counters it needs and gives the startup discovery step and the warm-up path a concrete set to work with. Additional components declare their own counters the same way. #### Outputs -None — Registers the default counter paths in the global store. +None -- Registers the default counter paths in the global store. #### Examples @@ -532,7 +583,7 @@ PS> Register-IcingaDefaultPerformanceCounter #### Notes -The literal counter list here is what the discovery step reads from the compiled kernel. The +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)* @@ -547,18 +598,18 @@ set is intentionally minimal and generic; it is an example, not a fixed contract #### Description -`Register-IcingaPerformanceCounterFromComponents` parses the compiled module kernel -(`lib\IcingaForWindows.Kernel.ps1`, which contains every source file concatenated) and -finds all calls to `New-IcingaPerformanceCounter`. For each call it extracts the literal -counter paths passed to the `-Counter` parameter and registers them in the global store. -No component code is executed — the declaration is read statically from the syntax tree. - -This runs once during performance-counter environment initialization so that every +`Register-IcingaPerformanceCounterFromComponents` parses the compiled module kernel +(`lib\IcingaForWindows.Kernel.ps1`, which contains every source file concatenated) and +finds all calls to `New-IcingaPerformanceCounter`. For each call it extracts the literal +counter paths passed to the `-Counter` parameter and registers them in the global store. +No component code is executed -- the declaration is read statically from the syntax tree. + +This runs once during performance-counter environment initialization so that every counter any component declares is warmed as soon as the daemon starts. #### Outputs -None — Populates `(Get-GlobalRuntimeVariable).Public.PerformanceCounter.Registered`. +None -- Populates `(Get-GlobalRuntimeVariable).Public.PerformanceCounter.Registered`. #### Examples @@ -568,7 +619,7 @@ PS> Register-IcingaPerformanceCounterFromComponents #### Notes -Only literal array/string arguments are discoverable. The kernel file is produced by +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)* @@ -583,21 +634,21 @@ Only literal array/string arguments are discoverable. The kernel file is produce #### Description -`Start-IcingaPerformanceCounterDaemon` initializes the performance-counter environment and -then runs the request/refresh loop while `Test-ThreadRunning` is true. Each cycle it blocks -briefly on the request queue; when a request arrives it resolves the requested counters -through the central manager and pushes the result into the caller's pending response queue, -keyed by the request id. When idle (and on a throttled interval) it runs the maintenance -step which refreshes the heartbeat, reconciles transient instances, evicts unused counters -and persists the cache. - -Because every performance counter handle is created, sampled and disposed here on this one -thread, callers never touch the non-thread-safe counter objects directly — they exchange +`Start-IcingaPerformanceCounterDaemon` initializes the performance-counter environment and +then runs the request/refresh loop while `Test-ThreadRunning` is true. Each cycle it blocks +briefly on the request queue; when a request arrives it resolves the requested counters +through the central manager and pushes the result into the caller's pending response queue, +keyed by the request id. When idle (and on a throttled interval) it runs the maintenance +step which refreshes the heartbeat, reconciles transient instances, evicts unused counters +and persists the cache. + +Because every performance counter handle is created, sampled and disposed here on this one +thread, callers never touch the non-thread-safe counter objects directly -- they exchange data through the thread-safe queues only. #### Outputs -None — Operates for side effects (serves requests and maintains counters). +None -- Operates for side effects (serves requests and maintains counters). #### Examples @@ -607,8 +658,8 @@ PS> Start-IcingaPerformanceCounterDaemon #### Notes -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 +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. *Source: [src/PerformanceCounter/Private/Start-IcingaPerformanceCounterDaemon.ps1](../../src/PerformanceCounter/Private/Start-IcingaPerformanceCounterDaemon.ps1)* @@ -623,15 +674,15 @@ the runtime at startup. The daemon exits cleanly when `Test-ThreadRunning` retur #### Description -`Test-IcingaPerformanceCounterDaemon` checks the heartbeat timestamp the daemon refreshes -on every loop cycle. If the heartbeat is recent the daemon is considered alive and callers -route their reads through the request/response queue; otherwise `Get-IcingaPerformanceCounter` -falls back to a synchronous inline read. Using the heartbeat keeps the check decoupled from +`Test-IcingaPerformanceCounterDaemon` checks the heartbeat timestamp the daemon refreshes +on every loop cycle. If the heartbeat is recent the daemon is considered alive and callers +route their reads through the request/response queue; otherwise `Get-IcingaPerformanceCounter` +falls back to a synchronous inline read. Using the heartbeat keeps the check decoupled from the thread registry. #### Outputs -System.Boolean — $true when the daemon heartbeat is recent, otherwise $false. +System.Boolean -- $true when the daemon heartbeat is recent, otherwise $false. #### Examples @@ -641,7 +692,7 @@ PS> if (Test-IcingaPerformanceCounterDaemon) { 'daemon is serving requests' } #### Notes -The heartbeat lives at `(Get-GlobalRuntimeVariable).Public.PerformanceCounter.Heartbeat`. +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)* @@ -656,28 +707,28 @@ A heartbeat older than five seconds is treated as not alive. #### Description -`Update-IcingaPerformanceCounterState` is the periodic maintenance step run by the -performance-counter daemon. On every call it refreshes the daemon heartbeat. When the -configured refresh interval has elapsed it additionally evicts counters that have not been -requested for longer than the eviction window, reconciles the manager against the current -registration set (adding new instances and disposing vanished ones such as a removed disk), -takes a fresh sample of every counter to keep rate values current, and persists the cache -file. - -Extracting this maintenance out of the daemon loop keeps the loop body small and lets the +`Update-IcingaPerformanceCounterState` is the periodic maintenance step run by the +performance-counter daemon. On every call it refreshes the daemon heartbeat. When the +configured refresh interval has elapsed it additionally evicts counters that have not been +requested for longer than the eviction window, reconciles the manager against the current +registration set (adding new instances and disposing vanished ones such as a removed disk), +takes a fresh sample of every counter to keep rate values current, and persists the cache +file. + +Extracting this maintenance out of the daemon loop keeps the loop body small and lets the throttling logic live in one place. #### Parameters **`$Store`** -| Name | Type | Description | Default | -|-------|---------------|-------------------------------------------------------------------------|---------| +| Name | Type | Description | Default | +|-------|---------------|--------------------------------------------------------------------------------------|---------| | Store | System.Object | The performance-counter store to operate on. Resolved from the runtime when omitted. | $null | #### Outputs -None — Mutates the global performance-counter store and writes the cache file. +None -- Mutates the global performance-counter store and writes the cache file. #### Examples @@ -687,8 +738,8 @@ PS> Update-IcingaPerformanceCounterState #### Notes -Reads configuration (`RefreshIntervalMs`, `EvictionMinutes`) from the store's Config object. -Heartbeat is always refreshed so liveness detection stays responsive even under load. The daemon +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. *Source: [src/PerformanceCounter/Private/Update-IcingaPerformanceCounterState.ps1](../../src/PerformanceCounter/Private/Update-IcingaPerformanceCounterState.ps1)* @@ -703,15 +754,15 @@ passes its cached store reference to avoid re-resolving it through Get-GlobalRun #### Description -`Write-IcingaPerformanceCounterCache` serializes the registered counter paths and their -last-seen timestamps to a JSON file in the module cache directory. The daemon calls this -each refresh cycle so the warm counter set survives restarts and self-maintains — new -counters are added and stale ones drop out over time. The file is written atomically by +`Write-IcingaPerformanceCounterCache` serializes the registered counter paths and their +last-seen timestamps to a JSON file in the module cache directory. The daemon calls this +each refresh cycle so the warm counter set survives restarts and self-maintains -- new +counters are added and stale ones drop out over time. The file is written atomically by writing to a temporary file and renaming it into place. #### Outputs -None — Writes the cache file to disk. +None -- Writes the cache file to disk. #### Examples @@ -721,8 +772,8 @@ PS> Write-IcingaPerformanceCounterCache #### Notes -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 +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. *Source: [src/PerformanceCounter/Private/Write-IcingaPerformanceCounterCache.ps1](../../src/PerformanceCounter/Private/Write-IcingaPerformanceCounterCache.ps1)* diff --git a/docs/index.md b/docs/index.md index ace2960..09f1fa3 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,6 +1,6 @@ # Icinga API Reference -*Auto-generated on 2026-08-27 15:12:43.* +*Auto-generated on 2026-11-12 17:35:53.* | Component | Public functions | Private helpers | |-----------|------------------|-----------------| @@ -14,14 +14,14 @@ | [Icinga.Core.Threading](Icinga.Core.Threading.md) | 2 | 14 | | [Icinga.Core.WebSocket](Icinga.Core.WebSocket.md) | 3 | 16 | | [Icinga.IcingaProtocol](Icinga.IcingaProtocol.md) | 5 | 19 | -| [Icinga.PerformanceCounter](Icinga.PerformanceCounter.md) | 3 | 12 | +| [Icinga.PerformanceCounter](Icinga.PerformanceCounter.md) | 4 | 12 | | [Icinga.Security](Icinga.Security.md) | 0 | 7 | | [Icinga.Tools](Icinga.Tools.md) | 5 | 5 | ## Totals - Components: 13 -- Documented functions: 162 -- Public: 27 +- Documented functions: 163 +- Public: 28 - Private: 135 diff --git a/src/Classes/Icinga/IcingaPerformanceCounter.ps1 b/src/Classes/Icinga/IcingaPerformanceCounter.ps1 index 251910b..e7e5af9 100644 --- a/src/Classes/Icinga/IcingaPerformanceCounter.ps1 +++ b/src/Classes/Icinga/IcingaPerformanceCounter.ps1 @@ -7,8 +7,8 @@ IcingaPerformanceCounterEntry owns exactly one `System.Diagnostics.PerformanceCo handle for a fully-qualified counter path (category, optional instance, counter). It implements the prime-then-read pattern required for accurate rate counters: `Prime` takes the first (throwaway) sample, and `Read` takes the second sample and returns the -uniform value hashtable. The class never throws on counter errors — failures are -surfaced through the `error` key of the returned hashtable — and disposes its handle +uniform value hashtable. The class never throws on counter errors -- failures are +surfaced through the `error` key of the returned hashtable -- and disposes its handle through `Dispose`. The handle is created and read on a single thread only (the performance-counter @@ -16,7 +16,7 @@ daemon, or a transient one-shot resolver). The class holds no global state and i therefore safe to construct in any runspace, mirroring the IcingaUnit class. .OUTPUTS -IcingaPerformanceCounterEntry — A single initialized counter wrapper. +IcingaPerformanceCounterEntry -- A single initialized counter wrapper. .EXAMPLE PS> [IcingaPerformanceCounterEntry]::new('\Processor(_Total)\% Processor Time', 'Processor', '_Total', '% Processor Time') @@ -33,6 +33,7 @@ class IcingaPerformanceCounterEntry [string]$Counter = ''; [System.Diagnostics.PerformanceCounter]$Handle = $null; [bool]$Primed = $false; + [string]$LastError = ''; <# .SYNOPSIS @@ -43,27 +44,27 @@ class IcingaPerformanceCounterEntry lazily on the first `Prime` call, not in the constructor. .PARAMETER FullName - | Name | Type | Description | Default | - |----------|---------------|----------------------------------------------------|---------| - | FullName | System.String | The complete counter path, e.g. '\Cat(Inst)\Ctr'. | | +| Name | Type | Description | Default | +|----------|---------------|---------------------------------------------------|---------| +| FullName | System.String | The complete counter path, e.g. '\Cat(Inst)\Ctr'. | | .PARAMETER Category - | Name | Type | Description | Default | - |----------|---------------|-----------------------------------|---------| - | Category | System.String | The performance counter category. | | +| Name | Type | Description | Default | +|----------|---------------|-----------------------------------|---------| +| Category | System.String | The performance counter category. | | .PARAMETER Instance - | Name | Type | Description | Default | - |----------|---------------|----------------------------------------------------|---------| - | Instance | System.String | The instance name, or empty for single-instance. | | +| Name | Type | Description | Default | +|----------|---------------|--------------------------------------------------|---------| +| Instance | System.String | The instance name, or empty for single-instance. | | .PARAMETER Counter - | Name | Type | Description | Default | - |---------|---------------|---------------------------|---------| - | Counter | System.String | The counter name to read. | | +| Name | Type | Description | Default | +|---------|---------------|---------------------------|---------| +| Counter | System.String | The counter name to read. | | .OUTPUTS - IcingaPerformanceCounterEntry — The configured, not-yet-primed entry. + IcingaPerformanceCounterEntry -- The configured, not-yet-primed entry. .EXAMPLE PS> [IcingaPerformanceCounterEntry]::new('\Memory\Available Bytes', 'Memory', '', 'Available Bytes') @@ -87,7 +88,7 @@ class IcingaPerformanceCounterEntry `Read`. Priming errors are swallowed and surface later through `Read`. .OUTPUTS - None — Populates the `Handle` field and sets `Primed`. + None -- Populates the `Handle` field and sets `Primed`. .EXAMPLE PS> $entry.Prime() @@ -98,21 +99,23 @@ class IcingaPerformanceCounterEntry #> [void] Prime() { - if ($null -eq $this.Handle) { - $this.Handle = New-Object System.Diagnostics.PerformanceCounter; - $this.Handle.CategoryName = $this.Category; - $this.Handle.CounterName = $this.Counter; + try { + if ($null -eq $this.Handle) { + $this.Handle = [System.Diagnostics.PerformanceCounter]::new(); + $this.Handle.CategoryName = $this.Category; + $this.Handle.CounterName = $this.Counter; - if (-not [string]::IsNullOrEmpty($this.Instance)) { - $this.Handle.InstanceName = $this.Instance; + if (-not [string]::IsNullOrEmpty($this.Instance)) { + $this.Handle.InstanceName = $this.Instance; + } } - } - try { $this.Handle.NextValue() | Out-Null; $this.Handle.NextSample() | Out-Null; + $this.LastError = ''; } catch { # A priming failure is reported on the next Read call through the error key. + $this.LastError = $_.Exception.Message; $Error.Clear(); } @@ -126,11 +129,11 @@ class IcingaPerformanceCounterEntry .DESCRIPTION Takes the second sample of the counter and returns a hashtable with the fixed keys `value`, `sample`, `help`, `type` and `error`. `value` is rounded to six decimals. - The method never throws — any exception is captured into the `error` key while the + The method never throws -- any exception is captured into the `error` key while the remaining keys keep their defaults. .OUTPUTS - System.Collections.Hashtable — Keys value, sample, help, type, error. + System.Collections.Hashtable -- Keys value, sample, help, type, error. .EXAMPLE PS> $result = $entry.Read() @@ -146,7 +149,12 @@ class IcingaPerformanceCounterEntry }; if ($null -eq $this.Handle) { - $Result['error'] = 'Counter not initialized'; + if ([string]::IsNullOrEmpty($this.LastError)) { + $Result['error'] = 'Counter not initialized'; + } else { + $Result['error'] = $this.LastError; + } + return $Result; } @@ -176,7 +184,7 @@ class IcingaPerformanceCounterEntry the entry can be safely discarded. Safe to call multiple times. .OUTPUTS - None — Releases the native handle. + None -- Releases the native handle. .EXAMPLE PS> $entry.Dispose() @@ -213,7 +221,7 @@ process with the same name exits; its rate counters then read 0 until the next snapshot. .OUTPUTS -IcingaPerformanceCounterCategory — The snapshot reader of one category. +IcingaPerformanceCounterCategory -- The snapshot reader of one category. .EXAMPLE PS> $Snapshot = [IcingaPerformanceCounterCategory]::new('Process') @@ -243,12 +251,12 @@ class IcingaPerformanceCounterCategory Stores the category name. The category is read for the first time by `Prime`. .PARAMETER Category - | Name | Type | Description | Default | - |----------|---------------|-----------------------------------|---------| - | Category | System.String | The performance counter category. | | +| Name | Type | Description | Default | +|----------|---------------|-----------------------------------|---------| +| Category | System.String | The performance counter category. | | .OUTPUTS - IcingaPerformanceCounterCategory — The not yet primed reader. + IcingaPerformanceCounterCategory -- The not yet primed reader. .EXAMPLE PS> [IcingaPerformanceCounterCategory]::new('Processor Information') @@ -268,7 +276,7 @@ class IcingaPerformanceCounterCategory that cannot be read is remembered in `LastError` instead of throwing. .OUTPUTS - None — Populates the current snapshot. + None -- Populates the current snapshot. .EXAMPLE PS> $Snapshot.Prime() @@ -276,7 +284,7 @@ class IcingaPerformanceCounterCategory [void] Prime() { try { - $this.Reader = New-Object System.Diagnostics.PerformanceCounterCategory($this.Category); + $this.Reader = [System.Diagnostics.PerformanceCounterCategory]::new($this.Category); $this.Current = $this.Reader.ReadCategory(); $this.ReadTime = [datetime]::UtcNow; $this.LastError = ''; @@ -295,7 +303,7 @@ class IcingaPerformanceCounterCategory keeps both snapshots and stores the reason in `LastError`. .OUTPUTS - None — Advances the snapshots. + None -- Advances the snapshots. .EXAMPLE PS> $Snapshot.Refresh() @@ -328,7 +336,7 @@ class IcingaPerformanceCounterCategory the category was never read. .OUTPUTS - System.Double — Age of the current snapshot. + System.Double -- Age of the current snapshot. .EXAMPLE PS> $Snapshot.AgeMilliseconds() @@ -352,14 +360,14 @@ class IcingaPerformanceCounterCategory category returns no instances, like `GetInstanceNames`. .OUTPUTS - System.String[] — The instance names of the current snapshot. + System.String[] -- The instance names of the current snapshot. .EXAMPLE PS> $Snapshot.GetInstanceNames() #> [string[]] GetInstanceNames() { - $Names = New-Object 'System.Collections.Generic.List[string]'; + $Names = [System.Collections.Generic.List[string]]::new(); if ($null -eq $this.Current) { return $Names.ToArray(); @@ -390,17 +398,17 @@ class IcingaPerformanceCounterCategory value is calculated from the current sample alone. The method never throws. .PARAMETER Instance - | Name | Type | Description | Default | - |----------|---------------|-----------------------|---------| - | Instance | System.String | The instance to read. | | +| Name | Type | Description | Default | +|----------|---------------|-----------------------|---------| +| Instance | System.String | The instance to read. | | .PARAMETER Counter - | Name | Type | Description | Default | - |---------|---------------|----------------------|---------| - | Counter | System.String | The counter to read. | | +| Name | Type | Description | Default | +|---------|---------------|----------------------|---------| +| Counter | System.String | The counter to read. | | .OUTPUTS - System.Collections.Hashtable — Keys value, sample, help, type, error. + System.Collections.Hashtable -- Keys value, sample, help, type, error. .EXAMPLE PS> $Snapshot.Read('_Total', '% Processor Time') @@ -471,17 +479,17 @@ class IcingaPerformanceCounterCategory counter) the name now belongs to a different process. .PARAMETER Instance - | Name | Type | Description | Default | - |----------|---------------|--------------------|---------| - | Instance | System.String | The instance name. | | +| Name | Type | Description | Default | +|----------|---------------|--------------------|---------| +| Instance | System.String | The instance name. | | .PARAMETER Counter - | Name | Type | Description | Default | - |---------|---------------|-------------------|---------| - | Counter | System.String | The counter name. | | +| Name | Type | Description | Default | +|---------|---------------|-------------------|---------| +| Counter | System.String | The counter name. | | .OUTPUTS - System.Diagnostics.InstanceData — The previous data, or $null. + System.Diagnostics.InstanceData -- The previous data, or $null. .EXAMPLE PS> $Snapshot.FindPrevious('svchost#3', '% Processor Time') @@ -529,17 +537,17 @@ class IcingaPerformanceCounterCategory away. Later calls answer from the cached texts. .PARAMETER Counter - | Name | Type | Description | Default | - |---------|---------------|-------------------|---------| - | Counter | System.String | The counter name. | | +| Name | Type | Description | Default | +|---------|---------------|-------------------|---------| +| Counter | System.String | The counter name. | | .PARAMETER Instance - | Name | Type | Description | Default | - |----------|---------------|---------------------------------------------|---------| - | Instance | System.String | An existing instance used to list counters. | | +| Name | Type | Description | Default | +|----------|---------------|---------------------------------------------|---------| +| Instance | System.String | An existing instance used to list counters. | | .OUTPUTS - System.String — The help text, or $null when it cannot be read. + System.String -- The help text, or $null when it cannot be read. .EXAMPLE PS> $Snapshot.GetHelp('% Processor Time', '_Total') @@ -580,12 +588,12 @@ are picked up by the category snapshots. The manager is created and used exclusively on the performance-counter daemon thread, so its internal `ConcurrentDictionary` is never mutated concurrently. Callers on other -threads never touch the manager directly — they exchange requests and responses through +threads never touch the manager directly -- they exchange requests and responses through the thread-safe queues in the global runtime store. The self-contained one-shot `ResolveOnce` supports command-line usage where no daemon is running. .OUTPUTS -IcingaPerformanceCounter — The counter manager instance. +IcingaPerformanceCounter -- The counter manager instance. .EXAMPLE PS> $manager = [IcingaPerformanceCounter]::new() @@ -598,9 +606,9 @@ the module's runspace model. #> class IcingaPerformanceCounter { - [System.Collections.Concurrent.ConcurrentDictionary[string, IcingaPerformanceCounterEntry]]$Counters = $null; - [System.Collections.Concurrent.ConcurrentDictionary[string, IcingaPerformanceCounterCategory]]$Categories = $null; - [int]$WarmupMilliseconds = 250; + [System.Collections.Concurrent.ConcurrentDictionary[string, object]]$Counters = $null; + [System.Collections.Concurrent.ConcurrentDictionary[string, object]]$Categories = $null; + [int]$WarmupMilliseconds = 250; <# .SYNOPSIS @@ -611,15 +619,15 @@ class IcingaPerformanceCounter Nothing is read until `Warmup`, `Resolve` or `Reconcile` is called. .OUTPUTS - IcingaPerformanceCounter — An empty manager. + IcingaPerformanceCounter -- An empty manager. .EXAMPLE PS> [IcingaPerformanceCounter]::new() #> IcingaPerformanceCounter() { - $this.Counters = New-Object 'System.Collections.Concurrent.ConcurrentDictionary[string, IcingaPerformanceCounterEntry]'; - $this.Categories = New-Object 'System.Collections.Concurrent.ConcurrentDictionary[string, IcingaPerformanceCounterCategory]'; + $this.Counters = [System.Collections.Concurrent.ConcurrentDictionary[string, object]]::new(); + $this.Categories = [System.Collections.Concurrent.ConcurrentDictionary[string, object]]::new(); } <# @@ -627,18 +635,20 @@ class IcingaPerformanceCounter Parse a counter path into its category, instance and counter components .DESCRIPTION - Splits a fully-qualified counter path of the form '\Category\Counter' or - '\Category(Instance)\Counter' into its parts. Returns a hashtable with `Category`, - `Instance`, `Counter` and a `Valid` flag. Invalid input yields `Valid = $false` - instead of throwing. + Splits a fully-qualified counter path of the form '\Category\Counter', + '\Category(Instance)\Counter' or '\\\Category\Counter' into its parts. + Local machine prefixes ('\\.\', '\\localhost\', '\\127.0.0.1\', '\\::1\' and + '\\\') are accepted and stripped automatically; remote host prefixes + are rejected. Returns a hashtable with `Category`, `Instance`, `Counter` and a + `Valid` flag. Invalid input yields `Valid = $false` instead of throwing. .PARAMETER Path - | Name | Type | Description | Default | - |------|---------------|------------------------------------|---------| - | Path | System.String | The counter path string to parse. | | +| Name | Type | Description | Default | +|------|---------------|-----------------------------------|---------| +| Path | System.String | The counter path string to parse. | | .OUTPUTS - System.Collections.Hashtable — Keys Category, Instance, Counter, Valid. + System.Collections.Hashtable -- Keys Category, Instance, Counter, Valid. .EXAMPLE PS> [IcingaPerformanceCounter]::ParsePath('\PhysicalDisk(0 C:)\Disk Reads/sec') @@ -656,11 +666,27 @@ class IcingaPerformanceCounter return $Result; } + if ($Path.StartsWith('\\')) { + [int]$NextSlash = $Path.IndexOf('\', 2); + + if ($NextSlash -le 2) { + return $Result; + } + + [string]$Machine = $Path.Substring(2, $NextSlash - 2); + + if ($Machine -ne '.' -and -not $Machine.Equals('localhost', [System.StringComparison]::OrdinalIgnoreCase) -and $Machine -ne '127.0.0.1' -and $Machine -ne '::1' -and -not $Machine.Equals([System.Environment]::MachineName, [System.StringComparison]::OrdinalIgnoreCase)) { + return $Result; + } + + $Path = $Path.Substring($NextSlash); + } + [string[]]$Parts = $Path.Split('\'); # A valid path starts with a backslash, so the first split element is empty and - # there are at least three elements: '', category(+instance), counter. - if ($Parts.Count -lt 3 -or -not [string]::IsNullOrEmpty($Parts[0])) { + # there are three elements: '', category(+instance), counter. + if ($Parts.Count -ne 3 -or -not [string]::IsNullOrEmpty($Parts[0])) { return $Result; } @@ -688,6 +714,137 @@ class IcingaPerformanceCounter return $Result; } + <# + .SYNOPSIS + Normalize a counter path by stripping any local machine prefix + + .DESCRIPTION + Parses the given counter path and returns its canonical machine-less form + ('\Category\Counter' or '\Category(Instance)\Counter'). Invalid paths are returned + unchanged. + + .PARAMETER Path +| Name | Type | Description | Default | +|------|---------------|---------------------------------------|---------| +| Path | System.String | The counter path string to normalize. | | + + .OUTPUTS + System.String -- The canonical counter path without a machine prefix. + + .EXAMPLE + PS> [IcingaPerformanceCounter]::NormalizePath('\\.\Memory\Available Bytes') + #> + static [string] NormalizePath([string]$Path) + { + $CounterType = 'IcingaPerformanceCounter' -as [type]; + $Parsed = $CounterType::ParsePath($Path); + + if (-not $Parsed.Valid) { + return $Path; + } + + if ([string]::IsNullOrEmpty($Parsed.Instance)) { + return ('\{0}\{1}' -f $Parsed.Category, $Parsed.Counter); + } + + return ('\{0}({1})\{2}' -f $Parsed.Category, $Parsed.Instance, $Parsed.Counter); + } + + <# + .SYNOPSIS + Check whether a performance counter category exists on the local system + + .DESCRIPTION + Accepts either a plain category name ('Processor') or a full counter path + ('\Processor(*)\% Processor Time' or '\\.\Processor(_Total)\% Processor Time') and + returns $true when the category exists and is accessible on this system, or $false + otherwise. Never throws. + + .PARAMETER Category +| Name | Type | Description | Default | +|----------|---------------|---------------------------------------------|---------| +| Category | System.String | The category name or counter path to check. | | + + .OUTPUTS + System.Boolean -- $true when the category exists on the system; $false otherwise. + + .EXAMPLE + PS> [IcingaPerformanceCounter]::CategoryExists('Processor') + #> + static [bool] CategoryExists([string]$Category) + { + if ([string]::IsNullOrWhiteSpace($Category)) { + return $false; + } + + [string]$TargetCategory = $Category.Trim(); + + if ($TargetCategory.StartsWith('\')) { + $CounterType = 'IcingaPerformanceCounter' -as [type]; + $Parsed = $CounterType::ParsePath($TargetCategory); + + if ($Parsed.Valid) { + $TargetCategory = $Parsed.Category; + } else { + return $false; + } + } + + if ([string]::IsNullOrWhiteSpace($TargetCategory)) { + return $false; + } + + try { + $CategoryObject = [System.Diagnostics.PerformanceCounterCategory]::new($TargetCategory); + + if ($null -eq $CategoryObject -or $null -eq $CategoryObject.CategoryType) { + return $false; + } + + return $true; + } catch { + $Error.Clear(); + return $false; + } + } + + <# + .SYNOPSIS + Return the last error recorded for a category snapshot + + .DESCRIPTION + Returns the `LastError` string of a registered category snapshot when priming or + refreshing that category failed (for example when the category does not exist or + access is denied), or an empty string when the category snapshot is healthy. + + .PARAMETER Category +| Name | Type | Description | Default | +|----------|---------------|-----------------------------------|---------| +| Category | System.String | The performance counter category. | | + + .OUTPUTS + System.String -- The last error message for the category, or an empty string. + + .EXAMPLE + PS> $manager.GetCategoryError('Processor') + #> + [string] GetCategoryError([string]$Category) + { + if ([string]::IsNullOrWhiteSpace($Category)) { + return 'Category name is empty'; + } + + if ($this.Categories.ContainsKey($Category)) { + $Snapshot = $this.Categories[$Category]; + + if ($null -ne $Snapshot -and -not [string]::IsNullOrEmpty($Snapshot.LastError)) { + return $Snapshot.LastError; + } + } + + return ''; + } + <# .SYNOPSIS Expand a counter path into the concrete per-instance paths that exist right now @@ -699,19 +856,20 @@ class IcingaPerformanceCounter array rather than throwing. .PARAMETER Path - | Name | Type | Description | Default | - |------|---------------|--------------------------------------|---------| - | Path | System.String | The (possibly wildcard) counter path.| | +| Name | Type | Description | Default | +|------|---------------|---------------------------------------|---------| +| Path | System.String | The (possibly wildcard) counter path. | | .OUTPUTS - System.String[] — The concrete counter paths currently present. + System.String[] -- The concrete counter paths currently present. .EXAMPLE PS> $manager.ExpandPath('\PhysicalDisk(*)\Disk Reads/sec') #> [string[]] ExpandPath([string]$Path) { - $Parsed = [IcingaPerformanceCounter]::ParsePath($Path); + $CounterType = 'IcingaPerformanceCounter' -as [type]; + $Parsed = $CounterType::ParsePath($Path); if (-not $Parsed.Valid) { return @(); @@ -724,7 +882,7 @@ class IcingaPerformanceCounter [string[]]$Expanded = @(); try { - $CategoryObject = New-Object System.Diagnostics.PerformanceCounterCategory($Parsed.Category); + $CategoryObject = [System.Diagnostics.PerformanceCounterCategory]::new($Parsed.Category); foreach ($InstanceName in $CategoryObject.GetInstanceNames()) { $Expanded += ('\{0}({1})\{2}' -f $Parsed.Category, $InstanceName, $Parsed.Counter); } @@ -745,25 +903,29 @@ class IcingaPerformanceCounter invalid paths so the caller can skip them. .PARAMETER Path - | Name | Type | Description | Default | - |------|---------------|---------------------------------|---------| - | Path | System.String | The concrete counter path. | | +| Name | Type | Description | Default | +|------|---------------|----------------------------|---------| +| Path | System.String | The concrete counter path. | | .OUTPUTS - IcingaPerformanceCounterEntry — The new entry, or $null when the path is invalid. + IcingaPerformanceCounterEntry -- The new entry, or $null when the path is invalid. .EXAMPLE PS> $manager.CreateEntry('\Memory\Available Bytes') #> - [IcingaPerformanceCounterEntry] CreateEntry([string]$Path) + [object] CreateEntry([string]$Path) { - $Parsed = [IcingaPerformanceCounter]::ParsePath($Path); + $CounterType = 'IcingaPerformanceCounter' -as [type]; + $EntryType = 'IcingaPerformanceCounterEntry' -as [type]; + $Parsed = $CounterType::ParsePath($Path); if (-not $Parsed.Valid) { return $null; } - return [IcingaPerformanceCounterEntry]::new($Path, $Parsed.Category, $Parsed.Instance, $Parsed.Counter); + [string]$Normalized = $CounterType::NormalizePath($Path); + + return $EntryType::new($Normalized, $Parsed.Category, $Parsed.Instance, $Parsed.Counter); } <# @@ -777,12 +939,12 @@ class IcingaPerformanceCounter repeated calls are cheap. .PARAMETER Paths - | Name | Type | Description | Default | - |-------|-----------------|------------------------------------------|---------| - | Paths | System.String[] | The counter paths to ensure are warm. | | +| Name | Type | Description | Default | +|-------|-----------------|---------------------------------------|---------| +| Paths | System.String[] | The counter paths to ensure are warm. | | .OUTPUTS - None — Populates the internal registry. + None -- Populates the internal registry. .EXAMPLE PS> $manager.Warmup(@('\Processor(_Total)\% Processor Time')) @@ -794,9 +956,10 @@ class IcingaPerformanceCounter [void] Warmup([string[]]$Paths) { [bool]$PrimedAny = $false; + $CounterType = 'IcingaPerformanceCounter' -as [type]; foreach ($Path in $Paths) { - $Parsed = [IcingaPerformanceCounter]::ParsePath($Path); + $Parsed = $CounterType::ParsePath($Path); if (-not $Parsed.Valid) { continue; @@ -810,10 +973,12 @@ class IcingaPerformanceCounter continue; } - if (-not $this.Counters.ContainsKey($Path)) { - $Entry = $this.CreateEntry($Path); + [string]$Normalized = $CounterType::NormalizePath($Path); - if ($null -ne $Entry -and $this.Counters.TryAdd($Path, $Entry)) { + if (-not $this.Counters.ContainsKey($Normalized)) { + $Entry = $this.CreateEntry($Normalized); + + if ($null -ne $Entry -and $this.Counters.TryAdd($Normalized, $Entry)) { $Entry.Prime(); $PrimedAny = $true; } @@ -834,12 +999,12 @@ class IcingaPerformanceCounter when a new snapshot was primed, so the caller knows a warm-up sleep is needed. .PARAMETER Category - | Name | Type | Description | Default | - |----------|---------------|-----------------------------------|---------| - | Category | System.String | The performance counter category. | | +| Name | Type | Description | Default | +|----------|---------------|-----------------------------------|---------| +| Category | System.String | The performance counter category. | | .OUTPUTS - System.Boolean — $true when a new snapshot was created and primed. + System.Boolean -- $true when a new snapshot was created and primed. .EXAMPLE PS> $manager.AddCategory('Process') @@ -850,7 +1015,8 @@ class IcingaPerformanceCounter return $false; } - $Snapshot = [IcingaPerformanceCounterCategory]::new($Category); + $CategoryType = 'IcingaPerformanceCounterCategory' -as [type]; + $Snapshot = $CategoryType::new($Category); if (-not $this.Categories.TryAdd($Category, $Snapshot)) { return $false; @@ -870,20 +1036,23 @@ class IcingaPerformanceCounter present in the registry, a result with a populated `error` key is returned. .PARAMETER Path - | Name | Type | Description | Default | - |------|---------------|----------------------------|---------| - | Path | System.String | The concrete counter path. | | +| Name | Type | Description | Default | +|------|---------------|----------------------------|---------| +| Path | System.String | The concrete counter path. | | .OUTPUTS - System.Collections.Hashtable — Keys value, sample, help, type, error. + System.Collections.Hashtable -- Keys value, sample, help, type, error. .EXAMPLE PS> $manager.ReadPath('\Memory\Available Bytes') #> [hashtable] ReadPath([string]$Path) { - if ($this.Counters.ContainsKey($Path)) { - $Entry = $this.Counters[$Path]; + $CounterType = 'IcingaPerformanceCounter' -as [type]; + [string]$Normalized = $CounterType::NormalizePath($Path); + + if ($this.Counters.ContainsKey($Normalized)) { + $Entry = $this.Counters[$Normalized]; if ($null -ne $Entry) { return $Entry.Read(); @@ -914,12 +1083,12 @@ class IcingaPerformanceCounter interval; the daemon additionally refreshes every snapshot on each `Sample`. .PARAMETER Paths - | Name | Type | Description | Default | - |-------|-----------------|------------------------------------|---------| - | Paths | System.String[] | The counter paths to read. | | +| Name | Type | Description | Default | +|-------|-----------------|----------------------------|---------| +| Paths | System.String[] | The counter paths to read. | | .OUTPUTS - System.Collections.Hashtable — Keyed by requested path; flat or nested per path. + System.Collections.Hashtable -- Keyed by requested path; flat or nested per path. .EXAMPLE PS> $manager.Resolve(@('\PhysicalDisk(*)\Disk Reads/sec')) @@ -930,9 +1099,10 @@ class IcingaPerformanceCounter [hashtable]$Result = @{ }; [hashtable]$ReadCache = @{ }; + $CounterType = 'IcingaPerformanceCounter' -as [type]; foreach ($Path in $Paths) { - $Parsed = [IcingaPerformanceCounter]::ParsePath($Path); + $Parsed = $CounterType::ParsePath($Path); if ($Parsed.Valid -and $Parsed.Instance -eq '*') { [hashtable]$Group = @{ }; @@ -960,11 +1130,13 @@ class IcingaPerformanceCounter $Result[$Path] = $Group; } else { - if (-not $ReadCache.ContainsKey($Path)) { - $ReadCache[$Path] = $this.ReadPath($Path); + [string]$Normalized = $CounterType::NormalizePath($Path); + + if (-not $ReadCache.ContainsKey($Normalized)) { + $ReadCache[$Normalized] = $this.ReadPath($Normalized); } - $Result[$Path] = $ReadCache[$Path]; + $Result[$Path] = $ReadCache[$Normalized]; } } @@ -978,11 +1150,11 @@ class IcingaPerformanceCounter .DESCRIPTION Calls `NextValue` on each live handle and refreshes every category snapshot, so the next read computes an accurate rate over the refresh interval. Sampling errors are - ignored — dead instances are removed separately by `Reconcile`, and a category + ignored -- dead instances are removed separately by `Reconcile`, and a category snapshot keeps its last read when a refresh fails. .OUTPUTS - None — Advances the internal sample of every counter. + None -- Advances the internal sample of every counter. .EXAMPLE PS> $manager.Sample() @@ -1024,23 +1196,24 @@ class IcingaPerformanceCounter sleep. .PARAMETER RegisteredPaths - | Name | Type | Description | Default | - |-----------------|-----------------|-----------------------------------------------|---------| - | RegisteredPaths | System.String[] | The counter paths that should be kept warm. | | +| Name | Type | Description | Default | +|-----------------|-----------------|---------------------------------------------|---------| +| RegisteredPaths | System.String[] | The counter paths that should be kept warm. | | .OUTPUTS - None — Adds and removes counter handles to match the desired set. + None -- Adds and removes counter handles to match the desired set. .EXAMPLE PS> $manager.Reconcile(@('\PhysicalDisk(*)\Disk Reads/sec')) #> [void] Reconcile([string[]]$RegisteredPaths) { - $Desired = New-Object 'System.Collections.Generic.HashSet[string]'; - $DesiredCategories = New-Object 'System.Collections.Generic.HashSet[string]'; + $Desired = [System.Collections.Generic.HashSet[string]]::new(); + $DesiredCategories = [System.Collections.Generic.HashSet[string]]::new(); + $CounterType = 'IcingaPerformanceCounter' -as [type]; foreach ($Path in $RegisteredPaths) { - $Parsed = [IcingaPerformanceCounter]::ParsePath($Path); + $Parsed = $CounterType::ParsePath($Path); if (-not $Parsed.Valid) { continue; @@ -1049,7 +1222,7 @@ class IcingaPerformanceCounter if ($Parsed.Instance -eq '*') { [void]$DesiredCategories.Add($Parsed.Category); } else { - [void]$Desired.Add($Path); + [void]$Desired.Add($CounterType::NormalizePath($Path)); } } @@ -1078,7 +1251,7 @@ class IcingaPerformanceCounter foreach ($Key in @($this.Counters.Keys)) { if (-not $Desired.Contains($Key)) { - [IcingaPerformanceCounterEntry]$Stale = $null; + [object]$Stale = $null; if ($this.Counters.TryRemove($Key, [ref]$Stale) -and $null -ne $Stale) { $Stale.Dispose(); @@ -1088,7 +1261,7 @@ class IcingaPerformanceCounter foreach ($Key in @($this.Categories.Keys)) { if (-not $DesiredCategories.Contains($Key)) { - [IcingaPerformanceCounterCategory]$StaleCategory = $null; + [object]$StaleCategory = $null; $this.Categories.TryRemove($Key, [ref]$StaleCategory) | Out-Null; } } @@ -1104,7 +1277,7 @@ class IcingaPerformanceCounter one-shot resolver. .OUTPUTS - None — Releases all native handles. + None -- Releases all native handles. .EXAMPLE PS> $manager.Dispose() @@ -1135,24 +1308,25 @@ class IcingaPerformanceCounter shares no state with the daemon and is safe on any thread. .PARAMETER Paths - | Name | Type | Description | Default | - |-------|-----------------|-----------------------------------|---------| - | Paths | System.String[] | The counter paths to read once. | | +| Name | Type | Description | Default | +|-------|-----------------|---------------------------------|---------| +| Paths | System.String[] | The counter paths to read once. | | .PARAMETER WarmupMilliseconds - | Name | Type | Description | Default | - |--------------------|--------------|---------------------------------------------|---------| - | WarmupMilliseconds | System.Int32 | Shared warm-up sleep between the two samples.| 250 | +| Name | Type | Description | Default | +|--------------------|--------------|-----------------------------------------------|---------| +| WarmupMilliseconds | System.Int32 | Shared warm-up sleep between the two samples. | 250 | .OUTPUTS - System.Collections.Hashtable — Same shape as Resolve. + System.Collections.Hashtable -- Same shape as Resolve. .EXAMPLE PS> [IcingaPerformanceCounter]::ResolveOnce(@('\Processor(_Total)\% Processor Time'), 250) #> static [hashtable] ResolveOnce([string[]]$Paths, [int]$WarmupMilliseconds) { - $Manager = [IcingaPerformanceCounter]::new(); + $CounterType = 'IcingaPerformanceCounter' -as [type]; + $Manager = $CounterType::new(); $Manager.WarmupMilliseconds = $WarmupMilliseconds; try { diff --git a/src/PerformanceCounter/Private/ConvertTo-IcingaPerformanceCounterInstanceStructure.ps1 b/src/PerformanceCounter/Private/ConvertTo-IcingaPerformanceCounterInstanceStructure.ps1 index 0ece3c7..5f830cf 100644 --- a/src/PerformanceCounter/Private/ConvertTo-IcingaPerformanceCounterInstanceStructure.ps1 +++ b/src/PerformanceCounter/Private/ConvertTo-IcingaPerformanceCounterInstanceStructure.ps1 @@ -18,17 +18,17 @@ The requested paths are re-parsed to decide the shape, so the transform never ha nested value is a value hashtable or an instance group. .PARAMETER Result -| Name | Type | Description | Default | -|--------|-----------------------------|------------------------------------------------------------|---------| -| Result | System.Collections.Hashtable| The result returned by the manager, keyed by requested path.| @{ } | +| Name | Type | Description | Default | +|--------|------------------------------|--------------------------------------------------------------|---------| +| Result | System.Collections.Hashtable | The result returned by the manager, keyed by requested path. | @{ } | .PARAMETER Counter -| Name | Type | Description | Default | -|---------|--------------|---------------------------------------------------------|---------| -| Counter | System.Array | The originally requested counter paths, used to drive the reshape. | @() | +| Name | Type | Description | Default | +|---------|--------------|--------------------------------------------------------------------|---------| +| Counter | System.Array | The originally requested counter paths, used to drive the reshape. | @() | .OUTPUTS -System.Collections.Hashtable — Nested structure keyed by instance/category or category, with the +System.Collections.Hashtable -- Nested structure keyed by instance/category or category, with the uniform value hashtable at the leaf. .EXAMPLE @@ -51,13 +51,15 @@ function ConvertTo-IcingaPerformanceCounterInstanceStructure() return $Structured; } + $CounterType = 'IcingaPerformanceCounter' -as [type]; + foreach ($RequestedPath in $Counter) { if ([string]::IsNullOrEmpty($RequestedPath) -or -not $Result.ContainsKey($RequestedPath)) { continue; } - $Entry = $Result[$RequestedPath]; - $Parsed = [IcingaPerformanceCounter]::ParsePath($RequestedPath); + $Entry = $Result[$RequestedPath]; + $Parsed = $CounterType::ParsePath($RequestedPath); # Normalize to a set of concrete "counter path -> value hashtable" pairs. A wildcard result # is already keyed by each expanded path; a concrete request maps to a single pair. @@ -70,7 +72,7 @@ function ConvertTo-IcingaPerformanceCounterInstanceStructure() } foreach ($ConcretePath in $Concrete.Keys) { - $Path = [IcingaPerformanceCounter]::ParsePath($ConcretePath); + $Path = $CounterType::ParsePath($ConcretePath); $Value = $Concrete[$ConcretePath]; if (-not [string]::IsNullOrEmpty($Path.Instance)) { diff --git a/src/PerformanceCounter/Private/Get-IcingaPerformanceCounterLiteral.ps1 b/src/PerformanceCounter/Private/Get-IcingaPerformanceCounterLiteral.ps1 index af8936d..06e064a 100644 --- a/src/PerformanceCounter/Private/Get-IcingaPerformanceCounterLiteral.ps1 +++ b/src/PerformanceCounter/Private/Get-IcingaPerformanceCounterLiteral.ps1 @@ -7,16 +7,16 @@ Extract literal counter path strings from an AST argument node collects the value of every string constant it contains. It is used by the startup discovery step to read the literal counter list passed to a `New-IcingaPerformanceCounter` call without executing any component code. Non-literal arguments (variables, expressions) -contribute no values, which is intentional — only statically declarable counters are +contribute no values, which is intentional -- only statically declarable counters are discovered. .PARAMETER Argument -| Name | Type | Description | Default | -|----------|---------------------------------------------|---------------------------------------------|---------| -| Argument | System.Management.Automation.Language.Ast | The AST node of the `-Counter` argument. | $null | +| Name | Type | Description | Default | +|----------|-------------------------------------------|------------------------------------------|---------| +| Argument | System.Management.Automation.Language.Ast | The AST node of the `-Counter` argument. | $null | .OUTPUTS -System.Array — The literal string values found in the argument, or an empty array. +System.Array -- The literal string values found in the argument, or an empty array. .EXAMPLE PS> Get-IcingaPerformanceCounterLiteral -Argument $argumentAst diff --git a/src/PerformanceCounter/Private/Get-IcingaPerformanceCounterValue.ps1 b/src/PerformanceCounter/Private/Get-IcingaPerformanceCounterValue.ps1 index d9d6e34..91ad144 100644 --- a/src/PerformanceCounter/Private/Get-IcingaPerformanceCounterValue.ps1 +++ b/src/PerformanceCounter/Private/Get-IcingaPerformanceCounterValue.ps1 @@ -13,12 +13,12 @@ Because the value is always numeric and the error is always a string, callers ca with a simple type check (`$result -is [string]` means an error was returned). .PARAMETER InputObject -| Name | Type | Description | Default | -|-------------|---------------|----------------------------------------------------------------------|---------| +| Name | Type | Description | Default | +|-------------|---------------|-----------------------------------------------------------------------|---------| | InputObject | System.Object | A single counter value object (the leaf hashtable of a counter read). | $null | .OUTPUTS -System.Object — The counter value (typically System.Decimal), or the error message (System.String) +System.Object -- The counter value (typically System.Decimal), or the error message (System.String) when the counter reported one. Returns $null when the input is not a counter value object. .EXAMPLE diff --git a/src/PerformanceCounter/Private/New-IcingaPerformanceCounter.ps1 b/src/PerformanceCounter/Private/New-IcingaPerformanceCounter.ps1 index 518ded0..c6bc64f 100644 --- a/src/PerformanceCounter/Private/New-IcingaPerformanceCounter.ps1 +++ b/src/PerformanceCounter/Private/New-IcingaPerformanceCounter.ps1 @@ -15,12 +15,12 @@ before it is ever requested. The function only writes to the thread-safe registr dictionary, so it is safe to call from any thread. .PARAMETER Counter -| Name | Type | Description | Default | -|---------|---------------|---------------------------------------------------------|---------| -| Counter | System.Array | One or more counter paths to register, e.g. '\Cat\Ctr'. | @() | +| Name | Type | Description | Default | +|---------|--------------|---------------------------------------------------------|---------| +| Counter | System.Array | One or more counter paths to register, e.g. '\Cat\Ctr'. | @() | .OUTPUTS -None — Registers the counter paths in the global store. +None -- Registers the counter paths in the global store. .EXAMPLE PS> New-IcingaPerformanceCounter -Counter @('\Processor(*)\% Processor Time', '\Memory\Available Bytes') @@ -29,7 +29,7 @@ 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. +This function does not return counter values -- use `Get-IcingaPerformanceCounter` to read them. #> function New-IcingaPerformanceCounter() { diff --git a/src/PerformanceCounter/Private/New-IcingaPerformanceCounterEnvironment.ps1 b/src/PerformanceCounter/Private/New-IcingaPerformanceCounterEnvironment.ps1 index 6d6a8e7..ba038f6 100644 --- a/src/PerformanceCounter/Private/New-IcingaPerformanceCounterEnvironment.ps1 +++ b/src/PerformanceCounter/Private/New-IcingaPerformanceCounterEnvironment.ps1 @@ -14,7 +14,7 @@ This function is expected to run inside the performance-counter daemon runspace, daemon enters its processing loop, so the manager is created and used on a single thread. .OUTPUTS -None — Populates `(Get-GlobalRuntimeVariable).Public.PerformanceCounter`. +None -- Populates `(Get-GlobalRuntimeVariable).Public.PerformanceCounter`. .EXAMPLE PS> New-IcingaPerformanceCounterEnvironment diff --git a/src/PerformanceCounter/Private/Read-IcingaPerformanceCounterCache.ps1 b/src/PerformanceCounter/Private/Read-IcingaPerformanceCounterCache.ps1 index bc9f680..8710830 100644 --- a/src/PerformanceCounter/Private/Read-IcingaPerformanceCounterCache.ps1 +++ b/src/PerformanceCounter/Private/Read-IcingaPerformanceCounterCache.ps1 @@ -10,7 +10,7 @@ previous runs are warmed immediately at startup. A missing, empty or corrupt cac is ignored silently so a bad cache never blocks the daemon. .OUTPUTS -None — Populates `(Get-GlobalRuntimeVariable).Public.PerformanceCounter.Registered`. +None -- Populates `(Get-GlobalRuntimeVariable).Public.PerformanceCounter.Registered`. .EXAMPLE PS> Read-IcingaPerformanceCounterCache diff --git a/src/PerformanceCounter/Private/Register-IcingaDefaultPerformanceCounter.ps1 b/src/PerformanceCounter/Private/Register-IcingaDefaultPerformanceCounter.ps1 index 3ef297c..bc23681 100644 --- a/src/PerformanceCounter/Private/Register-IcingaDefaultPerformanceCounter.ps1 +++ b/src/PerformanceCounter/Private/Register-IcingaDefaultPerformanceCounter.ps1 @@ -10,7 +10,7 @@ declares the counters it needs and gives the startup discovery step and the warm concrete set to work with. Additional components declare their own counters the same way. .OUTPUTS -None — Registers the default counter paths in the global store. +None -- Registers the default counter paths in the global store. .EXAMPLE PS> Register-IcingaDefaultPerformanceCounter diff --git a/src/PerformanceCounter/Private/Register-IcingaPerformanceCounterFromComponents.ps1 b/src/PerformanceCounter/Private/Register-IcingaPerformanceCounterFromComponents.ps1 index 2a2e45b..afe3cb5 100644 --- a/src/PerformanceCounter/Private/Register-IcingaPerformanceCounterFromComponents.ps1 +++ b/src/PerformanceCounter/Private/Register-IcingaPerformanceCounterFromComponents.ps1 @@ -7,13 +7,13 @@ Discover component-declared performance counters by scanning the compiled kernel (`lib\IcingaForWindows.Kernel.ps1`, which contains every source file concatenated) and finds all calls to `New-IcingaPerformanceCounter`. For each call it extracts the literal counter paths passed to the `-Counter` parameter and registers them in the global store. -No component code is executed — the declaration is read statically from the syntax tree. +No component code is executed -- the declaration is read statically from the syntax tree. This runs once during performance-counter environment initialization so that every counter any component declares is warmed as soon as the daemon starts. .OUTPUTS -None — Populates `(Get-GlobalRuntimeVariable).Public.PerformanceCounter.Registered`. +None -- Populates `(Get-GlobalRuntimeVariable).Public.PerformanceCounter.Registered`. .EXAMPLE PS> Register-IcingaPerformanceCounterFromComponents @@ -36,19 +36,16 @@ function Register-IcingaPerformanceCounterFromComponents() return; } - $Tokens = $null; - $Errors = $null; - $Ast = [System.Management.Automation.Language.Parser]::ParseFile($KernelPath, [ref]$Tokens, [ref]$Errors); - - $Calls = $Ast.FindAll( + $Tokens = $null; + $Errors = $null; + $Ast = [System.Management.Automation.Language.Parser]::ParseFile($KernelPath, [ref]$Tokens, [ref]$Errors); + $Calls = $Ast.FindAll( { param ($Node) - $Node -is [System.Management.Automation.Language.CommandAst] -and - $Node.GetCommandName() -eq 'New-IcingaPerformanceCounter' + $Node -is [System.Management.Automation.Language.CommandAst] -and $Node.GetCommandName() -eq 'New-IcingaPerformanceCounter' }, $true ); - [datetime]$Now = (Get-Date); foreach ($Call in $Calls) { diff --git a/src/PerformanceCounter/Private/Start-IcingaPerformanceCounterDaemon.ps1 b/src/PerformanceCounter/Private/Start-IcingaPerformanceCounterDaemon.ps1 index 52f2384..4783ac6 100644 --- a/src/PerformanceCounter/Private/Start-IcingaPerformanceCounterDaemon.ps1 +++ b/src/PerformanceCounter/Private/Start-IcingaPerformanceCounterDaemon.ps1 @@ -12,11 +12,11 @@ step which refreshes the heartbeat, reconciles transient instances, evicts unuse and persists the cache. Because every performance counter handle is created, sampled and disposed here on this one -thread, callers never touch the non-thread-safe counter objects directly — they exchange +thread, callers never touch the non-thread-safe counter objects directly -- they exchange data through the thread-safe queues only. .OUTPUTS -None — Operates for side effects (serves requests and maintains counters). +None -- Operates for side effects (serves requests and maintains counters). .EXAMPLE PS> Start-IcingaPerformanceCounterDaemon diff --git a/src/PerformanceCounter/Private/Test-IcingaPerformanceCounterDaemon.ps1 b/src/PerformanceCounter/Private/Test-IcingaPerformanceCounterDaemon.ps1 index 68dc863..26973f8 100644 --- a/src/PerformanceCounter/Private/Test-IcingaPerformanceCounterDaemon.ps1 +++ b/src/PerformanceCounter/Private/Test-IcingaPerformanceCounterDaemon.ps1 @@ -10,7 +10,7 @@ falls back to a synchronous inline read. Using the heartbeat keeps the check dec the thread registry. .OUTPUTS -System.Boolean — $true when the daemon heartbeat is recent, otherwise $false. +System.Boolean -- $true when the daemon heartbeat is recent, otherwise $false. .EXAMPLE PS> if (Test-IcingaPerformanceCounterDaemon) { 'daemon is serving requests' } diff --git a/src/PerformanceCounter/Private/Update-IcingaPerformanceCounterState.ps1 b/src/PerformanceCounter/Private/Update-IcingaPerformanceCounterState.ps1 index b0a664e..e269891 100644 --- a/src/PerformanceCounter/Private/Update-IcingaPerformanceCounterState.ps1 +++ b/src/PerformanceCounter/Private/Update-IcingaPerformanceCounterState.ps1 @@ -15,12 +15,12 @@ Extracting this maintenance out of the daemon loop keeps the loop body small and throttling logic live in one place. .PARAMETER Store -| Name | Type | Description | Default | -|-------|---------------|-------------------------------------------------------------------------|---------| +| Name | Type | Description | Default | +|-------|---------------|--------------------------------------------------------------------------------------|---------| | Store | System.Object | The performance-counter store to operate on. Resolved from the runtime when omitted. | $null | .OUTPUTS -None — Mutates the global performance-counter store and writes the cache file. +None -- Mutates the global performance-counter store and writes the cache file. .EXAMPLE PS> Update-IcingaPerformanceCounterState @@ -46,8 +46,7 @@ function Update-IcingaPerformanceCounterState() # Always refresh the heartbeat so callers can detect the daemon is alive. $Store.Heartbeat = (Get-Date); - - $Manager = $Store.Manager; + $Manager = $Store.Manager; if ($null -eq $Manager) { return; @@ -79,5 +78,5 @@ function Update-IcingaPerformanceCounterState() Write-IcingaPerformanceCounterCache; - $Store.LastRefresh = (Get-Date); + $Store.LastRefresh = (Get-Date); } diff --git a/src/PerformanceCounter/Private/Write-IcingaPerformanceCounterCache.ps1 b/src/PerformanceCounter/Private/Write-IcingaPerformanceCounterCache.ps1 index 019a820..c61faeb 100644 --- a/src/PerformanceCounter/Private/Write-IcingaPerformanceCounterCache.ps1 +++ b/src/PerformanceCounter/Private/Write-IcingaPerformanceCounterCache.ps1 @@ -5,12 +5,12 @@ Persist the registered performance counters to the cache file .DESCRIPTION `Write-IcingaPerformanceCounterCache` serializes the registered counter paths and their last-seen timestamps to a JSON file in the module cache directory. The daemon calls this -each refresh cycle so the warm counter set survives restarts and self-maintains — new +each refresh cycle so the warm counter set survives restarts and self-maintains -- new counters are added and stale ones drop out over time. The file is written atomically by writing to a temporary file and renaming it into place. .OUTPUTS -None — Writes the cache file to disk. +None -- Writes the cache file to disk. .EXAMPLE PS> Write-IcingaPerformanceCounterCache @@ -36,8 +36,7 @@ function Write-IcingaPerformanceCounterCache() [string]$CacheFile = Join-Path -Path $CacheDir -ChildPath 'PerformanceCounter.json'; [string]$TempFile = Join-Path -Path $CacheDir -ChildPath 'PerformanceCounter.json.tmp'; - - [hashtable]$Data = @{ }; + [hashtable]$Data = @{ }; foreach ($Key in @($Store.Registered.Keys)) { $Timestamp = $Store.Registered[$Key]; diff --git a/src/PerformanceCounter/Public/Get-IcingaPerformanceCounter.ps1 b/src/PerformanceCounter/Public/Get-IcingaPerformanceCounter.ps1 index 66c5462..1d55fa6 100644 --- a/src/PerformanceCounter/Public/Get-IcingaPerformanceCounter.ps1 +++ b/src/PerformanceCounter/Public/Get-IcingaPerformanceCounter.ps1 @@ -24,22 +24,22 @@ Requesting a counter also refreshes its last-seen timestamp in the registry, kee counters warm and out of the eviction path. .PARAMETER Counter -| Name | Type | Description | Default | -|---------|--------------|----------------------------------------------------------------|---------| -| Counter | System.Array | One or more counter paths to read, e.g. '\Processor(*)\...'. | @() | +| Name | Type | Description | Default | +|---------|--------------|--------------------------------------------------------------|---------| +| Counter | System.Array | One or more counter paths to read, e.g. '\Processor(*)\...'. | @() | .PARAMETER TimeoutMs -| Name | Type | Description | Default | -|-----------|--------------|-------------------------------------------------------------|---------| -| TimeoutMs | System.Int32 | Milliseconds to wait for the daemon response before giving up.| 5000 | +| Name | Type | Description | Default | +|-----------|--------------|----------------------------------------------------------------|---------| +| TimeoutMs | System.Int32 | Milliseconds to wait for the daemon response before giving up. | 5000 | .PARAMETER StructureByInstance -| Name | Type | Description | Default | -|---------------------|----------------------------------------------|--------------------------------------------------------------------------|---------| -| StructureByInstance | System.Management.Automation.SwitchParameter | Reshape the result to instance/category/counter (category/counter when no instance). | $false | +| Name | Type | Description | Default | +|---------------------|----------------------------------------------|--------------------------------------------------------------------------------------|---------| +| StructureByInstance | System.Management.Automation.SwitchParameter | Reshape the result to instance/category/counter (category/counter when no instance). | $false | .OUTPUTS -System.Collections.Hashtable — By default keyed by requested path (flat for concrete paths, nested for +System.Collections.Hashtable -- By default keyed by requested path (flat for concrete paths, nested for wildcard paths). With `-StructureByInstance`, keyed by instance then category then counter, or by category then counter for counters without an instance. Returns an empty hashtable when no counter is requested, or $null when the daemon request times out. @@ -82,7 +82,7 @@ function Get-IcingaPerformanceCounter() if ($null -eq $Store) { # The environment is not initialized at all; do a fully transient read. - $Result = [IcingaPerformanceCounter]::ResolveOnce([string[]]$Counter, 250); + $Result = ('IcingaPerformanceCounter' -as [type])::ResolveOnce([string[]]$Counter, 250); } else { # Keep the requested counters alive in the registry and cache. [datetime]$Now = (Get-Date); @@ -95,9 +95,8 @@ function Get-IcingaPerformanceCounter() if (Test-IcingaPerformanceCounterDaemon) { # Daemon is alive: dispatch through the request/response queue. - [string]$RequestId = (New-Guid).ToString(); - $ResponseQueue = [System.Collections.Concurrent.BlockingCollection[PSObject]]::New(1); - + [string]$RequestId = (New-Guid).ToString(); + $ResponseQueue = [System.Collections.Concurrent.BlockingCollection[PSObject]]::new(1); $Store.PendingRequests[$RequestId] = $ResponseQueue; try { @@ -140,7 +139,7 @@ function Get-IcingaPerformanceCounter() } $script:IcingaPerformanceCounterInlineManager.WarmupMilliseconds = $Store.Config.WarmupMilliseconds; - $Result = $script:IcingaPerformanceCounterInlineManager.Resolve([string[]]$Counter); + $Result = $script:IcingaPerformanceCounterInlineManager.Resolve([string[]]$Counter); } } diff --git a/src/PerformanceCounter/Public/Show-IcingaPerformanceCounter.ps1 b/src/PerformanceCounter/Public/Show-IcingaPerformanceCounter.ps1 index b1ea258..ff019cd 100644 --- a/src/PerformanceCounter/Public/Show-IcingaPerformanceCounter.ps1 +++ b/src/PerformanceCounter/Public/Show-IcingaPerformanceCounter.ps1 @@ -16,22 +16,22 @@ Because it only reads metadata it is safe to call from any thread and does not r daemon. Errors are logged and yield an empty result rather than throwing. .PARAMETER Category -| Name | Type | Description | Default | -|----------|---------------|----------------------------------------------------------|---------| -| Category | System.String | List the counters within this category. | $null | +| Name | Type | Description | Default | +|----------|---------------|-----------------------------------------|---------| +| Category | System.String | List the counters within this category. | $null | .PARAMETER Counter -| Name | Type | Description | Default | -|---------|---------------|-----------------------------------------------------------------|---------| -| Counter | System.String | Wildcard counter path whose live instances should be listed. | $null | +| Name | Type | Description | Default | +|---------|---------------|--------------------------------------------------------------|---------| +| Counter | System.String | Wildcard counter path whose live instances should be listed. | $null | .PARAMETER Filter -| Name | Type | Description | Default | -|--------|---------------|------------------------------------------------------------|---------| -| Filter | System.String | Wildcard filter applied when listing categories. | $null | +| Name | Type | Description | Default | +|--------|---------------|--------------------------------------------------|---------| +| Filter | System.String | Wildcard filter applied when listing categories. | $null | .OUTPUTS -System.Array — Category names, counter paths, or instance paths depending on the mode. +System.Array -- Category names, counter paths, or instance paths depending on the mode. .EXAMPLE PS> Show-IcingaPerformanceCounter @@ -63,14 +63,14 @@ function Show-IcingaPerformanceCounter() # Mode: list live instance paths for a wildcard counter. if (-not [string]::IsNullOrEmpty($Counter)) { [array]$Instances = @(); - $Parsed = [IcingaPerformanceCounter]::ParsePath($Counter); + $Parsed = ('IcingaPerformanceCounter' -as [type])::ParsePath($Counter); if (-not $Parsed.Valid) { return $Instances; } try { - $CategoryObject = New-Object System.Diagnostics.PerformanceCounterCategory($Parsed.Category); + $CategoryObject = [System.Diagnostics.PerformanceCounterCategory]::new($Parsed.Category); foreach ($InstanceName in $CategoryObject.GetInstanceNames()) { $Instances += ('\{0}({1})\{2}' -f $Parsed.Category, $InstanceName, $Parsed.Counter); @@ -90,7 +90,7 @@ function Show-IcingaPerformanceCounter() [array]$Counters = @(); try { - $CategoryObject = New-Object System.Diagnostics.PerformanceCounterCategory($Category); + $CategoryObject = [System.Diagnostics.PerformanceCounterCategory]::new($Category); $InstanceNames = $CategoryObject.GetInstanceNames(); if ($null -ne $InstanceNames -and $InstanceNames.Count -gt 0) { diff --git a/src/PerformanceCounter/Public/Show-IcingaPerformanceCounterDetails.ps1 b/src/PerformanceCounter/Public/Show-IcingaPerformanceCounterDetails.ps1 index 8c7c121..9c50dea 100644 --- a/src/PerformanceCounter/Public/Show-IcingaPerformanceCounterDetails.ps1 +++ b/src/PerformanceCounter/Public/Show-IcingaPerformanceCounterDetails.ps1 @@ -10,17 +10,17 @@ paths. The result keeps the uniform shape: a hashtable keyed by counter path wit hashtables for concrete paths and nested hashtables for wildcard paths. .PARAMETER Counter -| Name | Type | Description | Default | -|---------|--------------|--------------------------------------------------------------------|---------| -| Counter | System.Array | Counter paths to show. Empty shows all registered counters. | @() | +| Name | Type | Description | Default | +|---------|--------------|-------------------------------------------------------------|---------| +| Counter | System.Array | Counter paths to show. Empty shows all registered counters. | @() | .PARAMETER StructureByInstance -| Name | Type | Description | Default | -|---------------------|----------------------------------------------|--------------------------------------------------------------------------|---------| -| StructureByInstance | System.Management.Automation.SwitchParameter | Reshape the result to instance/category/counter, forwarded to Get-IcingaPerformanceCounter. | $false | +| Name | Type | Description | Default | +|---------------------|----------------------------------------------|---------------------------------------------------------------------------------------------|---------| +| StructureByInstance | System.Management.Automation.SwitchParameter | Reshape the result to instance/category/counter, forwarded to Get-IcingaPerformanceCounter. | $false | .OUTPUTS -System.Collections.Hashtable — Keyed by counter path; values as returned by +System.Collections.Hashtable -- Keyed by counter path; values as returned by `Get-IcingaPerformanceCounter`. With `-StructureByInstance`, keyed by instance/category/counter. Empty when nothing is registered and nothing is requested. diff --git a/src/PerformanceCounter/Public/Test-IcingaPerformanceCounterCategory.ps1 b/src/PerformanceCounter/Public/Test-IcingaPerformanceCounterCategory.ps1 new file mode 100644 index 0000000..c0d84dc --- /dev/null +++ b/src/PerformanceCounter/Public/Test-IcingaPerformanceCounterCategory.ps1 @@ -0,0 +1,44 @@ +<# +.SYNOPSIS +Check whether a Windows performance counter category exists on the local system + +.DESCRIPTION +`Test-IcingaPerformanceCounterCategory` checks whether the given performance counter category +is present and accessible on the local system. It accepts either a plain category name +(such as 'Processor' or 'Memory') or a full counter path (such as +'\Processor(*)\% Processor Time' or '\\.\Processor(_Total)\% Processor Time'). + +Because it only queries category metadata and never throws, it is safe to call from any +thread or provider before reading optional role counters (such as Hyper-V, IIS or MSSQL). + +.PARAMETER Category +| Name | Type | Description | Default | +|----------|---------------|-----------------------------------------------------------|---------| +| Category | System.String | The category name or counter path to check for existence. | | + +.OUTPUTS +System.Boolean -- $true when the category exists and is accessible on this system; $false otherwise. + +.EXAMPLE +PS> Test-IcingaPerformanceCounterCategory -Category 'Processor' + +Returns $true when the 'Processor' performance counter category exists on the system. + +.EXAMPLE +PS> Test-IcingaPerformanceCounterCategory -Category '\Hyper-V Virtual Machine Health Summary(*)\Health Critical' + +Extracts the category name from the counter path and returns $true when the category exists. + +.NOTES +Delegates to `IcingaPerformanceCounter::CategoryExists`. Never throws and reads no global state. +#> +function Test-IcingaPerformanceCounterCategory() +{ + param ( + [string]$Category = '' + ); + + $CounterType = 'IcingaPerformanceCounter' -as [type]; + + return $CounterType::CategoryExists($Category); +} diff --git a/src/Tools/Public/ConvertTo-IcingaUnit.ps1 b/src/Tools/Public/ConvertTo-IcingaUnit.ps1 index 8ca35de..3deb493 100644 --- a/src/Tools/Public/ConvertTo-IcingaUnit.ps1 +++ b/src/Tools/Public/ConvertTo-IcingaUnit.ps1 @@ -26,27 +26,27 @@ the function logs the reason through the module return-value system and returns $null. .PARAMETER InputValue -| Name | Type | Description | Default | -|------------|---------------|----------------------------------------------------------------------------------------------|---------| -| InputValue | System.String | Value to convert, either as a plain number ('1000') or with a unit suffix ('1000B', '1.5MiB').| $null | +| Name | Type | Description | Default | +|------------|---------------|------------------------------------------------------------------------------------------------|---------| +| InputValue | System.String | Value to convert, either as a plain number ('1000') or with a unit suffix ('1000B', '1.5MiB'). | $null | .PARAMETER InputUnit -| Name | Type | Description | Default | -|-----------|---------------|-------------------------------------------------------------------------------------------------|---------| -| InputUnit | System.String | Unit of the input when InputValue has no suffix. A suffix on InputValue takes precedence. | $null | +| Name | Type | Description | Default | +|-----------|---------------|-------------------------------------------------------------------------------------------|---------| +| InputUnit | System.String | Unit of the input when InputValue has no suffix. A suffix on InputValue takes precedence. | $null | .PARAMETER TargetUnit -| Name | Type | Description | Default | -|------------|---------------|------------------------------------------------------------------------------------------------------|---------| -| TargetUnit | System.String | Unit to convert to. Must be in the same family as the input. When omitted the best-fitting unit wins.| $null | +| Name | Type | Description | Default | +|------------|---------------|-------------------------------------------------------------------------------------------------------|---------| +| TargetUnit | System.String | Unit to convert to. Must be in the same family as the input. When omitted the best-fitting unit wins. | $null | .PARAMETER AsHumanReadable -| Name | Type | Description | Default | -|-----------------|----------------------------------------------|---------------------------------------------------------------------------------------------|---------| -| AsHumanReadable | System.Management.Automation.SwitchParameter | Render OutputString with full, pluralized unit names ('2 Hours 23 Minutes 20 Seconds'). | $false | +| Name | Type | Description | Default | +|-----------------|----------------------------------------------|-----------------------------------------------------------------------------------------|---------| +| AsHumanReadable | System.Management.Automation.SwitchParameter | Render OutputString with full, pluralized unit names ('2 Hours 23 Minutes 20 Seconds'). | $false | .OUTPUTS -IcingaUnit — Object with InputValue, InputUnit, OutputValue, OutputUnit and +IcingaUnit -- Object with InputValue, InputUnit, OutputValue, OutputUnit and OutputString describing the conversion. Returns $null via Write-FunctionReturnValue on failure with return codes IcingaUnitInvalidInputValue, IcingaUnitMissingInputUnit, IcingaUnitUnknownUnit or IcingaUnitFamilyMismatch. @@ -83,7 +83,7 @@ function ConvertTo-IcingaUnit() [switch]$AsHumanReadable = $false ); - $Unit = [IcingaUnit]::new($InputValue, $InputUnit, $TargetUnit, $AsHumanReadable.IsPresent); + $Unit = ('IcingaUnit' -as [type])::new($InputValue, $InputUnit, $TargetUnit, $AsHumanReadable.IsPresent); if (-not $Unit.Success) { return (Write-FunctionReturnValue -ReturnValue $Unit.ReturnCode -Data @{