Repository navigation
Expand file tree
/
Copy pathWrite-IcingaPerformanceCounterCache.ps1
More file actions
71 lines (59 loc) · 2.59 KB
/
Copy pathWrite-IcingaPerformanceCounterCache.ps1
File metadata and controls
71 lines (59 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<#
.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 using UTF-8 without BOM.
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 via a temporary file and guarded with try/catch so transient file locks
or permission issues never interrupt the daemon.
.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.
SPDX-FileCopyrightText: 2026 Icinga GmbH <https://icinga.com>
SPDX-License-Identifier: GPL-3.0-or-later
#>
function Write-IcingaPerformanceCounterCache()
{
$Store = (Get-GlobalRuntimeVariable).Public.PerformanceCounter;
if ($null -eq $Store) {
return;
}
[string]$CacheDir = Get-ModuleCacheDirectory;
[string]$CacheFile = Join-Path -Path $CacheDir -ChildPath 'PerformanceCounter.json';
[string]$TempFile = Join-Path -Path $CacheDir -ChildPath ('PerformanceCounter.{0}.tmp' -f [System.Guid]::NewGuid().ToString('N'));
[hashtable]$Data = @{ };
foreach ($Key in @($Store.Registered.Keys)) {
$Timestamp = $Store.Registered[$Key];
if ($null -ne $Timestamp) {
$Data[$Key] = $Timestamp.ToString('o');
}
}
try {
if (-not (Test-Path -Path $CacheDir)) {
New-Item -Path $CacheDir -ItemType Directory -Force -ErrorAction Stop | Out-Null;
}
# Write UTF-8 without BOM to a unique temporary file first, then atomically replace the cache file
[string]$Json = ConvertTo-ModuleJson -InputObject $Data;
[System.IO.File]::WriteAllText($TempFile, $Json, (New-Object System.Text.UTF8Encoding($false)));
Move-Item -Path $TempFile -Destination $CacheFile -Force -ErrorAction Stop;
} catch {
if (Test-Path -Path $TempFile) {
try {
Remove-Item -Path $TempFile -Force -ErrorAction Stop;
} catch {
[void]$_;
}
}
Write-LoggingEntry -Message 'Failed to persist PerformanceCounter cache file' -Level 'Warning' -Data @{
'CacheFile' = $CacheFile;
'ExceptionMessage' = $_.Exception.Message;
};
}
}